@blockspark/chat-widget 1.0.8 → 1.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -123
- package/dist/ChatWidget-DFIQ9wIN.js +2 -0
- package/dist/ChatWidget-DFIQ9wIN.js.map +1 -0
- package/dist/{core/stateManager.esm.js → ChatWidget-DqEGRWH3.mjs} +450 -4
- package/dist/ChatWidget-DqEGRWH3.mjs.map +1 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +1338 -7
- package/dist/index.esm.js.map +1 -1
- package/dist/nuxt.cjs.js +1 -1
- package/dist/nuxt.esm.js +4 -5
- package/dist/nuxt.esm.js.map +1 -1
- package/dist/sanitize-7Fj9oshH.js +3 -0
- package/dist/sanitize-7Fj9oshH.js.map +1 -0
- package/dist/sanitize-BNRb-K3t.mjs +2847 -0
- package/dist/sanitize-BNRb-K3t.mjs.map +1 -0
- package/dist/utils/frameworkDetector.d.ts.map +1 -1
- package/dist/utils/sanitize.d.ts.map +1 -1
- package/dist/vue.cjs.js +1 -1
- package/dist/vue.esm.js +4 -5
- package/dist/vue.esm.js.map +1 -1
- package/package.json +1 -1
- package/dist/_virtual/_plugin-vue_export-helper.cjs.js +0 -2
- package/dist/_virtual/_plugin-vue_export-helper.cjs.js.map +0 -1
- package/dist/_virtual/_plugin-vue_export-helper.esm.js +0 -11
- package/dist/_virtual/_plugin-vue_export-helper.esm.js.map +0 -1
- package/dist/components/ChatWidget.cjs.js +0 -2
- package/dist/components/ChatWidget.cjs.js.map +0 -1
- package/dist/components/ChatWidget.esm.js +0 -1129
- package/dist/components/ChatWidget.esm.js.map +0 -1
- package/dist/components/ChatWidget.vue.cjs.js +0 -2
- package/dist/components/ChatWidget.vue.cjs.js.map +0 -1
- package/dist/components/ChatWidget.vue.cjs2.js +0 -2
- package/dist/components/ChatWidget.vue.cjs2.js.map +0 -1
- package/dist/components/ChatWidget.vue.esm.js +0 -8
- package/dist/components/ChatWidget.vue.esm.js.map +0 -1
- package/dist/components/ChatWidget.vue.esm2.js +0 -374
- package/dist/components/ChatWidget.vue.esm2.js.map +0 -1
- package/dist/composables/useChatWidget.cjs.js +0 -2
- package/dist/composables/useChatWidget.cjs.js.map +0 -1
- package/dist/composables/useChatWidget.esm.js +0 -75
- package/dist/composables/useChatWidget.esm.js.map +0 -1
- package/dist/core/stateManager.cjs.js +0 -2
- package/dist/core/stateManager.cjs.js.map +0 -1
- package/dist/core/stateManager.esm.js.map +0 -1
- package/dist/entry/vanilla.cjs.js +0 -2
- package/dist/entry/vanilla.cjs.js.map +0 -1
- package/dist/entry/vanilla.esm.js +0 -50
- package/dist/entry/vanilla.esm.js.map +0 -1
- package/dist/hooks/useChatMode.cjs.js +0 -2
- package/dist/hooks/useChatMode.cjs.js.map +0 -1
- package/dist/hooks/useChatMode.esm.js +0 -61
- package/dist/hooks/useChatMode.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/jws/compact/sign.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/jws/compact/sign.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/jws/compact/sign.esm.js +0 -21
- package/dist/node_modules/jose/dist/browser/jws/compact/sign.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/jws/flattened/sign.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/jws/flattened/sign.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/jws/flattened/sign.esm.js +0 -84
- package/dist/node_modules/jose/dist/browser/jws/flattened/sign.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/jwt/produce.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/jwt/produce.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/jwt/produce.esm.js +0 -72
- package/dist/node_modules/jose/dist/browser/jwt/produce.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/jwt/sign.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/jwt/sign.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/jwt/sign.esm.js +0 -22
- package/dist/node_modules/jose/dist/browser/jwt/sign.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/key/import.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/key/import.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/key/import.esm.js +0 -11
- package/dist/node_modules/jose/dist/browser/key/import.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/buffer_utils.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/lib/buffer_utils.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/buffer_utils.esm.js +0 -18
- package/dist/node_modules/jose/dist/browser/lib/buffer_utils.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/check_key_type.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/lib/check_key_type.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/check_key_type.esm.js +0 -77
- package/dist/node_modules/jose/dist/browser/lib/check_key_type.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/crypto_key.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/lib/crypto_key.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/crypto_key.esm.js +0 -101
- package/dist/node_modules/jose/dist/browser/lib/crypto_key.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/epoch.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/lib/epoch.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/epoch.esm.js +0 -5
- package/dist/node_modules/jose/dist/browser/lib/epoch.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/invalid_key_input.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/lib/invalid_key_input.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/invalid_key_input.esm.js +0 -32
- package/dist/node_modules/jose/dist/browser/lib/invalid_key_input.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/is_disjoint.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/lib/is_disjoint.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/is_disjoint.esm.js +0 -25
- package/dist/node_modules/jose/dist/browser/lib/is_disjoint.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/is_jwk.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/lib/is_jwk.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/is_jwk.esm.js +0 -20
- package/dist/node_modules/jose/dist/browser/lib/is_jwk.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/is_object.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/lib/is_object.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/is_object.esm.js +0 -20
- package/dist/node_modules/jose/dist/browser/lib/is_object.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/secs.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/lib/secs.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/secs.esm.js +0 -59
- package/dist/node_modules/jose/dist/browser/lib/secs.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/validate_crit.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/lib/validate_crit.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/lib/validate_crit.esm.js +0 -34
- package/dist/node_modules/jose/dist/browser/lib/validate_crit.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/asn1.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/runtime/asn1.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/asn1.esm.js +0 -103
- package/dist/node_modules/jose/dist/browser/runtime/asn1.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/base64url.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/runtime/base64url.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/base64url.esm.js +0 -43
- package/dist/node_modules/jose/dist/browser/runtime/base64url.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/check_key_length.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/runtime/check_key_length.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/check_key_length.esm.js +0 -12
- package/dist/node_modules/jose/dist/browser/runtime/check_key_length.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/get_sign_verify_key.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/runtime/get_sign_verify_key.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/get_sign_verify_key.esm.js +0 -25
- package/dist/node_modules/jose/dist/browser/runtime/get_sign_verify_key.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/is_key_like.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/runtime/is_key_like.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/is_key_like.esm.js +0 -13
- package/dist/node_modules/jose/dist/browser/runtime/is_key_like.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/jwk_to_key.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/runtime/jwk_to_key.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/jwk_to_key.esm.js +0 -107
- package/dist/node_modules/jose/dist/browser/runtime/jwk_to_key.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/normalize_key.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/runtime/normalize_key.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/normalize_key.esm.js +0 -71
- package/dist/node_modules/jose/dist/browser/runtime/normalize_key.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/sign.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/runtime/sign.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/sign.esm.js +0 -14
- package/dist/node_modules/jose/dist/browser/runtime/sign.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/subtle_dsa.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/runtime/subtle_dsa.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/subtle_dsa.esm.js +0 -32
- package/dist/node_modules/jose/dist/browser/runtime/subtle_dsa.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/webcrypto.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/runtime/webcrypto.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/runtime/webcrypto.esm.js +0 -7
- package/dist/node_modules/jose/dist/browser/runtime/webcrypto.esm.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/util/errors.cjs.js +0 -2
- package/dist/node_modules/jose/dist/browser/util/errors.cjs.js.map +0 -1
- package/dist/node_modules/jose/dist/browser/util/errors.esm.js +0 -131
- package/dist/node_modules/jose/dist/browser/util/errors.esm.js.map +0 -1
- package/dist/node_modules/react-dom/client.cjs.js +0 -2
- package/dist/node_modules/react-dom/client.cjs.js.map +0 -1
- package/dist/node_modules/react-dom/client.esm.js +0 -21
- package/dist/node_modules/react-dom/client.esm.js.map +0 -1
- package/dist/services/chatService.cjs.js +0 -2
- package/dist/services/chatService.cjs.js.map +0 -1
- package/dist/services/chatService.esm.js +0 -482
- package/dist/services/chatService.esm.js.map +0 -1
- package/dist/services/dialogflowClient.cjs.js +0 -2
- package/dist/services/dialogflowClient.cjs.js.map +0 -1
- package/dist/services/dialogflowClient.esm.js +0 -282
- package/dist/services/dialogflowClient.esm.js.map +0 -1
- package/dist/services/sessionManager.cjs.js +0 -2
- package/dist/services/sessionManager.cjs.js.map +0 -1
- package/dist/services/sessionManager.esm.js +0 -48
- package/dist/services/sessionManager.esm.js.map +0 -1
- package/dist/utils/frameworkDetector.cjs.js +0 -2
- package/dist/utils/frameworkDetector.cjs.js.map +0 -1
- package/dist/utils/frameworkDetector.esm.js +0 -125
- package/dist/utils/frameworkDetector.esm.js.map +0 -1
- package/dist/utils/sanitize.cjs.js +0 -2
- package/dist/utils/sanitize.cjs.js.map +0 -1
- package/dist/utils/sanitize.esm.js +0 -52
- package/dist/utils/sanitize.esm.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ChatWidget-DqEGRWH3.mjs","sources":["../src/core/stateManager.ts","../src/composables/useChatWidget.ts","../src/components/ChatWidget.vue"],"sourcesContent":["/**\n * State Manager - Framework Agnostic\n * Manages widget state independently of framework\n */\n\nimport type { WidgetState, WidgetConfig, ChatMessage } from './types';\nimport {\n createDialogflowSession,\n sendDialogflowMessage,\n type DialogflowConfig,\n} from '../services/dialogflowClient';\nimport { \n createChatService, \n ChatResolvedError,\n type WebSocketMessage\n} from '../services/chatService';\n\nexport class WidgetStateManager {\n private state: WidgetState;\n private config: WidgetConfig;\n private listeners: Set<(state: WidgetState) => void> = new Set();\n private chatMode: 'ai' | 'human' = 'ai';\n private chatId: string | null = null;\n private supportSessionId: string | null = null;\n private chatService: ReturnType<typeof createChatService> | null = null;\n \n // User info collection for handoff\n private collectingUserInfo: boolean = false;\n private userInfoStep: 'name' | 'email' | 'mobile' | null = null;\n private collectedUserName: string = '';\n private collectedUserEmail: string = '';\n private collectedUserMobile: string = '';\n \n // Additional state for human support\n private wsConnected: boolean = false;\n private agentTyping: boolean = false;\n private currentAgent: { name: string; id?: string } = { name: 'Agent' };\n private isConnectingToAgent: boolean = false;\n private agentAccepted: boolean = false;\n private chatResolved: boolean = false;\n private historyLoaded: string | null = null;\n \n // Typing timeout refs (stored as class properties since we can't use refs)\n private typingTimeout: NodeJS.Timeout | null = null;\n private agentTypingTimeout: NodeJS.Timeout | null = null;\n\n constructor(config: WidgetConfig) {\n this.config = config;\n this.state = {\n isOpen: false,\n showWelcomePopup: false,\n messages: [],\n inputValue: '',\n isLoading: false,\n error: null,\n sessionId: null,\n chatMode: 'ai',\n };\n \n // Initialize ChatService\n this.chatService = createChatService({\n baseUrl: this.config.backendBaseUrl || 'http://localhost:8012',\n wsUrl: this.config.backendWsUrl || 'ws://localhost:8012',\n debug: this.config.debug || false,\n });\n \n // Load chat mode and chat IDs from localStorage if available\n if (typeof window !== 'undefined' && window.localStorage) {\n const savedMode = localStorage.getItem('blockspark_chat_mode');\n this.chatMode = savedMode === 'HUMAN' ? 'human' : 'ai';\n this.state.chatMode = this.chatMode;\n \n this.chatId = localStorage.getItem('blockspark_chat_id');\n this.supportSessionId = localStorage.getItem('blockspark_session_id');\n }\n }\n\n /**\n * Subscribe to state changes\n */\n subscribe(listener: (state: WidgetState) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Get current state\n */\n getState(): WidgetState {\n return { ...this.state };\n }\n\n /**\n * Update state and notify listeners\n */\n private setState(updates: Partial<WidgetState>): void {\n this.state = { ...this.state, ...updates };\n this.listeners.forEach(listener => listener(this.getState()));\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<WidgetConfig>): void {\n this.config = { ...this.config, ...config };\n }\n\n /**\n * Open chat\n */\n async openChat(): Promise<void> {\n this.setState({ isOpen: true });\n if (this.state.showWelcomePopup) {\n this.setState({ showWelcomePopup: false });\n }\n \n // Initialize Dialogflow session when chat opens (if in AI mode and no session exists)\n if (this.state.chatMode === 'ai' && !this.state.sessionId && this.config.dfProjectId && this.config.dfAgentId) {\n try {\n this.setState({ isLoading: true });\n const dialogflowConfig: DialogflowConfig = {\n dfProjectId: this.config.dfProjectId,\n dfLocation: this.config.dfLocation || 'us-central1',\n dfAgentId: this.config.dfAgentId,\n serviceAccountKey: this.config.serviceAccountKey,\n accessToken: this.config.accessToken,\n languageCode: this.config.languageCode || 'en',\n };\n \n const session = await createDialogflowSession(dialogflowConfig);\n this.setState({ \n sessionId: session.session_id,\n isLoading: false,\n });\n \n // Add welcome message from Dialogflow if available\n if (session.message) {\n const welcomeMessage: ChatMessage = {\n id: `welcome-${Date.now()}`,\n text: session.message,\n sender: 'bot',\n timestamp: new Date(),\n richContent: session.richContent,\n };\n this.setState({\n messages: [welcomeMessage],\n });\n }\n } catch (error: any) {\n console.error('Error initializing Dialogflow session:', error);\n this.setState({ \n isLoading: false,\n error: error.message || 'Failed to initialize chat',\n });\n \n // Show fallback welcome message\n const fallbackMessage: ChatMessage = {\n id: `fallback-${Date.now()}`,\n text: this.config.fallbackWelcomeMessage || 'Hello! How can I help you today?',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [fallbackMessage],\n });\n }\n }\n }\n\n /**\n * Close chat\n */\n closeChat(): void {\n this.setState({ isOpen: false });\n }\n\n /**\n * Close welcome popup\n */\n closeWelcomePopup(): void {\n this.setState({ showWelcomePopup: false });\n }\n\n /**\n * Toggle chat\n */\n toggleChat(): void {\n const willBeOpen = !this.state.isOpen;\n this.setState({ isOpen: willBeOpen });\n if (willBeOpen && this.state.showWelcomePopup) {\n this.setState({ showWelcomePopup: false });\n }\n }\n\n /**\n * Set input value\n */\n setInputValue(value: string): void {\n this.setState({ inputValue: value });\n }\n\n /**\n * Clear error\n */\n clearError(): void {\n this.setState({ error: null });\n }\n\n /**\n * Send message\n */\n async sendMessage(text: string, skipUserMessage: boolean = false): Promise<void> {\n if (!text.trim() || this.state.isLoading) {\n return;\n }\n\n // Handle user info collection for handoff\n if (this.collectingUserInfo) {\n // Add user message first so it appears in chat\n const userMessage: ChatMessage = {\n id: `user-${Date.now()}`,\n text: text.trim(),\n sender: 'user',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, userMessage],\n inputValue: '',\n isLoading: false,\n error: null,\n });\n \n // Then handle the info collection\n await this.handleUserInfoCollection(text);\n return;\n }\n\n // Add user message unless skipped (e.g., when chip button already added it)\n if (!skipUserMessage) {\n const userMessage: ChatMessage = {\n id: `user-${Date.now()}`,\n text: text.trim(),\n sender: 'user',\n timestamp: new Date(),\n };\n\n this.setState({\n messages: [...this.state.messages, userMessage],\n inputValue: '',\n isLoading: true,\n error: null,\n });\n } else {\n this.setState({\n inputValue: '',\n isLoading: true,\n error: null,\n });\n }\n\n try {\n if (this.state.chatMode === 'human') {\n // Human support mode\n await this.sendHumanMessage(text);\n } else {\n // AI mode (Dialogflow)\n await this.sendAIMessage(text);\n }\n } catch (error: any) {\n console.error('Error sending message:', error);\n \n // chat_resolved is a normal terminal condition, not an error\n if (error instanceof ChatResolvedError || error?.name === 'ChatResolvedError' || error?.message === 'chat_resolved') {\n this.enterResolvedState(this.chatId);\n return;\n }\n \n // Add error message to chat\n const errorMessage: ChatMessage = {\n id: `error-${Date.now()}`,\n text: this.config.debug \n ? `Error: ${error.message || 'Failed to send message'}`\n : error.message?.includes('CORS') || error.message?.includes('Failed to fetch')\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 \n this.setState({\n messages: [...this.state.messages, errorMessage],\n error: error.message || 'Failed to send message',\n isLoading: false,\n });\n }\n }\n\n /**\n * Send message to Dialogflow\n */\n private async sendAIMessage(text: string): Promise<void> {\n if (!this.config.dfProjectId || !this.config.dfAgentId) {\n throw new Error('Dialogflow configuration is missing');\n }\n\n const dialogflowConfig: DialogflowConfig = {\n dfProjectId: this.config.dfProjectId!,\n dfLocation: this.config.dfLocation || 'us-central1',\n dfAgentId: this.config.dfAgentId!,\n serviceAccountKey: this.config.serviceAccountKey,\n accessToken: this.config.accessToken,\n languageCode: this.config.languageCode || 'en',\n };\n\n // Create session if needed\n if (!this.state.sessionId) {\n const session = await createDialogflowSession(dialogflowConfig);\n this.setState({ sessionId: session.session_id });\n }\n\n // Send message (correct parameter order: message, sessionId, config)\n if (this.config.debug) {\n console.log('Sending message to Dialogflow:', {\n message: text,\n sessionId: this.state.sessionId,\n hasConfig: !!dialogflowConfig,\n });\n }\n \n const response = await sendDialogflowMessage(\n text,\n this.state.sessionId!,\n dialogflowConfig\n );\n\n if (this.config.debug) {\n console.log('Dialogflow response:', {\n response: response.response,\n hasRichContent: !!response.richContent,\n richContent: response.richContent,\n });\n }\n\n // Check for handoff\n if (response.handoff === true) {\n // Add bot response first\n const botMessage: ChatMessage = {\n id: `bot-${Date.now()}`,\n text: response.response || this.config.fallbackWelcomeMessage || 'No response',\n sender: 'bot',\n timestamp: new Date(),\n richContent: response.richContent,\n };\n this.setState({\n messages: [...this.state.messages, botMessage],\n isLoading: false,\n });\n \n // Start collecting user info for handoff\n this.startUserInfoCollection();\n return;\n }\n \n const botMessage: ChatMessage = {\n id: `bot-${Date.now()}`,\n text: response.response || this.config.fallbackWelcomeMessage || 'No response',\n sender: 'bot',\n timestamp: new Date(),\n richContent: response.richContent,\n };\n\n this.setState({\n messages: [...this.state.messages, botMessage],\n isLoading: false,\n });\n }\n\n /**\n * Send message to human support\n */\n private async sendHumanMessage(text: string): Promise<void> {\n if (!this.chatId || !this.supportSessionId) {\n const errorMessage: ChatMessage = {\n id: `error-${Date.now()}`,\n text: 'Chat session not initialized. Please try again.',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, errorMessage],\n isLoading: false,\n });\n return;\n }\n\n if (!this.chatService) {\n throw new Error('Chat service not initialized');\n }\n\n // Send typing_stop before sending message\n this.chatService.sendTypingIndicator('typing_stop');\n if (this.typingTimeout) {\n clearTimeout(this.typingTimeout);\n this.typingTimeout = null;\n }\n\n try {\n // Try WebSocket first, fallback to REST API\n const sentViaWs = this.chatService.sendMessageViaWebSocket(text.trim());\n \n if (!sentViaWs) {\n // Fallback to REST API\n await this.chatService.sendMessageToAgent(this.chatId, this.supportSessionId, text.trim());\n }\n \n this.setState({ isLoading: false });\n } catch (error: any) {\n // chat_resolved is a normal terminal condition, not an error\n if (error instanceof ChatResolvedError || error?.name === 'ChatResolvedError' || error?.message === 'chat_resolved') {\n this.enterResolvedState(this.chatId);\n return;\n }\n\n // Handle 401/404 - clear chat_id and reinitialize\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 (this.config.debug) {\n console.log('⚠️ Chat expired. Re-initializing...');\n }\n \n // Clear chat_id\n this.chatId = null;\n this.supportSessionId = null;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.removeItem('blockspark_chat_id');\n localStorage.removeItem('blockspark_session_id');\n }\n \n // Try to reinitialize chat\n try {\n const newSession = await this.chatService.startSupportChat(\n this.state.sessionId || null,\n null,\n null,\n null\n );\n this.chatId = newSession.chat_id;\n this.supportSessionId = newSession.session_id;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem('blockspark_chat_id', this.chatId);\n localStorage.setItem('blockspark_session_id', this.supportSessionId);\n }\n \n // Retry sending message\n if (this.chatId && this.supportSessionId) {\n await this.chatService.sendMessageToAgent(\n this.chatId,\n this.supportSessionId,\n text.trim()\n );\n }\n this.setState({ isLoading: false });\n return;\n } catch (retryError: any) {\n if (retryError instanceof ChatResolvedError || retryError?.message === 'chat_resolved') {\n this.enterResolvedState(this.chatId);\n return;\n }\n throw retryError;\n }\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Switch to human mode\n */\n switchToHumanMode(): void {\n this.chatMode = 'human';\n this.setState({ chatMode: 'human' });\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem('blockspark_chat_mode', 'HUMAN');\n }\n }\n\n /**\n * Switch to AI mode\n */\n switchToBotMode(): void {\n this.chatMode = 'ai';\n this.setState({ chatMode: 'ai' });\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem('blockspark_chat_mode', 'BOT');\n }\n }\n\n /**\n * Initialize welcome popup\n */\n initializeWelcomePopup(): void {\n if (this.config.showWelcomePopup !== false) {\n const delay = this.config.welcomePopupDelay || 1500;\n setTimeout(() => {\n if (!this.state.isOpen) {\n this.setState({ showWelcomePopup: true });\n }\n }, delay);\n }\n }\n\n /**\n * Start user info collection for handoff\n */\n private startUserInfoCollection(): void {\n this.collectingUserInfo = true;\n this.userInfoStep = 'name';\n this.collectedUserName = '';\n this.collectedUserEmail = '';\n this.collectedUserMobile = '';\n \n // Ask for name\n const namePrompt: ChatMessage = {\n id: `prompt-${Date.now()}`,\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 this.setState({\n messages: [...this.state.messages, namePrompt],\n });\n }\n\n /**\n * Handle user info collection\n */\n private async handleUserInfoCollection(text: string): Promise<void> {\n if (this.userInfoStep === 'name') {\n // Save name and ask for email\n const name = text.trim();\n this.collectedUserName = name;\n this.userInfoStep = 'email';\n \n // Ask for email\n const emailPrompt: ChatMessage = {\n id: `prompt-${Date.now()}`,\n text: 'Thank you! Now please provide your email address:',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, emailPrompt],\n inputValue: '',\n });\n return;\n } else if (this.userInfoStep === 'email') {\n // Validate email format\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: ChatMessage = {\n id: `prompt-${Date.now()}`,\n text: 'Please provide a valid email address:',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, invalidEmailMessage],\n inputValue: '',\n });\n return;\n }\n \n // Save email and ask for mobile\n this.collectedUserEmail = email;\n this.userInfoStep = 'mobile';\n \n // Ask for mobile\n const mobilePrompt: ChatMessage = {\n id: `prompt-${Date.now()}`,\n text: 'Thank you! Now please provide your mobile number:',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, mobilePrompt],\n inputValue: '',\n });\n return;\n } else if (this.userInfoStep === 'mobile') {\n // Validate mobile format\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: ChatMessage = {\n id: `prompt-${Date.now()}`,\n text: 'Please provide a valid mobile number (e.g., +1234567890):',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, invalidMobileMessage],\n inputValue: '',\n });\n return;\n }\n \n // Save mobile and proceed with handoff\n this.collectedUserMobile = mobile;\n \n // Reset collection state\n this.collectingUserInfo = false;\n this.userInfoStep = null;\n \n // Proceed with handoff using collected info\n await this.handleHandoff(this.collectedUserName, this.collectedUserEmail, mobile);\n this.setState({ inputValue: '' });\n }\n }\n\n /**\n * Handle handoff from Dialogflow to human support\n */\n async handleHandoff(customerName?: string, customerEmail?: string, customerMobile?: string): Promise<void> {\n if (!this.chatService) {\n throw new Error('Chat service not initialized');\n }\n\n try {\n this.isConnectingToAgent = true;\n \n // Get Dialogflow session ID if available\n const dialogflowSessionId = this.state.sessionId;\n \n // STEP 1: Ensure chat is initialized\n const session = await this.chatService.ensureChatInitialized(\n this.chatId,\n this.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 !== this.chatId) {\n this.chatId = currentChatId;\n this.supportSessionId = currentSupportSessionId;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem('blockspark_chat_id', this.chatId);\n localStorage.setItem('blockspark_session_id', this.supportSessionId);\n }\n if (this.config.debug) {\n console.log('✅ Chat initialized:', { chatId: currentChatId, sessionId: currentSupportSessionId });\n }\n }\n\n // STEP 2: Request handoff\n try {\n await this.chatService.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 (this.config.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\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 (this.config.debug) {\n console.log('⚠️ Chat expired or not found. Re-initializing chat...');\n }\n \n // Clear old chat_id\n this.chatId = null;\n this.supportSessionId = null;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.removeItem('blockspark_chat_id');\n localStorage.removeItem('blockspark_session_id');\n }\n \n // Create new chat session\n const newSession = await this.chatService.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 this.chatId = newSession.chat_id;\n this.supportSessionId = newSession.session_id;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem('blockspark_chat_id', this.chatId);\n localStorage.setItem('blockspark_session_id', this.supportSessionId);\n }\n \n // Retry handoff with new chat_id\n await this.chatService.requestHandoff(\n this.chatId,\n this.supportSessionId,\n 'Customer requested human agent',\n dialogflowSessionId || null,\n customerName || null,\n customerEmail || null,\n customerMobile || null\n );\n \n if (this.config.debug) {\n console.log('✅ Handoff requested successfully after retry');\n }\n } else {\n throw handoffError;\n }\n }\n\n // Switch to human mode\n this.switchToHumanMode();\n this.chatResolved = false;\n this.agentAccepted = false;\n\n // Add connecting message\n const connectingMessage: ChatMessage = {\n id: `connecting-${Date.now()}`,\n text: 'Connecting you to a human agent...',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, connectingMessage],\n });\n\n // Connect WebSocket with handlers\n if (currentChatId && currentSupportSessionId) {\n this.chatService.connectWebSocket(\n currentChatId,\n currentSupportSessionId,\n (message: WebSocketMessage) => {\n this.handleWebSocketMessage(message);\n },\n (connected: boolean) => {\n this.wsConnected = connected;\n }\n );\n }\n \n this.isConnectingToAgent = false;\n } catch (error: any) {\n console.error('Error handling handoff:', error);\n const errorMessage: ChatMessage = {\n id: `error-${Date.now()}`,\n text: this.config.debug\n ? `Handoff error: ${error.message}`\n : 'Failed to connect to agent. Please try again.',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, errorMessage],\n });\n this.isConnectingToAgent = false;\n }\n }\n\n /**\n * Handle WebSocket messages\n */\n private handleWebSocketMessage(message: WebSocketMessage): void {\n switch (message.type) {\n case 'message':\n if (message.content) {\n // Only display messages from agent\n if (message.sender_type === 'agent' || !message.sender_type) {\n const agentMessage: ChatMessage = {\n id: message.id || `agent-${Date.now()}`,\n text: message.content,\n sender: 'agent',\n timestamp: new Date(message.timestamp || Date.now()),\n };\n \n // Avoid duplicate messages\n const existingIds = new Set(this.state.messages.map(m => m.id));\n if (!existingIds.has(agentMessage.id)) {\n this.setState({\n messages: [...this.state.messages, agentMessage],\n });\n }\n \n // Hide typing indicator when message received\n this.agentTyping = false;\n if (this.agentTypingTimeout) {\n clearTimeout(this.agentTypingTimeout);\n this.agentTypingTimeout = null;\n }\n }\n }\n break;\n\n case 'typing_start':\n if (message.sender_type === 'agent') {\n this.agentTyping = true;\n // Auto-hide after 3 seconds if no message received\n if (this.agentTypingTimeout) {\n clearTimeout(this.agentTypingTimeout);\n }\n this.agentTypingTimeout = setTimeout(() => {\n this.agentTyping = false;\n }, 3000);\n }\n break;\n\n case 'typing_stop':\n if (message.sender_type === 'agent') {\n this.agentTyping = false;\n if (this.agentTypingTimeout) {\n clearTimeout(this.agentTypingTimeout);\n this.agentTypingTimeout = null;\n }\n }\n break;\n\n case 'agent_changed':\n if (message.to_agent) {\n this.currentAgent = {\n id: message.to_agent_id,\n name: message.to_agent,\n };\n\n // Add system message to chat\n const systemMessage: ChatMessage = {\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 this.setState({\n messages: [...this.state.messages, systemMessage],\n });\n }\n break;\n\n case 'agent_accepted':\n this.agentAccepted = true;\n this.isConnectingToAgent = false;\n const acceptedMessage: ChatMessage = {\n id: message.id || `agent-accepted-${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 const existingIds = new Set(this.state.messages.map(m => m.id));\n if (!existingIds.has(acceptedMessage.id)) {\n this.setState({\n messages: [...this.state.messages, acceptedMessage],\n });\n }\n if (message.to_agent) {\n this.currentAgent = {\n name: message.to_agent,\n id: message.to_agent_id,\n };\n }\n break;\n\n case 'chat_resolved':\n case 'chat_ended':\n this.enterResolvedState(message.chat_id || null);\n break;\n\n case 'chat_info':\n if (message.status === 'active') {\n this.isConnectingToAgent = false;\n this.agentAccepted = true;\n } else if (message.status === 'resolved' || message.status === 'ended') {\n this.enterResolvedState(message.chat_id || null);\n }\n if (message.agent_id) {\n this.currentAgent = {\n ...this.currentAgent,\n id: message.agent_id,\n };\n }\n break;\n\n case 'error':\n console.error('WebSocket error:', message.error);\n const errorMessage: ChatMessage = {\n id: `error-${Date.now()}`,\n text: message.error || 'An error occurred. Please try again.',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, errorMessage],\n });\n break;\n }\n }\n\n /**\n * Enter resolved state\n */\n private enterResolvedState(resolvedChatId?: string | null): void {\n this.chatResolved = true;\n this.isConnectingToAgent = false;\n this.agentAccepted = false;\n this.agentTyping = false;\n if (this.agentTypingTimeout) {\n clearTimeout(this.agentTypingTimeout);\n this.agentTypingTimeout = null;\n }\n\n // Stop WS + prevent any reuse of the old chat_id\n if (this.chatService) {\n this.chatService.disconnectWebSocket();\n }\n this.chatId = null;\n this.supportSessionId = null;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.removeItem('blockspark_chat_id');\n localStorage.removeItem('blockspark_session_id');\n }\n \n // Add thank you message before reset\n const thankYouMessage: ChatMessage = {\n id: `resolved-${Date.now()}`,\n text: 'Thank you for contacting us!',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, thankYouMessage],\n });\n \n // Automatically reset to BOT mode after showing thank you message\n setTimeout(async () => {\n this.switchToBotMode();\n this.chatResolved = false;\n this.setState({\n messages: [],\n sessionId: null, // Clear session ID to force recreation\n });\n this.collectingUserInfo = false;\n this.userInfoStep = null;\n this.collectedUserName = '';\n this.collectedUserEmail = '';\n this.collectedUserMobile = '';\n \n // Recreate Dialogflow session to start fresh\n if (this.config.dfProjectId && this.config.dfAgentId && this.state.isOpen) {\n try {\n this.setState({ isLoading: true });\n const dialogflowConfig: DialogflowConfig = {\n dfProjectId: this.config.dfProjectId,\n dfLocation: this.config.dfLocation || 'us-central1',\n dfAgentId: this.config.dfAgentId,\n serviceAccountKey: this.config.serviceAccountKey,\n accessToken: this.config.accessToken,\n languageCode: this.config.languageCode || 'en',\n };\n \n const session = await createDialogflowSession(dialogflowConfig);\n this.setState({ \n sessionId: session.session_id,\n isLoading: false,\n });\n \n // Add welcome message from Dialogflow if available\n if (session.message) {\n const welcomeMessage: ChatMessage = {\n id: `welcome-${Date.now()}`,\n text: session.message,\n sender: 'bot',\n timestamp: new Date(),\n richContent: session.richContent,\n };\n this.setState({\n messages: [welcomeMessage],\n });\n }\n } catch (error: any) {\n console.error('Error recreating Dialogflow session after handoff:', error);\n this.setState({ \n isLoading: false,\n error: error.message || 'Failed to initialize chat',\n });\n \n // Show fallback welcome message\n const fallbackMessage: ChatMessage = {\n id: `fallback-${Date.now()}`,\n text: this.config.fallbackWelcomeMessage || 'Hello! How can I help you today?',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [fallbackMessage],\n });\n }\n }\n }, 2000);\n }\n\n /**\n * Load message history\n */\n async loadMessageHistory(preserveExisting: boolean = false): Promise<void> {\n if (!this.chatService || !this.chatId || !this.supportSessionId) {\n return;\n }\n\n try {\n if (this.chatId && this.supportSessionId) {\n const history = await this.chatService.loadMessageHistory(this.chatId, this.supportSessionId);\n \n const historyMessages: ChatMessage[] = history.map((msg: any) => ({\n id: msg.id || `history-${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 const existingIds = new Set(this.state.messages.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 = [...this.state.messages, ...newMessages].sort((a, b) => \n a.timestamp.getTime() - b.timestamp.getTime()\n );\n \n this.setState({\n messages: combined,\n });\n } else {\n // Replace all messages\n this.setState({\n messages: historyMessages,\n });\n }\n }\n } catch (error: any) {\n console.error('Error loading message history:', error);\n if (this.config.debug) {\n const errorMessage: ChatMessage = {\n id: `error-${Date.now()}`,\n text: `Failed to load chat history: ${error.message}`,\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, errorMessage],\n });\n }\n }\n }\n\n /**\n * Get additional state for UI (not in WidgetState but needed by components)\n */\n getAdditionalState() {\n return {\n wsConnected: this.wsConnected,\n agentTyping: this.agentTyping,\n currentAgent: this.currentAgent,\n isConnectingToAgent: this.isConnectingToAgent,\n agentAccepted: this.agentAccepted,\n chatResolved: this.chatResolved,\n };\n }\n\n /**\n * Cleanup\n */\n destroy(): void {\n if (this.typingTimeout) {\n clearTimeout(this.typingTimeout);\n }\n if (this.agentTypingTimeout) {\n clearTimeout(this.agentTypingTimeout);\n }\n if (this.chatService) {\n this.chatService.disconnectWebSocket();\n }\n this.listeners.clear();\n }\n}\n","/**\n * useChatWidget Composable\n * Headless mode for Vue 3 - use logic without UI\n */\n\nimport { ref, computed, onUnmounted, watch, readonly, type Ref } from 'vue';\nimport { WidgetStateManager } from '../core/stateManager';\nimport type { WidgetConfig, WidgetState, ChatMessage } from '../core/types';\n\nexport interface UseChatWidgetReturn {\n // State\n state: Readonly<Ref<WidgetState>>;\n isOpen: Readonly<Ref<boolean>>;\n messages: Readonly<Ref<ChatMessage[]>>;\n isLoading: Readonly<Ref<boolean>>;\n error: Readonly<Ref<string | null>>;\n chatMode: Readonly<Ref<'ai' | 'human'>>;\n\n // Additional state\n wsConnected: Readonly<Ref<boolean>>;\n agentTyping: Readonly<Ref<boolean>>;\n currentAgent: Readonly<Ref<{ name: string; id?: string }>>;\n isConnectingToAgent: Readonly<Ref<boolean>>;\n\n // Actions\n openChat: () => Promise<void>;\n closeChat: () => void;\n sendMessage: (text: string) => Promise<void>;\n toggleChat: () => Promise<void>;\n setInputValue: (value: string) => void;\n clearError: () => void;\n\n // Manager instance (for advanced usage)\n manager: WidgetStateManager;\n}\n\n/**\n * Headless chat widget composable\n * Use this for custom UI implementations\n */\nexport function useChatWidget(config: WidgetConfig): UseChatWidgetReturn {\n // Create state manager\n const manager = new WidgetStateManager(config);\n\n // Reactive state\n const state = ref<WidgetState>(manager.getState());\n const wsConnected = ref(false);\n const agentTyping = ref(false);\n const currentAgent = ref<{ name: string; id?: string }>({ name: 'Agent' });\n const isConnectingToAgent = ref(false);\n\n // Subscribe to state changes\n const unsubscribe = manager.subscribe((newState) => {\n state.value = { ...newState };\n \n // Update additional state\n const additional = manager.getAdditionalState();\n wsConnected.value = additional.wsConnected;\n agentTyping.value = additional.agentTyping;\n currentAgent.value = additional.currentAgent;\n isConnectingToAgent.value = additional.isConnectingToAgent;\n });\n\n // Computed properties\n const isOpen = computed(() => state.value.isOpen);\n const messages = computed(() => state.value.messages);\n const isLoading = computed(() => state.value.isLoading);\n const error = computed(() => state.value.error);\n const chatMode = computed(() => state.value.chatMode);\n\n // Actions\n const openChat = async () => {\n await manager.openChat();\n };\n\n const closeChat = () => {\n manager.closeChat();\n };\n\n const sendMessage = async (text: string) => {\n await manager.sendMessage(text);\n };\n\n const toggleChat = async () => {\n await manager.toggleChat();\n };\n\n const setInputValue = (value: string) => {\n manager.setInputValue(value);\n };\n\n const clearError = () => {\n manager.clearError();\n };\n\n // Cleanup on unmount\n onUnmounted(() => {\n unsubscribe();\n manager.destroy();\n });\n\n // Watch config changes\n watch(\n () => config,\n (newConfig) => {\n manager.updateConfig(newConfig);\n },\n { deep: true }\n );\n\n return {\n state: state as Readonly<Ref<WidgetState>>,\n isOpen: isOpen as Readonly<Ref<boolean>>,\n messages: messages as Readonly<Ref<ChatMessage[]>>,\n isLoading: isLoading as Readonly<Ref<boolean>>,\n error: error as Readonly<Ref<string | null>>,\n chatMode: chatMode as Readonly<Ref<'ai' | 'human'>>,\n wsConnected: wsConnected as Readonly<Ref<boolean>>,\n agentTyping: agentTyping as Readonly<Ref<boolean>>,\n currentAgent: currentAgent as Readonly<Ref<{ name: string; id?: string }>>,\n isConnectingToAgent: isConnectingToAgent as Readonly<Ref<boolean>>,\n openChat,\n closeChat,\n sendMessage,\n toggleChat,\n setInputValue,\n clearError,\n manager,\n };\n}\n","<template>\n <div class=\"custom-chat-widget\" v-bind=\"$attrs\">\n <!-- Welcome Popup -->\n <div\n v-if=\"state.showWelcomePopup && !state.isOpen\"\n class=\"custom-welcome-popup\"\n @click=\"handleOpenChat\"\n >\n <div class=\"custom-welcome-header\">\n <div class=\"custom-welcome-title\">{{ config.welcomeTitle }}</div>\n <button\n class=\"custom-close-popup\"\n @click.stop=\"handleCloseWelcomePopup\"\n aria-label=\"Close welcome popup\"\n >\n ×\n </button>\n </div>\n <div class=\"custom-welcome-message\">{{ config.welcomeMessage }}</div>\n <div class=\"custom-welcome-cta\">{{ config.welcomeCta }}</div>\n </div>\n\n <!-- Chat Toggle Button -->\n <button\n v-if=\"!state.isOpen\"\n class=\"custom-chat-toggle-btn\"\n @click=\"handleOpenChat\"\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 stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"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 <!-- Chat Window -->\n <div v-if=\"state.isOpen\" class=\"custom-chat-window\">\n <div class=\"custom-chat-header\">\n <div class=\"custom-chat-header-content\">\n <div class=\"custom-chat-title\">{{ config.title }}</div>\n <div class=\"custom-chat-subtitle\">\n {{ config.subtitle }}\n <span v-if=\"state.chatMode === 'human'\" class=\"custom-mode-indicator\">\n • {{ wsConnected ? '🟢 Connected' : '🟡 Connecting...' }}\n </span>\n </div>\n <div v-if=\"state.chatMode === 'human'\" class=\"custom-mode-badge\">\n Human Support Mode\n </div>\n <div v-if=\"state.chatMode === 'human'\" class=\"custom-agent-info\">\n <span class=\"custom-agent-label\">Agent:</span>\n <span class=\"custom-agent-name\">{{ currentAgent.name }}</span>\n </div>\n <div v-if=\"state.chatMode === 'ai'\" class=\"custom-mode-badge\">\n Bot Mode\n </div>\n </div>\n <button\n class=\"custom-chat-close-btn\"\n @click=\"handleCloseChat\"\n aria-label=\"Close chat\"\n >\n ×\n </button>\n </div>\n\n <div class=\"custom-chat-messages\" ref=\"messagesContainer\">\n <!-- Empty State -->\n <div v-if=\"isInitializing && state.messages.length === 0\" class=\"custom-chat-empty\">\n <div class=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n <p>Initializing chat...</p>\n </div>\n <div v-else-if=\"!isInitializing && state.messages.length === 0\" class=\"custom-chat-empty\">\n <div class=\"custom-chat-empty-icon\">👋</div>\n <p>{{ config.emptyStateMessage }}</p>\n </div>\n\n <!-- Messages -->\n <div\n v-for=\"message in state.messages\"\n :key=\"message.id\"\n :class=\"[\n 'custom-message', \n `custom-message-${message.sender}`,\n { 'custom-handoff-message': isHandoffMessage(message.text) }\n ]\"\n >\n <div \n class=\"custom-message-content\"\n :class=\"{ 'custom-handoff-content': isHandoffMessage(message.text) }\"\n v-html=\"safeLinkifyText(message.text).replace(/\\n/g, '<br>')\"\n ></div>\n \n <!-- Rich Content (Chips) -->\n <div\n v-if=\"message.richContent && Array.isArray(message.richContent) && message.richContent.length > 0\"\n class=\"custom-chips-container\"\n >\n <template v-for=\"(contentGroup, groupIndex) in message.richContent\" :key=\"groupIndex\">\n <template v-if=\"!Array.isArray(contentGroup)\">\n <div\n v-if=\"contentGroup.type === 'chips' && contentGroup.options\"\n class=\"custom-chips-group\"\n >\n <button\n v-for=\"(chip, chipIndex) in contentGroup.options\"\n :key=\"chipIndex\"\n class=\"custom-chip-button\"\n type=\"button\"\n @click=\"handleChipClick(chip.text, chip.payload)\"\n >\n {{ chip.text }}\n </button>\n </div>\n </template>\n <template v-else>\n <template\n v-for=\"(content, contentIndex) in contentGroup\"\n :key=\"`${groupIndex}-${contentIndex}`\"\n >\n <div\n v-if=\"content.type === 'chips' && content.options\"\n class=\"custom-chips-group\"\n >\n <button\n v-for=\"(chip, chipIndex) in content.options\"\n :key=\"chipIndex\"\n class=\"custom-chip-button\"\n type=\"button\"\n @click=\"handleChipClick(chip.text, chip.payload)\"\n >\n {{ chip.text }}\n </button>\n </div>\n </template>\n </template>\n </template>\n </div>\n\n <div class=\"custom-message-time\">\n {{ formatTime(message.timestamp) }}\n </div>\n </div>\n\n <!-- Loading Indicator -->\n <div v-if=\"state.isLoading\" class=\"custom-message custom-message-bot\">\n <div class=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n </div>\n\n <!-- Connecting to Agent Indicator -->\n <div v-if=\"isConnectingToAgent\" class=\"custom-message custom-message-bot\">\n <div class=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n <div class=\"custom-message-content\">\n Connecting to agent...\n </div>\n </div>\n\n <!-- Agent Typing Indicator -->\n <div v-if=\"state.chatMode === 'human' && agentTyping\" class=\"custom-agent-typing-indicator\">\n <span class=\"custom-typing-dots\">\n <span></span>\n <span></span>\n <span></span>\n </span>\n <span class=\"custom-typing-text\">Agent is typing...</span>\n </div>\n\n <div ref=\"messagesEndRef\"></div>\n </div>\n\n <!-- Input Form -->\n <form class=\"custom-chat-input-form\" @submit.prevent=\"handleSubmit\">\n <input\n type=\"text\"\n class=\"custom-chat-input\"\n :value=\"state.inputValue\"\n @input=\"handleInput\"\n :placeholder=\"config.inputPlaceholder\"\n :disabled=\"state.isLoading || isInitializing || isStartingNewChat\"\n />\n <button\n type=\"submit\"\n class=\"custom-chat-send-btn\"\n :disabled=\"!state.inputValue.trim() || state.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 stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"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 </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { ref, computed, onMounted, nextTick, watch } from 'vue';\nimport { useChatWidget } from '../composables/useChatWidget';\nimport { safeLinkifyText } from '../utils/sanitize';\nimport type { WidgetConfig } from '../core/types';\n\n// Handle attributes properly to avoid Vue warnings\n// For Vue 3.3+, defineOptions is available as a compiler macro\n// @ts-ignore - defineOptions is a compiler macro\ndefineOptions({\n inheritAttrs: false, // We handle attrs manually via v-bind=\"$attrs\"\n});\n\n// Props\nconst props = withDefaults(defineProps<WidgetConfig>(), {\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: 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});\n\n// Use headless composable\nconst {\n state,\n isOpen,\n messages,\n isLoading,\n error,\n chatMode,\n wsConnected,\n agentTyping,\n currentAgent,\n isConnectingToAgent: isConnectingToAgentFromComposable,\n openChat,\n closeChat,\n sendMessage,\n toggleChat,\n setInputValue,\n clearError,\n manager,\n} = useChatWidget(props);\n\n// Refs\nconst messagesEndRef = ref<HTMLDivElement | null>(null);\nconst messagesContainer = ref<HTMLDivElement | null>(null);\n\n// Computed config (for reactivity)\nconst config = computed(() => props);\n\n// Computed state for initialization and connection (matching React component)\nconst isInitializing = computed(() => {\n return state.value.isLoading && state.value.messages.length === 0 && !state.value.sessionId;\n});\n\nconst isStartingNewChat = computed(() => {\n // This would be tracked in manager if needed, for now return false\n return false;\n});\n\n// Use isConnectingToAgent from composable (already computed in manager)\nconst isConnectingToAgent = isConnectingToAgentFromComposable;\n\n// Auto-scroll to bottom when messages change\nwatch(\n () => messages.value.length,\n () => {\n nextTick(() => {\n messagesEndRef.value?.scrollIntoView({ behavior: 'smooth' });\n });\n }\n);\n\n// Handlers\nconst handleOpenChat = async () => {\n // Ensure immediate UI response\n if (!state.value.isOpen) {\n state.value.isOpen = true;\n state.value.showWelcomePopup = false;\n }\n await openChat();\n};\n\nconst handleCloseChat = () => {\n closeChat();\n};\n\nconst handleCloseWelcomePopup = () => {\n manager.closeWelcomePopup();\n};\n\nconst handleInput = (event: Event) => {\n const target = event.target as HTMLInputElement;\n setInputValue(target.value);\n};\n\nconst handleSubmit = async (event: Event) => {\n event.preventDefault();\n if (state.value.inputValue.trim()) {\n await sendMessage(state.value.inputValue);\n }\n};\n\nconst handleChipClick = async (chipText: string, payload?: string) => {\n const messageToSend = chipText || payload || '';\n await sendMessage(messageToSend);\n};\n\n// Utility functions\nconst formatTime = (date: Date): string => {\n return date.toLocaleTimeString([], {\n hour: '2-digit',\n minute: '2-digit',\n });\n};\n\n// Check if message is a handoff message\nconst isHandoffMessage = (text: string): boolean => {\n return text.includes('👤') || \n text.includes('being connected') || \n text.includes('live support agent') ||\n text.includes('transfer your conversation');\n};\n\n// Initialize welcome popup on mount (SSR-safe)\nonMounted(() => {\n if (config.value.showWelcomePopup && typeof window !== 'undefined') {\n manager.initializeWelcomePopup();\n }\n});\n</script>\n\n<style scoped>\n/* Styles are imported separately by users */\n/* This ensures SSR compatibility */\n</style>\n"],"names":["botMessage","existingIds","_openBlock","_createElementBlock","_mergeProps","$attrs","_unref","_createElementVNode","_toDisplayString","_Fragment","_renderList","_normalizeClass"],"mappings":";;AAiBO,MAAM,mBAAmB;AAAA,EA6B9B,YAAY,QAAsB;AA1BlC,SAAQ,gCAAmD,IAAA;AAC3D,SAAQ,WAA2B;AACnC,SAAQ,SAAwB;AAChC,SAAQ,mBAAkC;AAC1C,SAAQ,cAA2D;AAGnE,SAAQ,qBAA8B;AACtC,SAAQ,eAAmD;AAC3D,SAAQ,oBAA4B;AACpC,SAAQ,qBAA6B;AACrC,SAAQ,sBAA8B;AAGtC,SAAQ,cAAuB;AAC/B,SAAQ,cAAuB;AAC/B,SAAQ,eAA8C,EAAE,MAAM,QAAA;AAC9D,SAAQ,sBAA+B;AACvC,SAAQ,gBAAyB;AACjC,SAAQ,eAAwB;AAChC,SAAQ,gBAA+B;AAGvC,SAAQ,gBAAuC;AAC/C,SAAQ,qBAA4C;AAGlD,SAAK,SAAS;AACd,SAAK,QAAQ;AAAA,MACX,QAAQ;AAAA,MACR,kBAAkB;AAAA,MAClB,UAAU,CAAA;AAAA,MACV,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,OAAO;AAAA,MACP,WAAW;AAAA,MACX,UAAU;AAAA,IAAA;AAIZ,SAAK,cAAc,kBAAkB;A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OAAA;AAAA,uBAAvB;AAAA,cAAJ,KAAI;AAAA,YAAA;;UAIXA,mBA4BO,QAAA;AAAA,YA5BD,OAAM;AAAA,YAA0B,wBAAgB,cAAY,CAAA,SAAA,CAAA;AAAA,UAAA;YAChEA,mBAOE,SAAA;AAAA,cANA,MAAK;AAAA,cACL,OAAM;AAAA,cACL,OAAOD,MAAA,KAAA,EAAM;AAAA,cACb,SAAO;AAAA,cACP,aAAa,OAAA,MAAO;AAAA,cACpB,UAAUA,MAAA,KAAA,EAAM,aAAa,eAAA,SAAkB,kBAAA;AAAA,YAAA;YAElDC,mBAkBS,UAAA;AAAA,cAjBP,MAAK;AAAA,cACL,OAAM;AAAA,cACL,UAAQ,CAAGD,MAAA,KAAA,EAAM,WAAW,KAAA,KAAUA,MAAA,KAAA,EAAM,aAAa,eAAA,SAAkB,kBAAA;AAAA,YAAA;cAE5EC,mBAYM,OAAA;AAAA,gBAXJ,OAAM;AAAA,gBACN,QAAO;AAAA,gBACP,SAAQ;AAAA,gBACR,MAAK;AAAA,gBACL,QAAO;AAAA,gBACP,gBAAa;AAAA,gBACb,kBAAe;AAAA,gBACf,mBAAgB;AAAA,cAAA;gBAEhBA,mBAA4C,QAAA;AAAA,kBAAtC,IAAG;AAAA,kBAAK,IAAG;AAAA,kBAAI,IAAG;AAAA,kBAAK,IAAG;AAAA,gBAAA;gBAChCA,mBAAsD,WAAA,EAA7C,QAAO,6BAA2B;AAAA,cAAA;;;;;;;;;;;;;;;;"}
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./components/ChatWidget.cjs.js"),t=require("./services/dialogflowClient.cjs.js"),r=require("./utils/frameworkDetector.cjs.js"),s=require("./entry/vanilla.cjs.js");exports.ChatWidget=e.default,exports.ReactChatWidget=e.default,exports.default=e.default,exports.createDialogflowSession=t.createDialogflowSession,exports.sendDialogflowMessage=t.sendDialogflowMessage,exports.getFramework=r.getFramework,exports.setFramework=r.setFramework,exports.VanillaChatWidget=s.ChatWidget,exports.createChatWidget=s.createChatWidget;
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("react/jsx-runtime"),t=require("react"),n=require("./sanitize-7Fj9oshH.js"),s=require("react-dom");var a="undefined"!=typeof document?document.currentScript:null;const o="blockspark_chat_mode",r="blockspark_chat_id",i="blockspark_session_id";function c({title:s="💬 BlockSpark AI Assistant",subtitle:a="We're here to help",welcomeTitle:c="👋 Welcome to Blockspark",welcomeMessage:l="My name is BlockSpark AI Assistant and I'll guide you.",welcomeCta:u="💬 Click here to start chatting!",showWelcomePopup:d=!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:f=!1,dfProjectId:w,dfLocation:y="us-central1",dfAgentId:x,serviceAccountKey:v,accessToken:S,languageCode:b="en",backendBaseUrl:_,backendWsUrl:D}){const[C,j]=t.useState(!1),[k,N]=t.useState(!1),[T,I]=t.useState([]),[E,R]=t.useState(""),[A,$]=t.useState(!1),[M,P]=t.useState(null),[U,H]=t.useState(!1),[B,W]=t.useState(!1),[F,L]=t.useState(!1),[O,V]=t.useState(!1),[q,z]=t.useState({name:"Agent"}),[K,X]=t.useState(!1),[Y,G]=t.useState(!1),[J,Q]=t.useState(!1),[Z,ee]=t.useState(!1),[te,ne]=t.useState(null),[se,ae]=t.useState(""),[oe,re]=t.useState(""),[ie,ce]=t.useState(""),le=t.useRef(""),ue=t.useRef(null),de=t.useRef(null),me=t.useRef(null),he=t.useRef(n.createChatService({baseUrl:_||"undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_BASE_URL,wsUrl:D||"undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_WS_URL,debug:f})),ge=t.useRef(null),{currentMode:pe,switchToHumanMode:fe,switchToBotMode:we,chatId:ye,sessionId:xe,setChatId:ve,setSessionId:Se}=function(){const[e,n]=t.useState(()=>"HUMAN"===localStorage.getItem(o)?"HUMAN":"BOT"),[s,a]=t.useState(()=>localStorage.getItem(r)),[c,l]=t.useState(()=>localStorage.getItem(i));t.useEffect(()=>{localStorage.setItem(o,e)},[e]);const u=t.useCallback(e=>{a(e),e?localStorage.setItem(r,e):localStorage.removeItem(r)},[]),d=t.useCallback(e=>{l(e),e?localStorage.setItem(i,e):localStorage.removeItem(i)},[]),m=t.useCallback(()=>{n("HUMAN")},[]),h=t.useCallback(()=>{n("BOT")},[]),g=t.useCallback(e=>!1,[]);return{currentMode:e,switchToHumanMode:m,switchToBotMode:h,isHandoffTriggered:g,chatId:s,sessionId:c,setChatId:u,setSessionId:d}}(),be=t.useCallback(e=>{G(!0),W(!1),ee(!1),V(!1),me.current&&(clearTimeout(me.current),me.current=null),he.current.disconnectWebSocket(),ve(null),Se(null);const t={id:`resolved-${Date.now()}`,text:"Thank you for contacting us!",sender:"bot",timestamp:new Date};I(e=>[...e,t]),setTimeout(()=>{we(),G(!1),I([]),X(!1),ne(null),ae(""),re(""),ce(""),le.current="",Te().catch(console.error)},2e3)},[ve,Se,we]);t.useCallback(async()=>{if(!J){Q(!0);try{const e=le.current||se||null,t=oe||null,n=ie||null,s=await he.current.startSupportChat(M||null,e,t,n);fe(),ve(s.chat_id),Se(s.session_id),G(!1),R("")}catch(e){I(t=>[...t,{id:`error-new-chat-${Date.now()}`,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)}}},[oe,ie,se,f,J,M,ve,Se,fe]);const _e=()=>{if(w&&x)return{dfProjectId:w,dfLocation:y||"us-central1",dfAgentId:x,serviceAccountKey:v,accessToken:S,languageCode:b||"en"}};t.useEffect(()=>{if(!d)return;const e=setTimeout(()=>{N(!0)},m);return()=>clearTimeout(e)},[d,m]),t.useEffect(()=>{ue.current?.scrollIntoView({behavior:"smooth"})},[T]);const De=t.useCallback(e=>{if(e.to_agent){z({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};I(e=>[...e,t])}},[f]),Ce=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||`agent-${Date.now()}`,text:e.content,sender:"agent",timestamp:new Date(e.timestamp||Date.now())};I(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),V(!1),me.current&&(clearTimeout(me.current),me.current=null)}break;case"typing_start":"agent"===e.sender_type&&(V(!0),me.current&&clearTimeout(me.current),me.current=setTimeout(()=>{V(!1)},3e3));break;case"typing_stop":"agent"===e.sender_type&&(V(!1),me.current&&(clearTimeout(me.current),me.current=null));break;case"agent_changed":De(e);break;case"chat_info":"active"===e.status?(W(!1),ee(!0)):"resolved"!==e.status&&"ended"!==e.status||be(e.chat_id||null),e.agent_id&&z(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};I(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),e.to_agent&&z({name:e.to_agent,id:e.to_agent_id});break;case"chat_resolved":case"chat_ended":be(e.chat_id||null);break;case"error":const n={id:`error-${Date.now()}`,text:e.error||"An error occurred. Please try again.",sender:"bot",timestamp:new Date};I(e=>[...e,n])}},[f,be,De]),je=t.useCallback(e=>{4e3===e.code&&be(ye)},[ye,be]),ke=t.useCallback(e=>{L(e),e&&W(!1)},[]);t.useEffect(()=>{if("HUMAN"===pe&&ye&&xe)return he.current.connectWebSocket(ye,xe,Ce,ke,je),()=>{he.current.disconnectWebSocket()}},[pe,ye,xe,Ce,ke,je]);const Ne=t.useCallback(async(e=!0)=>{if(ye&&xe)try{$(!0);const t=(await he.current.loadMessageHistory(ye,xe)).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)}));I(e?e=>{const n=new Set(e.map(e=>e.id)),s=t.filter(e=>!n.has(e.id));return[...e,...s].sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}:t)}catch(t){if(f){const e={id:`error-${Date.now()}`,text:`Failed to load chat history: ${t.message}`,sender:"bot",timestamp:new Date};I(t=>[...t,e])}}finally{$(!1)}},[ye,xe,f]);t.useEffect(()=>{if("HUMAN"===pe&&ye&&xe){const e=`${ye}-${xe}`;if(ge.current!==e){ge.current=e;setTimeout(()=>{0===T.length&&Ne(!1).catch(console.error)},0)}}else"BOT"===pe&&(ge.current=null)},[pe,ye,xe,Ne,T.length]);const Te=async()=>{if(M)return M;try{H(!0);const e=_e();if(!e)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const t=await n.createDialogflowSession(e);if(P(t.session_id),t.message){const e={id:`welcome-${Date.now()}`,text:t.message,sender:"bot",timestamp:new Date,richContent:t.richContent};I([e])}return t.session_id}catch(e){const t={id:`error-${Date.now()}`,text:f?`Error: ${e.message||"Failed to create session. Please check your Dialogflow configuration."}`:h,sender:"bot",timestamp:new Date};return I([t]),null}finally{H(!1)}},Ie=async(e,t,s=!1)=>{if(!e.trim())return;if(K){if("name"===te){const t=e.trim();ae(t),le.current=t,ne("email");const n={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,n]);const s={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your email address:",sender:"bot",timestamp:new Date};return I(e=>[...e,s]),void R("")}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 I(t=>[...t,e]),void R("")}re(t),ne("mobile");const n={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,n]);const s={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your mobile number:",sender:"bot",timestamp:new Date};return I(e=>[...e,s]),void R("")}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 I(t=>[...t,e]),void R("")}ce(t);const n={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};I(e=>[...e,n]);const s=le.current,a=oe;return X(!1),ne(null),le.current="",await(async(e,t,n)=>{try{W(!0);const a=M,o=await he.current.ensureChatInitialized(ye,xe,a||null,e||null,t||null,n||null);if(!o||!o.chat_id)throw new Error("Failed to initialize chat session");const r=o.chat_id,i=o.session_id;r!==ye&&(ve(r),Se(i));try{await he.current.requestHandoff(r,i,"Customer requested human agent",a||null,e||null,t||null,n||null)}catch(s){if(!(s.message?.includes("Invalid chat_id")||s.message?.includes("Chat not found")||s.message?.includes("unauthorized")||s.message?.includes("400")||s.message?.includes("401")||s.message?.includes("404")||s.message?.includes("expired")))throw s;{ve(null),Se(null);const s=await he.current.startSupportChat(a||null,e||null,t||null,n||null);if(!s||!s.chat_id)throw new Error("Failed to re-initialize chat session");const o=s.chat_id,r=s.session_id;ve(o),Se(r),await he.current.requestHandoff(o,r,"Customer requested human agent",a||null,e||null,t||null,n||null);const i=`${o}-${r}`;ge.current!==i&&(ge.current=i,await Ne(!0))}}fe(),G(!1),ee(!1);const c={id:`connecting-${Date.now()}`,text:"Connecting you to a human agent...",sender:"bot",timestamp:new Date};I(e=>[...e,c]);const l=`${r}-${i}`;ge.current=l}catch(a){const e={id:`error-${Date.now()}`,text:f?`Handoff error: ${a.message}`:"Failed to connect to agent. Please try again.",sender:"bot",timestamp:new Date};I(t=>[...t,e]),W(!1)}})(s,a,t),void R("")}}if("HUMAN"===pe){if(!ye||!xe){const e={id:Date.now().toString(),text:"Chat session not initialized. Please try again.",sender:"bot",timestamp:new Date};return void I(t=>[...t,e])}if(!s){const n={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};I(e=>[...e,n])}he.current.sendTypingIndicator("typing_stop"),de.current&&(clearTimeout(de.current),de.current=null),R(""),$(!0);try{he.current.sendMessageViaWebSocket(e.trim())||await he.current.sendMessageToAgent(ye,xe,e.trim())}catch(o){if(o instanceof n.ChatResolvedError||"ChatResolvedError"===o?.name||"chat_resolved"===o?.message)return void be(ye);if(o.message?.includes("Chat not found")||o.message?.includes("unauthorized")||o.message?.includes("401")||o.message?.includes("404")){ve(null),Se(null);try{const t=await he.current.startSupportChat(M||null,null,null,null);ve(t.chat_id),Se(t.session_id);try{await he.current.sendMessageToAgent(t.chat_id,t.session_id,e.trim())}catch(r){if(r instanceof n.ChatResolvedError||"ChatResolvedError"===r?.name||"chat_resolved"===r?.message)return void be(t.chat_id);throw r}return}catch(r){if(r instanceof n.ChatResolvedError||"ChatResolvedError"===r?.name||"chat_resolved"===r?.message)return void be(ye);const e={id:(Date.now()+1).toString(),text:f?`Error: ${r.message||"Failed to send message."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};I(t=>[...t,e])}}else{const e={id:(Date.now()+1).toString(),text:f?`Error: ${o.message||"Failed to send message to agent."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};I(t=>[...t,e])}}finally{$(!1)}return}let a=M;if(!a)try{if(a=await Te(),!a){const e={id:Date.now().toString(),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 I(t=>[...t,e])}}catch(o){const e={id:Date.now().toString(),text:f?`Connection Error: ${o.message||"Please check your Dialogflow configuration."}`:"Sorry, I'm having trouble connecting. Please check your configuration.",sender:"bot",timestamp:new Date};return void I(t=>[...t,e])}if(!s){const n={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};I(e=>[...e,n])}R(""),$(!0);try{const t=_e();if(!t)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId, dfAgentId, and either serviceAccountKey or accessToken.");const s=await n.sendDialogflowMessage(e.trim(),a,t);if(!0===s.handoff){const e={id:(Date.now()+1).toString(),text:s.response,sender:"bot",timestamp:new Date(s.timestamp||Date.now()),richContent:s.richContent};I(t=>[...t,e]),X(!0),ne("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 I(e=>[...e,t])}const o={id:(Date.now()+1).toString(),text:s.response,sender:"bot",timestamp:new Date(s.timestamp||Date.now()),richContent:s.richContent};I(e=>[...e,o])}catch(o){const e={id:(Date.now()+1).toString(),text:f?`Error: ${o.message||"Failed to send message. Please check your Dialogflow configuration."}`:o.message?.includes("Failed to fetch")||o.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};I(t=>[...t,e])}finally{$(!1)}};t.useEffect(()=>()=>{de.current&&clearTimeout(de.current),me.current&&clearTimeout(me.current)},[]);const Ee=async()=>{j(!0),N(!1),M||await Te()},Re=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&&!C&&e.jsxs("div",{className:"custom-welcome-popup",onClick:Ee,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:u})]}),!C&&e.jsx("button",{className:"custom-chat-toggle-btn",onClick:Ee,"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"})})}),C&&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:s}),e.jsxs("div",{className:"custom-chat-subtitle",children:[a,"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:q.name})]})]}),"BOT"===pe&&e.jsx("div",{className:"custom-mode-badge",children:"Bot Mode"})]}),e.jsx("button",{className:"custom-chat-close-btn",onClick:()=>{j(!1),"HUMAN"===pe&&he.current.disconnectWebSocket()},"aria-label":"Close chat",children:"×"})]}),e.jsxs("div",{className:"custom-chat-messages",children:[U&&0===T.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..."})]}),!U&&0===T.length&&e.jsxs("div",{className:"custom-chat-empty",children:[e.jsx("div",{className:"custom-chat-empty-icon",children:"👋"}),e.jsx("p",{children:p})]}),T.map(t=>e.jsxs("div",{className:`custom-message custom-message-${t.sender} ${Re(t.text)?"custom-handoff-message":""}`,children:[e.jsx("div",{className:"custom-message-content "+(Re(t.text)?"custom-handoff-content":""),dangerouslySetInnerHTML:{__html:n.linkifyText(t.text).replace(/\n/g,"<br>")}}),(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 s=t;return s&&"chips"===s.type&&s.options?e.jsx("div",{className:"custom-chips-group",children:s.options.map((t,n)=>e.jsx("button",{className:"custom-chip-button",onClick:()=>{const e={id:Date.now().toString(),text:t.text,sender:"user",timestamp:new Date};I(t=>[...t,e]),Ie(t.text,t.text,!0)},type:"button",children:t.text},n))},n):null}return t.map((t,s)=>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:Date.now().toString(),text:t.text,sender:"user",timestamp:new Date};I(t=>[...t,e]),Ie(t.text,t.text,!0)},type:"button",children:t.text},n))},`${n}-${s}`):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",{})]})}),B&&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&&O&&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:ue})]}),e.jsxs("form",{className:"custom-chat-input-form",onSubmit:e=>{e.preventDefault(),Ie(E)},children:[e.jsx("input",{type:"text",className:"custom-chat-input",value:E,onChange:e=>{const t=e.target.value;R(t),"HUMAN"===pe&&F&&(he.current.sendTypingIndicator("typing_start"),de.current&&clearTimeout(de.current),de.current=setTimeout(()=>{he.current.sendTypingIndicator("typing_stop"),de.current=null},2e3))},placeholder:g,disabled:A||U||J}),e.jsx("button",{type:"submit",className:"custom-chat-send-btn",disabled:!E.trim()||A||U||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"})]})})]})]})]})}function l(){const e="undefined"==typeof window;if("undefined"!=typeof process&&process.env?.NEXT_RUNTIME)return{name:"next",version:process.env.NEXT_VERSION,isSSR:e};if("undefined"!=typeof process&&(process.env?.NUXT||globalThis.__NUXT__))return{name:"nuxt",version:process.env.NUXT_VERSION,isSSR:e};if(void 0!=={url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("index.cjs.js",document.baseURI).href}){const t={url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("index.cjs.js",document.baseURI).href};if(t.env?.DEV)return{name:"vite",version:t.env?.VITE_VERSION,isSSR:e}}return function(){if("undefined"!=typeof window&&(window.React||window.react))return!0;if("undefined"!=typeof window)try{if("undefined"!=typeof module&&module.hot)return!0}catch{}return!1}()?{name:"react",version:u(),isSSR:e}:function(){if("undefined"!=typeof window&&(window.Vue||window.vue))return!0;return!1}()?{name:"vue",version:d(),isSSR:e}:{name:"vanilla",isSSR:e}}function u(){try{if("undefined"!=typeof window&&window.React?.version)return window.React.version}catch{}}function d(){try{if("undefined"!=typeof window&&window.Vue?.version)return window.Vue.version}catch{}}let m=null;var h,g=s;if("production"===process.env.NODE_ENV)h=g.createRoot,g.hydrateRoot;else{var p=g.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;h=function(e,t){p.usingClientEntryPoint=!0;try{return g.createRoot(e,t)}finally{p.usingClientEntryPoint=!1}}}class f{constructor(e,t){if(this.root=null,this.config=t,"string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error(`Container element "${e}" not found`);this.container=t}else this.container=e;this.root=h(this.container),this.render()}render(){this.root&&this.root.render(t.createElement(c,this.config))}updateConfig(e){this.config={...this.config,...e},this.render()}destroy(){this.root&&(this.root.unmount(),this.root=null)}}exports.createDialogflowSession=n.createDialogflowSession,exports.sendDialogflowMessage=n.sendDialogflowMessage,exports.ChatWidget=c,exports.ReactChatWidget=c,exports.VanillaChatWidget=f,exports.createChatWidget=function(e,t){return new f(e,t)},exports.default=c,exports.getFramework=function(){return m?{name:m,isSSR:"undefined"==typeof window}:l()},exports.setFramework=function(e){m=e};
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/hooks/useChatMode.ts","../src/components/ChatWidget.tsx","../src/utils/frameworkDetector.ts","../node_modules/react-dom/client.js","../src/entry/vanilla.ts"],"sourcesContent":["// hooks/useChatMode.ts\nimport { useState, useEffect, useCallback } from \"react\";\nimport type { ChatResponse } from \"../services/dialogflowClient\";\n\nexport type ChatMode = \"BOT\" | \"HUMAN\";\n\nconst MODE_STORAGE_KEY = \"blockspark_chat_mode\";\nconst CHAT_ID_STORAGE_KEY = \"blockspark_chat_id\";\nconst SESSION_ID_STORAGE_KEY = \"blockspark_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 // Load from localStorage on init\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 return localStorage.getItem(CHAT_ID_STORAGE_KEY);\n });\n\n const [sessionId, setSessionIdState] = useState<string | null>(() => {\n return localStorage.getItem(SESSION_ID_STORAGE_KEY);\n });\n\n // Persist mode to localStorage\n useEffect(() => {\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 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} ","/**\n * Framework Detection Utility\n * Detects which framework is available in the runtime environment\n */\n\nexport type Framework = 'react' | 'vue' | 'next' | 'nuxt' | 'vite' | 'vanilla';\n\nexport interface FrameworkInfo {\n name: Framework;\n version?: string;\n isSSR: boolean;\n}\n\n/**\n * Detects the framework in the current environment\n */\nexport function detectFramework(): FrameworkInfo {\n const isSSR = typeof window === 'undefined';\n \n // Check for Next.js\n if (typeof process !== 'undefined' && process.env?.NEXT_RUNTIME) {\n return {\n name: 'next',\n version: process.env.NEXT_VERSION,\n isSSR,\n };\n }\n \n // Check for Nuxt\n if (typeof process !== 'undefined' && (process.env?.NUXT || (globalThis as any).__NUXT__)) {\n return {\n name: 'nuxt',\n version: (process.env as any).NUXT_VERSION,\n isSSR,\n };\n }\n \n // Check for Vite (development)\n if (typeof import.meta !== 'undefined') {\n const meta = import.meta as any;\n if (meta.env?.DEV) {\n return {\n name: 'vite',\n version: meta.env?.VITE_VERSION,\n isSSR,\n };\n }\n }\n \n // Check for React\n if (detectReact()) {\n return {\n name: 'react',\n version: getReactVersion(),\n isSSR,\n };\n }\n \n // Check for Vue\n if (detectVue()) {\n return {\n name: 'vue',\n version: getVueVersion(),\n isSSR,\n };\n }\n \n // Default to vanilla\n return {\n name: 'vanilla',\n isSSR,\n };\n}\n\n/**\n * Detects if React is available\n */\nfunction detectReact(): boolean {\n // Check global React\n if (typeof window !== 'undefined') {\n if ((window as any).React || (window as any).react) {\n return true;\n }\n }\n \n // Check for React in ES modules (runtime) - try dynamic import\n if (typeof window !== 'undefined') {\n try {\n // Check if React is available via global or module system\n // In browser, React should be available as a global or via module system\n // We can't use require() in browser, so we check for global or module presence\n if (typeof module !== 'undefined' && (module as any).hot) {\n // Likely in a module environment that supports React\n return true;\n }\n } catch {\n // React not available\n }\n }\n \n return false;\n}\n\n/**\n * Gets React version if available\n */\nfunction getReactVersion(): string | undefined {\n try {\n if (typeof window !== 'undefined' && (window as any).React?.version) {\n return (window as any).React.version;\n }\n } catch {\n // Version not available\n }\n \n return undefined;\n}\n\n/**\n * Detects if Vue is available\n */\nfunction detectVue(): boolean {\n // Check global Vue\n if (typeof window !== 'undefined') {\n if ((window as any).Vue || (window as any).vue) {\n return true;\n }\n }\n \n // In browser/module environment, Vue should be available via module system\n // We can't use require() in browser, so we rely on global detection\n return false;\n}\n\n/**\n * Gets Vue version if available\n */\nfunction getVueVersion(): string | undefined {\n try {\n if (typeof window !== 'undefined' && (window as any).Vue?.version) {\n return (window as any).Vue.version;\n }\n } catch {\n // Version not available\n }\n \n return undefined;\n}\n\n/**\n * Forces a specific framework (useful for testing or explicit configuration)\n */\nlet forcedFramework: Framework | null = null;\n\nexport function setFramework(framework: Framework): void {\n forcedFramework = framework;\n}\n\nexport function getFramework(): FrameworkInfo {\n if (forcedFramework) {\n return {\n name: forcedFramework,\n isSSR: typeof window === 'undefined',\n };\n }\n return detectFramework();\n}\n","'use strict';\n\nvar m = require('react-dom');\nif (process.env.NODE_ENV === 'production') {\n exports.createRoot = m.createRoot;\n exports.hydrateRoot = m.hydrateRoot;\n} else {\n var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n exports.createRoot = function(c, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.createRoot(c, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n exports.hydrateRoot = function(c, h, o) {\n i.usingClientEntryPoint = true;\n try {\n return m.hydrateRoot(c, h, o);\n } finally {\n i.usingClientEntryPoint = false;\n }\n };\n}\n","/**\n * Vanilla JavaScript Entry Point\n * Uses the original ChatWidget.tsx component via ReactDOM\n * Reuses the same component to reduce code duplication\n */\n\nimport React from 'react';\nimport { createRoot, Root } from 'react-dom/client';\nimport ChatWidgetComponent from '../components/ChatWidget';\nimport type { ChatWidgetProps } from '../components/ChatWidget';\nimport '../styles/chatWidget.css';\n\n/**\n * Vanilla JS Chat Widget\n * Renders the original React component using ReactDOM\n * This reuses the same component code, reducing duplication\n */\nexport class ChatWidget {\n private container: HTMLElement;\n private config: ChatWidgetProps;\n private root: Root | null = null;\n\n constructor(container: HTMLElement | string, config: ChatWidgetProps) {\n this.config = config;\n \n // Get container element\n if (typeof container === 'string') {\n const element = document.querySelector(container);\n if (!element) {\n throw new Error(`Container element \"${container}\" not found`);\n }\n this.container = element as HTMLElement;\n } else {\n this.container = container;\n }\n\n // Create React root and render the component\n // This reuses the same ChatWidget.tsx component\n this.root = createRoot(this.container);\n this.render();\n }\n\n private render(): void {\n // Render the original React component using ReactDOM\n // This reuses the same component code, reducing duplication\n if (this.root) {\n this.root.render(React.createElement(ChatWidgetComponent, this.config));\n }\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<ChatWidgetProps>): void {\n this.config = { ...this.config, ...config };\n this.render();\n }\n\n /**\n * Destroy the widget\n */\n destroy(): void {\n if (this.root) {\n this.root.unmount();\n this.root = null;\n }\n }\n}\n\n/**\n * Factory function for easier usage\n */\nexport function createChatWidget(\n container: HTMLElement | string,\n config: ChatWidgetProps\n): ChatWidget {\n return new ChatWidget(container, config);\n}\n\nexport default ChatWidget;\n"],"names":["MODE_STORAGE_KEY","CHAT_ID_STORAGE_KEY","SESSION_ID_STORAGE_KEY","ChatWidget","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","setCurrentMode","localStorage","getItem","setChatIdState","setSessionIdState","useEffect","setItem","useCallback","id","removeItem","isHandoffTriggered","dialogflowResponse","useChatMode","enterResolvedState","_resolvedChatId","current","clearTimeout","disconnectWebSocket","thankYouMessage","Date","now","text","sender","timestamp","prev","setTimeout","createSession","catch","console","error","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","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","onSubmit","preventDefault","value","onChange","target","placeholder","disabled","x1","y1","x2","y2","points","detectFramework","isSSR","window","NEXT_RUNTIME","version","NEXT_VERSION","NUXT","globalThis","__NUXT__","NUXT_VERSION","url","document","require","pathToFileURL","__filename","href","_documentCurrentScript","tagName","toUpperCase","src","URL","baseURI","meta","DEV","VITE_VERSION","React","react","module","hot","detectReact","getReactVersion","Vue","vue","detectVue","getVueVersion","forcedFramework","require$$0","NODE_ENV","createRoot","hydrateRoot","i","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","c","o","usingClientEntryPoint","constructor","container","config","this","root","element","querySelector","render","createElement","ChatWidgetComponent","updateConfig","destroy","unmount","framework"],"mappings":"8RAMA,MAAMA,EAAmB,uBACnBC,EAAsB,qBACtBC,EAAyB,wBCkE/B,SAAwBC,GAAWC,MACjCA,EAAQ,6BAAAC,SACRA,EAAW,qBAAAC,aACXA,EAAe,2BAAAC,eACfA,EAAiB,yDAAAC,WACjBA,EAAa,mCACbC,iBAAkBC,GAAqB,EAAAC,kBACvCA,EAAoB,KAAAC,uBACpBA,EAAyB,gEAAAC,iBACzBA,EAAmB,uBAAAC,kBACnBA,EAAoB,6DAAAC,MACpBA,GAAQ,EAAAC,YACRA,EAAAC,WACAA,EAAa,cAAAC,UACbA,EAAAC,kBACAA,EAAAC,YACAA,EAAAC,aACAA,EAAe,KAAAC,eACfA,EAAAC,aACAA,IAEA,MAAOC,EAAQC,GAAaC,EAAAA,UAAS,IAC9BjB,EAAkBkB,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,IAC9CY,EAAqBC,GAA0Bb,EAAAA,UAAS,IACxDc,EAAaC,GAAkBf,EAAAA,UAAS,IACxCgB,EAAaC,GAAkBjB,EA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