File size: 44,712 Bytes
c2efbe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
import { useState, useEffect, useRef } from "react"
import { motion, AnimatePresence } from "framer-motion"
import {
  MessageCircle,
  X,
  Send,
  Bot,
  Phone,
  Mail,
  Star,
  Minimize2,
  Maximize2,
  Smile,
  Paperclip,
  MoreVertical,
  Shield,
  Zap,
  Crown,
  Sparkles,
} from "lucide-react"
import "./LiveChat.css"

const LiveChat = ({ isOpen, setIsOpen }) => {
  const [isMinimized, setIsMinimized] = useState(false)
  const [showTooltip, setShowTooltip] = useState(false)
  const [messages, setMessages] = useState([
    {
      id: 1,
      type: "bot",
      message: "Welcome to MKCart, where luxury meets excellence! I'm Sarah Johnson, your dedicated Personal Shopping Concierge and Premium Support Executive. I'm here to curate an extraordinary shopping experience tailored exclusively for you. As your personal luxury advisor, I have access to our most exclusive collections, VIP services, and bespoke solutions. How may I serve you today?",
      timestamp: new Date(),
      agent: "Sarah",
    },
  ])
  const [inputMessage, setInputMessage] = useState("")
  const [isTyping, setIsTyping] = useState(false)
  const [unreadCount, setUnreadCount] = useState(0)
  const [isOnline, setIsOnline] = useState(true)
  const [currentAgent, setCurrentAgent] = useState({
    name: "Sarah Johnson",
    role: "Premium Support Executive",
    avatar: "👩‍💼",
    status: "online",
  })
  const [userContext, setUserContext] = useState({
    name: "",
    preferences: [],
    previousOrders: [],
    lastInteraction: null,
    satisfaction: 5,
  })

  const messagesEndRef = useRef(null)
  const inputRef = useRef(null)
  const tooltipTimeoutRef = useRef(null)

  const intelligentResponses = {
    greetings: [
      "Welcome to MKCart, where luxury meets excellence! I'm Sarah Johnson, your dedicated Personal Shopping Concierge and Premium Support Executive. I'm here to curate an extraordinary shopping experience tailored exclusively for you. How may I serve you today?",
      "Good day! I'm Sarah, your personal luxury shopping advisor at MKCart. I'm committed to providing you with the most exceptional service and expertise that our distinguished clientele deserves. What brings you to our exclusive collection today?",
      "Hello and welcome to MKCart! I'm Sarah Johnson, your Premium Support Executive. I'm here to ensure your shopping journey is nothing short of magnificent. How can I be of service to you today?",
      "Welcome to the world of luxury shopping! I'm Sarah, your dedicated concierge at MKCart. I'm here to provide you with the most sophisticated and personalized assistance. What can I do to enhance your shopping experience today?",
      "Greetings! I'm Sarah Johnson, your personal shopping consultant at MKCart. I'm here to ensure that every interaction exceeds your expectations and provides you with the premium service you deserve. How may I assist you?",
    ],
    productInquiries: [
      "I'd be absolutely delighted to help you discover the perfect luxury item! Our exclusive Premium collection features meticulously curated pieces with unparalleled quality, craftsmanship, and sophistication. Could you share more about your preferences and what you're seeking?",
      "Excellent taste! Our Premium products represent the pinnacle of luxury and quality, featuring extended warranties, priority concierge support, and exclusive VIP benefits. Allow me to guide you through our distinguished selection to find exactly what you desire.",
      "I'm thrilled to help you explore our exceptional Premium offerings! Each product is carefully handpicked for its superior quality, timeless style, and exceptional value. What specific features, categories, or luxury elements interest you most?",
      "I'd be honored to assist you in finding the perfect luxury addition to your collection! Our Premium products are sourced from the world's finest artisans and brands. What type of luxury experience are you looking for today?",
      "I'm excited to help you discover our exclusive Premium collection! Each piece is selected for its exceptional craftsmanship and timeless elegance. What aspects of luxury shopping are most important to you?",
    ],
    orderTracking: [
      "I'll be delighted to track your luxury order for you! Our Premium delivery service ensures your package is handled with the utmost care and discretion, with white-glove service every step of the way. Could you please provide your order number?",
      "Absolutely! I can help you track your order status with our exclusive Premium tracking system. Our VIP customers receive real-time updates, priority handling, and personalized delivery coordination. Please share your order details, and I'll provide you with comprehensive information immediately.",
      "Of course! I'm here to keep you fully informed about your luxury order. Our Premium tracking system provides detailed updates throughout the entire journey, ensuring complete transparency and peace of mind. May I have your order number?",
      "I'd be happy to track your exclusive order! Our Premium delivery service includes personalized tracking, secure handling, and priority processing. Please provide your order details so I can give you the most current information.",
      "I'm here to ensure you have complete visibility into your luxury order! Our Premium tracking provides real-time updates with the highest level of security and discretion. Could you share your order number?",
    ],
    returns: [
      "I understand your concern completely, and I'm here to make this process as seamless and dignified as possible. Our Premium return policy offers extended return windows, white-glove pickup service, and completely hassle-free processing. Let me assist you with all the details.",
      "I sincerely appreciate you bringing this to my attention. As a Premium customer, you have access to our exclusive VIP return service with expedited processing, complimentary pickup, and priority handling. Let me help you initiate this process with the utmost care.",
      "I'm here to ensure your complete satisfaction and peace of mind. Our Premium return policy is designed to make returns effortless, stress-free, and completely dignified. Please share the details, and I'll guide you through this process with the highest level of service.",
      "I understand that returns should be as luxurious as the shopping experience itself. Our Premium return service includes personalized pickup, expedited processing, and complete discretion. Let me assist you with this matter immediately.",
      "I'm committed to making this return process as smooth and elegant as possible. Our Premium customers enjoy the most sophisticated return experience with priority handling and personalized service. Please share the details so I can assist you.",
    ],
    complaints: [
      "I sincerely and deeply apologize for any inconvenience you've experienced. Your satisfaction is our absolute highest priority, and I'm here to resolve this matter immediately with the attention and care you deserve. Please share the details so I can take immediate and appropriate action.",
      "I completely understand your frustration, and I want to assure you that I'm personally committed to resolving this issue to your complete and total satisfaction. As your Premium Support Executive, I have the full authority to expedite solutions and ensure your peace of mind.",
      "Thank you for bringing this to my attention - your feedback is invaluable to us. I take your concerns very seriously and will personally ensure this matter is addressed promptly with the highest level of care and attention. Let me gather all necessary information to provide you with the most comprehensive resolution possible.",
      "I sincerely apologize for any disappointment you've experienced. As your dedicated concierge, I'm here to ensure this matter is resolved with the utmost urgency and care. Your satisfaction is my personal priority, and I will see this through to completion.",
      "I understand how important this is to you, and I want to assure you that I'm here to resolve this matter with the highest level of attention and care. Your experience should be nothing short of exceptional, and I'm committed to making that right.",
    ],
    general: [
      "I'm here to provide you with the most comprehensive and sophisticated support, ensuring your MKCart experience is nothing short of extraordinary. Is there anything specific you'd like to know about our exclusive services, luxury products, or premium policies?",
      "As your dedicated Premium Support Executive, I'm committed to exceeding your expectations in every possible way. How else can I assist you in creating the most exceptional and memorable shopping experience?",
      "I'm absolutely delighted to help you with any questions or concerns you may have. Your satisfaction is my personal priority, and I'm here to provide you with the most exceptional level of service available.",
      "I'm here to ensure your MKCart experience is nothing short of magnificent. As your personal concierge, I'm available to assist you with any aspect of your luxury shopping journey. What would you like to know more about?",
      "I'm committed to providing you with the most sophisticated and personalized support possible. Your satisfaction is paramount, and I'm here to ensure every interaction exceeds your expectations.",
    ],
    technical: [
      "I understand that technical issues can be frustrating, especially when you're seeking a luxury experience. Let me help you resolve this immediately with our Premium technical support team, available 24/7, and I can escalate your case for the most urgent attention possible.",
      "I'm here to ensure your technical issue is resolved with the highest priority and care. As a Premium customer, you have access to our exclusive priority technical support with the fastest response times and our most dedicated specialists.",
      "Let me assist you with this technical matter immediately. Our Premium support includes the most advanced troubleshooting capabilities and expedited resolution services to ensure your complete satisfaction.",
      "I understand the importance of seamless technology in your luxury shopping experience. Let me connect you with our Premium technical team who will resolve this matter with the utmost urgency and care.",
      "I'm here to ensure this technical issue is resolved promptly and professionally. Our Premium technical support is designed to provide you with the most sophisticated assistance available.",
    ],
    pricing: [
      "I'd be delighted to discuss our competitive luxury pricing and the exceptional value our Premium products offer. Each item is carefully selected to provide the finest quality at the most reasonable prices, ensuring you receive the best value for your investment.",
      "Our pricing reflects the premium quality, craftsmanship, and service you receive. I can also inform you about our exclusive VIP discounts, loyalty programs, and special offers available to our most valued customers.",
      "I understand that pricing is an important consideration in your luxury shopping decisions. Let me highlight the exceptional value proposition of our products and any current exclusive promotions that might interest you.",
      "I'd be happy to discuss our luxury pricing structure and the exceptional value we provide. Our Premium products represent the perfect balance of quality, craftsmanship, and competitive pricing.",
      "I understand the importance of value in luxury shopping. Let me share information about our pricing philosophy and the exceptional benefits that come with our Premium products.",
    ],
    recommendations: [
      "I'd be absolutely thrilled to provide you with the most personalized luxury recommendations! Based on your sophisticated preferences and our exclusive Premium collection, I can suggest products that perfectly match your refined taste and lifestyle.",
      "As your personal luxury shopping concierge, I'm excited to curate a selection exclusively for you! Our Premium products are handpicked for their exceptional quality, timeless style, and sophisticated appeal. I can recommend items that align perfectly with your preferences.",
      "I'm here to help you discover products that exceed even the highest expectations! Let me understand your preferences so I can provide you with the most tailored recommendations from our exclusive Premium collection.",
      "I'd be honored to provide you with personalized luxury recommendations! Our Premium collection features the most sophisticated and carefully curated items, and I'm here to help you find exactly what you're looking for.",
      "I'm excited to help you discover our most exclusive offerings! As your personal shopping advisor, I can provide recommendations that reflect your sophisticated taste and lifestyle preferences.",
    ],
    luxury: [
      "I'm delighted to assist you with our most exclusive luxury offerings! Our Premium collection represents the pinnacle of sophistication and quality, featuring items that are truly extraordinary. What aspect of luxury shopping interests you most?",
      "Welcome to the world of exceptional luxury! Our Premium products are carefully curated to provide you with the most sophisticated and exclusive shopping experience. How can I help you discover our finest offerings?",
      "I'm here to guide you through our most prestigious collection! Our Premium items represent the highest standards of quality, craftsmanship, and luxury. What type of luxury experience are you seeking today?",
      "I'd be honored to introduce you to our most exclusive luxury collection! Each piece is selected for its exceptional quality and timeless elegance. What aspects of luxury are most important to you?",
      "I'm excited to help you explore our most sophisticated offerings! Our Premium collection features the finest luxury items, carefully selected for discerning customers like yourself.",
    ],
    vip: [
      "As our valued VIP customer, you have access to our most exclusive services and benefits! I'm here to ensure you receive the highest level of personalized attention and care. How may I serve you today?",
      "Welcome back to MKCart! As a VIP customer, you enjoy our most premium services and exclusive benefits. I'm here to provide you with the exceptional treatment you deserve. What can I do for you today?",
      "I'm delighted to assist our distinguished VIP customer! You have access to our most exclusive offerings and personalized services. How can I enhance your luxury shopping experience today?",
      "As a VIP customer, you're entitled to our most sophisticated services and exclusive benefits. I'm here to ensure you receive the highest level of care and attention. What would you like to know about your VIP privileges?",
      "I'm honored to serve our VIP customer! You have access to our most exclusive collection and personalized services. How may I assist you with your luxury shopping needs today?",
    ],
    exclusive: [
      "I'm excited to share our most exclusive offerings with you! Our Premium collection features items that are truly unique and extraordinary. What type of exclusive experience are you looking for today?",
      "Welcome to our exclusive collection! Our Premium products are carefully selected for their uniqueness and exceptional quality. How can I help you discover our most exclusive offerings?",
      "I'd be delighted to introduce you to our most exclusive items! Our Premium collection features pieces that are truly one-of-a-kind and extraordinary. What aspects of exclusivity interest you most?",
      "I'm here to guide you through our most exclusive offerings! Our Premium collection represents the pinnacle of uniqueness and sophistication. What type of exclusive experience are you seeking?",
      "I'm thrilled to help you explore our most exclusive collection! Our Premium items are selected for their exceptional uniqueness and quality. What would you like to know about our exclusive offerings?",
    ],
    personalization: [
      "I'm here to provide you with the most personalized luxury shopping experience! Let me understand your preferences so I can curate a selection that's perfectly tailored to your sophisticated taste and lifestyle.",
      "I'd be honored to create a personalized shopping experience just for you! Our Premium collection offers endless possibilities for personalization. What aspects of your lifestyle and preferences should I consider?",
      "I'm excited to help you discover products that are perfectly suited to your unique style and preferences! Let me understand what makes your luxury shopping experience special.",
      "I'm here to provide you with the most personalized recommendations! Our Premium collection can be tailored to match your specific preferences and lifestyle. What would you like me to focus on?",
      "I'd be delighted to create a personalized shopping experience for you! Our Premium offerings can be customized to meet your exact preferences and needs. What aspects are most important to you?",
    ],
  }

  const generateExecutiveResponse = (userMessage) => {
    const lowerMessage = userMessage.toLowerCase()

    const intent = analyzeIntent(lowerMessage)
    const sentiment = analyzeSentiment(lowerMessage)
    const context = getConversationContext()

    let response = ""

    if (intent.vip) {
      response = getRandomResponse(intelligentResponses.vip)
    } else if (intent.luxury) {
      response = getRandomResponse(intelligentResponses.luxury)
    } else if (intent.exclusive) {
      response = getRandomResponse(intelligentResponses.exclusive)
    } else if (intent.personalization) {
      response = getRandomResponse(intelligentResponses.personalization)
    } else if (intent.greeting) {
      response = getRandomResponse(intelligentResponses.greetings)
    } else if (intent.product) {
      response = getRandomResponse(intelligentResponses.productInquiries)
    } else if (intent.tracking) {
      response = getRandomResponse(intelligentResponses.orderTracking)
    } else if (intent.return) {
      response = getRandomResponse(intelligentResponses.returns)
    } else if (intent.complaint) {
      response = getRandomResponse(intelligentResponses.complaints)
    } else if (intent.technical) {
      response = getRandomResponse(intelligentResponses.technical)
    } else if (intent.pricing) {
      response = getRandomResponse(intelligentResponses.pricing)
    } else if (intent.recommendation) {
      response = getRandomResponse(intelligentResponses.recommendations)
    } else {
      response = getRandomResponse(intelligentResponses.general)
    }

    if (userContext.name) {
      response = response.replace("you", userContext.name)
    }

    response = addLuxuryExecutiveTouch(response, sentiment, context, intent)
    
    return response
  }

  const analyzeIntent = (message) => {
    const intent = {
      greeting: false,
      product: false,
      tracking: false,
      return: false,
      complaint: false,
      technical: false,
      pricing: false,
      recommendation: false,
      luxury: false,
      vip: false,
      exclusive: false,
      personalization: false,
    }

    if (message.includes("hello") || message.includes("hi") || message.includes("hey") || message.includes("good morning") || message.includes("good afternoon") || message.includes("good evening")) {
      intent.greeting = true
    }

    if (message.includes("product") || message.includes("item") || message.includes("buy") || message.includes("purchase") || message.includes("collection") || message.includes("catalog")) {
      intent.product = true
    }

    if (message.includes("track") || message.includes("order") || message.includes("delivery") || message.includes("shipping") || message.includes("package") || message.includes("status")) {
      intent.tracking = true
    }

    if (message.includes("return") || message.includes("refund") || message.includes("exchange") || message.includes("send back") || message.includes("replace")) {
      intent.return = true
    }

    if (message.includes("problem") || message.includes("issue") || message.includes("wrong") || message.includes("broken") || message.includes("damaged") || message.includes("defective") || message.includes("complaint")) {
      intent.complaint = true
    }

    if (message.includes("technical") || message.includes("website") || message.includes("app") || message.includes("login") || message.includes("password") || message.includes("error") || message.includes("bug")) {
      intent.technical = true
    }

    if (message.includes("price") || message.includes("cost") || message.includes("expensive") || message.includes("cheap") || message.includes("discount") || message.includes("sale") || message.includes("offer")) {
      intent.pricing = true
    }

    if (message.includes("recommend") || message.includes("suggest") || message.includes("best") || message.includes("popular") || message.includes("trending") || message.includes("favorite")) {
      intent.recommendation = true
    }

    if (message.includes("luxury") || message.includes("premium") || message.includes("exclusive") || message.includes("high-end") || message.includes("prestigious") || message.includes("sophisticated") || message.includes("elegant")) {
      intent.luxury = true
    }

    if (message.includes("vip") || message.includes("very important") || message.includes("priority") || message.includes("concierge") || message.includes("personal") || message.includes("dedicated")) {
      intent.vip = true
    }

    if (message.includes("exclusive") || message.includes("limited") || message.includes("rare") || message.includes("unique") || message.includes("one of a kind") || message.includes("special edition")) {
      intent.exclusive = true
    }

    if (message.includes("personalize") || message.includes("custom") || message.includes("tailored") || message.includes("bespoke") || message.includes("individual") || message.includes("specific")) {
      intent.personalization = true
    }
    
    return intent
  }

  const analyzeSentiment = (message) => {
    const positiveWords = [
      "good", "great", "excellent", "amazing", "love", "happy", "satisfied", "perfect", 
      "wonderful", "fantastic", "outstanding", "brilliant", "superb", "magnificent", 
      "delighted", "pleased", "thrilled", "ecstatic", "overjoyed", "impressed", 
      "beautiful", "gorgeous", "stunning", "elegant", "sophisticated", "luxurious",
      "premium", "exclusive", "high-quality", "superior", "exceptional", "extraordinary"
    ]
    const negativeWords = [
      "bad", "terrible", "awful", "hate", "angry", "frustrated", "disappointed", "upset",
      "horrible", "dreadful", "miserable", "annoyed", "irritated", "disgusted", 
      "furious", "livid", "outraged", "devastated", "heartbroken", "crushed",
      "cheap", "poor", "inferior", "substandard", "defective", "broken", "damaged"
    ]
    const luxuryWords = [
      "luxury", "premium", "exclusive", "sophisticated", "elegant", "prestigious",
      "high-end", "upscale", "refined", "distinguished", "elite", "vip", "concierge",
      "bespoke", "custom", "tailored", "personalized", "unique", "rare", "limited"
    ]
    
    let sentiment = "neutral"
    let score = 0
    let luxuryScore = 0
    
    positiveWords.forEach(word => {
      if (message.includes(word)) score += 1
    })
    
    negativeWords.forEach(word => {
      if (message.includes(word)) score -= 1
    })
    
    luxuryWords.forEach(word => {
      if (message.includes(word)) luxuryScore += 1
    })
    
    if (score > 0) sentiment = "positive"
    else if (score < 0) sentiment = "negative"
    else if (luxuryScore > 0) sentiment = "luxury"
    
    return sentiment
  }

  const getConversationContext = () => {
    const recentMessages = messages.slice(-5)
    const context = {
      hasPreviousInteraction: recentMessages.length > 1,
      isReturningCustomer: userContext.previousOrders.length > 0,
      lastTopic: recentMessages.length > 1 ? recentMessages[recentMessages.length - 2].message : "",
    }
    return context
  }

  const getRandomResponse = (responses) => {
    return responses[Math.floor(Math.random() * responses.length)]
  }

  const addLuxuryExecutiveTouch = (response, sentiment, context, intent) => {
    let enhancedResponse = response

    if (sentiment === "negative") {
      enhancedResponse = "I sincerely and deeply understand your concern, and I want to assure you with the utmost sincerity that " + enhancedResponse.toLowerCase()
    } else if (sentiment === "positive") {
      enhancedResponse = "I'm absolutely delighted to hear that! " + enhancedResponse
    }

    if (context.hasPreviousInteraction) {
      enhancedResponse += " I'm here to continue providing you with the most exceptional and sophisticated service you deserve."
    }

    if (intent.vip || userContext.previousOrders.length > 2) {
      enhancedResponse += " As our valued VIP customer, you have access to our most exclusive services and benefits."
    }

    const luxuryClosings = [
      " Is there anything else I can assist you with today to ensure your complete satisfaction?",
      " How else may I serve you and enhance your luxury shopping experience?",
      " What other questions do you have for me, and how can I further exceed your expectations?",
      " Is there anything specific you'd like to know more about regarding our exclusive offerings?",
      " How can I continue to provide you with the most exceptional service possible?",
      " What other aspects of your luxury shopping journey can I assist you with today?",
      " Is there anything else you'd like to explore in our exclusive collection?",
      " How may I further enhance your sophisticated shopping experience?",
    ]
    
    enhancedResponse += getRandomResponse(luxuryClosings)
    
    return enhancedResponse
  }

  const quickActions = [
    { icon: Phone, label: "VIP Call", action: "call" },
    { icon: Mail, label: "Concierge Email", action: "email" },
    { icon: Star, label: "Rate Experience", action: "rate" },
    { icon: Crown, label: "VIP Services", action: "vip" },
    { icon: Sparkles, label: "Exclusive Offers", action: "exclusive" },
  ]

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  useEffect(() => {
    if (!isOpen && unreadCount === 0) {
      const timer = setTimeout(() => {
        setUnreadCount(1)
      }, 30000) 
      return () => clearTimeout(timer)
    }
  }, [isOpen, unreadCount])

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
  }

  const handleSendMessage = () => {
    if (!inputMessage.trim()) return

    const newMessage = {
      id: Date.now(),
      type: "user",
      message: inputMessage,
      timestamp: new Date(),
      avatar: "👤",
    }

    setMessages((prev) => [...prev, newMessage])
    setInputMessage("")
    setIsTyping(true)

    setTimeout(() => {
      const intelligentResponse = generateExecutiveResponse(inputMessage)
        const botMessage = {
          id: Date.now() + 1,
          type: "bot",
        message: intelligentResponse,
          timestamp: new Date(),
          avatar: "🤖",
        }
        setMessages((prev) => [...prev, botMessage])
        setIsTyping(false)

      updateUserContext(inputMessage)
    }, 1500 + Math.random() * 1000)
  }

  const updateUserContext = (message) => {
    const lowerMessage = message.toLowerCase()

    if (lowerMessage.includes("my name is") || lowerMessage.includes("i'm") || lowerMessage.includes("i am")) {
      const nameMatch = message.match(/(?:my name is|i'm|i am)\s+([a-zA-Z]+)/i)
      if (nameMatch && !userContext.name) {
        setUserContext(prev => ({ ...prev, name: nameMatch[1] }))
      }
    }

    const luxuryKeywords = ["luxury", "premium", "exclusive", "high-end", "sophisticated", "elegant", "vip", "concierge"]
    luxuryKeywords.forEach(keyword => {
      if (lowerMessage.includes(keyword) && !userContext.preferences.includes(keyword)) {
        setUserContext(prev => ({ 
          ...prev, 
          preferences: [...prev.preferences, keyword],
          isLuxuryCustomer: true 
        }))
      }
    })

    const categories = ["electronics", "fashion", "jewelry", "watches", "accessories", "home", "beauty", "automotive"]
    categories.forEach(category => {
      if (lowerMessage.includes(category) && !userContext.preferences.includes(category)) {
        setUserContext(prev => ({ 
          ...prev, 
          preferences: [...prev.preferences, category]
        }))
      }
    })

    if (lowerMessage.includes("expensive") || lowerMessage.includes("high price") || lowerMessage.includes("luxury")) {
      setUserContext(prev => ({ ...prev, spendingIntent: "high" }))
    } else if (lowerMessage.includes("cheap") || lowerMessage.includes("budget") || lowerMessage.includes("affordable")) {
      setUserContext(prev => ({ ...prev, spendingIntent: "moderate" }))
    }

    setUserContext(prev => ({ ...prev, lastInteraction: new Date() }))
  }

  const handleKeyPress = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  const handleQuickAction = (action) => {
    switch (action) {
      case "call":
        const callMessage = {
          id: Date.now(),
          type: "bot",
          message: "I'd be absolutely delighted to connect you with our exclusive VIP support team! I'm initiating a priority call to our dedicated luxury concierge line. You'll receive a call from our senior support executive within 30 seconds.",
          timestamp: new Date(),
          avatar: "🤖",
        }
        setMessages((prev) => [...prev, callMessage])
        setTimeout(() => window.open("tel:+1234567890"), 1000)
        break
      case "email":
        const emailMessage = {
          id: Date.now(),
          type: "bot",
          message: "I'm preparing a comprehensive luxury concierge email for you with all the exclusive information we've discussed. You'll receive this detailed communication at your registered email address within the next few minutes, complete with our VIP offers and personalized recommendations.",
          timestamp: new Date(),
          avatar: "🤖",
        }
        setMessages((prev) => [...prev, emailMessage])
        setTimeout(() => window.open("mailto:support@mkcart.com"), 1000)
        break
      case "rate":
        const rateMessage = {
          id: Date.now(),
          type: "bot",
          message: "I truly value your feedback as it helps me provide even more exceptional service to you and our other distinguished customers. Your opinion is invaluable in maintaining our luxury standards. Please take a moment to rate our interaction.",
          timestamp: new Date(),
          avatar: "🤖",
        }
        setMessages((prev) => [...prev, rateMessage])
        
        break
      case "vip":
        const vipMessage = {
          id: Date.now(),
          type: "bot",
          message: "As our valued VIP customer, you have access to our most exclusive services including priority shipping, dedicated concierge support, exclusive product previews, and personalized shopping experiences. Would you like me to tell you more about your VIP benefits or assist you with any specific VIP service?",
          timestamp: new Date(),
          avatar: "🤖",
        }
        setMessages((prev) => [...prev, vipMessage])
        break
      case "exclusive":
        const exclusiveMessage = {
          id: Date.now(),
          type: "bot",
          message: "I'm excited to share our most exclusive offerings with you! We have limited-edition items, VIP-only collections, and special luxury packages available exclusively for our premium customers. Would you like me to showcase our current exclusive offerings or create a personalized selection for you?",
          timestamp: new Date(),
          avatar: "🤖",
        }
        setMessages((prev) => [...prev, exclusiveMessage])
        break
      default:
        break
    }
  }

  const openChat = () => {
    setIsOpen(true)
    setUnreadCount(0)
    setTimeout(() => inputRef.current?.focus(), 100)
  }

  const closeChat = () => {
    setIsOpen(false)
    setIsMinimized(false)
  }

  const toggleMinimize = () => {
    setIsMinimized(!isMinimized)
  }

  const handleMouseEnter = () => {
    setShowTooltip(true)
    if (tooltipTimeoutRef.current) {
      clearTimeout(tooltipTimeoutRef.current)
    }
  }

  const handleMouseLeave = () => {
    if (tooltipTimeoutRef.current) {
      clearTimeout(tooltipTimeoutRef.current)
    }
    tooltipTimeoutRef.current = setTimeout(() => {
      setShowTooltip(false)
    }, 3000)
  }

  useEffect(() => {
    const timer = setTimeout(() => {
      setShowTooltip(false)
    }, 3000)

    return () => {
      clearTimeout(timer)
      if (tooltipTimeoutRef.current) {
        clearTimeout(tooltipTimeoutRef.current)
      }
    }
  }, [])

  return (
    <>
      {}
      <AnimatePresence>
        {!isOpen && (
          <motion.div
            className="chat-toggle-container"
            initial={{ opacity: 0, y: 50 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 1.2 }}
          >
            <motion.button
              className="chat-toggle-btn"
              onClick={openChat}
              onMouseEnter={handleMouseEnter}
              onMouseLeave={handleMouseLeave}
              whileHover={{ scale: 1.1 }}
              whileTap={{ scale: 0.9 }}
            >
              <Crown size={32} />
              {}
              <div className="chat-particles">
                {[...Array(6)].map((_, i) => (
                  <motion.div
                    key={i}
                    className="chat-particle"
                    animate={{
                      rotate: [0, 360],
                      scale: [0, 1, 0],
                      opacity: [0, 1, 0],
                    }}
                    transition={{
                      duration: 2,
                      repeat: Number.POSITIVE_INFINITY,
                      delay: i * 0.3,
                    }}
                  />
                ))}
              </div>
            </motion.button>

            {}
            <AnimatePresence>
              {showTooltip && (
                <motion.div
                  className="chat-welcome-tooltip"
                  initial={{ opacity: 0, x: 20, scale: 0.8 }}
                  animate={{ opacity: 1, x: 0, scale: 1 }}
                  exit={{ opacity: 0, x: 20, scale: 0.8 }}
                  transition={{ duration: 0.3 }}
                >
                  <div className="tooltip-content">
                    <Crown size={16} />
                    <span>Need help? Chat with our Premium support!</span>
                  </div>
                  <div className="tooltip-arrow" />
                </motion.div>
              )}
            </AnimatePresence>
          </motion.div>
        )}
      </AnimatePresence>

      {}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            className={`chat-window ${isMinimized ? "minimized" : ""}`}
            initial={{ opacity: 0, scale: 0.8, y: 50 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.8, y: 50 }}
            transition={{ type: "spring", stiffness: 200, damping: 25 }}
          >
            {}
            <div className="chat-header">
              <div className="header-content">
                <div className="agent-info">
                  <div className="agent-avatar">
                    <span>{currentAgent.avatar}</span>
                    <div className={`status-indicator ${currentAgent.status}`} />
                  </div>
                  <div className="agent-details">
                    <h4 className="agent-name">{currentAgent.name}</h4>
                    <p className="agent-role">{currentAgent.role}</p>
                  </div>
                </div>

                <div className="header-actions">
                  <motion.button
                    className="header-btn"
                    onClick={toggleMinimize}
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    {isMinimized ? <Maximize2 size={16} /> : <Minimize2 size={16} />}
                  </motion.button>
                  <motion.button
                    className="header-btn close"
                    onClick={closeChat}
                    whileHover={{ scale: 1.1, rotate: 90 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <X size={16} />
                  </motion.button>
                </div>
              </div>

              {}
              <div className="status-bar">
                <div className="status-item">
                  <Shield size={12} />
                  <span>Secure Chat</span>
                </div>
                <div className="status-item">
                  <Zap size={12} />
                  <span>Instant Response</span>
                </div>
                <div className={`online-status ${isOnline ? "online" : "offline"}`}>
                  <div className="status-dot" />
                  <span>{isOnline ? "Online" : "Offline"}</span>
                </div>
              </div>

              <div className="header-glow" />
            </div>

            {}
            <AnimatePresence>
              {!isMinimized && (
                <motion.div
                  className="header-quick-actions"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: 20 }}
                  transition={{ duration: 0.3, delay: 0.1 }}
                >
                  {quickActions.map((action, index) => (
                    <motion.button
                      key={action.action}
                      className="header-quick-action-btn"
                      onClick={() => handleQuickAction(action.action)}
                      whileHover={{ scale: 1.05, y: -2 }}
                      whileTap={{ scale: 0.95 }}
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: index * 0.1 }}
                    >
                      <action.icon size={16} />
                      <span>{action.label}</span>
                      <div className="header-action-glow" />
                    </motion.button>
                  ))}
                </motion.div>
              )}
            </AnimatePresence>

            {}
            <AnimatePresence>
              {!isMinimized && (
                <motion.div
                  className="chat-messages"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: "auto" }}
                  exit={{ opacity: 0, height: 0 }}
                  transition={{ duration: 0.3 }}
                >
                  <div className="messages-container">
                    {messages.map((message, index) => (
                      <motion.div
                        key={message.id}
                        className={`message ${message.type}`}
                        initial={{ opacity: 0, y: 20, scale: 0.8 }}
                        animate={{ opacity: 1, y: 0, scale: 1 }}
                        transition={{
                          duration: 0.4,
                          delay: index * 0.1,
                          type: "spring",
                          stiffness: 200,
                        }}
                      >
                        <div className="message-avatar">
                          <span>{message.avatar}</span>
                          {message.type === "bot" && (
                            <div className="avatar-glow">
                              <Sparkles size={12} />
                            </div>
                          )}
                        </div>
                        <div className="message-content">
                          <div className="message-bubble">
                            <p>{message.message}</p>
                            <div className="message-glow" />
                          </div>
                          <div className="message-time">
                            {message.timestamp.toLocaleTimeString([], {
                              hour: "2-digit",
                              minute: "2-digit",
                            })}
                          </div>
                        </div>
                      </motion.div>
                    ))}

                    {}
                    <AnimatePresence>
                      {isTyping && (
                        <motion.div
                          className="message bot typing"
                          initial={{ opacity: 0, y: 20 }}
                          animate={{ opacity: 1, y: 0 }}
                          exit={{ opacity: 0, y: -20 }}
                          transition={{ duration: 0.3 }}
                        >
                          <div className="message-avatar">
                            <span>🤖</span>
                          </div>
                          <div className="message-content">
                            <div className="typing-indicator">
                              <div className="typing-dots">
                                <div className="dot" />
                                <div className="dot" />
                                <div className="dot" />
                              </div>
                              <span>AI is typing...</span>
                            </div>
                          </div>
                        </motion.div>
                      )}
                    </AnimatePresence>

                    <div ref={messagesEndRef} />
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            {}
            <AnimatePresence>
              {!isMinimized && (
                <motion.div
                  className="chat-input-container"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: 20 }}
                  transition={{ duration: 0.3, delay: 0.2 }}
                >
                  <div className="input-wrapper">
                    <motion.button className="input-action-btn" whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
                      <Paperclip size={18} />
                    </motion.button>

                    <input
                      ref={inputRef}
                      type="text"
                      value={inputMessage}
                      onChange={(e) => setInputMessage(e.target.value)}
                      onKeyPress={handleKeyPress}
                      placeholder="Type your message..."
                      className="chat-input"
                    />

                    <motion.button className="input-action-btn" whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
                      <Smile size={18} />
                    </motion.button>

                    <motion.button
                      className="send-btn"
                      onClick={handleSendMessage}
                      disabled={!inputMessage.trim()}
                      whileHover={{ scale: 1.05 }}
                      whileTap={{ scale: 0.95 }}
                    >
                      <Send size={18} />
                      <div className="send-glow" />
                    </motion.button>
                  </div>

                  <div className="input-footer">
                    <div className="powered-by">
                      <Bot size={12} />
                      <span>Powered by MKCart AI</span>
                    </div>
                    <div className="encryption-badge">
                      <Shield size={12} />
                      <span>End-to-end encrypted</span>
                    </div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  )
}

export default LiveChat