@theonexai/chartsconnect-chat-widget 1.0.29 → 1.0.31

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.
Files changed (39) hide show
  1. package/dist/ChatWidget-BSTmPqP1.cjs +2 -0
  2. package/dist/ChatWidget-BSTmPqP1.cjs.map +1 -0
  3. package/dist/{ChatWidget-mgpMEdRJ.js → ChatWidget-CM0TQ03R.js} +36 -250
  4. package/dist/ChatWidget-CM0TQ03R.js.map +1 -0
  5. package/dist/{ChatWidget-BdBSCHe8.js → ChatWidget-DP38pjhl.js} +13 -4
  6. package/dist/ChatWidget-DP38pjhl.js.map +1 -0
  7. package/dist/ChatWidget-p657ZwHb.cjs +2 -0
  8. package/dist/ChatWidget-p657ZwHb.cjs.map +1 -0
  9. package/dist/components/ChatWidget.d.ts.map +1 -1
  10. package/dist/core/stateManager.d.ts +0 -17
  11. package/dist/core/stateManager.d.ts.map +1 -1
  12. package/dist/index.cjs.js +1 -1
  13. package/dist/index.esm.js +2 -2
  14. package/dist/next.cjs.js +1 -1
  15. package/dist/next.esm.js +1 -1
  16. package/dist/nuxt.cjs.js +1 -1
  17. package/dist/nuxt.esm.js +2 -2
  18. package/dist/react.cjs.js +1 -1
  19. package/dist/react.esm.js +1 -1
  20. package/dist/services/chatService.d.ts.map +1 -1
  21. package/dist/services/dialogflowBackendService.d.ts +2 -0
  22. package/dist/services/dialogflowBackendService.d.ts.map +1 -1
  23. package/dist/{types-C86de8ud.js → types-Bl_MQGCd.js} +8 -5
  24. package/dist/types-Bl_MQGCd.js.map +1 -0
  25. package/dist/{types-DZpnH2vj.cjs → types-CzaiEB03.cjs} +3 -3
  26. package/dist/types-CzaiEB03.cjs.map +1 -0
  27. package/dist/vite.cjs.js +1 -1
  28. package/dist/vite.esm.js +1 -1
  29. package/dist/vue.cjs.js +1 -1
  30. package/dist/vue.esm.js +2 -2
  31. package/package.json +1 -1
  32. package/dist/ChatWidget-BdBSCHe8.js.map +0 -1
  33. package/dist/ChatWidget-BsI9NryC.cjs +0 -2
  34. package/dist/ChatWidget-BsI9NryC.cjs.map +0 -1
  35. package/dist/ChatWidget-D2U_E8s6.cjs +0 -2
  36. package/dist/ChatWidget-D2U_E8s6.cjs.map +0 -1
  37. package/dist/ChatWidget-mgpMEdRJ.js.map +0 -1
  38. package/dist/types-C86de8ud.js.map +0 -1
  39. package/dist/types-DZpnH2vj.cjs.map +0 -1
@@ -0,0 +1,2 @@
1
+ "use strict";const e=require("react/jsx-runtime"),t=require("react"),s=require("./types-CzaiEB03.cjs"),n="chartsconnect_chat_mode",a="chartsconnect_chat_id",r="chartsconnect_session_id";class o extends t.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){}render(){return this.state.hasError?null:this.props.children}}function c({title:o="💬 Charts Connect AI Assistant",subtitle:c="We're here to help",welcomeTitle:i="👋 Welcome to Charts Connect",welcomeMessage:l="My name is Charts Connect AI Assistant and I'll guide you.",welcomeCta:d="💬 Click here to start chatting!",showWelcomePopup:u=!0,welcomePopupDelay:m=1500,fallbackWelcomeMessage:g="Hello! I'm Charts Connect AI Assistant. How can I help you today?",inputPlaceholder:h="Type your message...",emptyStateMessage:p="Hi! I'm Charts Connect AI Assistant. How can I help you today?",debug:f=!1,dfProjectId:x,dfLocation:w="us-central1",dfAgentId:y,languageCode:b="en",backendBaseUrl:v,backendWsUrl:C,noMatchMessage:I=null}){const[j,_]=t.useState(!1),[M,S]=t.useState(!1),[N,k]=t.useState([]),[D,T]=t.useState(""),[A,E]=t.useState(!1),[P,H]=t.useState(null),[$,R]=t.useState(!1),[U,W]=t.useState(!1),[B,F]=t.useState(!1),[L,q]=t.useState(!1),[z,O]=t.useState({name:"Agent"}),[V,K]=t.useState(!1),[Y,G]=t.useState(!1),[J,Q]=t.useState(!1),[X,Z]=t.useState(!1),[ee,te]=t.useState(null),[se,ne]=t.useState(""),[ae,re]=t.useState(""),[oe,ce]=t.useState(""),ie=t.useRef(""),le=t.useRef(null),de=t.useRef(null),ue=t.useRef(null),me=t.useRef(null),ge=t.useRef(null),he=()=>v||"undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_BASE_URL,pe=t.useRef(s.createChatService({baseUrl:he(),wsUrl:C||"undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_WS_URL,debug:f})),fe=t.useRef(null),{currentMode:xe,switchToHumanMode:we,switchToBotMode:ye,chatId:be,sessionId:ve,setChatId:Ce,setSessionId:Ie}=function(){const[e,s]=t.useState(()=>"undefined"==typeof window?"BOT":"HUMAN"===localStorage.getItem(n)?"HUMAN":"BOT"),[o,c]=t.useState(()=>"undefined"==typeof window?null:localStorage.getItem(a)),[i,l]=t.useState(()=>"undefined"==typeof window?null:localStorage.getItem(r));t.useEffect(()=>{"undefined"!=typeof window&&localStorage.setItem(n,e)},[e]);const d=t.useCallback(e=>{c(e),e?localStorage.setItem(a,e):localStorage.removeItem(a)},[]),u=t.useCallback(e=>{l(e),e?localStorage.setItem(r,e):localStorage.removeItem(r)},[]),m=t.useCallback(()=>{s("HUMAN")},[]),g=t.useCallback(()=>{s("BOT")},[]),h=t.useCallback(e=>!1,[]);return{currentMode:e,switchToHumanMode:m,switchToBotMode:g,isHandoffTriggered:h,chatId:o,sessionId:i,setChatId:d,setSessionId:u}}(),je=t.useCallback(e=>{G(!0),W(!1),Z(!1),q(!1),ue.current&&(clearTimeout(ue.current),ue.current=null),pe.current.disconnectWebSocket(),Ce(null),Ie(null),H(null);const t={id:s.generateMessageId("resolved"),text:"Thank you for contacting us!",sender:"bot",timestamp:new Date};k(e=>[...e,t]),setTimeout(()=>{ye(),G(!1),k([]),K(!1),te(null),ne(""),re(""),ce(""),ie.current="",ge.current&&ge.current().catch(console.error)},2e3)},[Ce,Ie,ye]);t.useCallback(async()=>{if(!J){Q(!0);try{const e=ie.current||se||null,t=ae||null,s=oe||null,n=await pe.current.startSupportChat(P||null,e,t,s);we(),Ce(n.chat_id),Ie(n.session_id),G(!1),T("")}catch(e){k(t=>[...t,{id:s.generateMessageId("error-new-chat"),text:f?`Error: ${e?.message||"Failed to start a new chat."}`:"Sorry, I couldn't start a new chat. Please try again.",sender:"bot",timestamp:new Date}])}finally{Q(!1)}}},[ae,oe,se,f,J,P,Ce,Ie,we]);const _e=()=>{if(x&&y)return{dfProjectId:x,dfLocation:w||"us-central1",dfAgentId:y,languageCode:b||"en",backendBaseUrl:he()}};t.useEffect(()=>{if(!u)return;const e=setTimeout(()=>{S(!0)},m);return()=>clearTimeout(e)},[u,m]),t.useEffect(()=>{le.current?.scrollIntoView({behavior:"smooth"})},[N]);const Me=t.useCallback(e=>{if(e.to_agent){O({id:e.to_agent_id,name:e.to_agent});const t={id:s.generateMessageId("system"),text:e.from_agent?`Chat has been transferred from ${e.from_agent} to ${e.to_agent}`:`Chat has been transferred to ${e.to_agent}`,sender:"bot",timestamp:new Date};k(e=>[...e,t])}},[f]),Se=t.useCallback(e=>{switch(e.type){case"message":if(e.content)if("agent"!==e.sender_type&&e.sender_type)f&&e.sender_type;else{const t={id:e.id||s.generateMessageId("agent"),text:e.content,sender:"agent",timestamp:new Date(e.timestamp||Date.now())};k(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),q(!1),ue.current&&(clearTimeout(ue.current),ue.current=null)}break;case"typing_start":"agent"===e.sender_type&&(q(!0),ue.current&&clearTimeout(ue.current),ue.current=setTimeout(()=>{q(!1)},3e3));break;case"typing_stop":"agent"===e.sender_type&&(q(!1),ue.current&&(clearTimeout(ue.current),ue.current=null));break;case"agent_changed":Me(e);break;case"chat_info":"active"===e.status?(W(!1),Z(!0)):"resolved"!==e.status&&"ended"!==e.status||je(e.chat_id||null),e.agent_id&&O(t=>({...t,id:e.agent_id}));break;case"agent_accepted":Z(!0),W(!1);const t={id:e.id||s.generateMessageId("agent-accepted"),text:"You can chat now, the agent has accepted your request.",sender:"bot",timestamp:e.timestamp?new Date(e.timestamp):new Date};k(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),e.to_agent&&O({name:e.to_agent,id:e.to_agent_id});break;case"chat_resolved":case"chat_ended":je(e.chat_id||null);break;case"error":const n={id:s.generateMessageId("error"),text:e.error||"An error occurred. Please try again.",sender:"bot",timestamp:new Date};k(e=>[...e,n])}},[f,je,Me]),Ne=t.useCallback(e=>{4e3===e.code&&je(be)},[be,je]),ke=t.useCallback(e=>{F(e),e&&W(!1)},[]);t.useEffect(()=>{if("HUMAN"===xe&&be&&ve)return pe.current.connectWebSocket(be,ve,Se,ke,Ne),()=>{pe.current.disconnectWebSocket()}},[xe,be,ve,Se,ke,Ne]);const De=t.useCallback(async(e=!0)=>{if(be&&ve)try{E(!0);const t=(await pe.current.loadMessageHistory(be,ve)).map(e=>({id:e.id||s.generateMessageId("msg"),text:e.content,sender:"agent"===e.sender_type?"agent":"user",timestamp:new Date(e.timestamp)}));k(e?e=>{const s=new Set(e.map(e=>e.id)),n=t.filter(e=>!s.has(e.id));return[...e,...n].sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}:t)}catch(t){if(f){const e={id:s.generateMessageId("error"),text:`Failed to load chat history: ${t.message}`,sender:"bot",timestamp:new Date};k(t=>[...t,e])}}finally{E(!1)}},[be,ve,f]),Te=t.useRef(N.length);Te.current=N.length,t.useEffect(()=>{if("HUMAN"===xe&&be&&ve){const e=`${be}-${ve}`;if(fe.current!==e){fe.current=e;setTimeout(()=>{0===Te.current&&De(!1).catch(console.error)},0)}}else"BOT"===xe&&(fe.current=null)},[xe,be,ve,De]);const Ae=async(e=!1,t=!1)=>{if(P&&!e&&!t)return P;if(me.current)return me.current;return me.current=(async()=>{try{R(!0);const e=_e();if(!e)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId and dfAgentId.");const n=t&&P?P:null,a=await s.createDialogflowSession(e,n);if(H(a.session_id),a.message){const e={id:s.generateMessageId("welcome"),text:a.message,sender:"bot",timestamp:new Date,richContent:a.richContent};k(t=>0===t.length?[e]:[e,...t])}return a.session_id}catch(e){const t={id:s.generateMessageId("error"),text:f?`Error: ${e.message||"Failed to create session. Please check your Dialogflow configuration."}`:g,sender:"bot",timestamp:new Date};return k(e=>[...e,t]),null}finally{R(!1),me.current=null}})(),me.current};ge.current=Ae;const Ee=async(e,t,n=!1)=>{if(!e.trim())return;if(V){if("name"===ee){const t=e.trim();ne(t),ie.current=t,te("email");const n={id:s.generateMessageId("msg"),text:t,sender:"user",timestamp:new Date};k(e=>[...e,n]);const a={id:s.generateMessageId("msg"),text:"Thank you! Now please provide your email address:",sender:"bot",timestamp:new Date};return k(e=>[...e,a]),void T("")}if("email"===ee){const t=e.trim();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){const e={id:s.generateMessageId("msg"),text:"Please provide a valid email address:",sender:"bot",timestamp:new Date};return k(t=>[...t,e]),void T("")}re(t),te("mobile");const n={id:s.generateMessageId("msg"),text:t,sender:"user",timestamp:new Date};k(e=>[...e,n]);const a={id:s.generateMessageId("msg"),text:"Thank you! Now please provide your mobile number:",sender:"bot",timestamp:new Date};return k(e=>[...e,a]),void T("")}if("mobile"===ee){const t=e.trim();if(!/^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,9}$/.test(t)||t.length<10){const e={id:s.generateMessageId("msg"),text:"Please provide a valid mobile number (e.g., +1234567890):",sender:"bot",timestamp:new Date};return k(t=>[...t,e]),void T("")}ce(t);const n={id:s.generateMessageId("msg"),text:t,sender:"user",timestamp:new Date};k(e=>[...e,n]);const a=ie.current,r=ae;return K(!1),te(null),ie.current="",await(async(e,t,n)=>{try{W(!0);const r=P,o=await pe.current.ensureChatInitialized(be,ve,r||null,e||null,t||null,n||null);if(!o||!o.chat_id)throw new Error("Failed to initialize chat session");let c=o.chat_id,i=o.session_id;c!==be&&(Ce(c),Ie(i));try{await pe.current.requestHandoff(c,i,"Customer requested human agent",r||null,e||null,t||null,n||null)}catch(a){if(!(a.message?.includes("Invalid chat_id")||a.message?.includes("Chat not found")||a.message?.includes("unauthorized")||a.message?.includes("400")||a.message?.includes("401")||a.message?.includes("404")||a.message?.includes("expired")))throw a;{Ce(null),Ie(null);const s=await pe.current.startSupportChat(r||null,e||null,t||null,n||null);if(!s||!s.chat_id)throw new Error("Failed to re-initialize chat session");const a=s.chat_id,o=s.session_id;Ce(a),Ie(o),c=a,i=o,await pe.current.requestHandoff(a,o,"Customer requested human agent",r||null,e||null,t||null,n||null);const l=`${a}-${o}`;fe.current!==l&&(fe.current=l,await De(!0))}}we(),G(!1),Z(!1);const l={id:s.generateMessageId("connecting"),text:"Connecting you to a human agent...",sender:"bot",timestamp:new Date};k(e=>[...e,l]),pe.current.connectWebSocket(c,i,Se,ke,Ne);const d=`${c}-${i}`;fe.current=d}catch(r){const e={id:s.generateMessageId("error"),text:f?`Handoff error: ${r.message}`:"Failed to connect to agent. Please try again.",sender:"bot",timestamp:new Date};k(t=>[...t,e]),W(!1)}})(a,r,t),void T("")}}if("HUMAN"===xe){if(!be||!ve){const e={id:s.generateMessageId("msg"),text:"Chat session not initialized. Please try again.",sender:"bot",timestamp:new Date};return void k(t=>[...t,e])}if(!n){const n={id:s.generateMessageId("msg"),text:t||e.trim(),sender:"user",timestamp:new Date};k(e=>[...e,n])}pe.current.sendTypingIndicator("typing_stop"),de.current&&(clearTimeout(de.current),de.current=null),T(""),E(!0);try{pe.current.sendMessageViaWebSocket(e.trim())||await pe.current.sendMessageToAgent(be,ve,e.trim())}catch(r){if(r instanceof s.ChatResolvedError||"ChatResolvedError"===r?.name||"chat_resolved"===r?.message)return void je(be);if(r.message?.includes("Chat not found")||r.message?.includes("unauthorized")||r.message?.includes("401")||r.message?.includes("404")){Ce(null),Ie(null);try{const t=await pe.current.startSupportChat(P||null,null,null,null);Ce(t.chat_id),Ie(t.session_id);try{await pe.current.sendMessageToAgent(t.chat_id,t.session_id,e.trim())}catch(o){if(o instanceof s.ChatResolvedError||"ChatResolvedError"===o?.name||"chat_resolved"===o?.message)return void je(t.chat_id);throw o}return}catch(o){if(o instanceof s.ChatResolvedError||"ChatResolvedError"===o?.name||"chat_resolved"===o?.message)return void je(be);const e={id:s.generateMessageId("msg"),text:f?`Error: ${o.message||"Failed to send message."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};k(t=>[...t,e])}}else{const e={id:s.generateMessageId("msg"),text:f?`Error: ${r.message||"Failed to send message to agent."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};k(t=>[...t,e])}}finally{E(!1)}return}let a=P;if(!a)try{if(a=await Ae(),!a){const e={id:s.generateMessageId("msg"),text:f?"Failed to create session. Please check the console for details.":"Sorry, I'm having trouble connecting. Please try again.",sender:"bot",timestamp:new Date};return void k(t=>[...t,e])}}catch(r){const e={id:s.generateMessageId("msg"),text:f?`Connection Error: ${r.message||"Please check your Dialogflow configuration."}`:"Sorry, I'm having trouble connecting. Please check your configuration.",sender:"bot",timestamp:new Date};return void k(t=>[...t,e])}if(!n){const n={id:s.generateMessageId("msg"),text:t||e.trim(),sender:"user",timestamp:new Date};k(e=>[...e,n])}T(""),E(!0);try{const t=_e();if(!t)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId and dfAgentId.");const n=await s.sendDialogflowMessage(e.trim(),a,t);if(!0===n.handoff){if(n.response){const e={id:s.generateMessageId("msg"),text:n.response,sender:"bot",timestamp:new Date(n.timestamp||Date.now()),richContent:n.richContent};k(t=>[...t,e])}K(!0),te("name"),ne(""),re(""),ie.current="";const e={id:s.generateMessageId("msg"),text:"To connect you with a human agent, I'll need some information. Please provide your name:",sender:"bot",timestamp:new Date};return void k(t=>[...t,e])}const r=n.response||"";if(r){const e={id:s.generateMessageId("msg"),text:r,sender:"bot",timestamp:new Date(n.timestamp||Date.now()),richContent:n.richContent};k(t=>[...t,e])}}catch(r){const e={id:s.generateMessageId("msg"),text:f?`Error: ${r.message||"Failed to send message. Please check your Dialogflow configuration."}`:r.message?.includes("Failed to fetch")||r.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.",sender:"bot",timestamp:new Date};k(t=>[...t,e])}finally{E(!1)}};t.useEffect(()=>()=>{de.current&&clearTimeout(de.current),ue.current&&clearTimeout(ue.current)},[]);const Pe=async()=>{_(!0),S(!1),P||await Ae()},He=e=>e.includes("👤")||e.includes("being connected")||e.includes("live support agent")||e.includes("transfer your conversation")||e.includes("✅")||e.includes("🔄");return t.useEffect(()=>()=>{pe.current.disconnectWebSocket()},[]),e.jsxs(e.Fragment,{children:[M&&!j&&e.jsxs("div",{className:"custom-welcome-popup",onClick:Pe,children:[e.jsxs("div",{className:"custom-welcome-header",children:[e.jsx("div",{className:"custom-welcome-title",children:i}),e.jsx("button",{className:"custom-close-popup",onClick:e=>{e.stopPropagation(),S(!1)},children:"×"})]}),e.jsx("div",{className:"custom-welcome-message",children:l}),e.jsx("div",{className:"custom-welcome-cta",children:d})]}),!j&&e.jsx("button",{className:"custom-chat-toggle-btn",onClick:Pe,"aria-label":"Open chat",children:e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),j&&e.jsxs("div",{className:"custom-chat-window",role:"dialog","aria-label":"Chat window",children:[e.jsxs("div",{className:"custom-chat-header",children:[e.jsxs("div",{className:"custom-chat-header-content",children:[e.jsx("div",{className:"custom-chat-title",children:o}),e.jsxs("div",{className:"custom-chat-subtitle",children:[c,"HUMAN"===xe&&e.jsxs("span",{className:"custom-mode-indicator",children:[" ","• ",B?"🟢 Connected":"🟡 Connecting..."]})]}),"HUMAN"===xe&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"custom-mode-badge",children:"Human Support Mode"}),e.jsxs("div",{className:"custom-agent-info",children:[e.jsx("span",{className:"custom-agent-label",children:"Agent:"}),e.jsx("span",{className:"custom-agent-name",children:z.name})]})]}),"BOT"===xe&&e.jsx("div",{className:"custom-mode-badge",children:"Bot Mode"})]}),e.jsx("button",{className:"custom-chat-close-btn",onClick:()=>{_(!1),"HUMAN"===xe&&pe.current.disconnectWebSocket()},"aria-label":"Close chat",children:"×"})]}),e.jsxs("div",{className:"custom-chat-messages",role:"log","aria-live":"polite","aria-label":"Chat messages",children:[$&&0===N.length&&e.jsxs("div",{className:"custom-chat-empty",children:[e.jsxs("div",{className:"custom-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsx("p",{children:"Initializing chat..."})]}),!$&&0===N.length&&e.jsxs("div",{className:"custom-chat-empty",children:[e.jsx("div",{className:"custom-chat-empty-icon",children:"👋"}),e.jsx("p",{children:p})]}),N.map(t=>e.jsxs("div",{className:`custom-message custom-message-${t.sender} ${He(t.text)?"custom-handoff-message":""}`,children:[e.jsx("div",{className:"custom-message-content "+(He(t.text)?"custom-handoff-content":""),dangerouslySetInnerHTML:{__html:s.linkifyText(t.text)}}),(f&&t.richContent,t.richContent&&Array.isArray(t.richContent)&&t.richContent.length>0?e.jsx("div",{className:"custom-chips-container",children:t.richContent.map((t,n)=>{if(!Array.isArray(t)){const a=t;return a&&"chips"===a.type&&a.options?e.jsx("div",{className:"custom-chips-group",children:a.options.map((t,n)=>e.jsx("button",{className:"custom-chip-button",onClick:()=>{const e={id:s.generateMessageId("msg"),text:t.text,sender:"user",timestamp:new Date};k(t=>[...t,e]),Ee(t.text,t.text,!0)},type:"button",children:t.text},n))},n):null}return t.map((t,a)=>t&&"chips"===t.type&&t.options?e.jsx("div",{className:"custom-chips-group",children:t.options.map((t,n)=>e.jsx("button",{className:"custom-chip-button",onClick:()=>{const e={id:s.generateMessageId("msg"),text:t.text,sender:"user",timestamp:new Date};k(t=>[...t,e]),Ee(t.text,t.text,!0)},type:"button",children:t.text},n))},`${n}-${a}`):null)})}):null),e.jsx("div",{className:"custom-message-time",children:t.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]},t.id)),A&&e.jsx("div",{className:"custom-message custom-message-bot",children:e.jsxs("div",{className:"custom-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]})}),U&&e.jsxs("div",{className:"custom-message custom-message-bot",children:[e.jsxs("div",{className:"custom-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsx("div",{className:"custom-message-content",children:"Connecting to agent..."})]}),"HUMAN"===xe&&L&&e.jsxs("div",{className:"custom-agent-typing-indicator",children:[e.jsxs("span",{className:"custom-typing-dots",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsx("span",{className:"custom-typing-text",children:"Agent is typing..."})]}),e.jsx("div",{ref:le})]}),e.jsxs("form",{className:"custom-chat-input-form",onSubmit:e=>{e.preventDefault(),Ee(D)},children:[e.jsx("input",{type:"text",className:"custom-chat-input",value:D,onChange:e=>{const t=e.target.value;T(t),"HUMAN"===xe&&B&&(pe.current.sendTypingIndicator("typing_start"),de.current&&clearTimeout(de.current),de.current=setTimeout(()=>{pe.current.sendTypingIndicator("typing_stop"),de.current=null},2e3))},placeholder:h,"aria-label":h,disabled:A||$||J}),e.jsx("button",{type:"submit",className:"custom-chat-send-btn",disabled:!D.trim()||A||$||J,children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),e.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]})]})]})}exports.ChatWidget=function(t){return e.jsx(o,{children:e.jsx(c,{...t})})};
2
+ //# sourceMappingURL=ChatWidget-BSTmPqP1.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChatWidget-BSTmPqP1.cjs","sources":["../src/hooks/useChatMode.ts","../src/components/ChatWidget.tsx"],"sourcesContent":["// hooks/useChatMode.ts\nimport { useState, useEffect, useCallback } from \"react\";\nimport type { ChatResponse } from \"../services/dialogflowBackendService\";\n\nexport type ChatMode = \"BOT\" | \"HUMAN\";\n\nconst MODE_STORAGE_KEY = \"chartsconnect_chat_mode\";\nconst CHAT_ID_STORAGE_KEY = \"chartsconnect_chat_id\";\nconst SESSION_ID_STORAGE_KEY = \"chartsconnect_session_id\";\n\nexport interface UseChatModeReturn {\n currentMode: ChatMode;\n switchToHumanMode: () => void;\n switchToBotMode: () => void;\n isHandoffTriggered: (dialogflowResponse: ChatResponse) => boolean;\n chatId: string | null;\n sessionId: string | null;\n setChatId: (id: string | null) => void;\n setSessionId: (id: string | null) => void;\n}\n\n/**\n * Hook to manage chat mode (BOT or HUMAN)\n */\nexport function useChatMode(): UseChatModeReturn {\n const [currentMode, setCurrentMode] = useState<ChatMode>(() => {\n if (typeof window === 'undefined') return 'BOT';\n const savedMode = localStorage.getItem(MODE_STORAGE_KEY);\n return (savedMode === \"HUMAN\" ? \"HUMAN\" : \"BOT\") as ChatMode;\n });\n\n const [chatId, setChatIdState] = useState<string | null>(() => {\n if (typeof window === 'undefined') return null;\n return localStorage.getItem(CHAT_ID_STORAGE_KEY);\n });\n\n const [sessionId, setSessionIdState] = useState<string | null>(() => {\n if (typeof window === 'undefined') return null;\n return localStorage.getItem(SESSION_ID_STORAGE_KEY);\n });\n\n // Persist mode to localStorage\n useEffect(() => {\n if (typeof window === 'undefined') return;\n localStorage.setItem(MODE_STORAGE_KEY, currentMode);\n }, [currentMode]);\n\n // Persist chat_id to localStorage\n const setChatId = useCallback((id: string | null) => {\n setChatIdState(id);\n if (id) {\n localStorage.setItem(CHAT_ID_STORAGE_KEY, id);\n } else {\n localStorage.removeItem(CHAT_ID_STORAGE_KEY);\n }\n }, []);\n\n // Persist session_id to localStorage\n const setSessionId = useCallback((id: string | null) => {\n setSessionIdState(id);\n if (id) {\n localStorage.setItem(SESSION_ID_STORAGE_KEY, id);\n } else {\n localStorage.removeItem(SESSION_ID_STORAGE_KEY);\n }\n }, []);\n\n const switchToHumanMode = useCallback(() => {\n setCurrentMode(\"HUMAN\");\n }, []);\n\n const switchToBotMode = useCallback(() => {\n setCurrentMode(\"BOT\");\n }, []);\n\n /**\n * Check if Dialogflow response contains handoff trigger\n * Handoff is triggered when response contains {\"handoff\": true}\n * This can be in:\n * - queryResult.parameters.handoff\n * - queryResult.responseMessages payload\n * - queryResult.intent.displayName (if configured)\n */\n const isHandoffTriggered = useCallback(\n (dialogflowResponse: ChatResponse): boolean => {\n // Check if response has handoff flag\n // This would need to be extracted from Dialogflow response\n // For now, we'll check the response text or any custom fields\n \n // The handoff flag might come from Dialogflow's custom payload\n // We need to check the actual Dialogflow response structure\n // Since ChatResponse doesn't include the full response, we'll need to\n // modify the dialogflowClient to pass through handoff information\n \n // For now, return false - this will be handled by dialogflowHandler\n return false;\n },\n []\n );\n\n return {\n currentMode,\n switchToHumanMode,\n switchToBotMode,\n isHandoffTriggered,\n chatId,\n sessionId,\n setChatId,\n setSessionId,\n };\n}\n\n","import React, { useState, useEffect, useRef, useCallback } from \"react\";\nimport {\n createDialogflowSession,\n sendDialogflowMessage,\n type DialogflowBackendConfig,\n type SessionResponse,\n type ChatResponse,\n} from \"../services/dialogflowBackendService\";\nimport { useChatMode } from \"../hooks/useChatMode\";\nimport { ChatResolvedError, createChatService, type WebSocketMessage } from \"../services/chatService\";\nimport { linkifyText } from \"../utils/sanitize\";\nimport { generateMessageId } from \"../core/types\";\nimport \"../styles/chatWidget.css\";\n\ninterface ChipOption {\n text: string;\n payload: string;\n}\n\ninterface RichContent {\n type?: string;\n options?: ChipOption[];\n}\n\ntype RichContentArray = RichContent | RichContent[];\n\ninterface Message {\n id: string;\n text: string;\n sender: \"user\" | \"bot\" | \"agent\";\n timestamp: Date;\n richContent?: RichContentArray[];\n}\n\nexport interface ChatWidgetProps {\n /** Custom title for the chat widget */\n title?: string;\n /** Custom subtitle for the chat widget */\n subtitle?: string;\n /** Welcome popup title */\n welcomeTitle?: string;\n /** Welcome popup message */\n welcomeMessage?: string;\n /** Welcome popup CTA text */\n welcomeCta?: string;\n /** Whether to show the welcome popup */\n showWelcomePopup?: boolean;\n /** Delay in milliseconds before showing welcome popup */\n welcomePopupDelay?: number;\n /** Fallback welcome message if API fails */\n fallbackWelcomeMessage?: string;\n /** Placeholder text for input field */\n inputPlaceholder?: string;\n /** Custom empty state message */\n emptyStateMessage?: string;\n /** Enable/disable debug logging */\n debug?: boolean;\n /** Dialogflow project ID */\n dfProjectId?: string;\n /** Dialogflow location (e.g., \"us-central1\") */\n dfLocation?: string;\n /** Dialogflow agent ID */\n dfAgentId?: string;\n /** Language code for Dialogflow */\n languageCode?: string;\n /** Backend API base URL (default: http://localhost:8012) */\n backendBaseUrl?: string;\n /** WebSocket URL (default: ws://localhost:8012) */\n backendWsUrl?: string;\n /** Message to show on Dialogflow no-match. Set to null to suppress entirely. Default: null (suppressed) */\n noMatchMessage?: string | null;\n}\n\nclass ChatWidgetErrorBoundary extends React.Component<\n { children: React.ReactNode },\n { hasError: boolean }\n> {\n constructor(props: { children: React.ReactNode }) {\n super(props);\n this.state = { hasError: false };\n }\n static getDerivedStateFromError() {\n return { hasError: true };\n }\n componentDidCatch(error: Error, info: React.ErrorInfo) {\n console.error('ChatWidget error:', error, info.componentStack);\n }\n render() {\n if (this.state.hasError) {\n return null; // Silently hide widget on error — don't crash host app\n }\n return this.props.children;\n }\n}\n\nfunction ChatWidgetInner({\n title = \"💬 Charts Connect AI Assistant\",\n subtitle = \"We're here to help\",\n welcomeTitle = \"👋 Welcome to Charts Connect\",\n welcomeMessage = \"My name is Charts Connect AI Assistant and I'll guide you.\",\n welcomeCta = \"💬 Click here to start chatting!\",\n showWelcomePopup: enableWelcomePopup = true,\n welcomePopupDelay = 1500,\n fallbackWelcomeMessage = \"Hello! I'm Charts Connect AI Assistant. How can I help you today?\",\n inputPlaceholder = \"Type your message...\",\n emptyStateMessage = \"Hi! I'm Charts Connect AI Assistant. How can I help you today?\",\n debug = false,\n dfProjectId,\n dfLocation = \"us-central1\",\n dfAgentId,\n languageCode = \"en\",\n backendBaseUrl,\n backendWsUrl,\n noMatchMessage = null,\n}: ChatWidgetProps) {\n const [isOpen, setIsOpen] = useState(false);\n const [showWelcomePopup, setShowWelcomePopup] = useState(false);\n const [messages, setMessages] = useState<Message[]>([]);\n const [inputValue, setInputValue] = useState(\"\");\n const [isLoading, setIsLoading] = useState(false);\n const [sessionId, setSessionId] = useState<string | null>(null);\n const [isInitializing, setIsInitializing] = useState(false);\n const [isConnectingToAgent, setIsConnectingToAgent] = useState(false);\n const [wsConnected, setWsConnected] = useState(false);\n const [agentTyping, setAgentTyping] = useState(false);\n const [currentAgent, setCurrentAgent] = useState<{ name: string; id?: string }>({ name: \"Agent\" });\n const [collectingUserInfo, setCollectingUserInfo] = useState(false);\n const [chatResolved, setChatResolved] = useState(false);\n const [isStartingNewChat, setIsStartingNewChat] = useState(false);\n const [agentAccepted, setAgentAccepted] = useState(false);\n const [userInfoStep, setUserInfoStep] = useState<\"name\" | \"email\" | \"mobile\" | null>(null);\n const [collectedUserName, setCollectedUserName] = useState<string>(\"\");\n const [collectedUserEmail, setCollectedUserEmail] = useState<string>(\"\");\n const [collectedUserMobile, setCollectedUserMobile] = useState<string>(\"\");\n const collectedUserNameRef = useRef<string>(\"\");\n const messagesEndRef = useRef<HTMLDivElement>(null);\n const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null);\n const agentTypingTimeoutRef = useRef<NodeJS.Timeout | null>(null);\n const sessionPromiseRef = useRef<Promise<string | null> | null>(null); // Promise-based lock for createSession\n const createSessionRef = useRef<((forceRecreate?: boolean, reuseSessionId?: boolean) => Promise<string | null>) | null>(null); // Ref for createSession to avoid stale closure\n \n // Get backend URLs from props or environment variables\n const getBackendBaseUrl = () => {\n return backendBaseUrl || \n (typeof process !== 'undefined' && (process as any).env?.REACT_APP_BACKEND_BASE_URL)\n };\n \n const getBackendWsUrl = () => {\n return backendWsUrl || \n (typeof process !== 'undefined' && (process as any).env?.REACT_APP_BACKEND_WS_URL)\n };\n \n const chatServiceRef = useRef(\n createChatService({ \n baseUrl: getBackendBaseUrl(), \n wsUrl: getBackendWsUrl(),\n debug: debug\n })\n );\n const historyLoadedRef = useRef<string | null>(null);\n \n // Use chat mode hook\n const {\n currentMode,\n switchToHumanMode,\n switchToBotMode,\n chatId,\n sessionId: supportSessionId,\n setChatId,\n setSessionId: setSupportSessionId,\n } = useChatMode();\n\n const enterResolvedState = useCallback(\n (_resolvedChatId?: string | null) => {\n setChatResolved(true);\n setIsConnectingToAgent(false);\n setAgentAccepted(false);\n setAgentTyping(false);\n if (agentTypingTimeoutRef.current) {\n clearTimeout(agentTypingTimeoutRef.current);\n agentTypingTimeoutRef.current = null;\n }\n\n // Stop WS + prevent any reuse of the old chat_id\n chatServiceRef.current.disconnectWebSocket();\n setChatId(null);\n setSupportSessionId(null);\n setSessionId(null); // Fix #1: Clear sessionId to force new session creation\n \n // Add thank you message before reset\n const thankYouMessage: Message = {\n id: generateMessageId('resolved'),\n text: \"Thank you for contacting us!\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, thankYouMessage]);\n \n // Automatically reset to BOT mode after showing thank you message\n setTimeout(() => {\n switchToBotMode();\n setChatResolved(false);\n setMessages([]);\n setCollectingUserInfo(false);\n setUserInfoStep(null);\n setCollectedUserName(\"\");\n setCollectedUserEmail(\"\");\n setCollectedUserMobile(\"\");\n collectedUserNameRef.current = \"\";\n \n // Recreate Dialogflow session to start fresh (sessionId already cleared above)\n // Use ref to access latest createSession function to avoid stale closure\n if (createSessionRef.current) {\n createSessionRef.current().catch(console.error);\n }\n }, 2000); // 2 second delay to show thank you message\n },\n [setChatId, setSupportSessionId, switchToBotMode] // createSession accessed via ref, no need in deps\n );\n\n const handleStartNewChat = useCallback(async () => {\n if (isStartingNewChat) return;\n setIsStartingNewChat(true);\n try {\n const customerName = collectedUserNameRef.current || collectedUserName || null;\n const customerEmail = collectedUserEmail || null;\n const customerMobile = collectedUserMobile || null;\n\n const newSession = await chatServiceRef.current.startSupportChat(\n sessionId || null,\n customerName,\n customerEmail,\n customerMobile\n );\n\n switchToHumanMode();\n setChatId(newSession.chat_id);\n setSupportSessionId(newSession.session_id);\n setChatResolved(false);\n setInputValue(\"\");\n } catch (error: any) {\n console.error(\"Error starting new chat:\", error);\n setMessages((prev) => [\n ...prev,\n {\n id: generateMessageId('error-new-chat'),\n text: debug\n ? `Error: ${error?.message || \"Failed to start a new chat.\"}`\n : \"Sorry, I couldn't start a new chat. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n },\n ]);\n } finally {\n setIsStartingNewChat(false);\n }\n }, [\n collectedUserEmail,\n collectedUserMobile,\n collectedUserName,\n debug,\n isStartingNewChat,\n sessionId,\n setChatId,\n setSupportSessionId,\n switchToHumanMode,\n ]);\n\n // Helper function to build Dialogflow config from props\n const getDialogflowConfig = (): DialogflowBackendConfig | undefined => {\n if (!dfProjectId || !dfAgentId) {\n return undefined;\n }\n \n return {\n dfProjectId,\n dfLocation: dfLocation || 'us-central1',\n dfAgentId,\n languageCode: languageCode || 'en',\n backendBaseUrl: getBackendBaseUrl(),\n };\n };\n\n // Show welcome popup after page load\n useEffect(() => {\n if (!enableWelcomePopup) return;\n \n const timer = setTimeout(() => {\n setShowWelcomePopup(true);\n }, welcomePopupDelay);\n return () => clearTimeout(timer);\n }, [enableWelcomePopup, welcomePopupDelay]);\n\n // Auto-scroll to bottom when new messages arrive\n useEffect(() => {\n messagesEndRef.current?.scrollIntoView({ behavior: \"smooth\" });\n }, [messages]);\n\n // Handle agent changed notification\n const handleAgentChanged = useCallback((message: WebSocketMessage) => {\n if (message.to_agent) {\n setCurrentAgent({\n id: message.to_agent_id,\n name: message.to_agent,\n });\n\n // Add system message to chat\n const systemMessage: Message = {\n id: generateMessageId('system'),\n text: message.from_agent\n ? `Chat has been transferred from ${message.from_agent} to ${message.to_agent}`\n : `Chat has been transferred to ${message.to_agent}`,\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, systemMessage]);\n\n if (debug) {\n console.log(\"Agent changed:\", {\n from: message.from_agent,\n to: message.to_agent,\n reason: message.reason,\n });\n }\n }\n }, [debug]);\n\n // Handle WebSocket messages\n const handleWebSocketMessage = useCallback((message: WebSocketMessage) => {\n switch (message.type) {\n case \"message\":\n if (message.content) {\n // Only display messages from agent, ignore customer messages (we already added them)\n if (message.sender_type === \"agent\" || !message.sender_type) {\n const agentMessage: Message = {\n id: message.id || generateMessageId('agent'),\n text: message.content,\n sender: \"agent\",\n timestamp: new Date(message.timestamp || Date.now()),\n };\n setMessages((prev) => {\n // Avoid duplicate messages by checking if message ID already exists\n const existingIds = new Set(prev.map(m => m.id));\n if (existingIds.has(agentMessage.id)) {\n return prev;\n }\n return [...prev, agentMessage];\n });\n // Hide typing indicator when message received\n setAgentTyping(false);\n if (agentTypingTimeoutRef.current) {\n clearTimeout(agentTypingTimeoutRef.current);\n agentTypingTimeoutRef.current = null;\n }\n } else if (debug && message.sender_type === \"customer\") {\n console.log(\"Ignoring customer message from WebSocket (already added)\");\n }\n // If sender_type is \"customer\", ignore it - we already added the user message\n } else if (debug) {\n console.warn(\"WebSocket message received without content:\", message);\n }\n break;\n\n case \"typing_start\":\n if (message.sender_type === \"agent\") {\n setAgentTyping(true);\n // Auto-hide after 3 seconds if no message received\n if (agentTypingTimeoutRef.current) {\n clearTimeout(agentTypingTimeoutRef.current);\n }\n agentTypingTimeoutRef.current = setTimeout(() => {\n setAgentTyping(false);\n }, 3000);\n }\n break;\n\n case \"typing_stop\":\n if (message.sender_type === \"agent\") {\n setAgentTyping(false);\n if (agentTypingTimeoutRef.current) {\n clearTimeout(agentTypingTimeoutRef.current);\n agentTypingTimeoutRef.current = null;\n }\n }\n break;\n\n case \"agent_changed\":\n handleAgentChanged(message);\n break;\n\n case \"chat_info\":\n if (debug) {\n console.log(\"Chat info:\", message);\n }\n // Update connection status based on chat info\n if (message.status === \"active\") {\n setIsConnectingToAgent(false);\n setAgentAccepted(true);\n } else if (message.status === \"resolved\" || message.status === \"ended\") {\n enterResolvedState(message.chat_id || null);\n }\n // Update agent info if provided\n if (message.agent_id) {\n setCurrentAgent((prev) => ({\n ...prev,\n id: message.agent_id,\n }));\n }\n break;\n\n case \"agent_accepted\":\n // Agent has accepted the chat request\n setAgentAccepted(true);\n setIsConnectingToAgent(false);\n const acceptedMessage: Message = {\n id: message.id || generateMessageId('agent-accepted'),\n text: \"You can chat now, the agent has accepted your request.\",\n sender: \"bot\",\n timestamp: message.timestamp ? new Date(message.timestamp) : new Date(),\n };\n setMessages((prev) => {\n // Avoid duplicate messages\n const existingIds = new Set(prev.map(m => m.id));\n if (existingIds.has(acceptedMessage.id)) {\n return prev;\n }\n return [...prev, acceptedMessage];\n });\n // Update agent info if provided\n if (message.to_agent) {\n setCurrentAgent({\n name: message.to_agent,\n id: message.to_agent_id,\n });\n }\n if (debug) {\n console.log(\"Agent accepted chat:\", message);\n }\n break;\n\n case \"chat_resolved\":\n case \"chat_ended\":\n // Chat has been resolved/ended by agent (terminal state)\n enterResolvedState(message.chat_id || null);\n if (debug) {\n console.log(\"Chat resolved/ended:\", message);\n }\n break;\n\n case \"error\":\n console.error(\"WebSocket error:\", message.error);\n const errorMessage: Message = {\n id: generateMessageId('error'),\n text: message.error || \"An error occurred. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n break;\n\n case \"pong\":\n // Keep-alive response, no action needed\n break;\n\n default:\n if (debug) {\n console.log(\"Unknown message type:\", message.type);\n }\n }\n }, [debug, enterResolvedState, handleAgentChanged]);\n\n const handleWebSocketClose = useCallback(\n (event: CloseEvent) => {\n // Backend uses 4000 to indicate the chat is resolved, and then closes.\n if (event.code === 4000) {\n enterResolvedState(chatId);\n }\n },\n [chatId, enterResolvedState]\n );\n\n // Handle WebSocket connection changes\n const handleConnectionChange = useCallback((connected: boolean) => {\n setWsConnected(connected);\n if (connected) {\n setIsConnectingToAgent(false);\n }\n }, []);\n\n // Initialize WebSocket when switching to HUMAN mode\n useEffect(() => {\n if (currentMode === \"HUMAN\" && chatId && supportSessionId) {\n chatServiceRef.current.connectWebSocket(\n chatId,\n supportSessionId,\n handleWebSocketMessage,\n handleConnectionChange,\n handleWebSocketClose\n );\n\n return () => {\n chatServiceRef.current.disconnectWebSocket();\n };\n }\n }, [\n currentMode,\n chatId,\n supportSessionId,\n handleWebSocketMessage,\n handleConnectionChange,\n handleWebSocketClose,\n ]);\n\n // Load message history from backend\n const loadMessageHistory = useCallback(async (preserveExisting: boolean = true) => {\n if (!chatId || !supportSessionId) return;\n\n try {\n setIsLoading(true);\n const history = await chatServiceRef.current.loadMessageHistory(chatId, supportSessionId);\n \n const historyMessages: Message[] = history.map((msg) => ({\n id: msg.id || generateMessageId('msg'),\n text: msg.content,\n sender: msg.sender_type === \"agent\" ? \"agent\" : \"user\",\n timestamp: new Date(msg.timestamp),\n }));\n\n if (preserveExisting) {\n // Merge with existing messages, avoiding duplicates\n setMessages((prevMessages) => {\n const existingIds = new Set(prevMessages.map(m => m.id));\n const newMessages = historyMessages.filter(m => !existingIds.has(m.id));\n \n // Combine existing messages with new history messages\n // Sort by timestamp to maintain chronological order\n const combined = [...prevMessages, ...newMessages].sort((a, b) => \n a.timestamp.getTime() - b.timestamp.getTime()\n );\n \n return combined;\n });\n } else {\n // Replace all messages (only if explicitly requested)\n setMessages(historyMessages);\n }\n } catch (error: any) {\n console.error(\"Error loading message history:\", error);\n if (debug) {\n const errorMessage: Message = {\n id: generateMessageId('error'),\n text: `Failed to load chat history: ${error.message}`,\n sender: \"bot\",\n timestamp: new Date(),\n };\n // Only add error message, don't replace existing messages\n setMessages((prev) => [...prev, errorMessage]);\n }\n } finally {\n setIsLoading(false);\n }\n }, [chatId, supportSessionId, debug]);\n\n // Track messages length in a ref so the effect below doesn't re-run on every message\n const messagesLengthRef = useRef(messages.length);\n messagesLengthRef.current = messages.length;\n\n // Load message history when switching to HUMAN mode\n useEffect(() => {\n if (currentMode === \"HUMAN\" && chatId && supportSessionId) {\n // Only load if we haven't loaded history for this chat session yet\n const sessionKey = `${chatId}-${supportSessionId}`;\n if (historyLoadedRef.current !== sessionKey) {\n historyLoadedRef.current = sessionKey;\n // Check if we have existing messages (from bot conversation during handoff)\n // If yes, preserve them and don't load history\n // If no, load history for new chat\n const checkAndLoad = () => {\n // Read from ref to get latest value without needing it as a dependency\n if (messagesLengthRef.current === 0) {\n // No existing messages, load history\n loadMessageHistory(false).catch(console.error);\n }\n // Has existing messages (bot conversation), keep them - don't load history\n };\n // Use setTimeout to ensure we check after state updates\n setTimeout(checkAndLoad, 0);\n }\n } else if (currentMode === \"BOT\") {\n // Reset history loaded flag when switching back to BOT mode\n historyLoadedRef.current = null;\n }\n }, [currentMode, chatId, supportSessionId, loadMessageHistory]);\n\n // Handle handoff from Dialogflow\n const handleHandoff = async (customerName?: string, customerEmail?: string, customerMobile?: string) => {\n try {\n setIsConnectingToAgent(true);\n \n // Get Dialogflow session ID if available\n const dialogflowSessionId = sessionId;\n \n // STEP 1: Ensure chat is initialized (validates existing or creates new)\n const session = await chatServiceRef.current.ensureChatInitialized(\n chatId,\n supportSessionId,\n dialogflowSessionId || null,\n customerName || null,\n customerEmail || null,\n customerMobile || null\n );\n \n if (!session || !session.chat_id) {\n throw new Error(\"Failed to initialize chat session\");\n }\n \n let currentChatId = session.chat_id;\n let currentSupportSessionId = session.session_id;\n \n // Update state if chat was newly initialized\n if (currentChatId !== chatId) {\n setChatId(currentChatId);\n setSupportSessionId(currentSupportSessionId);\n if (debug) {\n console.log(\"✅ Chat initialized:\", { chatId: currentChatId, sessionId: currentSupportSessionId });\n }\n }\n\n // STEP 2: Request handoff with valid chat_id (include name/email/mobile to update existing chat)\n try {\n await chatServiceRef.current.requestHandoff(\n currentChatId,\n currentSupportSessionId,\n \"Customer requested human agent\",\n dialogflowSessionId || null,\n customerName || null,\n customerEmail || null,\n customerMobile || null\n );\n \n if (debug) {\n console.log(\"✅ Handoff requested successfully\");\n }\n } catch (handoffError: any) {\n // Handle 401/404 or \"chat not found\" - clear chat_id and retry (but keep session logic)\n if (handoffError.message?.includes(\"Invalid chat_id\") || \n handoffError.message?.includes(\"Chat not found\") ||\n handoffError.message?.includes(\"unauthorized\") ||\n handoffError.message?.includes(\"400\") ||\n handoffError.message?.includes(\"401\") ||\n handoffError.message?.includes(\"404\") ||\n handoffError.message?.includes(\"expired\")) {\n if (debug) {\n console.log(\"⚠️ Chat expired or not found. Re-initializing chat...\");\n }\n \n // Clear old chat_id (but keep session logic - session_id is managed by sessionManager)\n setChatId(null);\n setSupportSessionId(null);\n \n // Create new chat session (session_id will be automatically included from session manager)\n const newSession = await chatServiceRef.current.startSupportChat(\n dialogflowSessionId || null,\n customerName || null,\n customerEmail || null,\n customerMobile || null\n );\n \n if (!newSession || !newSession.chat_id) {\n throw new Error(\"Failed to re-initialize chat session\");\n }\n \n const newChatId = newSession.chat_id;\n const newSessionId = newSession.session_id;\n setChatId(newChatId);\n setSupportSessionId(newSessionId);\n // Update local vars so the WebSocket connect below uses the right IDs\n currentChatId = newChatId;\n currentSupportSessionId = newSessionId;\n\n // Retry handoff with new chat_id\n await chatServiceRef.current.requestHandoff(\n newChatId,\n newSessionId,\n \"Customer requested human agent\",\n dialogflowSessionId || null,\n customerName || null,\n customerEmail || null,\n customerMobile || null\n );\n \n if (debug) {\n console.log(\"✅ Handoff requested successfully after retry\");\n }\n \n // Update for message history loading\n const newSessionKey = `${newChatId}-${newSessionId}`;\n if (historyLoadedRef.current !== newSessionKey) {\n historyLoadedRef.current = newSessionKey;\n await loadMessageHistory(true);\n }\n } else {\n throw handoffError;\n }\n }\n\n // Switch to human mode\n switchToHumanMode();\n // Reset states for new handoff\n setChatResolved(false);\n setAgentAccepted(false);\n\n // Add connecting message (preserve existing messages)\n const connectingMessage: Message = {\n id: generateMessageId('connecting'),\n text: \"Connecting you to a human agent...\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, connectingMessage]);\n\n // Connect WebSocket immediately using local variables (not React state)\n // to avoid race condition where useEffect fires before state is flushed.\n // The useEffect at line ~491 acts as a safety net for page reloads.\n chatServiceRef.current.connectWebSocket(\n currentChatId,\n currentSupportSessionId,\n handleWebSocketMessage,\n handleConnectionChange,\n handleWebSocketClose\n );\n\n // Don't load history during handoff - preserve existing bot conversation\n // History will be loaded automatically via useEffect if needed for new sessions\n const sessionKey = `${currentChatId}-${currentSupportSessionId}`;\n historyLoadedRef.current = sessionKey;\n } catch (error: any) {\n console.error(\"Error handling handoff:\", error);\n const errorMessage: Message = {\n id: generateMessageId('error'),\n text: debug\n ? `Handoff error: ${error.message}`\n : \"Failed to connect to agent. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n setIsConnectingToAgent(false);\n }\n };\n\n // Create new session\n const createSession = async (forceRecreate: boolean = false, reuseSessionId: boolean = false) => {\n // If sessionId exists and we're not forcing recreation, return existing session\n if (sessionId && !forceRecreate && !reuseSessionId) return sessionId;\n\n // Promise-based lock: if already creating, await the existing promise\n if (sessionPromiseRef.current) {\n return sessionPromiseRef.current;\n }\n\n const doCreate = async (): Promise<string | null> => {\n try {\n setIsInitializing(true);\n const dfConfig = getDialogflowConfig();\n if (!dfConfig) {\n throw new Error('Dialogflow configuration is missing. Please provide dfProjectId and dfAgentId.');\n }\n \n // Pass existing sessionId if reuseSessionId is true and sessionId exists\n // Backend can decide whether to reuse it or create a new one\n const existingSessionId = (reuseSessionId && sessionId) ? sessionId : null;\n const data = await createDialogflowSession(dfConfig, existingSessionId);\n setSessionId(data.session_id);\n\n // Add welcome message from backend\n if (data.message) {\n if (debug) {\n console.log('Session response richContent:', data.richContent);\n console.log('Full session response:', data);\n }\n \n const welcomeMessage: Message = {\n id: generateMessageId('welcome'),\n text: data.message,\n sender: \"bot\",\n timestamp: new Date(),\n richContent: data.richContent,\n };\n // Preserve existing messages instead of replacing (fix message replacement bug)\n setMessages((prev) => {\n // Only replace if no messages exist, otherwise prepend welcome message\n if (prev.length === 0) {\n return [welcomeMessage];\n }\n return [welcomeMessage, ...prev];\n });\n }\n\n return data.session_id;\n } catch (error: any) {\n console.error(\"Error creating session:\", error);\n if (debug) {\n console.error(\"Full error details:\", {\n message: error.message,\n stack: error.stack,\n config: getDialogflowConfig(),\n });\n }\n // Show error message to user\n const errorMessage: Message = {\n id: generateMessageId('error'),\n text: debug \n ? `Error: ${error.message || 'Failed to create session. Please check your Dialogflow configuration.'}`\n : fallbackWelcomeMessage,\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n return null;\n } finally {\n setIsInitializing(false);\n sessionPromiseRef.current = null; // Release lock\n }\n };\n\n sessionPromiseRef.current = doCreate();\n return sessionPromiseRef.current;\n };\n\n // Update createSession ref when function is defined (fixes stale closure issue)\n createSessionRef.current = createSession;\n\n // Note: Dialogflow manages conversation history internally\n // History is maintained through the session, so we don't need to load it separately\n\n // Send message to backend API\n const sendMessage = async (text: string, displayText?: string, skipUserMessage: boolean = false) => {\n if (!text.trim()) return;\n\n // Handle user info collection for handoff\n if (collectingUserInfo) {\n if (userInfoStep === \"name\") {\n // Save name and ask for email\n const name = text.trim();\n setCollectedUserName(name);\n collectedUserNameRef.current = name;\n setUserInfoStep(\"email\");\n \n // Add user message\n const userMessage: Message = {\n id: generateMessageId('msg'),\n text: name,\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n \n // Ask for email\n const emailPrompt: Message = {\n id: generateMessageId('msg'),\n text: \"Thank you! Now please provide your email address:\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, emailPrompt]);\n setInputValue(\"\");\n return;\n } else if (userInfoStep === \"email\") {\n // Validate email format (basic validation)\n const email = text.trim();\n const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n \n if (!emailRegex.test(email)) {\n // Invalid email, ask again\n const invalidEmailMessage: Message = {\n id: generateMessageId('msg'),\n text: \"Please provide a valid email address:\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, invalidEmailMessage]);\n setInputValue(\"\");\n return;\n }\n \n // Save email and ask for mobile\n setCollectedUserEmail(email);\n setUserInfoStep(\"mobile\");\n \n // Add user message\n const userMessage: Message = {\n id: generateMessageId('msg'),\n text: email,\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n \n // Ask for mobile\n const mobilePrompt: Message = {\n id: generateMessageId('msg'),\n text: \"Thank you! Now please provide your mobile number:\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, mobilePrompt]);\n setInputValue(\"\");\n return;\n } else if (userInfoStep === \"mobile\") {\n // Validate mobile format (basic validation - allows +, digits, spaces, dashes)\n const mobile = text.trim();\n const mobileRegex = /^[\\+]?[(]?[0-9]{1,4}[)]?[-\\s\\.]?[(]?[0-9]{1,4}[)]?[-\\s\\.]?[0-9]{1,9}$/;\n \n if (!mobileRegex.test(mobile) || mobile.length < 10) {\n // Invalid mobile, ask again\n const invalidMobileMessage: Message = {\n id: generateMessageId('msg'),\n text: \"Please provide a valid mobile number (e.g., +1234567890):\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, invalidMobileMessage]);\n setInputValue(\"\");\n return;\n }\n \n // Save mobile and proceed with handoff\n setCollectedUserMobile(mobile);\n \n // Add user message\n const userMessage: Message = {\n id: generateMessageId('msg'),\n text: mobile,\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n \n // Get the collected info from ref and state (avoids state timing issues)\n const userName = collectedUserNameRef.current;\n const userEmail = collectedUserEmail;\n \n // Reset collection state\n setCollectingUserInfo(false);\n setUserInfoStep(null);\n collectedUserNameRef.current = \"\";\n \n // Proceed with handoff using collected info\n await handleHandoff(userName, userEmail, mobile);\n setInputValue(\"\");\n return;\n }\n }\n\n // Handle HUMAN mode\n if (currentMode === \"HUMAN\") {\n if (!chatId || !supportSessionId) {\n const errorMessage: Message = {\n id: generateMessageId('msg'),\n text: \"Chat session not initialized. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n return;\n }\n\n // Add user message unless skipped\n if (!skipUserMessage) {\n const userMessage: Message = {\n id: generateMessageId('msg'),\n text: displayText || text.trim(),\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n }\n\n // Send typing_stop before sending message\n chatServiceRef.current.sendTypingIndicator(\"typing_stop\");\n \n // Clear typing timeout\n if (typingTimeoutRef.current) {\n clearTimeout(typingTimeoutRef.current);\n typingTimeoutRef.current = null;\n }\n\n setInputValue(\"\");\n setIsLoading(true);\n\n try {\n // Try WebSocket first, fallback to REST API\n const sentViaWs = chatServiceRef.current.sendMessageViaWebSocket(text.trim());\n \n if (!sentViaWs) {\n // Fallback to REST API\n await chatServiceRef.current.sendMessageToAgent(chatId, supportSessionId, text.trim());\n }\n } catch (error: any) {\n // chat_resolved is a normal terminal success condition, not an error.\n if (\n error instanceof ChatResolvedError ||\n error?.name === \"ChatResolvedError\" ||\n error?.message === \"chat_resolved\"\n ) {\n enterResolvedState(chatId);\n return;\n }\n\n console.error(\"Error sending message to agent:\", error);\n \n // Handle 401/404 - clear chat_id and reinitialize (but keep session logic)\n if (error.message?.includes(\"Chat not found\") ||\n error.message?.includes(\"unauthorized\") ||\n error.message?.includes(\"401\") ||\n error.message?.includes(\"404\")) {\n if (debug) {\n console.log(\"⚠️ Chat expired. Re-initializing...\");\n }\n \n // Clear chat_id (session_id is managed by sessionManager)\n setChatId(null);\n setSupportSessionId(null);\n \n // Try to reinitialize chat\n try {\n const newSession = await chatServiceRef.current.startSupportChat(\n sessionId || null,\n null,\n null,\n null\n );\n setChatId(newSession.chat_id);\n setSupportSessionId(newSession.session_id);\n \n // Retry sending message\n try {\n await chatServiceRef.current.sendMessageToAgent(\n newSession.chat_id,\n newSession.session_id,\n text.trim()\n );\n } catch (retryError: any) {\n if (\n retryError instanceof ChatResolvedError ||\n retryError?.name === \"ChatResolvedError\" ||\n retryError?.message === \"chat_resolved\"\n ) {\n enterResolvedState(newSession.chat_id);\n return;\n }\n throw retryError;\n }\n return; // Success, exit early\n } catch (retryError: any) {\n if (\n retryError instanceof ChatResolvedError ||\n retryError?.name === \"ChatResolvedError\" ||\n retryError?.message === \"chat_resolved\"\n ) {\n enterResolvedState(chatId);\n return;\n }\n // If retry fails, show error\n const errorMessage: Message = {\n id: generateMessageId('msg'),\n text: debug\n ? `Error: ${retryError.message || 'Failed to send message.'}`\n : \"Sorry, I'm having trouble sending your message. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n }\n } else {\n const errorMessage: Message = {\n id: generateMessageId('msg'),\n text: debug\n ? `Error: ${error.message || 'Failed to send message to agent.'}`\n : \"Sorry, I'm having trouble sending your message. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n }\n } finally {\n setIsLoading(false);\n }\n return;\n }\n\n // Handle BOT mode (Dialogflow)\n // Ensure we have a session\n let currentSessionId = sessionId;\n if (!currentSessionId) {\n try {\n currentSessionId = await createSession();\n if (!currentSessionId) {\n const errorMessage: Message = {\n id: generateMessageId('msg'),\n text: debug \n ? \"Failed to create session. Please check the console for details.\"\n : \"Sorry, I'm having trouble connecting. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n return;\n }\n } catch (error: any) {\n console.error(\"Error in createSession:\", error);\n const errorMessage: Message = {\n id: generateMessageId('msg'),\n text: debug \n ? `Connection Error: ${error.message || 'Please check your Dialogflow configuration.'}`\n : \"Sorry, I'm having trouble connecting. Please check your configuration.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n return;\n }\n }\n\n // Add user message unless skipped (e.g., when chip button already added it)\n if (!skipUserMessage) {\n const userMessage: Message = {\n id: generateMessageId('msg'),\n text: displayText || text.trim(),\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n }\n \n setInputValue(\"\");\n setIsLoading(true);\n\n try {\n const dfConfig = getDialogflowConfig();\n if (!dfConfig) {\n throw new Error('Dialogflow configuration is missing. Please provide dfProjectId and dfAgentId.');\n }\n \n const data = await sendDialogflowMessage(text.trim(), currentSessionId, dfConfig);\n\n if (debug) {\n console.log('Chat response richContent:', data.richContent);\n console.log('Full chat response:', data);\n console.log('Handoff detected:', data.handoff);\n }\n \n // Check for handoff\n if (data.handoff === true) {\n // Add bot response first (only if there's actual text)\n if (data.response) {\n const botMessage: Message = {\n id: generateMessageId('msg'),\n text: data.response,\n sender: \"bot\",\n timestamp: new Date(data.timestamp || Date.now()),\n richContent: data.richContent,\n };\n setMessages((prev) => [...prev, botMessage]);\n }\n\n // Start collecting user info for handoff\n setCollectingUserInfo(true);\n setUserInfoStep(\"name\");\n setCollectedUserName(\"\");\n setCollectedUserEmail(\"\");\n collectedUserNameRef.current = \"\";\n\n // Ask for name\n const namePrompt: Message = {\n id: generateMessageId('msg'),\n text: \"To connect you with a human agent, I'll need some information. Please provide your name:\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, namePrompt]);\n return;\n }\n\n // Show backend response directly (no client-side filtering)\n const responseText = data.response || '';\n if (responseText) {\n const botMessage: Message = {\n id: generateMessageId('msg'),\n text: responseText,\n sender: \"bot\",\n timestamp: new Date(data.timestamp || Date.now()),\n richContent: data.richContent,\n };\n setMessages((prev) => [...prev, botMessage]);\n }\n } catch (error: any) {\n console.error(\"Error sending message:\", error);\n if (debug) {\n console.error(\"Full error details:\", {\n message: error.message,\n stack: error.stack,\n sessionId: currentSessionId,\n config: getDialogflowConfig(),\n });\n }\n const errorMessage: Message = {\n id: generateMessageId('msg'),\n text: debug\n ? `Error: ${error.message || 'Failed to send message. Please check your Dialogflow configuration.'}`\n : error.message?.includes(\"Failed to fetch\") || error.message?.includes(\"CORS\")\n ? \"Unable to connect to Dialogflow. Please check your configuration and network.\"\n : \"Sorry, I'm having trouble processing your message. Please try again.\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, errorMessage]);\n } finally {\n setIsLoading(false);\n }\n };\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n sendMessage(inputValue);\n };\n\n // Handle input change - send typing indicators (only in HUMAN mode)\n const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const value = e.target.value;\n setInputValue(value);\n\n // Only send typing indicators in HUMAN mode with WebSocket connected\n if (currentMode === \"HUMAN\" && wsConnected) {\n // Send typing_start\n chatServiceRef.current.sendTypingIndicator(\"typing_start\");\n\n // Clear existing timeout\n if (typingTimeoutRef.current) {\n clearTimeout(typingTimeoutRef.current);\n }\n\n // Send typing_stop after 2 seconds of inactivity\n typingTimeoutRef.current = setTimeout(() => {\n chatServiceRef.current.sendTypingIndicator(\"typing_stop\");\n typingTimeoutRef.current = null;\n }, 2000);\n }\n };\n\n // Cleanup typing timeouts on unmount\n useEffect(() => {\n return () => {\n if (typingTimeoutRef.current) {\n clearTimeout(typingTimeoutRef.current);\n }\n if (agentTypingTimeoutRef.current) {\n clearTimeout(agentTypingTimeoutRef.current);\n }\n };\n }, []);\n\n const openChat = async () => {\n setIsOpen(true);\n setShowWelcomePopup(false);\n\n // Create session when chat opens if it doesn't exist\n if (!sessionId) {\n await createSession();\n }\n // Note: Dialogflow maintains conversation history internally through the session\n };\n\n const closeChat = () => {\n setIsOpen(false);\n // Disconnect WebSocket when closing chat\n if (currentMode === \"HUMAN\") {\n chatServiceRef.current.disconnectWebSocket();\n }\n };\n\n // Check if message is a handoff message\n const isHandoffMessage = (text: string): boolean => {\n return (\n text.includes(\"👤\") ||\n text.includes(\"being connected\") ||\n text.includes(\"live support agent\") ||\n text.includes(\"transfer your conversation\") ||\n text.includes(\"✅\") ||\n text.includes(\"🔄\")\n );\n };\n\n // Cleanup WebSocket on unmount\n useEffect(() => {\n return () => {\n chatServiceRef.current.disconnectWebSocket();\n };\n }, []);\n\n return (\n <>\n {/* Welcome Popup */}\n {showWelcomePopup && !isOpen && (\n <div className=\"custom-welcome-popup\" onClick={openChat}>\n <div className=\"custom-welcome-header\">\n <div className=\"custom-welcome-title\">{welcomeTitle}</div>\n <button\n className=\"custom-close-popup\"\n onClick={(e) => {\n e.stopPropagation();\n setShowWelcomePopup(false);\n }}\n >\n ×\n </button>\n </div>\n <div className=\"custom-welcome-message\">\n {welcomeMessage}\n </div>\n <div className=\"custom-welcome-cta\">{welcomeCta}</div>\n </div>\n )}\n\n {/* Chat Toggle Button */}\n {!isOpen && (\n <button\n className=\"custom-chat-toggle-btn\"\n onClick={openChat}\n aria-label=\"Open chat\"\n >\n <svg\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\"></path>\n </svg>\n </button>\n )}\n\n {/* Chat Window */}\n {isOpen && (\n <div className=\"custom-chat-window\" role=\"dialog\" aria-label=\"Chat window\">\n <div className=\"custom-chat-header\">\n <div className=\"custom-chat-header-content\">\n <div className=\"custom-chat-title\">{title}</div>\n <div className=\"custom-chat-subtitle\">\n {subtitle}\n {currentMode === \"HUMAN\" && (\n <span className=\"custom-mode-indicator\">\n {\" \"}\n • {wsConnected ? \"🟢 Connected\" : \"🟡 Connecting...\"}\n </span>\n )}\n </div>\n {currentMode === \"HUMAN\" && (\n <>\n <div className=\"custom-mode-badge\">Human Support Mode</div>\n <div className=\"custom-agent-info\">\n <span className=\"custom-agent-label\">Agent:</span>\n <span className=\"custom-agent-name\">{currentAgent.name}</span>\n </div>\n </>\n )}\n {currentMode === \"BOT\" && (\n <div className=\"custom-mode-badge\">Bot Mode</div>\n )}\n </div>\n <button\n className=\"custom-chat-close-btn\"\n onClick={closeChat}\n aria-label=\"Close chat\"\n >\n ×\n </button>\n </div>\n\n <div className=\"custom-chat-messages\" role=\"log\" aria-live=\"polite\" aria-label=\"Chat messages\">\n {isInitializing && messages.length === 0 && (\n <div className=\"custom-chat-empty\">\n <div className=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n <p>Initializing chat...</p>\n </div>\n )}\n {!isInitializing && messages.length === 0 && (\n <div className=\"custom-chat-empty\">\n <div className=\"custom-chat-empty-icon\">👋</div>\n <p>{emptyStateMessage}</p>\n </div>\n )}\n {messages.map((message) => (\n <div\n key={message.id}\n className={`custom-message custom-message-${message.sender} ${\n isHandoffMessage(message.text) ? \"custom-handoff-message\" : \"\"\n }`}\n >\n <div \n className={`custom-message-content ${\n isHandoffMessage(message.text) ? \"custom-handoff-content\" : \"\"\n }`}\n dangerouslySetInnerHTML={{ \n __html: linkifyText(message.text) \n }}\n />\n {(() => {\n // Debug: Log rich content structure\n if (debug && message.richContent) {\n console.log('Rendering message with richContent:', message.richContent);\n console.log('richContent type:', typeof message.richContent);\n console.log('richContent is array:', Array.isArray(message.richContent));\n console.log('richContent length:', message.richContent?.length);\n }\n \n // Check if richContent exists and has data\n if (message.richContent && Array.isArray(message.richContent) && message.richContent.length > 0) {\n return (\n <div className=\"custom-chips-container\">\n {message.richContent.map((contentGroup, groupIndex) => {\n if (debug) {\n console.log(`Processing contentGroup ${groupIndex}:`, contentGroup);\n }\n if (!Array.isArray(contentGroup)) {\n // Handle case where contentGroup is not an array (single RichContent object)\n const content = contentGroup as RichContent;\n if (content && content.type === \"chips\" && content.options) {\n return (\n <div key={groupIndex} className=\"custom-chips-group\">\n {content.options.map((chip: ChipOption, chipIndex: number) => (\n <button\n key={chipIndex}\n className=\"custom-chip-button\"\n onClick={() => {\n const userMessage: Message = {\n id: generateMessageId('msg'),\n text: chip.text,\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n // Send the chip text instead of payload for better intent matching\n // Dialogflow will match the text to the intent\n sendMessage(chip.text, chip.text, true);\n }}\n type=\"button\"\n >\n {chip.text}\n </button>\n ))}\n </div>\n );\n }\n return null;\n }\n return contentGroup.map((content: RichContent, contentIndex: number) => {\n if (debug) {\n console.log(`Processing content ${groupIndex}-${contentIndex}:`, content);\n }\n if (content && content.type === \"chips\" && content.options) {\n return (\n <div key={`${groupIndex}-${contentIndex}`} className=\"custom-chips-group\">\n {content.options.map((chip: ChipOption, chipIndex: number) => (\n <button\n key={chipIndex}\n className=\"custom-chip-button\"\n onClick={() => {\n const userMessage: Message = {\n id: generateMessageId('msg'),\n text: chip.text,\n sender: \"user\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, userMessage]);\n // Send the chip text instead of payload for better intent matching\n sendMessage(chip.text, chip.text, true);\n }}\n type=\"button\"\n >\n {chip.text}\n </button>\n ))}\n </div>\n );\n }\n return null;\n });\n })}\n </div>\n );\n }\n return null;\n })()}\n <div className=\"custom-message-time\">\n {message.timestamp.toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n })}\n </div>\n </div>\n ))}\n {isLoading && (\n <div className=\"custom-message custom-message-bot\">\n <div className=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n </div>\n )}\n {isConnectingToAgent && (\n <div className=\"custom-message custom-message-bot\">\n <div className=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n <div className=\"custom-message-content\">\n Connecting to agent...\n </div>\n </div>\n )}\n {/* Agent Typing Indicator */}\n {currentMode === \"HUMAN\" && agentTyping && (\n <div className=\"custom-agent-typing-indicator\">\n <span className=\"custom-typing-dots\">\n <span></span>\n <span></span>\n <span></span>\n </span>\n <span className=\"custom-typing-text\">Agent is typing...</span>\n </div>\n )}\n <div ref={messagesEndRef} />\n </div>\n\n <form className=\"custom-chat-input-form\" onSubmit={handleSubmit}>\n <input\n type=\"text\"\n className=\"custom-chat-input\"\n value={inputValue}\n onChange={handleInputChange}\n placeholder={inputPlaceholder}\n aria-label={inputPlaceholder}\n disabled={isLoading || isInitializing || isStartingNewChat}\n />\n <button\n type=\"submit\"\n className=\"custom-chat-send-btn\"\n disabled={!inputValue.trim() || isLoading || isInitializing || isStartingNewChat}\n >\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <line x1=\"22\" y1=\"2\" x2=\"11\" y2=\"13\"></line>\n <polygon points=\"22 2 15 22 11 13 2 9 22 2\"></polygon>\n </svg>\n </button>\n </form>\n </div>\n )}\n </>\n );\n}\n\nexport default function ChatWidget(props: ChatWidgetProps) {\n return (\n <ChatWidgetErrorBoundary>\n <ChatWidgetInner {...props} />\n </ChatWidgetErrorBoundary>\n );\n} "],"names":["MODE_STORAGE_KEY","CHAT_ID_STORAGE_KEY","SESSION_ID_STORAGE_KEY","ChatWidgetErrorBoundary","React","Component","constructor","props","super","this","state","hasError","getDerivedStateFromError","componentDidCatch","error","info","render","children","ChatWidgetInner","title","subtitle","welcomeTitle","welcomeMessage","welcomeCta","showWelcomePopup","enableWelcomePopup","welcomePopupDelay","fallbackWelcomeMessage","inputPlaceholder","emptyStateMessage","debug","dfProjectId","dfLocation","dfAgentId","languageCode","backendBaseUrl","backendWsUrl","noMatchMessage","isOpen","setIsOpen","useState","setShowWelcomePopup","messages","setMessages","inputValue","setInputValue","isLoading","setIsLoading","sessionId","setSessionId","isInitializing","setIsInitializing","isConnectingToAgent","setIsConnectingToAgent","wsConnected","setWsConnected","agentTyping","setAgentTyping","currentAgent","setCurrentAgent","name","collectingUserInfo","setCollectingUserInfo","chatResolved","setChatResolved","isStartingNewChat","setIsStartingNewChat","agentAccepted","setAgentAccepted","userInfoStep","setUserInfoStep","collectedUserName","setCollectedUserName","collectedUserEmail","setCollectedUserEmail","collectedUserMobile","setCollectedUserMobile","collectedUserNameRef","useRef","messagesEndRef","typingTimeoutRef","agentTypingTimeoutRef","sessionPromiseRef","createSessionRef","getBackendBaseUrl","process","env","REACT_APP_BACKEND_BASE_URL","chatServiceRef","createChatService","baseUrl","wsUrl","REACT_APP_BACKEND_WS_URL","historyLoadedRef","currentMode","switchToHumanMode","switchToBotMode","chatId","supportSessionId","setChatId","setSupportSessionId","setCurrentMode","window","localStorage","getItem","setChatIdState","setSessionIdState","useEffect","setItem","useCallback","id","removeItem","isHandoffTriggered","dialogflowResponse","useChatMode","enterResolvedState","_resolvedChatId","current","clearTimeout","disconnectWebSocket","thankYouMessage","generateMessageId","text","sender","timestamp","Date","prev","setTimeout","catch","console","async","customerName","customerEmail","customerMobile","newSession","startSupportChat","chat_id","session_id","message","getDialogflowConfig","timer","scrollIntoView","behavior","handleAgentChanged","to_agent","to_agent_id","systemMessage","from_agent","handleWebSocketMessage","type","content","sender_type","agentMessage","now","Set","map","m","has","status","agent_id","acceptedMessage","errorMessage","handleWebSocketClose","event","code","handleConnectionChange","connected","connectWebSocket","loadMessageHistory","preserveExisting","historyMessages","msg","prevMessages","existingIds","newMessages","filter","sort","a","b","getTime","messagesLengthRef","length","sessionKey","createSession","forceRecreate","reuseSessionId","dfConfig","Error","existingSessionId","data","createDialogflowSession","richContent","doCreate","sendMessage","displayText","skipUserMessage","trim","userMessage","emailPrompt","email","test","invalidEmailMessage","mobilePrompt","mobile","invalidMobileMessage","userName","userEmail","dialogflowSessionId","session","ensureChatInitialized","currentChatId","currentSupportSessionId","requestHandoff","handoffError","includes","newChatId","newSessionId","newSessionKey","connectingMessage","handleHandoff","sendTypingIndicator","sendMessageViaWebSocket","sendMessageToAgent","ChatResolvedError","retryError","currentSessionId","sendDialogflowMessage","handoff","response","botMessage","namePrompt","responseText","openChat","isHandoffMessage","jsxs","Fragment","className","onClick","jsx","e","stopPropagation","width","height","viewBox","fill","stroke","strokeWidth","strokeLinecap","strokeLinejoin","d","role","dangerouslySetInnerHTML","__html","linkifyText","Array","isArray","contentGroup","groupIndex","options","chip","chipIndex","contentIndex","toLocaleTimeString","hour","minute","ref","onSubmit","preventDefault","value","onChange","target","placeholder","disabled","x1","y1","x2","y2","points"],"mappings":"uGAMMA,EAAmB,0BACnBC,EAAsB,wBACtBC,EAAyB,2BCiE/B,MAAMC,UAAgCC,EAAMC,UAI1C,WAAAC,CAAYC,GACVC,MAAMD,GACNE,KAAKC,MAAQ,CAAEC,UAAU,EAC3B,CACA,+BAAOC,GACL,MAAO,CAAED,UAAU,EACrB,CACA,iBAAAE,CAAkBC,EAAcC,GAEhC,CACA,MAAAC,GACE,OAAIP,KAAKC,MAAMC,SACN,KAEFF,KAAKF,MAAMU,QACpB,EAGF,SAASC,GAAgBC,MACvBA,EAAQ,iCAAAC,SACRA,EAAW,qBAAAC,aACXA,EAAe,+BAAAC,eACfA,EAAiB,6DAAAC,WACjBA,EAAa,mCACbC,iBAAkBC,GAAqB,EAAAC,kBACvCA,EAAoB,KAAAC,uBACpBA,EAAyB,oEAAAC,iBACzBA,EAAmB,uBAAAC,kBACnBA,EAAoB,iEAAAC,MACpBA,GAAQ,EAAAC,YACRA,EAAAC,WACAA,EAAa,cAAAC,UACbA,EAAAC,aACAA,EAAe,KAAAC,eACfA,EAAAC,aACAA,EAAAC,eACAA,EAAiB,OAEjB,MAAOC,EAAQC,GAAaC,EAAAA,UAAS,IAC9BhB,EAAkBiB,GAAuBD,EAAAA,UAAS,IAClDE,EAAUC,GAAeH,EAAAA,SAAoB,KAC7CI,EAAYC,GAAiBL,EAAAA,SAAS,KACtCM,EAAWC,GAAgBP,EAAAA,UAAS,IACpCQ,EAAWC,GAAgBT,EAAAA,SAAwB,OACnDU,EAAgBC,GAAqBX,EAAAA,UAAS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A,OAAA,CAAA,MAEHA,EAAAA,IAAC,OAAA,CAAKF,UAAU,qBAAqB3N,SAAA,4BAGzC6N,IAAC,MAAA,CAAI2B,IAAK1L,QAGZ2J,EAAAA,KAAC,OAAA,CAAKE,UAAU,yBAAyB8B,SAnU3B3B,IACpBA,EAAE4B,iBACF1E,GAAYrJ,IAkUJ3B,SAAA,CAAA6N,EAAAA,IAAC,QAAA,CACCzF,KAAK,OACLuF,UAAU,oBACVgC,MAAOhO,EACPiO,SAlUe9B,IACzB,MAAM6B,EAAQ7B,EAAE+B,OAAOF,MACvB/N,EAAc+N,GAGM,UAAhB9K,IAA2BxC,IAE7BkC,GAAe6B,QAAQuG,oBAAoB,gBAGvC5I,GAAiBqC,SACnBC,aAAatC,GAAiBqC,SAIhCrC,GAAiBqC,QAAUU,WAAW,KACpCvC,GAAe6B,QAAQuG,oBAAoB,eAC3C5I,GAAiBqC,QAAU,MAC1B,OAiTK0J,YAAanP,EACb,aAAYA,EACZoP,SAAUlO,GAAaI,GAAkBe,IAE3C6K,EAAAA,IAAC,SAAA,CACCzF,KAAK,SACLuF,UAAU,uBACVoC,UAAWpO,EAAWwJ,QAAUtJ,GAAaI,GAAkBe,EAE/DhD,SAAAyN,EAAAA,KAAC,MAAA,CACCO,MAAM,KACNC,OAAO,KACPC,QAAQ,YACRC,KAAK,OACLC,OAAO,eACPC,YAAY,IACZC,cAAc,QACdC,eAAe,QAEfvO,SAAA,CAAA6N,EAAAA,IAAC,OAAA,CAAKmC,GAAG,KAAKC,GAAG,IAAIC,GAAG,KAAKC,GAAG,SAChCtC,IAAC,UAAA,CAAQuC,OAAO,2CAQhC,oBAEA,SAAmC9Q,GACjC,aACGJ,EAAA,CACCc,SAAA6N,EAAAA,IAAC5N,EAAA,IAAoBX,KAG3B"}
@@ -1,5 +1,5 @@
1
1
  import { ref, computed, onUnmounted, watch, defineComponent, nextTick, onMounted, openBlock, createElementBlock, mergeProps, unref, createElementVNode, toDisplayString, withModifiers, createCommentVNode, createTextVNode, Fragment, renderList, normalizeClass } from "vue";
2
- import { a as createChatService, c as createDialogflowSession, g as generateMessageId, C as ChatResolvedError, s as sendDialogflowMessage, b as safeLinkifyText } from "./types-C86de8ud.js";
2
+ import { a as createChatService, c as createDialogflowSession, g as generateMessageId, C as ChatResolvedError, s as sendDialogflowMessage, b as safeLinkifyText } from "./types-Bl_MQGCd.js";
3
3
  class WidgetStateManager {
4
4
  constructor(config) {
5
5
  this.listeners = /* @__PURE__ */ new Set();
@@ -7,11 +7,6 @@ class WidgetStateManager {
7
7
  this.chatId = null;
8
8
  this.supportSessionId = null;
9
9
  this.chatService = null;
10
- this.collectingUserInfo = false;
11
- this.userInfoStep = null;
12
- this.collectedUserName = "";
13
- this.collectedUserEmail = "";
14
- this.collectedUserMobile = "";
15
10
  this.wsConnected = false;
16
11
  this.agentTyping = false;
17
12
  this.currentAgent = { name: "Agent" };
@@ -168,22 +163,6 @@ class WidgetStateManager {
168
163
  if (!text.trim() || this.state.isLoading) {
169
164
  return;
170
165
  }
171
- if (this.collectingUserInfo) {
172
- const userMessage = {
173
- id: generateMessageId("user"),
174
- text: text.trim(),
175
- sender: "user",
176
- timestamp: /* @__PURE__ */ new Date()
177
- };
178
- this.setState({
179
- messages: [...this.state.messages, userMessage],
180
- inputValue: "",
181
- isLoading: false,
182
- error: null
183
- });
184
- await this.handleUserInfoCollection(text);
185
- return;
186
- }
187
166
  if (!skipUserMessage) {
188
167
  const userMessage = {
189
168
  id: generateMessageId("user"),
@@ -282,7 +261,40 @@ class WidgetStateManager {
282
261
  } else {
283
262
  this.setState({ isLoading: false });
284
263
  }
285
- this.startUserInfoCollection();
264
+ if (response.chat_id && response.support_session_id) {
265
+ this.chatId = response.chat_id;
266
+ this.supportSessionId = response.support_session_id;
267
+ if (typeof window !== "undefined" && window.localStorage) {
268
+ localStorage.setItem("chartsconnect_chat_id", this.chatId);
269
+ localStorage.setItem("chartsconnect_session_id", this.supportSessionId);
270
+ }
271
+ this.switchToHumanMode();
272
+ this.chatResolved = false;
273
+ this.agentAccepted = false;
274
+ const connectingMessage = {
275
+ id: generateMessageId("connecting"),
276
+ text: "Connecting you to a human agent...",
277
+ sender: "bot",
278
+ timestamp: /* @__PURE__ */ new Date()
279
+ };
280
+ this.setState({
281
+ messages: [...this.state.messages, connectingMessage]
282
+ });
283
+ if (this.chatService) {
284
+ this.chatService.connectWebSocket(
285
+ this.chatId,
286
+ this.supportSessionId,
287
+ (message) => {
288
+ this.handleWebSocketMessage(message);
289
+ },
290
+ (connected) => {
291
+ this.wsConnected = connected;
292
+ }
293
+ );
294
+ }
295
+ this.isConnectingToAgent = false;
296
+ return;
297
+ }
286
298
  return;
287
299
  }
288
300
  const responseText = response.response || "";
@@ -416,224 +428,6 @@ class WidgetStateManager {
416
428
  }, delay);
417
429
  }
418
430
  }
419
- /**
420
- * Start user info collection for handoff
421
- */
422
- startUserInfoCollection() {
423
- this.collectingUserInfo = true;
424
- this.userInfoStep = "name";
425
- this.collectedUserName = "";
426
- this.collectedUserEmail = "";
427
- this.collectedUserMobile = "";
428
- const namePrompt = {
429
- id: generateMessageId("prompt"),
430
- text: "To connect you with a human agent, I'll need some information. Please provide your name:",
431
- sender: "bot",
432
- timestamp: /* @__PURE__ */ new Date()
433
- };
434
- this.setState({
435
- messages: [...this.state.messages, namePrompt]
436
- });
437
- }
438
- /**
439
- * Handle user info collection
440
- */
441
- async handleUserInfoCollection(text) {
442
- if (this.userInfoStep === "name") {
443
- const name = text.trim();
444
- this.collectedUserName = name;
445
- this.userInfoStep = "email";
446
- const emailPrompt = {
447
- id: generateMessageId("prompt"),
448
- text: "Thank you! Now please provide your email address:",
449
- sender: "bot",
450
- timestamp: /* @__PURE__ */ new Date()
451
- };
452
- this.setState({
453
- messages: [...this.state.messages, emailPrompt],
454
- inputValue: ""
455
- });
456
- return;
457
- } else if (this.userInfoStep === "email") {
458
- const email = text.trim();
459
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
460
- if (!emailRegex.test(email)) {
461
- const invalidEmailMessage = {
462
- id: generateMessageId("prompt"),
463
- text: "Please provide a valid email address:",
464
- sender: "bot",
465
- timestamp: /* @__PURE__ */ new Date()
466
- };
467
- this.setState({
468
- messages: [...this.state.messages, invalidEmailMessage],
469
- inputValue: ""
470
- });
471
- return;
472
- }
473
- this.collectedUserEmail = email;
474
- this.userInfoStep = "mobile";
475
- const mobilePrompt = {
476
- id: generateMessageId("prompt"),
477
- text: "Thank you! Now please provide your mobile number:",
478
- sender: "bot",
479
- timestamp: /* @__PURE__ */ new Date()
480
- };
481
- this.setState({
482
- messages: [...this.state.messages, mobilePrompt],
483
- inputValue: ""
484
- });
485
- return;
486
- } else if (this.userInfoStep === "mobile") {
487
- const mobile = text.trim();
488
- const mobileRegex = /^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,9}$/;
489
- if (!mobileRegex.test(mobile) || mobile.length < 10) {
490
- const invalidMobileMessage = {
491
- id: generateMessageId("prompt"),
492
- text: "Please provide a valid mobile number (e.g., +1234567890):",
493
- sender: "bot",
494
- timestamp: /* @__PURE__ */ new Date()
495
- };
496
- this.setState({
497
- messages: [...this.state.messages, invalidMobileMessage],
498
- inputValue: ""
499
- });
500
- return;
501
- }
502
- this.collectedUserMobile = mobile;
503
- this.collectingUserInfo = false;
504
- this.userInfoStep = null;
505
- await this.handleHandoff(this.collectedUserName, this.collectedUserEmail, mobile);
506
- this.setState({ inputValue: "" });
507
- }
508
- }
509
- /**
510
- * Handle handoff from Dialogflow to human support
511
- */
512
- async handleHandoff(customerName, customerEmail, customerMobile) {
513
- if (!this.chatService) {
514
- throw new Error("Chat service not initialized");
515
- }
516
- try {
517
- this.isConnectingToAgent = true;
518
- const dialogflowSessionId = this.state.sessionId;
519
- const session = await this.chatService.ensureChatInitialized(
520
- this.chatId,
521
- this.supportSessionId,
522
- dialogflowSessionId || null,
523
- customerName || null,
524
- customerEmail || null,
525
- customerMobile || null
526
- );
527
- if (!session || !session.chat_id) {
528
- throw new Error("Failed to initialize chat session");
529
- }
530
- const currentChatId = session.chat_id;
531
- const currentSupportSessionId = session.session_id;
532
- if (currentChatId !== this.chatId) {
533
- this.chatId = currentChatId;
534
- this.supportSessionId = currentSupportSessionId;
535
- if (typeof window !== "undefined" && window.localStorage) {
536
- localStorage.setItem("chartsconnect_chat_id", this.chatId);
537
- localStorage.setItem("chartsconnect_session_id", this.supportSessionId);
538
- }
539
- if (this.config.debug) {
540
- console.log("✅ Chat initialized:", { chatId: currentChatId, sessionId: currentSupportSessionId });
541
- }
542
- }
543
- try {
544
- await this.chatService.requestHandoff(
545
- currentChatId,
546
- currentSupportSessionId,
547
- "Customer requested human agent",
548
- dialogflowSessionId || null,
549
- customerName || null,
550
- customerEmail || null,
551
- customerMobile || null
552
- );
553
- if (this.config.debug) {
554
- console.log("✅ Handoff requested successfully");
555
- }
556
- } catch (handoffError) {
557
- 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")) {
558
- if (this.config.debug) {
559
- console.log("⚠️ Chat expired or not found. Re-initializing chat...");
560
- }
561
- this.chatId = null;
562
- this.supportSessionId = null;
563
- if (typeof window !== "undefined" && window.localStorage) {
564
- localStorage.removeItem("chartsconnect_chat_id");
565
- localStorage.removeItem("chartsconnect_session_id");
566
- }
567
- const newSession = await this.chatService.startSupportChat(
568
- dialogflowSessionId || null,
569
- customerName || null,
570
- customerEmail || null,
571
- customerMobile || null
572
- );
573
- if (!newSession || !newSession.chat_id) {
574
- throw new Error("Failed to re-initialize chat session");
575
- }
576
- this.chatId = newSession.chat_id;
577
- this.supportSessionId = newSession.session_id;
578
- if (typeof window !== "undefined" && window.localStorage) {
579
- localStorage.setItem("chartsconnect_chat_id", this.chatId);
580
- localStorage.setItem("chartsconnect_session_id", this.supportSessionId);
581
- }
582
- await this.chatService.requestHandoff(
583
- this.chatId,
584
- this.supportSessionId,
585
- "Customer requested human agent",
586
- dialogflowSessionId || null,
587
- customerName || null,
588
- customerEmail || null,
589
- customerMobile || null
590
- );
591
- if (this.config.debug) {
592
- console.log("✅ Handoff requested successfully after retry");
593
- }
594
- } else {
595
- throw handoffError;
596
- }
597
- }
598
- this.switchToHumanMode();
599
- this.chatResolved = false;
600
- this.agentAccepted = false;
601
- const connectingMessage = {
602
- id: generateMessageId("connecting"),
603
- text: "Connecting you to a human agent...",
604
- sender: "bot",
605
- timestamp: /* @__PURE__ */ new Date()
606
- };
607
- this.setState({
608
- messages: [...this.state.messages, connectingMessage]
609
- });
610
- if (currentChatId && currentSupportSessionId) {
611
- this.chatService.connectWebSocket(
612
- currentChatId,
613
- currentSupportSessionId,
614
- (message) => {
615
- this.handleWebSocketMessage(message);
616
- },
617
- (connected) => {
618
- this.wsConnected = connected;
619
- }
620
- );
621
- }
622
- this.isConnectingToAgent = false;
623
- } catch (error) {
624
- console.error("Error handling handoff:", error);
625
- const errorMessage = {
626
- id: generateMessageId("error"),
627
- text: this.config.debug ? `Handoff error: ${error.message}` : "Failed to connect to agent. Please try again.",
628
- sender: "bot",
629
- timestamp: /* @__PURE__ */ new Date()
630
- };
631
- this.setState({
632
- messages: [...this.state.messages, errorMessage]
633
- });
634
- this.isConnectingToAgent = false;
635
- }
636
- }
637
431
  /**
638
432
  * Handle WebSocket messages
639
433
  */
@@ -791,11 +585,6 @@ class WidgetStateManager {
791
585
  sessionId: null
792
586
  // Clear session ID to force recreation
793
587
  });
794
- this.collectingUserInfo = false;
795
- this.userInfoStep = null;
796
- this.collectedUserName = "";
797
- this.collectedUserEmail = "";
798
- this.collectedUserMobile = "";
799
588
  if (this.config.dfProjectId && this.config.dfAgentId && this.state.isOpen) {
800
589
  try {
801
590
  this.setState({ isLoading: true });
@@ -911,9 +700,6 @@ class WidgetStateManager {
911
700
  if (this.agentTypingTimeout) {
912
701
  clearTimeout(this.agentTypingTimeout);
913
702
  }
914
- if (this.welcomePopupTimeout) {
915
- clearTimeout(this.welcomePopupTimeout);
916
- }
917
703
  if (this.chatService) {
918
704
  this.chatService.disconnectWebSocket();
919
705
  }
@@ -1374,4 +1160,4 @@ export {
1374
1160
  WidgetStateManager as W,
1375
1161
  useChatWidget as u
1376
1162
  };
1377
- //# sourceMappingURL=ChatWidget-mgpMEdRJ.js.map
1163
+ //# sourceMappingURL=ChatWidget-CM0TQ03R.js.map