@blockspark/chat-widget 1.0.20 → 1.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { jsxs, Fragment, jsx } from "react/jsx-runtime";
2
2
  import React, { useState, useEffect, useCallback, useRef } from "react";
3
- import { c as createChatService, l as linkifyText, a as createDialogflowSession, C as ChatResolvedError, s as sendDialogflowMessage } from "./sanitize-Cm1kskSD.js";
3
+ import { c as createChatService, l as linkifyText, a as createDialogflowSession, C as ChatResolvedError, s as sendDialogflowMessage } from "./sanitize-Q7JIm8H8.js";
4
4
  import require$$0 from "react-dom";
5
5
  const MODE_STORAGE_KEY = "chartsconnectect_chat_mode";
6
6
  const CHAT_ID_STORAGE_KEY = "chartsconnect_chat_id";
@@ -77,6 +77,8 @@ function ChatWidget$1({
77
77
  backendBaseUrl,
78
78
  backendWsUrl
79
79
  }) {
80
+ const msgIdCounter = useRef(0);
81
+ const uid = (prefix = "msg") => `${prefix}-${Date.now()}-${++msgIdCounter.current}`;
80
82
  const [isOpen, setIsOpen] = useState(false);
81
83
  const [showWelcomePopup, setShowWelcomePopup] = useState(false);
82
84
  const [messages, setMessages] = useState([]);
@@ -88,25 +90,20 @@ function ChatWidget$1({
88
90
  const [wsConnected, setWsConnected] = useState(false);
89
91
  const [agentTyping, setAgentTyping] = useState(false);
90
92
  const [currentAgent, setCurrentAgent] = useState({ name: "Agent" });
91
- const [collectingUserInfo, setCollectingUserInfo] = useState(false);
92
93
  const [chatResolved, setChatResolved] = useState(false);
93
94
  const [isStartingNewChat, setIsStartingNewChat] = useState(false);
94
95
  const [agentAccepted, setAgentAccepted] = useState(false);
95
- const [userInfoStep, setUserInfoStep] = useState(null);
96
- const [collectedUserName, setCollectedUserName] = useState("");
97
- const [collectedUserEmail, setCollectedUserEmail] = useState("");
98
- const [collectedUserMobile, setCollectedUserMobile] = useState("");
99
- const collectedUserNameRef = useRef("");
100
96
  const messagesEndRef = useRef(null);
101
97
  const typingTimeoutRef = useRef(null);
102
98
  const agentTypingTimeoutRef = useRef(null);
103
99
  const creatingSessionRef = useRef(false);
100
+ const resolvedResetTimerRef = useRef(null);
104
101
  const createSessionRef = useRef(null);
105
102
  const getBackendBaseUrl = () => {
106
- return backendBaseUrl || typeof process !== "undefined" && process.env?.REACT_APP_BACKEND_BASE_URL;
103
+ return backendBaseUrl || "https://chartconnect.blockspark.in";
107
104
  };
108
105
  const getBackendWsUrl = () => {
109
- return backendWsUrl || typeof process !== "undefined" && process.env?.REACT_APP_BACKEND_WS_URL;
106
+ return backendWsUrl || "wss://chartconnect.blockspark.in";
110
107
  };
111
108
  const chatServiceRef = useRef(
112
109
  createChatService({
@@ -140,22 +137,18 @@ function ChatWidget$1({
140
137
  setSupportSessionId(null);
141
138
  setSessionId(null);
142
139
  const thankYouMessage = {
143
- id: `resolved-${Date.now()}`,
140
+ id: uid("resolved"),
144
141
  text: "Thank you for contacting us!",
145
142
  sender: "bot",
146
143
  timestamp: /* @__PURE__ */ new Date()
147
144
  };
148
145
  setMessages((prev) => [...prev, thankYouMessage]);
149
- setTimeout(() => {
146
+ if (resolvedResetTimerRef.current) clearTimeout(resolvedResetTimerRef.current);
147
+ resolvedResetTimerRef.current = setTimeout(() => {
148
+ resolvedResetTimerRef.current = null;
150
149
  switchToBotMode();
151
150
  setChatResolved(false);
152
151
  setMessages([]);
153
- setCollectingUserInfo(false);
154
- setUserInfoStep(null);
155
- setCollectedUserName("");
156
- setCollectedUserEmail("");
157
- setCollectedUserMobile("");
158
- collectedUserNameRef.current = "";
159
152
  if (createSessionRef.current) {
160
153
  createSessionRef.current().catch(console.error);
161
154
  }
@@ -168,14 +161,8 @@ function ChatWidget$1({
168
161
  if (isStartingNewChat) return;
169
162
  setIsStartingNewChat(true);
170
163
  try {
171
- const customerName = collectedUserNameRef.current || collectedUserName || null;
172
- const customerEmail = collectedUserEmail || null;
173
- const customerMobile = collectedUserMobile || null;
174
164
  const newSession = await chatServiceRef.current.startSupportChat(
175
- sessionId || null,
176
- customerName,
177
- customerEmail,
178
- customerMobile
165
+ sessionId || null
179
166
  );
180
167
  switchToHumanMode();
181
168
  setChatId(newSession.chat_id);
@@ -187,7 +174,7 @@ function ChatWidget$1({
187
174
  setMessages((prev) => [
188
175
  ...prev,
189
176
  {
190
- id: `error-new-chat-${Date.now()}`,
177
+ id: uid("error"),
191
178
  text: debug ? `Error: ${error?.message || "Failed to start a new chat."}` : "Sorry, I couldn't start a new chat. Please try again.",
192
179
  sender: "bot",
193
180
  timestamp: /* @__PURE__ */ new Date()
@@ -197,9 +184,6 @@ function ChatWidget$1({
197
184
  setIsStartingNewChat(false);
198
185
  }
199
186
  }, [
200
- collectedUserEmail,
201
- collectedUserMobile,
202
- collectedUserName,
203
187
  debug,
204
188
  isStartingNewChat,
205
189
  sessionId,
@@ -222,12 +206,21 @@ function ChatWidget$1({
222
206
  useEffect(() => {
223
207
  if (!enableWelcomePopup) return;
224
208
  const timer = setTimeout(() => {
225
- setShowWelcomePopup(true);
209
+ if (!isOpen) {
210
+ setShowWelcomePopup(true);
211
+ }
226
212
  }, welcomePopupDelay);
227
213
  return () => clearTimeout(timer);
228
- }, [enableWelcomePopup, welcomePopupDelay]);
214
+ }, [enableWelcomePopup, welcomePopupDelay, isOpen]);
215
+ const scrollTimeoutRef = useRef(null);
229
216
  useEffect(() => {
230
- messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
217
+ if (scrollTimeoutRef.current) clearTimeout(scrollTimeoutRef.current);
218
+ scrollTimeoutRef.current = setTimeout(() => {
219
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
220
+ }, 80);
221
+ return () => {
222
+ if (scrollTimeoutRef.current) clearTimeout(scrollTimeoutRef.current);
223
+ };
231
224
  }, [messages]);
232
225
  const handleAgentChanged = useCallback((message) => {
233
226
  if (message.to_agent) {
@@ -236,7 +229,7 @@ function ChatWidget$1({
236
229
  name: message.to_agent
237
230
  });
238
231
  const systemMessage = {
239
- id: `system-${Date.now()}`,
232
+ id: uid("system"),
240
233
  text: message.from_agent ? `Chat has been transferred from ${message.from_agent} to ${message.to_agent}` : `Chat has been transferred to ${message.to_agent}`,
241
234
  sender: "bot",
242
235
  timestamp: /* @__PURE__ */ new Date()
@@ -257,7 +250,7 @@ function ChatWidget$1({
257
250
  if (message.content) {
258
251
  if (message.sender_type === "agent" || !message.sender_type) {
259
252
  const agentMessage = {
260
- id: message.id || `agent-${Date.now()}`,
253
+ id: message.id || uid("agent"),
261
254
  text: message.content,
262
255
  sender: "agent",
263
256
  timestamp: new Date(message.timestamp || Date.now())
@@ -325,7 +318,7 @@ function ChatWidget$1({
325
318
  setAgentAccepted(true);
326
319
  setIsConnectingToAgent(false);
327
320
  const acceptedMessage = {
328
- id: message.id || `agent-accepted-${message.chat_id || Date.now()}-${Date.now()}`,
321
+ id: message.id || uid("agent-accepted"),
329
322
  text: "You can chat now, the agent has accepted your request.",
330
323
  sender: "bot",
331
324
  timestamp: message.timestamp ? new Date(message.timestamp) : /* @__PURE__ */ new Date()
@@ -357,7 +350,7 @@ function ChatWidget$1({
357
350
  case "error":
358
351
  console.error("WebSocket error:", message.error);
359
352
  const errorMessage = {
360
- id: `error-${Date.now()}`,
353
+ id: uid("error"),
361
354
  text: message.error || "An error occurred. Please try again.",
362
355
  sender: "bot",
363
356
  timestamp: /* @__PURE__ */ new Date()
@@ -413,7 +406,7 @@ function ChatWidget$1({
413
406
  setIsLoading(true);
414
407
  const history = await chatServiceRef.current.loadMessageHistory(chatId, supportSessionId);
415
408
  const historyMessages = history.map((msg) => ({
416
- id: msg.id || `msg-${Date.now()}-${Math.random()}`,
409
+ id: msg.id || uid("history"),
417
410
  text: msg.content,
418
411
  sender: msg.sender_type === "agent" ? "agent" : "user",
419
412
  timestamp: new Date(msg.timestamp)
@@ -434,7 +427,7 @@ function ChatWidget$1({
434
427
  console.error("Error loading message history:", error);
435
428
  if (debug) {
436
429
  const errorMessage = {
437
- id: `error-${Date.now()}`,
430
+ id: uid("error"),
438
431
  text: `Failed to load chat history: ${error.message}`,
439
432
  sender: "bot",
440
433
  timestamp: /* @__PURE__ */ new Date()
@@ -461,17 +454,14 @@ function ChatWidget$1({
461
454
  historyLoadedRef.current = null;
462
455
  }
463
456
  }, [currentMode, chatId, supportSessionId, loadMessageHistory, messages.length]);
464
- const handleHandoff = async (customerName, customerEmail, customerMobile) => {
457
+ const handleHandoff = async (webhookChatId, webhookSessionId) => {
465
458
  try {
466
459
  setIsConnectingToAgent(true);
467
460
  const dialogflowSessionId = sessionId;
468
- const session = await chatServiceRef.current.ensureChatInitialized(
461
+ const session = webhookChatId && webhookSessionId ? { chat_id: webhookChatId, session_id: webhookSessionId } : await chatServiceRef.current.ensureChatInitialized(
469
462
  chatId,
470
463
  supportSessionId,
471
- dialogflowSessionId || null,
472
- customerName || null,
473
- customerEmail || null,
474
- customerMobile || null
464
+ dialogflowSessionId || null
475
465
  );
476
466
  if (!session || !session.chat_id) {
477
467
  throw new Error("Failed to initialize chat session");
@@ -485,76 +475,64 @@ function ChatWidget$1({
485
475
  console.log("✅ Chat initialized:", { chatId: currentChatId, sessionId: currentSupportSessionId });
486
476
  }
487
477
  }
488
- try {
489
- await chatServiceRef.current.requestHandoff(
490
- currentChatId,
491
- currentSupportSessionId,
492
- "Customer requested human agent",
493
- dialogflowSessionId || null,
494
- customerName || null,
495
- customerEmail || null,
496
- customerMobile || null
497
- );
498
- if (debug) {
499
- console.log("✅ Handoff requested successfully");
500
- }
501
- } catch (handoffError) {
502
- if (handoffError.message?.includes("Invalid chat_id") || handoffError.message?.includes("Chat not found") || handoffError.message?.includes("unauthorized") || handoffError.message?.includes("400") || handoffError.message?.includes("401") || handoffError.message?.includes("404") || handoffError.message?.includes("expired")) {
503
- if (debug) {
504
- console.log("⚠️ Chat expired or not found. Re-initializing chat...");
505
- }
506
- setChatId(null);
507
- setSupportSessionId(null);
508
- const newSession = await chatServiceRef.current.startSupportChat(
509
- dialogflowSessionId || null,
510
- customerName || null,
511
- customerEmail || null,
512
- customerMobile || null
513
- );
514
- if (!newSession || !newSession.chat_id) {
515
- throw new Error("Failed to re-initialize chat session");
516
- }
517
- const newChatId = newSession.chat_id;
518
- const newSessionId = newSession.session_id;
519
- setChatId(newChatId);
520
- setSupportSessionId(newSessionId);
478
+ if (!webhookChatId) {
479
+ try {
521
480
  await chatServiceRef.current.requestHandoff(
522
- newChatId,
523
- newSessionId,
481
+ currentChatId,
482
+ currentSupportSessionId,
524
483
  "Customer requested human agent",
525
- dialogflowSessionId || null,
526
- customerName || null,
527
- customerEmail || null,
528
- customerMobile || null
484
+ dialogflowSessionId || null
529
485
  );
530
486
  if (debug) {
531
- console.log("✅ Handoff requested successfully after retry");
487
+ console.log("✅ Handoff requested successfully");
532
488
  }
533
- const newSessionKey = `${newChatId}-${newSessionId}`;
534
- if (historyLoadedRef.current !== newSessionKey) {
535
- historyLoadedRef.current = newSessionKey;
536
- await loadMessageHistory(true);
489
+ } catch (handoffError) {
490
+ if (handoffError.message?.includes("Invalid chat_id") || handoffError.message?.includes("Chat not found") || handoffError.message?.includes("unauthorized") || handoffError.message?.includes("400") || handoffError.message?.includes("401") || handoffError.message?.includes("404") || handoffError.message?.includes("expired")) {
491
+ if (debug) {
492
+ console.log("⚠️ Chat expired or not found. Re-initializing chat...");
493
+ }
494
+ setChatId(null);
495
+ setSupportSessionId(null);
496
+ const newSession = await chatServiceRef.current.startSupportChat(
497
+ dialogflowSessionId || null
498
+ );
499
+ if (!newSession || !newSession.chat_id) {
500
+ throw new Error("Failed to re-initialize chat session");
501
+ }
502
+ const newChatId = newSession.chat_id;
503
+ const newSessionId = newSession.session_id;
504
+ setChatId(newChatId);
505
+ setSupportSessionId(newSessionId);
506
+ await chatServiceRef.current.requestHandoff(
507
+ newChatId,
508
+ newSessionId,
509
+ "Customer requested human agent",
510
+ dialogflowSessionId || null
511
+ );
512
+ if (debug) {
513
+ console.log("✅ Handoff requested successfully after retry");
514
+ }
515
+ const newSessionKey = `${newChatId}-${newSessionId}`;
516
+ if (historyLoadedRef.current !== newSessionKey) {
517
+ historyLoadedRef.current = newSessionKey;
518
+ await loadMessageHistory(true);
519
+ }
520
+ } else {
521
+ throw handoffError;
537
522
  }
538
- } else {
539
- throw handoffError;
540
523
  }
524
+ } else if (debug) {
525
+ console.log("✅ Using webhook-created chat, skipping requestHandoff");
541
526
  }
542
527
  switchToHumanMode();
543
528
  setChatResolved(false);
544
529
  setAgentAccepted(false);
545
- const connectingMessage = {
546
- id: `connecting-${Date.now()}`,
547
- text: "Connecting you to a human agent...",
548
- sender: "bot",
549
- timestamp: /* @__PURE__ */ new Date()
550
- };
551
- setMessages((prev) => [...prev, connectingMessage]);
552
530
  const sessionKey = `${currentChatId}-${currentSupportSessionId}`;
553
531
  historyLoadedRef.current = sessionKey;
554
532
  } catch (error) {
555
533
  console.error("Error handling handoff:", error);
556
534
  const errorMessage = {
557
- id: `error-${Date.now()}`,
535
+ id: uid("error"),
558
536
  text: debug ? `Handoff error: ${error.message}` : "Failed to connect to agent. Please try again.",
559
537
  sender: "bot",
560
538
  timestamp: /* @__PURE__ */ new Date()
@@ -586,7 +564,7 @@ function ChatWidget$1({
586
564
  console.log("Full session response:", data);
587
565
  }
588
566
  const welcomeMessage2 = {
589
- id: `welcome-${Date.now()}`,
567
+ id: uid("welcome"),
590
568
  text: data.message,
591
569
  sender: "bot",
592
570
  timestamp: /* @__PURE__ */ new Date(),
@@ -610,7 +588,7 @@ function ChatWidget$1({
610
588
  });
611
589
  }
612
590
  const errorMessage = {
613
- id: `error-${Date.now()}`,
591
+ id: uid("error"),
614
592
  text: debug ? `Error: ${error.message || "Failed to create session. Please check your Dialogflow configuration."}` : fallbackWelcomeMessage,
615
593
  sender: "bot",
616
594
  timestamp: /* @__PURE__ */ new Date()
@@ -623,98 +601,22 @@ function ChatWidget$1({
623
601
  }
624
602
  };
625
603
  createSessionRef.current = createSession;
604
+ const sendingRef = useRef(false);
626
605
  const sendMessage = async (text, displayText, skipUserMessage = false) => {
627
- if (!text.trim()) return;
628
- if (collectingUserInfo) {
629
- if (userInfoStep === "name") {
630
- const name = text.trim();
631
- setCollectedUserName(name);
632
- collectedUserNameRef.current = name;
633
- setUserInfoStep("email");
634
- const userMessage = {
635
- id: Date.now().toString(),
636
- text: name,
637
- sender: "user",
638
- timestamp: /* @__PURE__ */ new Date()
639
- };
640
- setMessages((prev) => [...prev, userMessage]);
641
- const emailPrompt = {
642
- id: (Date.now() + 1).toString(),
643
- text: "Thank you! Now please provide your email address:",
644
- sender: "bot",
645
- timestamp: /* @__PURE__ */ new Date()
646
- };
647
- setMessages((prev) => [...prev, emailPrompt]);
648
- setInputValue("");
649
- return;
650
- } else if (userInfoStep === "email") {
651
- const email = text.trim();
652
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
653
- if (!emailRegex.test(email)) {
654
- const invalidEmailMessage = {
655
- id: (Date.now() + 1).toString(),
656
- text: "Please provide a valid email address:",
657
- sender: "bot",
658
- timestamp: /* @__PURE__ */ new Date()
659
- };
660
- setMessages((prev) => [...prev, invalidEmailMessage]);
661
- setInputValue("");
662
- return;
663
- }
664
- setCollectedUserEmail(email);
665
- setUserInfoStep("mobile");
666
- const userMessage = {
667
- id: Date.now().toString(),
668
- text: email,
669
- sender: "user",
670
- timestamp: /* @__PURE__ */ new Date()
671
- };
672
- setMessages((prev) => [...prev, userMessage]);
673
- const mobilePrompt = {
674
- id: (Date.now() + 1).toString(),
675
- text: "Thank you! Now please provide your mobile number:",
676
- sender: "bot",
677
- timestamp: /* @__PURE__ */ new Date()
678
- };
679
- setMessages((prev) => [...prev, mobilePrompt]);
680
- setInputValue("");
681
- return;
682
- } else if (userInfoStep === "mobile") {
683
- const mobile = text.trim();
684
- const mobileRegex = /^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,9}$/;
685
- if (!mobileRegex.test(mobile) || mobile.length < 10) {
686
- const invalidMobileMessage = {
687
- id: (Date.now() + 1).toString(),
688
- text: "Please provide a valid mobile number (e.g., +1234567890):",
689
- sender: "bot",
690
- timestamp: /* @__PURE__ */ new Date()
691
- };
692
- setMessages((prev) => [...prev, invalidMobileMessage]);
693
- setInputValue("");
694
- return;
695
- }
696
- setCollectedUserMobile(mobile);
697
- const userMessage = {
698
- id: Date.now().toString(),
699
- text: mobile,
700
- sender: "user",
701
- timestamp: /* @__PURE__ */ new Date()
702
- };
703
- setMessages((prev) => [...prev, userMessage]);
704
- const userName = collectedUserNameRef.current;
705
- const userEmail = collectedUserEmail;
706
- setCollectingUserInfo(false);
707
- setUserInfoStep(null);
708
- collectedUserNameRef.current = "";
709
- await handleHandoff(userName, userEmail, mobile);
710
- setInputValue("");
711
- return;
712
- }
606
+ if (!text.trim() || sendingRef.current) return;
607
+ sendingRef.current = true;
608
+ try {
609
+ await sendMessageInner(text, displayText, skipUserMessage);
610
+ } finally {
611
+ sendingRef.current = false;
713
612
  }
613
+ };
614
+ const sendMessageInner = async (text, displayText, skipUserMessage = false) => {
615
+ if (!text.trim()) return;
714
616
  if (currentMode === "HUMAN") {
715
617
  if (!chatId || !supportSessionId) {
716
618
  const errorMessage = {
717
- id: Date.now().toString(),
619
+ id: uid("msg"),
718
620
  text: "Chat session not initialized. Please try again.",
719
621
  sender: "bot",
720
622
  timestamp: /* @__PURE__ */ new Date()
@@ -724,7 +626,7 @@ function ChatWidget$1({
724
626
  }
725
627
  if (!skipUserMessage) {
726
628
  const userMessage = {
727
- id: Date.now().toString(),
629
+ id: uid("msg"),
728
630
  text: displayText || text.trim(),
729
631
  sender: "user",
730
632
  timestamp: /* @__PURE__ */ new Date()
@@ -757,10 +659,7 @@ function ChatWidget$1({
757
659
  setSupportSessionId(null);
758
660
  try {
759
661
  const newSession = await chatServiceRef.current.startSupportChat(
760
- sessionId || null,
761
- null,
762
- null,
763
- null
662
+ sessionId || null
764
663
  );
765
664
  setChatId(newSession.chat_id);
766
665
  setSupportSessionId(newSession.session_id);
@@ -784,7 +683,7 @@ function ChatWidget$1({
784
683
  return;
785
684
  }
786
685
  const errorMessage = {
787
- id: (Date.now() + 1).toString(),
686
+ id: uid("msg"),
788
687
  text: debug ? `Error: ${retryError.message || "Failed to send message."}` : "Sorry, I'm having trouble sending your message. Please try again.",
789
688
  sender: "bot",
790
689
  timestamp: /* @__PURE__ */ new Date()
@@ -793,7 +692,7 @@ function ChatWidget$1({
793
692
  }
794
693
  } else {
795
694
  const errorMessage = {
796
- id: (Date.now() + 1).toString(),
695
+ id: uid("msg"),
797
696
  text: debug ? `Error: ${error.message || "Failed to send message to agent."}` : "Sorry, I'm having trouble sending your message. Please try again.",
798
697
  sender: "bot",
799
698
  timestamp: /* @__PURE__ */ new Date()
@@ -811,7 +710,7 @@ function ChatWidget$1({
811
710
  currentSessionId = await createSession();
812
711
  if (!currentSessionId) {
813
712
  const errorMessage = {
814
- id: Date.now().toString(),
713
+ id: uid("msg"),
815
714
  text: debug ? "Failed to create session. Please check the console for details." : "Sorry, I'm having trouble connecting. Please try again.",
816
715
  sender: "bot",
817
716
  timestamp: /* @__PURE__ */ new Date()
@@ -822,7 +721,7 @@ function ChatWidget$1({
822
721
  } catch (error) {
823
722
  console.error("Error in createSession:", error);
824
723
  const errorMessage = {
825
- id: Date.now().toString(),
724
+ id: uid("msg"),
826
725
  text: debug ? `Connection Error: ${error.message || "Please check your Dialogflow configuration."}` : "Sorry, I'm having trouble connecting. Please check your configuration.",
827
726
  sender: "bot",
828
727
  timestamp: /* @__PURE__ */ new Date()
@@ -833,7 +732,7 @@ function ChatWidget$1({
833
732
  }
834
733
  if (!skipUserMessage) {
835
734
  const userMessage = {
836
- id: Date.now().toString(),
735
+ id: uid("msg"),
837
736
  text: displayText || text.trim(),
838
737
  sender: "user",
839
738
  timestamp: /* @__PURE__ */ new Date()
@@ -854,36 +753,29 @@ function ChatWidget$1({
854
753
  console.log("Handoff detected:", data.handoff);
855
754
  }
856
755
  if (data.handoff === true) {
857
- const botMessage2 = {
858
- id: (Date.now() + 1).toString(),
756
+ if (data.response || data.richContent) {
757
+ const botMessage = {
758
+ id: uid("msg"),
759
+ text: data.response,
760
+ sender: "bot",
761
+ timestamp: new Date(data.timestamp || Date.now()),
762
+ richContent: data.richContent
763
+ };
764
+ setMessages((prev) => [...prev, botMessage]);
765
+ }
766
+ await handleHandoff(data.chat_id, data.support_session_id);
767
+ return;
768
+ }
769
+ if (data.response || data.richContent) {
770
+ const botMessage = {
771
+ id: uid("msg"),
859
772
  text: data.response,
860
773
  sender: "bot",
861
774
  timestamp: new Date(data.timestamp || Date.now()),
862
775
  richContent: data.richContent
863
776
  };
864
- setMessages((prev) => [...prev, botMessage2]);
865
- setCollectingUserInfo(true);
866
- setUserInfoStep("name");
867
- setCollectedUserName("");
868
- setCollectedUserEmail("");
869
- collectedUserNameRef.current = "";
870
- const namePrompt = {
871
- id: (Date.now() + 2).toString(),
872
- text: "To connect you with a human agent, I'll need some information. Please provide your name:",
873
- sender: "bot",
874
- timestamp: /* @__PURE__ */ new Date()
875
- };
876
- setMessages((prev) => [...prev, namePrompt]);
877
- return;
777
+ setMessages((prev) => [...prev, botMessage]);
878
778
  }
879
- const botMessage = {
880
- id: (Date.now() + 1).toString(),
881
- text: data.response,
882
- sender: "bot",
883
- timestamp: new Date(data.timestamp || Date.now()),
884
- richContent: data.richContent
885
- };
886
- setMessages((prev) => [...prev, botMessage]);
887
779
  } catch (error) {
888
780
  console.error("Error sending message:", error);
889
781
  if (debug) {
@@ -895,7 +787,7 @@ function ChatWidget$1({
895
787
  });
896
788
  }
897
789
  const errorMessage = {
898
- id: (Date.now() + 1).toString(),
790
+ id: uid("msg"),
899
791
  text: debug ? `Error: ${error.message || "Failed to send message. Please check your Dialogflow configuration."}` : error.message?.includes("Failed to fetch") || error.message?.includes("CORS") ? "Unable to connect to Dialogflow. Please check your configuration and network." : "Sorry, I'm having trouble processing your message. Please try again.",
900
792
  sender: "bot",
901
793
  timestamp: /* @__PURE__ */ new Date()
@@ -1074,7 +966,7 @@ function ChatWidget$1({
1074
966
  className: "custom-chip-button",
1075
967
  onClick: () => {
1076
968
  const userMessage = {
1077
- id: Date.now().toString(),
969
+ id: uid("msg"),
1078
970
  text: chip.text,
1079
971
  sender: "user",
1080
972
  timestamp: /* @__PURE__ */ new Date()
@@ -1101,7 +993,7 @@ function ChatWidget$1({
1101
993
  className: "custom-chip-button",
1102
994
  onClick: () => {
1103
995
  const userMessage = {
1104
- id: Date.now().toString(),
996
+ id: uid("msg"),
1105
997
  text: chip.text,
1106
998
  sender: "user",
1107
999
  timestamp: /* @__PURE__ */ new Date()
@@ -1134,22 +1026,16 @@ function ChatWidget$1({
1134
1026
  /* @__PURE__ */ jsx("span", {}),
1135
1027
  /* @__PURE__ */ jsx("span", {})
1136
1028
  ] }) }),
1137
- isConnectingToAgent && /* @__PURE__ */ jsxs("div", { className: "custom-message custom-message-bot", children: [
1138
- /* @__PURE__ */ jsxs("div", { className: "custom-typing-indicator", children: [
1139
- /* @__PURE__ */ jsx("span", {}),
1140
- /* @__PURE__ */ jsx("span", {}),
1141
- /* @__PURE__ */ jsx("span", {})
1142
- ] }),
1143
- /* @__PURE__ */ jsx("div", { className: "custom-message-content", children: "Connecting to agent..." })
1144
- ] }),
1145
- currentMode === "HUMAN" && agentTyping && /* @__PURE__ */ jsxs("div", { className: "custom-agent-typing-indicator", children: [
1146
- /* @__PURE__ */ jsxs("span", { className: "custom-typing-dots", children: [
1147
- /* @__PURE__ */ jsx("span", {}),
1148
- /* @__PURE__ */ jsx("span", {}),
1149
- /* @__PURE__ */ jsx("span", {})
1150
- ] }),
1151
- /* @__PURE__ */ jsx("span", { className: "custom-typing-text", children: "Agent is typing..." })
1152
- ] }),
1029
+ isConnectingToAgent && /* @__PURE__ */ jsx("div", { className: "custom-message custom-message-bot", children: /* @__PURE__ */ jsxs("div", { className: "custom-typing-indicator", children: [
1030
+ /* @__PURE__ */ jsx("span", {}),
1031
+ /* @__PURE__ */ jsx("span", {}),
1032
+ /* @__PURE__ */ jsx("span", {})
1033
+ ] }) }),
1034
+ currentMode === "HUMAN" && agentTyping && /* @__PURE__ */ jsx("div", { className: "custom-message custom-message-bot", children: /* @__PURE__ */ jsxs("div", { className: "custom-typing-indicator", children: [
1035
+ /* @__PURE__ */ jsx("span", {}),
1036
+ /* @__PURE__ */ jsx("span", {}),
1037
+ /* @__PURE__ */ jsx("span", {})
1038
+ ] }) }),
1153
1039
  /* @__PURE__ */ jsx("div", { ref: messagesEndRef })
1154
1040
  ] }),
1155
1041
  /* @__PURE__ */ jsxs("form", { className: "custom-chat-input-form", onSubmit: handleSubmit, children: [