@om_patel_26/chat-widget 1.0.6 → 1.0.7

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 (48) hide show
  1. package/README.md +16 -102
  2. package/dist/components/ChatWidget.cjs.js +2 -0
  3. package/dist/components/ChatWidget.cjs.js.map +1 -0
  4. package/dist/components/ChatWidget.esm.js +1129 -0
  5. package/dist/components/ChatWidget.esm.js.map +1 -0
  6. package/dist/core/stateManager.cjs.js +1 -1
  7. package/dist/core/stateManager.cjs.js.map +1 -1
  8. package/dist/core/stateManager.d.ts.map +1 -1
  9. package/dist/core/stateManager.esm.js +38 -36
  10. package/dist/core/stateManager.esm.js.map +1 -1
  11. package/dist/entry/vanilla.cjs.js +2 -0
  12. package/dist/entry/vanilla.cjs.js.map +1 -0
  13. package/dist/entry/vanilla.esm.js +50 -0
  14. package/dist/entry/vanilla.esm.js.map +1 -0
  15. package/dist/entry/vue.d.ts +3 -2
  16. package/dist/entry/vue.d.ts.map +1 -1
  17. package/dist/hooks/useChatMode.cjs.js +2 -0
  18. package/dist/hooks/useChatMode.cjs.js.map +1 -0
  19. package/dist/hooks/useChatMode.esm.js +61 -0
  20. package/dist/hooks/useChatMode.esm.js.map +1 -0
  21. package/dist/index.cjs.js +1 -1
  22. package/dist/index.d.ts +18 -11
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.esm.js +9 -18
  25. package/dist/index.esm.js.map +1 -1
  26. package/dist/node_modules/jose/dist/browser/lib/check_key_type.cjs.js.map +1 -1
  27. package/dist/node_modules/react-dom/client.cjs.js +2 -0
  28. package/dist/node_modules/react-dom/client.cjs.js.map +1 -0
  29. package/dist/node_modules/react-dom/client.esm.js +21 -0
  30. package/dist/node_modules/react-dom/client.esm.js.map +1 -0
  31. package/dist/services/dialogflowClient.cjs.js.map +1 -1
  32. package/dist/services/dialogflowClient.d.ts.map +1 -1
  33. package/dist/services/dialogflowClient.esm.js.map +1 -1
  34. package/dist/styles.css +1 -0
  35. package/dist/utils/frameworkDetector.cjs.js +2 -0
  36. package/dist/utils/frameworkDetector.cjs.js.map +1 -0
  37. package/dist/utils/frameworkDetector.esm.js +125 -0
  38. package/dist/utils/frameworkDetector.esm.js.map +1 -0
  39. package/dist/utils/sanitize.cjs.js +1 -1
  40. package/dist/utils/sanitize.cjs.js.map +1 -1
  41. package/dist/utils/sanitize.esm.js +1 -6
  42. package/dist/utils/sanitize.esm.js.map +1 -1
  43. package/dist/vue.esm.js +3 -3
  44. package/package.json +20 -16
  45. package/dist/utils/ssr.cjs.js +0 -2
  46. package/dist/utils/ssr.cjs.js.map +0 -1
  47. package/dist/utils/ssr.esm.js +0 -48
  48. package/dist/utils/ssr.esm.js.map +0 -1
package/README.md CHANGED
@@ -1,8 +1,6 @@
1
1
  # BlockSpark Chat Widget
2
2
 
3
- A universal JavaScript chat widget library that connects directly with Dialogflow CX - no backend API required!
4
-
5
- **Supports:** React, Next.js, Vue.js, Nuxt, Vite, and Vanilla JavaScript
3
+ A reusable React chat widget component that connects directly with Dialogflow CX - no backend API required!
6
4
 
7
5
  ## Installation
8
6
 
@@ -32,12 +30,12 @@ npm link @blockspark/chat-widget
32
30
  npm run build
33
31
 
34
32
  # Publish to npm (make sure you're logged in)
35
- npm publish --access public
33
+ npm publish
36
34
  ```
37
35
 
38
36
  Then install in your project:
39
37
  ```bash
40
- npm install @om_patel_26/chat-widget
38
+ npm install @blockspark/chat-widget
41
39
  ```
42
40
 
43
41
  ## Usage
@@ -46,7 +44,7 @@ npm install @om_patel_26/chat-widget
46
44
 
47
45
  ```bash
48
46
  # Install
49
- npm install @om_patel_26/chat-widget
47
+ npm install @blockspark/chat-widget
50
48
  ```
51
49
 
52
50
  ```vue
@@ -59,73 +57,14 @@ npm install @om_patel_26/chat-widget
59
57
  </template>
60
58
 
61
59
  <script setup>
62
- import ChatWidget from '@om_patel_26/chat-widget/vue';
63
- import '@om_patel_26/chat-widget/dist/styles.css';
60
+ import ChatWidget from '@blockspark/chat-widget/vue';
61
+ import '@blockspark/chat-widget/dist/styles.css';
64
62
  import serviceAccountKey from './service-account-key.json';
65
63
  </script>
66
64
  ```
67
65
 
68
- **⚠️ Vite Users:** If you get a "504 Outdated Optimize Dep" error:
69
- 1. Clear Vite cache: `rm -rf node_modules/.vite && npm run dev`
70
- 2. Or add to `vite.config.ts`:
71
- ```ts
72
- optimizeDeps: {
73
- exclude: ['@om_patel_26/chat-widget'],
74
- }
75
- ```
76
- 3. See [FIX_VITE_504_ERROR.md](./FIX_VITE_504_ERROR.md) for details
77
-
78
66
  **📚 For detailed Vue.js setup guide, see [VUE_INSTALLATION_GUIDE.md](./VUE_INSTALLATION_GUIDE.md)**
79
67
 
80
- ### Nuxt 3 Usage (Important: Use ClientOnly!)
81
-
82
- ```bash
83
- # Install
84
- npm install @om_patel_26/chat-widget
85
- ```
86
-
87
- **⚠️ CRITICAL: The component MUST be wrapped in `<ClientOnly>` for Nuxt SSR!**
88
-
89
- ```vue
90
- <template>
91
- <div>
92
- <ClientOnly>
93
- <ChatWidget
94
- :df-project-id="'your-project-id'"
95
- :df-agent-id="'your-agent-id'"
96
- :service-account-key="serviceAccountKey"
97
- />
98
- <template #fallback>
99
- <div>Loading chat...</div>
100
- </template>
101
- </ClientOnly>
102
- </div>
103
- </template>
104
-
105
- <script setup>
106
- import ChatWidget from '@om_patel_26/chat-widget/nuxt';
107
- import '@om_patel_26/chat-widget/dist/styles.css';
108
- import serviceAccountKey from './service-account-key.json';
109
- </script>
110
- ```
111
-
112
- **In `nuxt.config.ts`:**
113
- ```typescript
114
- export default defineNuxtConfig({
115
- css: ['@om_patel_26/chat-widget/dist/styles.css'],
116
-
117
- vite: {
118
- optimizeDeps: {
119
- exclude: ['@om_patel_26/chat-widget'],
120
- },
121
- },
122
- });
123
- ```
124
-
125
- **Why ClientOnly?** The widget uses browser APIs (`localStorage`, `window`, `WebSocket`) that don't exist during SSR.
126
-
127
- **📚 For detailed Nuxt 3 setup guide, see [NUXT_USAGE.md](./NUXT_USAGE.md)**
128
-
129
68
  ---
130
69
 
131
70
  ### React/Next.js Usage
@@ -133,8 +72,8 @@ export default defineNuxtConfig({
133
72
  ### Basic Usage
134
73
 
135
74
  ```tsx
136
- import ChatWidget from '@om_patel_26/chat-widget';
137
- import '@om_patel_26/chat-widget/dist/styles.css';
75
+ import ChatWidget from '@blockspark/chat-widget';
76
+ import '@blockspark/chat-widget/dist/styles.css';
138
77
 
139
78
  // Load your Google Cloud service account key
140
79
  import serviceAccountKey from './path/to/service-account-key.json';
@@ -159,8 +98,8 @@ function App() {
159
98
  If you prefer to manage authentication yourself:
160
99
 
161
100
  ```tsx
162
- import ChatWidget from '@om_patel_26/chat-widget';
163
- import '@om_patel_26/chat-widget/dist/styles.css';
101
+ import ChatWidget from '@blockspark/chat-widget';
102
+ import '@blockspark/chat-widget/dist/styles.css';
164
103
 
165
104
  function App() {
166
105
  const [accessToken, setAccessToken] = useState<string>('');
@@ -186,8 +125,8 @@ function App() {
186
125
  ### With Custom Configuration
187
126
 
188
127
  ```tsx
189
- import ChatWidget from '@om_patel_26/chat-widget';
190
- import '@om_patel_26/chat-widget/dist/styles.css';
128
+ import ChatWidget from '@blockspark/chat-widget';
129
+ import '@blockspark/chat-widget/dist/styles.css';
191
130
  import serviceAccountKey from './service-account-key.json';
192
131
 
193
132
  function App() {
@@ -252,7 +191,7 @@ The widget displays mode indicators and connection status in the chat header.
252
191
  ### Import Types (TypeScript)
253
192
 
254
193
  ```tsx
255
- import ChatWidget, { ChatWidgetProps, DialogflowConfig } from '@om_patel_26/chat-widget';
194
+ import ChatWidget, { ChatWidgetProps, DialogflowConfig } from '@blockspark/chat-widget';
256
195
  ```
257
196
 
258
197
  ## Props
@@ -292,19 +231,11 @@ The widget connects **directly** to Dialogflow CX using the REST API - no backen
292
231
 
293
232
  ## Requirements
294
233
 
295
- ### For React/Next.js/Vite/Vanilla.js
296
- - React 16.8.0 or higher (peer dependency)
297
- - React DOM 16.8.0 or higher (peer dependency)
234
+ - React 16.8.0 or higher
235
+ - React DOM 16.8.0 or higher
298
236
  - Google Cloud service account with Dialogflow API enabled
299
237
  - Dialogflow CX agent
300
238
 
301
- ### For Vue.js
302
- - Vue 2.7.0 or higher OR Vue 3.0.0 or higher (peer dependency)
303
- - Google Cloud service account with Dialogflow API enabled
304
- - Dialogflow CX agent
305
-
306
- **Note:** Peer dependencies are optional - install only what you need for your framework.
307
-
308
239
  ## Getting Your Service Account Key
309
240
 
310
241
  1. Go to [Google Cloud Console](https://console.cloud.google.com/)
@@ -326,24 +257,6 @@ The widget connects **directly** to Dialogflow CX using the REST API - no backen
326
257
  - Or use OAuth2 flow to get access tokens securely
327
258
  - Consider using restricted service account keys with minimal permissions
328
259
 
329
- ## Troubleshooting
330
-
331
- ### Vite 504 Error
332
- If you get "504 Outdated Optimize Dep" error in Vite:
333
- - Clear cache: `rm -rf node_modules/.vite && npm run dev`
334
- - See [FIX_VITE_504_ERROR.md](./FIX_VITE_504_ERROR.md) for details
335
-
336
- ### Vue Warning About Attributes
337
- If you see Vue warnings about attributes:
338
- - This is fixed in the latest version
339
- - Ensure you're using the latest package version
340
- - See [FIX_VUE_WARNING.md](./FIX_VUE_WARNING.md) if issues persist
341
-
342
- ### Chat Not Opening
343
- - Check CSS is imported: `import '@om_patel_26/chat-widget/dist/styles.css'`
344
- - Verify Dialogflow config is provided
345
- - Enable debug mode: `:debug="true"` to see console logs
346
-
347
260
  ## Development
348
261
 
349
262
  ```bash
@@ -360,3 +273,4 @@ npm run dev
360
273
  ## License
361
274
 
362
275
  MIT
276
+ export NPM_TOKEN=your_token_here
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("react/jsx-runtime"),t=require("react"),s=require("../services/dialogflowClient.cjs.js"),n=require("../hooks/useChatMode.cjs.js"),a=require("../services/chatService.cjs.js"),o=require("../utils/sanitize.cjs.js");,/* empty css */exports.default=function({title:r="💬 BlockSpark AI Assistant",subtitle:i="We're here to help",welcomeTitle:c="👋 Welcome to Blockspark",welcomeMessage:l="My name is BlockSpark AI Assistant and I'll guide you.",welcomeCta:d="💬 Click here to start chatting!",showWelcomePopup:u=!0,welcomePopupDelay:m=1500,fallbackWelcomeMessage:h="Hello! I'm BlockSpark AI Assistant. How can I help you today?",inputPlaceholder:g="Type your message...",emptyStateMessage:p="Hi! I'm BlockSpark AI Assistant. How can I help you today?",debug:w=!1,dfProjectId:f,dfLocation:x="us-central1",dfAgentId:y,serviceAccountKey:b,accessToken:v,languageCode:j="en",backendBaseUrl:D,backendWsUrl:S}){const[k,C]=t.useState(!1),[_,N]=t.useState(!1),[A,T]=t.useState([]),[$,I]=t.useState(""),[P,M]=t.useState(!1),[E,H]=t.useState(null),[R,B]=t.useState(!1),[U,W]=t.useState(!1),[F,q]=t.useState(!1),[L,z]=t.useState(!1),[K,O]=t.useState({name:"Agent"}),[V,Y]=t.useState(!1),[G,J]=t.useState(!1),[Q,X]=t.useState(!1),[Z,ee]=t.useState(!1),[te,se]=t.useState(null),[ne,ae]=t.useState(""),[oe,re]=t.useState(""),[ie,ce]=t.useState(""),le=t.useRef(""),de=t.useRef(null),ue=t.useRef(null),me=t.useRef(null),he=t.useRef(a.createChatService({baseUrl:D||"undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_BASE_URL,wsUrl:S||"undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_WS_URL,debug:w})),ge=t.useRef(null),{currentMode:pe,switchToHumanMode:we,switchToBotMode:fe,chatId:xe,sessionId:ye,setChatId:be,setSessionId:ve}=n.useChatMode(),je=t.useCallback(e=>{J(!0),W(!1),ee(!1),z(!1),me.current&&(clearTimeout(me.current),me.current=null),he.current.disconnectWebSocket(),be(null),ve(null);const t={id:`resolved-${Date.now()}`,text:"Thank you for contacting us!",sender:"bot",timestamp:new Date};T(e=>[...e,t]),setTimeout(()=>{fe(),J(!1),T([]),Y(!1),se(null),ae(""),re(""),ce(""),le.current="",Ae().catch(console.error)},2e3)},[be,ve,fe]);t.useCallback(async()=>{if(!Q){X(!0);try{const e=le.current||ne||null,t=oe||null,s=ie||null,n=await he.current.startSupportChat(E||null,e,t,s);we(),be(n.chat_id),ve(n.session_id),J(!1),I("")}catch(e){T(t=>[...t,{id:`error-new-chat-${Date.now()}`,text:w?`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{X(!1)}}},[oe,ie,ne,w,Q,E,be,ve,we]);const De=()=>{if(f&&y)return{dfProjectId:f,dfLocation:x||"us-central1",dfAgentId:y,serviceAccountKey:b,accessToken:v,languageCode:j||"en"}};t.useEffect(()=>{if(!u)return;const e=setTimeout(()=>{N(!0)},m);return()=>clearTimeout(e)},[u,m]),t.useEffect(()=>{de.current?.scrollIntoView({behavior:"smooth"})},[A]);const Se=t.useCallback(e=>{if(e.to_agent){O({id:e.to_agent_id,name:e.to_agent});const t={id:`system-${Date.now()}`,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};T(e=>[...e,t])}},[w]),ke=t.useCallback(e=>{switch(e.type){case"message":if(e.content)if("agent"!==e.sender_type&&e.sender_type)w&&e.sender_type;else{const t={id:e.id||`agent-${Date.now()}`,text:e.content,sender:"agent",timestamp:new Date(e.timestamp||Date.now())};T(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),z(!1),me.current&&(clearTimeout(me.current),me.current=null)}break;case"typing_start":"agent"===e.sender_type&&(z(!0),me.current&&clearTimeout(me.current),me.current=setTimeout(()=>{z(!1)},3e3));break;case"typing_stop":"agent"===e.sender_type&&(z(!1),me.current&&(clearTimeout(me.current),me.current=null));break;case"agent_changed":Se(e);break;case"chat_info":"active"===e.status?(W(!1),ee(!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":ee(!0),W(!1);const t={id:e.id||`agent-accepted-${e.chat_id||Date.now()}-${Date.now()}`,text:"You can chat now, the agent has accepted your request.",sender:"bot",timestamp:e.timestamp?new Date(e.timestamp):new Date};T(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 s={id:`error-${Date.now()}`,text:e.error||"An error occurred. Please try again.",sender:"bot",timestamp:new Date};T(e=>[...e,s])}},[w,je,Se]),Ce=t.useCallback(e=>{4e3===e.code&&je(xe)},[xe,je]),_e=t.useCallback(e=>{q(e),e&&W(!1)},[]);t.useEffect(()=>{if("HUMAN"===pe&&xe&&ye)return he.current.connectWebSocket(xe,ye,ke,_e,Ce),()=>{he.current.disconnectWebSocket()}},[pe,xe,ye,ke,_e,Ce]);const Ne=t.useCallback(async(e=!0)=>{if(xe&&ye)try{M(!0);const t=(await he.current.loadMessageHistory(xe,ye)).map(e=>({id:e.id||`msg-${Date.now()}-${Math.random()}`,text:e.content,sender:"agent"===e.sender_type?"agent":"user",timestamp:new Date(e.timestamp)}));T(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(w){const e={id:`error-${Date.now()}`,text:`Failed to load chat history: ${t.message}`,sender:"bot",timestamp:new Date};T(t=>[...t,e])}}finally{M(!1)}},[xe,ye,w]);t.useEffect(()=>{if("HUMAN"===pe&&xe&&ye){const e=`${xe}-${ye}`;if(ge.current!==e){ge.current=e;setTimeout(()=>{0===A.length&&Ne(!1).catch(console.error)},0)}}else"BOT"===pe&&(ge.current=null)},[pe,xe,ye,Ne,A.length]);const Ae=async()=>{if(E)return E;try{B(!0);const e=De();if(!e)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const t=await s.createDialogflowSession(e);if(H(t.session_id),t.message){const e={id:`welcome-${Date.now()}`,text:t.message,sender:"bot",timestamp:new Date,richContent:t.richContent};T([e])}return t.session_id}catch(e){const t={id:`error-${Date.now()}`,text:w?`Error: ${e.message||"Failed to create session. Please check your Dialogflow configuration."}`:h,sender:"bot",timestamp:new Date};return T([t]),null}finally{B(!1)}},Te=async(e,t,n=!1)=>{if(!e.trim())return;if(V){if("name"===te){const t=e.trim();ae(t),le.current=t,se("email");const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};T(e=>[...e,s]);const n={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your email address:",sender:"bot",timestamp:new Date};return T(e=>[...e,n]),void I("")}if("email"===te){const t=e.trim();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){const e={id:(Date.now()+1).toString(),text:"Please provide a valid email address:",sender:"bot",timestamp:new Date};return T(t=>[...t,e]),void I("")}re(t),se("mobile");const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};T(e=>[...e,s]);const n={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your mobile number:",sender:"bot",timestamp:new Date};return T(e=>[...e,n]),void I("")}if("mobile"===te){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:(Date.now()+1).toString(),text:"Please provide a valid mobile number (e.g., +1234567890):",sender:"bot",timestamp:new Date};return T(t=>[...t,e]),void I("")}ce(t);const s={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};T(e=>[...e,s]);const n=le.current,a=oe;return Y(!1),se(null),le.current="",await(async(e,t,s)=>{try{W(!0);const a=E,o=await he.current.ensureChatInitialized(xe,ye,a||null,e||null,t||null,s||null);if(!o||!o.chat_id)throw new Error("Failed to initialize chat session");const r=o.chat_id,i=o.session_id;r!==xe&&(be(r),ve(i));try{await he.current.requestHandoff(r,i,"Customer requested human agent",a||null,e||null,t||null,s||null)}catch(n){if(!(n.message?.includes("Invalid chat_id")||n.message?.includes("Chat not found")||n.message?.includes("unauthorized")||n.message?.includes("400")||n.message?.includes("401")||n.message?.includes("404")||n.message?.includes("expired")))throw n;{be(null),ve(null);const n=await he.current.startSupportChat(a||null,e||null,t||null,s||null);if(!n||!n.chat_id)throw new Error("Failed to re-initialize chat session");const o=n.chat_id,r=n.session_id;be(o),ve(r),await he.current.requestHandoff(o,r,"Customer requested human agent",a||null,e||null,t||null,s||null);const i=`${o}-${r}`;ge.current!==i&&(ge.current=i,await Ne(!0))}}we(),J(!1),ee(!1);const c={id:`connecting-${Date.now()}`,text:"Connecting you to a human agent...",sender:"bot",timestamp:new Date};T(e=>[...e,c]);const l=`${r}-${i}`;ge.current=l}catch(a){const e={id:`error-${Date.now()}`,text:w?`Handoff error: ${a.message}`:"Failed to connect to agent. Please try again.",sender:"bot",timestamp:new Date};T(t=>[...t,e]),W(!1)}})(n,a,t),void I("")}}if("HUMAN"===pe){if(!xe||!ye){const e={id:Date.now().toString(),text:"Chat session not initialized. Please try again.",sender:"bot",timestamp:new Date};return void T(t=>[...t,e])}if(!n){const s={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};T(e=>[...e,s])}he.current.sendTypingIndicator("typing_stop"),ue.current&&(clearTimeout(ue.current),ue.current=null),I(""),M(!0);try{he.current.sendMessageViaWebSocket(e.trim())||await he.current.sendMessageToAgent(xe,ye,e.trim())}catch(r){if(r instanceof a.ChatResolvedError||"ChatResolvedError"===r?.name||"chat_resolved"===r?.message)return void je(xe);if(r.message?.includes("Chat not found")||r.message?.includes("unauthorized")||r.message?.includes("401")||r.message?.includes("404")){be(null),ve(null);try{const t=await he.current.startSupportChat(E||null,null,null,null);be(t.chat_id),ve(t.session_id);try{await he.current.sendMessageToAgent(t.chat_id,t.session_id,e.trim())}catch(i){if(i instanceof a.ChatResolvedError||"ChatResolvedError"===i?.name||"chat_resolved"===i?.message)return void je(t.chat_id);throw i}return}catch(i){if(i instanceof a.ChatResolvedError||"ChatResolvedError"===i?.name||"chat_resolved"===i?.message)return void je(xe);const e={id:(Date.now()+1).toString(),text:w?`Error: ${i.message||"Failed to send message."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};T(t=>[...t,e])}}else{const e={id:(Date.now()+1).toString(),text:w?`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};T(t=>[...t,e])}}finally{M(!1)}return}let o=E;if(!o)try{if(o=await Ae(),!o){const e={id:Date.now().toString(),text:w?"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 T(t=>[...t,e])}}catch(r){const e={id:Date.now().toString(),text:w?`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 T(t=>[...t,e])}if(!n){const s={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};T(e=>[...e,s])}I(""),M(!0);try{const t=De();if(!t)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const n=await s.sendDialogflowMessage(e.trim(),o,t);if(!0===n.handoff){const e={id:(Date.now()+1).toString(),text:n.response,sender:"bot",timestamp:new Date(n.timestamp||Date.now()),richContent:n.richContent};T(t=>[...t,e]),Y(!0),se("name"),ae(""),re(""),le.current="";const t={id:(Date.now()+2).toString(),text:"To connect you with a human agent, I'll need some information. Please provide your name:",sender:"bot",timestamp:new Date};return void T(e=>[...e,t])}const a={id:(Date.now()+1).toString(),text:n.response,sender:"bot",timestamp:new Date(n.timestamp||Date.now()),richContent:n.richContent};T(e=>[...e,a])}catch(r){const e={id:(Date.now()+1).toString(),text:w?`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};T(t=>[...t,e])}finally{M(!1)}};t.useEffect(()=>()=>{ue.current&&clearTimeout(ue.current),me.current&&clearTimeout(me.current)},[]);const $e=async()=>{C(!0),N(!1),E||await Ae()},Ie=e=>e.includes("👤")||e.includes("being connected")||e.includes("live support agent")||e.includes("transfer your conversation")||e.includes("✅")||e.includes("🔄");return t.useEffect(()=>()=>{he.current.disconnectWebSocket()},[]),e.jsxs(e.Fragment,{children:[_&&!k&&e.jsxs("div",{className:"custom-welcome-popup",onClick:$e,children:[e.jsxs("div",{className:"custom-welcome-header",children:[e.jsx("div",{className:"custom-welcome-title",children:c}),e.jsx("button",{className:"custom-close-popup",onClick:e=>{e.stopPropagation(),N(!1)},children:"×"})]}),e.jsx("div",{className:"custom-welcome-message",children:l}),e.jsx("div",{className:"custom-welcome-cta",children:d})]}),!k&&e.jsx("button",{className:"custom-chat-toggle-btn",onClick:$e,"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"})})}),k&&e.jsxs("div",{className:"custom-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:r}),e.jsxs("div",{className:"custom-chat-subtitle",children:[i,"HUMAN"===pe&&e.jsxs("span",{className:"custom-mode-indicator",children:[" ","• ",F?"🟢 Connected":"🟡 Connecting..."]})]}),"HUMAN"===pe&&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:K.name})]})]}),"BOT"===pe&&e.jsx("div",{className:"custom-mode-badge",children:"Bot Mode"})]}),e.jsx("button",{className:"custom-chat-close-btn",onClick:()=>{C(!1),"HUMAN"===pe&&he.current.disconnectWebSocket()},"aria-label":"Close chat",children:"×"})]}),e.jsxs("div",{className:"custom-chat-messages",children:[R&&0===A.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..."})]}),!R&&0===A.length&&e.jsxs("div",{className:"custom-chat-empty",children:[e.jsx("div",{className:"custom-chat-empty-icon",children:"👋"}),e.jsx("p",{children:p})]}),A.map(t=>e.jsxs("div",{className:`custom-message custom-message-${t.sender} ${Ie(t.text)?"custom-handoff-message":""}`,children:[e.jsx("div",{className:"custom-message-content "+(Ie(t.text)?"custom-handoff-content":""),dangerouslySetInnerHTML:{__html:o.linkifyText(t.text).replace(/\n/g,"<br>")}}),(w&&t.richContent,t.richContent&&Array.isArray(t.richContent)&&t.richContent.length>0?e.jsx("div",{className:"custom-chips-container",children:t.richContent.map((t,s)=>{if(!Array.isArray(t)){const n=t;return n&&"chips"===n.type&&n.options?e.jsx("div",{className:"custom-chips-group",children:n.options.map((t,s)=>e.jsx("button",{className:"custom-chip-button",onClick:()=>{const e={id:Date.now().toString(),text:t.text,sender:"user",timestamp:new Date};T(t=>[...t,e]),Te(t.text,t.text,!0)},type:"button",children:t.text},s))},s):null}return t.map((t,n)=>t&&"chips"===t.type&&t.options?e.jsx("div",{className:"custom-chips-group",children:t.options.map((t,s)=>e.jsx("button",{className:"custom-chip-button",onClick:()=>{const e={id:Date.now().toString(),text:t.text,sender:"user",timestamp:new Date};T(t=>[...t,e]),Te(t.text,t.text,!0)},type:"button",children:t.text},s))},`${s}-${n}`):null)})}):null),e.jsx("div",{className:"custom-message-time",children:t.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]},t.id)),P&&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"===pe&&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:de})]}),e.jsxs("form",{className:"custom-chat-input-form",onSubmit:e=>{e.preventDefault(),Te($)},children:[e.jsx("input",{type:"text",className:"custom-chat-input",value:$,onChange:e=>{const t=e.target.value;I(t),"HUMAN"===pe&&F&&(he.current.sendTypingIndicator("typing_start"),ue.current&&clearTimeout(ue.current),ue.current=setTimeout(()=>{he.current.sendTypingIndicator("typing_stop"),ue.current=null},2e3))},placeholder:g,disabled:P||R||Q}),e.jsx("button",{type:"submit",className:"custom-chat-send-btn",disabled:!$.trim()||P||R||Q,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"})]})})]})]})]})};
2
+ //# sourceMappingURL=ChatWidget.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChatWidget.cjs.js","sources":["../../src/components/ChatWidget.tsx"],"sourcesContent":["import React, { useState, useEffect, useRef, useCallback } from \"react\";\nimport {\n createDialogflowSession,\n sendDialogflowMessage,\n type DialogflowConfig,\n type SessionResponse,\n type ChatResponse,\n} from \"../services/dialogflowClient\";\nimport { useChatMode } from \"../hooks/useChatMode\";\nimport { ChatResolvedError, createChatService, type WebSocketMessage } from \"../services/chatService\";\nimport { linkifyText } from \"../utils/sanitize\";\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 /** Google Cloud service account key JSON object */\n serviceAccountKey?: any;\n /** Access token (alternative to serviceAccountKey) */\n accessToken?: 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}\n\nexport default function ChatWidget({\n title = \"💬 BlockSpark AI Assistant\",\n subtitle = \"We're here to help\",\n welcomeTitle = \"👋 Welcome to Blockspark\",\n welcomeMessage = \"My name is BlockSpark 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 BlockSpark AI Assistant. How can I help you today?\",\n inputPlaceholder = \"Type your message...\",\n emptyStateMessage = \"Hi! I'm BlockSpark AI Assistant. How can I help you today?\",\n debug = false,\n dfProjectId,\n dfLocation = \"us-central1\",\n dfAgentId,\n serviceAccountKey,\n accessToken,\n languageCode = \"en\",\n backendBaseUrl,\n backendWsUrl,\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 \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 \n // Add thank you message before reset\n const thankYouMessage: Message = {\n id: `resolved-${Date.now()}`,\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\n createSession().catch(console.error);\n }, 2000); // 3 second delay to show thank you message\n },\n [setChatId, setSupportSessionId, switchToBotMode]\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: `error-new-chat-${Date.now()}`,\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 = (): DialogflowConfig | undefined => {\n if (!dfProjectId || !dfAgentId) {\n return undefined;\n }\n \n return {\n dfProjectId,\n dfLocation: dfLocation || 'us-central1',\n dfAgentId,\n serviceAccountKey,\n accessToken,\n languageCode: languageCode || 'en',\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: `system-${Date.now()}`,\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 || `agent-${Date.now()}`,\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 || `agent-accepted-${message.chat_id || Date.now()}-${Date.now()}`,\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: `error-${Date.now()}`,\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 || `msg-${Date.now()}-${Math.random()}`,\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: `error-${Date.now()}`,\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 // 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 // Access messages state via a ref or check in the next tick\n const checkAndLoad = () => {\n // Check messages length - if 0, load history; if > 0, preserve existing\n if (messages.length === 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, messages.length]);\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 const currentChatId = session.chat_id;\n const 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 \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: `connecting-${Date.now()}`,\n text: \"Connecting you to a human agent...\",\n sender: \"bot\",\n timestamp: new Date(),\n };\n setMessages((prev) => [...prev, connectingMessage]);\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: `error-${Date.now()}`,\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 () => {\n if (sessionId) return sessionId;\n\n try {\n setIsInitializing(true);\n const dfConfig = getDialogflowConfig();\n if (!dfConfig) {\n throw new Error('Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.');\n }\n \n const data = await createDialogflowSession(dfConfig);\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: `welcome-${Date.now()}`,\n text: data.message,\n sender: \"bot\",\n timestamp: new Date(),\n richContent: data.richContent,\n };\n setMessages([welcomeMessage]);\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: `error-${Date.now()}`,\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([errorMessage]);\n return null;\n } finally {\n setIsInitializing(false);\n }\n };\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: Date.now().toString(),\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: (Date.now() + 1).toString(),\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: (Date.now() + 1).toString(),\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: Date.now().toString(),\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: (Date.now() + 1).toString(),\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: (Date.now() + 1).toString(),\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: Date.now().toString(),\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: Date.now().toString(),\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: Date.now().toString(),\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: (Date.now() + 1).toString(),\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: (Date.now() + 1).toString(),\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: Date.now().toString(),\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: Date.now().toString(),\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: Date.now().toString(),\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, dfAgentId, and either serviceAccountKey or accessToken.');\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\n const botMessage: Message = {\n id: (Date.now() + 1).toString(),\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 // 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: (Date.now() + 2).toString(),\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 const botMessage: Message = {\n id: (Date.now() + 1).toString(),\n text: data.response,\n sender: \"bot\",\n timestamp: new Date(data.timestamp || Date.now()),\n richContent: data.richContent,\n };\n\n setMessages((prev) => [...prev, botMessage]);\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: (Date.now() + 1).toString(),\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\">\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\">\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).replace(/\\n/g, \"<br>\") \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: Date.now().toString(),\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: Date.now().toString(),\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 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} "],"names":["title","subtitle","welcomeTitle","welcomeMessage","welcomeCta","showWelcomePopup","enableWelcomePopup","welcomePopupDelay","fallbackWelcomeMessage","inputPlaceholder","emptyStateMessage","debug","dfProjectId","dfLocation","dfAgentId","serviceAccountKey","accessToken","languageCode","backendBaseUrl","backendWsUrl","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","chatServiceRef","createChatService","baseUrl","process","env","REACT_APP_BACKEND_BASE_URL","wsUrl","REACT_APP_BACKEND_WS_URL","historyLoadedRef","currentMode","switchToHumanMode","switchToBotMode","chatId","supportSessionId","setChatId","setSupportSessionId","useChatMode","enterResolvedState","useCallback","_resolvedChatId","current","clearTimeout","disconnectWebSocket","thankYouMessage","id","Date","now","text","sender","timestamp","prev","setTimeout","createSession","catch","console","error","async","customerName","customerEmail","customerMobile","newSession","startSupportChat","chat_id","session_id","message","getDialogflowConfig","useEffect","timer","scrollIntoView","behavior","handleAgentChanged","to_agent","to_agent_id","systemMessage","from_agent","handleWebSocketMessage","type","content","sender_type","agentMessage","Set","map","m","has","status","agent_id","acceptedMessage","errorMessage","handleWebSocketClose","event","code","handleConnectionChange","connected","connectWebSocket","loadMessageHistory","preserveExisting","historyMessages","msg","Math","random","prevMessages","existingIds","newMessages","filter","sort","a","b","getTime","sessionKey","length","dfConfig","Error","data","createDialogflowSession","richContent","sendMessage","displayText","skipUserMessage","trim","userMessage","toString","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","botMessage","response","namePrompt","openChat","isHandoffMessage","jsxs","Fragment","children","className","onClick","jsx","e","stopPropagation","width","height","viewBox","fill","stroke","strokeWidth","strokeLinecap","strokeLinejoin","d","dangerouslySetInnerHTML","__html","linkifyText","replace","Array","isArray","contentGroup","groupIndex","options","chip","chipIndex","contentIndex","toLocaleTimeString","hour","minute","ref","onS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