sentifyd-bot 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import{io as t}from"socket.io-client";import{AudioConfig as e,SpeechRecognizer as i,ResultReason as n,CancellationReason as a,CancellationErrorCode as s,SpeechConfig as o,PropertyId as r,AutoDetectSourceLanguageConfig as c}from"microsoft-cognitiveservices-speech-sdk";import"js-cookie";import{jwtDecode as l}from"jwt-decode";import{v4 as h}from"uuid";import{createMachine as d,assign as u,fromPromise as p,createActor as g}from"xstate";import{TalkingHead as v}from"@met4citizen/talkinghead";import{html as m,nothing as _,css as b,LitElement as f}from"lit";import y from"toastify-js";import{styleMap as S}from"lit/directives/style-map.js";const k=t=>new Promise((e=>setTimeout(e,t))),C=t=>t?t.replace(/<prosody[^>]*>([\s\S]*?)<\/prosody>/gi,"$1").replace(/#\*[\s\S]*?\*#/g,""):t,w=t=>(t instanceof Date?t:new Date(t)).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});function A(){return"undefined"!=typeof window&&window.VITE_APP_SOCKET_URL?window.VITE_APP_SOCKET_URL:"https://sentifyd-serve.agreeablestone-0bc8c055.swedencentral.azurecontainerapps.io"}const x=A(),T={auth:{tokenRefreshInterval:6e5,speechTokenInterval:42e4,maxLoginRetries:3,loginRetryDelay:5e3,closeToExpirationLimit:6e4,speechTokenRetries:5,serverBaseURL:A()},avatar:{type:"gltf"},constants:{HEADROLL_BLENDSHAPE_INDEX:52,LEFTEYE_BLENDSHAPE_INDEX:53,RIGHTEYE_BLENDSHAPE_INDEX:54,FRAME_RATE:60},dom:{avatarDivId:"#avatar-container",toastifyDivId:"#toastify-container",canvasWidth:400,canvasHeight:500,headerAndFooterHeight:166,controlsHeight:90,smallDisplayWidth:768,smallScreenSafetyPadding:24},renderer:{alpha:!0,antialias:!0},speech:{authorizationEndPoint:"/api/v1/chatbot/get-speech-token",maxDurationTimeout:6e5,vad:{segmentationSilenceMs:1700,initialSilenceMs:12e3,semantic:!0},bargeIn:{enabled:!0,debug:!1}},captions:{wordsPerMinute:140,maxCharactersPerCaption:40,minCharactersPerCaption:15,captionChangeDelay:200,captionTimeout:1500},alerts:{maxAlerts:3,dismissableAlertDuration:4500},chatbot:{streaming:!1,thinkingTimeout:15e3,speakingTimeout:24e4},test:{stateTestMode:!1,enableDiagnostics:!1},connection:{reconnectInitialDelay:2e3,reconnectMaxDelay:3e4,reconnectFactor:1.6}},I=async(t,e)=>{for(const i of t){const{name:t}=i;switch(t){case"RequestUserData":await E(e);break;case"EndConversation":await M(e);break;case"DisableCaptions":await D(e);break;case"EnableCaptions":await R(e);break;case"SwitchToChatMode":await P(e);break;case"SwitchToAvatarMode":await O(e);break;case"SetAvatarView":await L(e,i.view);break;case"SetAvatarMood":await B(e,i.mood);break;case"PlayOrStopAvatarGesture":await N(e,i.gesture,i.dur||3,i.mirror||!1,i.ms||1e3);break;case"PlayOrStopAvatarAnimation":await z(e,i.animation,i.dur||3);break;case"ControlAvatarLookAt":await F(e,i.target,i.t||1e3,i.x||0,i.y||0)}}},E=async t=>{t.emit("event_command_UI_RequestUserData")},M=async t=>{t.emit("event_command_UI_EndConversation")},D=async t=>{t.emit("event_command_UI_DisableCaptions")},R=async t=>{t.emit("event_command_UI_EnableCaptions")},P=async t=>{t.emit("event_command_UI_SwitchToChatMode")},O=async t=>{t.emit("event_command_UI_SwitchToAvatarMode")},L=async(t,e)=>{t.emit("event_command_Avatar_SetAvatarView",{view:e})},B=async(t,e)=>{t.emit("event_command_Avatar_SetAvatarMood",{mood:e})},N=async(t,e,i,n,a)=>{t.emit("event_command_Avatar_PlayOrStopGesture",{gesture:e,duration:i,mirror:n,ms:a})},z=async(t,e,i)=>{t.emit("event_command_Avatar_PlayOrStopAnimation",{animation:e,dur:i})},F=async(t,e,i,n,a)=>{t.emit("event_command_Avatar_ControlAvatarLookAt",{target:e,t:i,x:n,y:a})};class ${constructor(t,e=null){this.validateDependencies({auth:t}),this.socketUrl=x,this.auth=t,this.socket=null,this.isAuthenticating=!1,this.onConnectionStatusChange=e}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize WebSocketManager due to missing dependencies: ${e.join(", ")}`)}async connect(){this.socket?.connected&&this.disconnect();const e=this.auth.getAccessToken();return new Promise(((i,n)=>{this.socket=t(this.socketUrl,{auth:{token:`Bearer ${e}`},path:"/socket.io",reconnection:!0,reconnectionAttempts:5,reconnectionDelay:500,reconnectionDelayMax:1e4}),this.registerWebsocketEventHandlers(i,n)}))}isSocketConnected(){return this.socket?.connected}isInitialised(){return null!==this.socket}disconnect(){this.socket&&(this.socket.disconnect(),this.socket.removeAllListeners(),this.socket=null)}registerWebsocketEventHandlers(t,e){this.socket.removeAllListeners(),this.socket.io.on("error",(t=>{})),this.socket.io.on("reconnect",(()=>{this.onConnectionStatusChange&&this.onConnectionStatusChange("connected")})),this.socket.io.on("reconnect_attempt",(t=>{})),this.socket.io.on("reconnect_error",(t=>{})),this.socket.io.on("reconnect_failed",(()=>{this.onConnectionStatusChange&&this.onConnectionStatusChange("failed"),this.socket=null,e(new Error("Websocket connection failed after maximum retries."))})),this.socket.on("connect",(()=>{this.socket.io.engine,this.onConnectionStatusChange&&this.onConnectionStatusChange("connected"),t()})),this.socket.on("connect_error",(t=>{t.message.includes("Token expired")||t.message.includes("Invalid token")?this.reAuthenticate():(this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected"),e?.(t))})),this.socket.on("disconnect",(t=>{this.socket&&this.socket.active||this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")})),this.socket.onAny(((t,...e)=>{}))}reAuthenticate(){this.isAuthenticating||(this.isAuthenticating=!0,this.auth.authenticate().then((()=>{this.connect(),this.isAuthenticating=!1})).catch((t=>{this.isAuthenticating=!1,this.onConnectionStatusChange("failed")})))}on(t,e){this.socket&&this.socket.on(t,e)}off(t,e){this.socket&&(e?this.socket.off(t,e):this.socket.off(t))}emit(t,e,i){this.isSocketConnected()?i?this.socket.emit(t,e,i):this.socket.emit(t,e):this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")}async emitWithResponse(t,e){return new Promise(((i,n)=>{this.isSocketConnected()?this.socket.emit(t,e,(t=>{i(t)})):(this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected"),n(new Error("Socket not connected")))}))}timeoutEmit(t,e,i,n){this.isSocketConnected()?n?this.socket.timeout(i).emit(t,e,n):this.socket.timeout(i).emit(t,e):this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")}destroy(){this.socket&&(this.socket.disconnect(),this.socket.removeAllListeners(),this.socket=null),this.isAuthenticating=!1,this.onConnectionStatusChange=null}}class V{constructor(t){if(!t||"string"!=typeof t)throw new Error("ConnectionModule requires a valid name");this.name=t,this.connectionState="disconnected",this.subscribers=[]}isConnecting(){return"connecting"===this.connectionState}isDisconnected(){return"disconnected"===this.connectionState}isReconnecting(){return"reconnecting"===this.connectionState}isConnected(){return"connected"===this.connectionState}isFailed(){return"failed"===this.connectionState}setConnected(){this.updateConnectionState("connected")}setDisconnected(){this.updateConnectionState("disconnected")}setConnecting(){this.updateConnectionState("connecting")}setReconnecting(){this.updateConnectionState("reconnecting")}setFailed(){this.updateConnectionState("failed")}updateConnectionState(t){return!!["connected","connecting","reconnecting","disconnected","failed"].includes(t)&&this.connectionState!==t&&(this.connectionState,this.connectionState=t,this.notifySubscribers(),!0)}reconnect(){}subscribe(t){return"function"==typeof t&&!this.subscribers.includes(t)&&(this.subscribers.push(t),!0)}unsubscribe(t){if("function"!=typeof t)return!1;const e=this.subscribers.length;return this.subscribers=this.subscribers.filter((e=>e!==t)),this.subscribers.length<e}notifySubscribers(){0!==this.subscribers.length&&[...this.subscribers].forEach(((t,e)=>{try{t(this.connectionState,this.name)}catch(i){}}))}destroy(){try{this.subscribers=[],this.connectionState="disconnected"}catch(t){}}getStateInfo(){return{name:this.name,state:this.connectionState,subscriberCount:this.subscribers.length}}}class U{constructor(t,e,i){this.id=t,this.state="CREATED",this.abortController=new AbortController,this.audio=(t=>{let e,i=!1;return{readable:new ReadableStream({start(n){e=n,t?.addEventListener("abort",(()=>{try{e.error(new DOMException("Aborted","AbortError"))}catch{}i=!0}))}}),push:t=>{if(!i)try{e?.enqueue(t)}catch(n){}},close:()=>{if(!i)try{e?.close(),i=!0}catch(t){}},get isClosed(){return i}}})(this.abortController.signal),this.lipsync=(t=>{let e,i=!1;return{readable:new ReadableStream({start(i){e=i,t?.addEventListener("abort",(()=>{try{e.error(new DOMException("Aborted","AbortError"))}catch{}}))}}),push:t=>{if(!i)try{e?.enqueue(t)}catch(n){}},close:()=>{if(!i)try{e?.close(),i=!0}catch(t){}},get isClosed(){return i}}})(this.abortController.signal),this._watchdog=setTimeout((()=>{this._watchdog=null,i?.(this)}),e)}activate(){this.state="ACTIVE"}finish(){if("FINISHED"!==this.state){this.state="FINISHED",clearTimeout(this._watchdog);try{this.audio.close()}catch{}try{this.lipsync.close()}catch{}this.abortController.abort("turn finished")}}abort(){"FINISHED"!==this.state&&(this.state="STOPPING",this.abortController.abort("turn interrupted"),clearTimeout(this._watchdog))}get isActive(){return"ACTIVE"===this.state}get done(){return"FINISHED"===this.state}}const H=12e4;class j extends V{static _instance=null;constructor(t,e,i,n){if(j._instance)return j._instance;super("chatSocket"),this.validateDependencies({bus:t,auth:e,sessionData:i,avatarOrchestrator:n}),this.socketManager=new $(e,(t=>this.updateConnectionState(t))),this.isChatbotShown=!0,this.chatbotMode="AVATAR",this.bus=t,this.sessionData=i,this.auth=e,this.avatarOrchestrator=n,this.pendingDelayedActions=null,this.turn=null,this.INTERRUPT_WATCHDOG=15e3,j._instance=this}static getInstance(t,e,i,n){return j._instance||(j._instance=new j(t,e,i,n)),j._instance}_isDataForCurrentTurn(){return!!this.turn&&!this.turn.done&&this.turn.id===this.sessionData.conversation.currentTurnId}static resetInstance(){j._instance&&(j._instance._cleanup(),j._instance=null)}_cleanup(){this.cleanupActiveStreams(),this.removeTTSEventHandlers(),this.socketManager?.disconnect(),this.pendingDelayedActions=null,this.turn=null,this.audioStream=null,this.lipsyncStream=null}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize ChatSocket due to missing dependencies: ${e.join(", ")}`)}async init(){if(!this.sessionData||!this.sessionData.avatarName||!this.sessionData.language)throw new Error("Missing required session data for chat connection.");this.sessionData.trainingId;try{this.setConnecting(),await this.socketManager.connect()}catch(t){this.setDisconnected()}this.registerTTSEventHandlers()}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.isFailed()?this.setReconnecting():this.setConnecting();try{if(await this.socketManager.connect(),!this.socketManager.isSocketConnected())throw new Error("Socket still not connected after connect()");this.registerTTSEventHandlers(),this.setConnected()}catch(t){this.setFailed()}}}removeTTSEventHandlers(){this.socketManager&&["conversation_ai_reply","tts_stream_start","tts_viseme","tts_word","tts_blend","tts_error","tts_chunk","tts_stream_end"].forEach((t=>{this.socketManager.off(t)}))}registerTTSEventHandlers(){this.removeTTSEventHandlers(),this.socketManager.on("conversation_ai_reply",(t=>this.handleConversationResponse(t))),this.socketManager.on("tts_stream_start",(t=>{t?.turnId,this.turn&&this.turn.id===this.sessionData.conversation.currentTurnId||this.prepareStreamsForTurn(this.sessionData.conversation.currentTurnId),this.turn.activate(),this.avatarOrchestrator&&this.avatarOrchestrator.sendEvent("STREAM_START",{audioStream:this.audioStream,lipsyncStream:this.lipsyncStream,turnId:this.turn.id})})),this.socketManager.on("tts_viseme",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed&&this.turn&&this.turn.isActive)try{this.lipsyncStream.push({type:"viseme",...t})}catch(e){if(e.message?.includes("closed readable stream"))return}})),this.socketManager.on("tts_word",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed){if(!this.turn||!this.turn.isActive||!this.lipsyncStream)return;try{this.lipsyncStream.push({type:"word",...t})}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_blend",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed){if(!this.turn||!this.turn.isActive||!this.lipsyncStream)return;try{this.lipsyncStream.push({type:"blend",...t})}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_error",(t=>{this.avatarOrchestrator&&this.avatarOrchestrator.sendEvent("TTS_ERROR",{error:t})})),this.socketManager.on("tts_chunk",(t=>{if(this._isDataForCurrentTurn()&&this.audioStream&&!this.audioStream.isClosed){if(!this.turn||!this.turn.isActive||!this.audioStream)return;try{this.audioStream.push(t)}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_stream_end",(t=>{const e=t?.turnId;t?.reason,this.turn&&e===this.turn.id&&(this.turn.finish(),this.avatarOrchestrator.sendEvent("STREAM_END"),this.turn=null)}))}async handleConversationResponse(t){if(this.sessionData?.conversation?.conversationId)if("success"===t?.status)t?.error,await this.processAIResponse(t);else if("error"===t?.status){const e={...t.error};t.conversationId&&!e.conversationId&&(e.conversationId=t.conversationId),this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:e,chatbotMode:this.chatbotMode})}else this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:{message:"No response from server. Please try again."},chatbotMode:this.chatbotMode})}async sendInitConversationEvent(){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");return new Promise(((t,e)=>{this.socketManager.timeoutEmit("init_conversation",{avatarId:this.sessionData.avatarId,trainingId:this.sessionData.trainingId,conversationId:this.sessionData.conversation.conversationId,chatbotMode:this.chatbotMode,streaming:!1},H,((i,n)=>{i||"success"!==n?.status?e(new Error(i||n?.error?.message||"Conversation init failed")):t({initialized:!0})}))}))}async sendStartConversationEvent(t=!1){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");return new Promise(((e,i)=>{this.socketManager.timeoutEmit("start_conversation",{avatarId:this.sessionData.avatarId,trainingId:this.sessionData.trainingId,conversationId:this.sessionData.conversation.conversationId,chatbotMode:this.chatbotMode,detectedLanguage:this.sessionData.language||"en-US",voice:this.sessionData.voice||"",lipsyncType:this.sessionData.lipsyncType,turnId:this.sessionData.conversation.currentTurnId,streaming:!1,isTermsAccepted:!0===this.sessionData.isTermsAccepted,isResume:t},H,(async(t,n)=>{if(t||"success"!==n?.status){const e=n?.error?.code,a=t||n?.error?.message||"Conversation start failed";i(new Error(e?`${e}: ${a}`:a))}else try{await this.processAIResponse(n),e(n)}catch(a){i(a)}}))}))}sendEndConversationEvent(t,e){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");this.socketManager.emit("end_conversation",{conversationId:t,satisfactionScore:e,chatbotMode:this.chatbotMode},(e=>{"success"===e?.status?this.avatarOrchestrator.sendEvent("CLEAR_CONVERSATION",{conversationId:t}):e?.status}))}prepareStreamsForTurn(t){this.turn&&!this.turn.done&&this.turn.abort(),this.turn=new U(t,this.INTERRUPT_WATCHDOG,(t=>{this.socketManager.emit("interrupt_tts",{turnId:t.id})})),this.audioStream=this.turn.audio,this.lipsyncStream=this.turn.lipsync}async processAIResponse(t){try{const e=t?.data?.actions||[],i=e.filter((t=>!1!==t.immediate)),n=e.filter((t=>!1===t.immediate));if(i.length>0&&await I(i,this.bus),n.length>0&&(this.pendingDelayedActions=n),"resume_silent"===t.data?.dataType)return;if("message"===t.data?.dataType?await this.receiveMessage(t.data,t.timestamp):"avatar_structured_response"===t.data?.dataType?await this.receiveAvatarStructuredResponse(t.data,t.timestamp):t?.data?.messageContent&&await this.receiveMessage(t.data,t.timestamp),"CHAT"===this.chatbotMode&&this.pendingDelayedActions&&this.pendingDelayedActions.length>0)try{await I(this.pendingDelayedActions,this.bus)}finally{this.pendingDelayedActions=null}}catch(e){this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:{message:"Error getting a response. Please try again."},chatbotMode:this.chatbotMode})}}async receiveAvatarStructuredResponse(t,e){if(!t?.structuredResponse)throw new Error("Avatar response is invalid");const i=w(e);this.avatarOrchestrator.sendEvent("AI_MESSAGE_RECEIVED",{message:t.messageContent,time:i,structuredResponse:t.structuredResponse,chatbotMode:this.chatbotMode})}async receiveMessage(t,e){if(!t?.messageContent)throw new Error("Message is invalid");const i=w(e);this.avatarOrchestrator.sendEvent("AI_MESSAGE_RECEIVED",{message:t.messageContent,time:i,chatbotMode:this.chatbotMode})}async sendMessage(t,e="CHAT"){if(this.pendingDelayedActions=null,!this.sessionData.trainingId||!t?.messageText)return{success:!1,error:"Missing required field(s)"};if(!this.sessionData.conversation.conversationId)return{success:!1,error:"No conversation found. Start a conversation first."};try{const i=this.sessionData.conversation.incrementTurnId();"AVATAR"===e?this.prepareStreamsForTurn(i):this.turn&&(this.turn.abort(),this.turn=null),this.socketManager.emit("user_chat_message",{trainingId:this.sessionData.trainingId,avatarId:this.sessionData.avatarId,userName:this.sessionData.username,conversationId:this.sessionData.conversation.conversationId,turnId:i,message:t.messageText,messageDuration:t?.messageDuration||0,chatbotMode:e,detectedLanguage:t?.detectedLanguage||this.sessionData.language,voice:this.sessionData.voice||"",lipsyncType:this.sessionData.lipsyncType,streaming:T.chatbot.streaming||!1});const n=w(new Date);return this.avatarOrchestrator.sendEvent("USER_MESSAGE_SENT",{message:t.messageText,time:n,chatbotMode:e}),this.sessionData.conversation.lastDetectedLanguage=t?.detectedLanguage,{success:!0}}catch(i){return{success:!1,error:i.message||"An error occurred while sending the message"}}}sendUserData(){const t=this.sessionData.conversation.incrementTurnId();if(this.prepareStreamsForTurn(t),this.avatarOrchestrator){const t=this.avatarOrchestrator.getSnapshot(),e=t?.matches("lifecycle.conversation.inProgress.thinking");e||this.avatarOrchestrator.sendEvent("USER_MESSAGE_SENT",{message:"[User data update]",time:w(new Date),chatbotMode:this.chatbotMode})}if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");this.socketManager.emit("update_user_data",{conversationId:this.sessionData.conversation.conversationId,turnId:t,detectedLanguage:this.sessionData.language||"en-US",voice:this.sessionData.voice||"",chatbotMode:this.chatbotMode,lipsyncType:this.sessionData.lipsyncType,userData:{username:this.sessionData.username,phoneNumber:this.sessionData.phoneNumber,email:this.sessionData.email,isTermsAccepted:this.sessionData.isTermsAccepted}},(async t=>{"success"===t?.status?this.processAIResponse(t):t?.status}))}cleanupActiveStreams(){this.turn&&this.turn.abort()}async interruptCurrentTurn(){if(!this.turn)return{status:"warning",message:"No active turn"};try{return this.turn.abort(),await this.socketManager.emitWithResponse("interrupt_tts",{turnId:this.turn.id,chatbotMode:this.chatbotMode})}catch(t){return{status:"error",message:"Interruption failed"}}}destroy(){this.socketManager?.destroy()}}class W{constructor({recognizer:t,speechConfig:e,audioConfig:i,bus:n,avatarOrchestrator:a,autoDetectLanguage:s}={}){this.validateDependencies({recognizer:t,speechConfig:e,audioConfig:i,bus:n,avatarOrchestrator:a}),this.bus=n,this.avatarOrchestrator=a,this.speechConfig=e,this.recognizer=t,this.audioConfig=i,this.messageText="",this.messageDuration=0,this.detectedLanguage="",this.isMessageSent=!1,this.isListening=!1,this.isMicDetected=!0,this.autoDetectLanguage=s,this.languageDurations={},this._isStopping=!1,this.maxDurationTimeoutId=null}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize SpeechRecognition due to missing dependencies: ${e.join(", ")}`)}static async build(t,e,i,n){if(!t)throw new Error("speechConfig is required");const{recognizer:a,audioConfig:s}=await this.init(t,e),o=new W({recognizer:a,speechConfig:t,audioConfig:s,bus:i,avatarOrchestrator:n,autoDetectLanguage:!!e});return o._registerRecognizerEvents(),o}static async init(t,n){try{const a=e.fromDefaultMicrophoneInput();let s=null;return s=n?i.FromConfig(t,n,a):new i(t,a),{recognizer:s,audioConfig:a}}catch(a){throw new Error("Error in SpeechRecognition initialization: "+a)}}static async checkMicrophoneAccess(){try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Media devices not supported");if(0===(await navigator.mediaDevices.enumerateDevices()).filter((t=>"audioinput"===t.kind)).length)throw new Error("No microphone devices found");return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach((t=>t.stop())),!0}catch(t){throw new Error(`Microphone access issue: ${t.message}`)}}start(){try{this._isStopping=!1,clearTimeout(this.maxDurationTimeoutId),this.messageText="",this.messageDuration=0,this.isMessageSent=!1,this.autoDetectLanguage&&(this.languageDurations={}),this.recognizeNewMessage(),this._setMaxDurationTimeout()}catch(t){this.stop()}}stop(){if(!this._isStopping){this._isStopping=!0;try{this.recognizer&&this.recognizer.stopContinuousRecognitionAsync()}catch(t){}finally{this.isListening=!1,this._isStopping=!1}clearTimeout(this.maxDurationTimeoutId)}}sendMessage(){if(!this.isMessageSent&&this.messageText&&this.messageText.trim())try{this.autoDetectLanguage?this.detectedLanguage=this._determineMainLanguage():this.detectedLanguage=this.speechConfig.speechRecognitionLanguage,this.avatarOrchestrator.sendEvent("SPEECH_RECOGNITION_COMPLETE",{messageText:this.messageText,messageDuration:this.messageDuration,detectedLanguage:this.detectedLanguage}),this.isMessageSent=!0}catch(t){}}simulateRecognition(){this.avatarOrchestrator.transitionToListening(),this.messageText="Hello, how are you doing today?",this.avatarOrchestrator.sendEvent("SPEECH_RECOGNITION_COMPLETE",{messageText:this.messageText,messageDuration:3e3,detectedLanguage:"en-US"})}recognizeNewMessage(){try{this._startRecognizer()}catch(t){this._emitAlert("alertMicrophoneStartFailed"),this.stop()}}_startRecognizer(){this.recognizer.startContinuousRecognitionAsync((()=>{this.avatarOrchestrator.is("listening"),this.isListening=!0}),(async t=>{await this._handleRecognitionStartupError(t),this.isMicDetected=!1,this.stop()}))}async _handleRecognitionStartupError(t){let e="alertMicrophoneCheckSettings";try{await W.checkMicrophoneAccess(),e="alertSpeechRecognitionSetupFailed"}catch(i){e=this._isBrowserPermissionError(i)?"alertMicrophoneAccessDenied":this._isBrowserDeviceError(i)?"alertNoMicrophoneDetected":"alertMicrophoneError"}this._emitAlert(e)}_isBrowserPermissionError(t){if(t&&"object"==typeof t)return"NotAllowedError"===t.name||"PermissionDeniedError"===t.name||"SecurityError"===t.name;const e=t.toString().toLowerCase();return e.includes("permission")||e.includes("notallowed")||e.includes("denied")}_isBrowserDeviceError(t){if(t&&"object"==typeof t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name;const e=t.toString().toLowerCase();return e.includes("notfound")||e.includes("device")||e.includes("microphone not found")}close(){this.stop(),this.recognizer&&(this.recognizer.close(),this.recognizer.dispose(!0),this.recognizer=void 0)}_registerRecognizerEvents(){this.recognizer.recognized=(t,e)=>{if(!this._isStopping&&this.isListening&&!this.isMessageSent&&e.result.reason===n.RecognizedSpeech&&""!==e.result.text){if(this.messageText=(this.messageText?this.messageText+" ":"")+e.result.text,this.messageDuration+=e.result.duration,this.autoDetectLanguage){const t=e.result.language,i=e.result.duration;this.languageDurations[t]?this.languageDurations[t]+=i:this.languageDurations[t]=i}this.bus.emit("event_command_UI_UpdateSTTCaption",{STTCaption:this.messageText}),this._completeRecognitionTurn()}},this.recognizer.recognizing=(t,e)=>{this._isStopping||!this.isListening||this.isMessageSent||""!==e.result.text&&this.bus.emit("event_command_UI_UpdateSTTCaption",{STTCaption:this.messageText+" "+e.result.text})},this.recognizer.speechStartDetected=(t,e)=>{},this.recognizer.speechEndDetected=(t,e)=>{this._isStopping||!this.isListening||this.isMessageSent||this.messageText?.trim()&&this._completeRecognitionTurn()},this.recognizer.canceled=(t,e)=>{e.reason===a.Error&&this._handleAzureSpeechError(e),this.stop()}}_handleAzureSpeechError(t){const e=t.errorCode,i=t.errorDetails||"No additional details available";let n="",a=!1;switch(e){case s.NoError:n="alertSomeErrorOccurred";break;case s.AuthenticationFailure:n="alertVoiceServicesUnavailable",a=!0;break;case s.BadRequestParameters:n="alertServiceTemporarilyUnavailable";break;case s.TooManyRequests:n="alertTooManyRequests";break;case s.ConnectionFailure:n="alertConnectionIssue";break;case s.ServiceTimeout:n="alertResponseTimeout";break;case s.ServiceError:n="alertServiceTemporarilyUnavailable";break;case s.RuntimeError:n="alertSomeErrorOccurred";break;case s.Forbidden:n="alertServiceBusy";break;default:n="alertSomeErrorOccurred"}a&&this.bus.emit("event_error_VoiceBot_ExpiredOrInvalidToken",i),this.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:n})}_emitAlert(t,e={}){if("string"!=typeof t||!this.bus)return;if(["alertMicrophoneStartFailed","alertMicrophoneCheckSettings","alertMicrophoneAccessDenied","alertNoMicrophoneDetected","alertMicrophoneError"].includes(t)&&this._isChatModeActive())return;const i={messageKey:t,...e};this.bus.emit("event_command_Alerts_ShowDismissableAlert",i)}_isChatModeActive(){try{const t=this.avatarOrchestrator?.getSnapshot?.(),e=t?.context?.chatSocket?.chatbotMode;return"CHAT"===e}catch(t){return!1}}_setMaxDurationTimeout(){this.maxDurationTimeoutId=setTimeout((()=>{this._completeRecognitionTurn()}),T.speech.maxDurationTimeout)}_completeRecognitionTurn(){this._isStopping||this.stop(),this.sendMessage()}_determineMainLanguage(){let t=null,e=0;for(const[i,n]of Object.entries(this.languageDurations))n>e&&(e=n,t=i);return t}destroy(){try{this.close()}catch(t){}}}class q extends V{constructor(t,e){super("speech-token"),this.auth=t,this.refreshTokenCallback=e,this.tokenRefreshLoop=null}async requestAuthorizationToken(t=T.auth.speechTokenRetries){for(let i=1;i<=t;i++)try{const t=await this.fetchSpeechToken();return this.setConnected(),t}catch(e){if(i===t)throw this.setFailed(),new Error(`Failed to fetch speech token after ${t} attempts`)}}async fetchSpeechToken(){try{const t=await this.auth.callSentifydApi(T.speech.authorizationEndPoint,"POST"),{token:e}=t.data;if(!e)throw new Error("Invalid token structure received from API.");return t.data}catch(t){throw new Error("Failed to fetch data from API.")}}async startTokenRefreshLoop(){await this.stopTokenRefreshLoop(),this.tokenRefreshLoop=setInterval((async()=>{try{const{token:t}=await this.requestAuthorizationToken();this.refreshTokenCallback(t),this.setConnected()}catch(t){this.setDisconnected()}}),T.auth.speechTokenInterval)}async stopTokenRefreshLoop(){this.tokenRefreshLoop&&(clearInterval(this.tokenRefreshLoop),this.tokenRefreshLoop=null)}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.isFailed()?this.setReconnecting():this.setConnecting(),await this.stopTokenRefreshLoop();try{const{token:t}=await this.requestAuthorizationToken();this.refreshTokenCallback(t),await this.startTokenRefreshLoop()}catch(t){this.setFailed()}}}}class G{constructor({speechService:t,speechConfig:e,autoDetectSourceLanguageConfig:i,speechRecognizer:n,bus:a,auth:s,avatarOrchestrator:o,sessionData:r}={}){this.validateDependencies({speechService:t,speechConfig:e,speechRecognizer:n,bus:a,auth:s,avatarOrchestrator:o,sessionData:r}),this.sessionData=r,this.speechService=t,this.speechConfig=e,this.speechRecognizer=n,this.bus=a,this.avatarOrchestrator=o,this.autoDetectSourceLanguageConfig=i,this._currentTurnId=0,this._expectedTurnId=0,this._lastInterruptionTime=0,this.INTERRUPTION_DEBOUNCE=100,this._isHandlingAudioEnd=!1,this.registerEventListeners(),this.speechService.startTokenRefreshLoop()}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize VoiceBot due to missing dependencies: ${e.join(", ")}`)}registerEventListeners(){this._busHandlers=this._busHandlers||[];const t=t=>{this.getNewSpeechToken()};this.bus.on("event_error_VoiceBot_ExpiredOrInvalidToken",t),this._busHandlers.push(["event_error_VoiceBot_ExpiredOrInvalidToken",t])}static async build(t,e,i,n){const{speechService:a,speechConfig:s,autoDetectSourceLanguageConfig:o,speechRecognizer:r}=await this.init(n,t,i,e);return new G({speechService:a,speechConfig:s,autoDetectSourceLanguageConfig:o,speechRecognizer:r,bus:t,auth:i,avatarOrchestrator:e,sessionData:n})}static async init(t,e,i,n){try{const a=t?.language||"en-US",s=(t?.voice,t?.autodetectLanguages||[]);let l=null,h=null;const d=new q(i,(t=>{l&&(l.authorizationToken=t)})),{token:u,region:p}=await d.requestAuthorizationToken();if(!u||!p)throw new Error("Failed to get authorization token");l=o.fromAuthorizationToken(u,p);const g=T?.speech?.vad??{},v=t?.speech?.vad??t?.vad??{},m=v.segmentationSilenceMs??g.segmentationSilenceMs??800,_=v.initialSilenceMs??g.initialSilenceMs??8e3;l.setProperty(r.Speech_SegmentationSilenceTimeoutMs,String(m)),l.setProperty(r.SpeechServiceConnection_InitialSilenceTimeoutMs,String(_));const b=v.strategy??g.strategy,f=v.semantic??g.semantic,y="string"==typeof b?b:!0===f?"Semantic":null;y&&l.setProperty(r.Speech_SegmentationStrategy,y),"multilingual"===a?s.length>0?h=c.fromLanguages(s):l.speechRecognitionLanguage="en-US":l.speechRecognitionLanguage=a;const S=await W.build(l,h,e,n);return{speechService:d,speechConfig:l,autoDetectSourceLanguageConfig:h,speechRecognizer:S}}catch(a){throw new Error("Error in VoiceBot initialization",{cause:a})}}async getNewSpeechToken(){try{const{token:t}=await this.speechService.requestAuthorizationToken();this.speechConfig.authorizationToken=t}catch(t){}}isConversationInProgress(){return!!this.sessionData?.conversation?.conversationId}async startListening(){if(this.speechRecognizer.isListening)return{success:!0,alreadyListening:!0};try{return this.speechRecognizer.isMicDetected||(this.speechRecognizer.close(),this.speechRecognizer=await W.build(this.speechConfig,this.autoDetectSourceLanguageConfig,this.bus,this.avatarOrchestrator),this.speechRecognizer.isMicDetected=!0),this.speechRecognizer.start(),{success:!0,started:!0}}catch(t){return{success:!1,error:t.message||"Failed to start speech recognition"}}}stopListening(){try{return this.speechRecognizer.stop(),{success:!0}}catch(t){return{success:!1,error:t.message||"Failed to stop speech recognition"}}}async updateSpeechLanguage(t){this.speechConfig.speechRecognitionLanguage=t,this.speechRecognizer.close(),this.speechRecognizer=await W.build(this.speechConfig,this.autoDetectSourceLanguageConfig,this.bus,this.avatarOrchestrator)}destroy(){this._busHandlers?.forEach((([t,e])=>this.bus.off(t,e))),this._busHandlers=[],this.speechRecognizer?.destroy(),this.speechService?.stopTokenRefreshLoop()}}const K={enabled:!0,micThreshold:.0033,avatarQuietFloor:.009,minSignalRatio:1.2,minSignalRatioWhileSpeaking:.38,minSignalDelta:.0028,absoluteMicOverride:.012,minDurationMs:200,cooldownMs:1500,envelopeAttack:.6,envelopeRelease:.8,leakAdaptRate:.06,leakFloor:0,leakCeil:.25,leakMargin:.012,leakDecayHoldMs:300,leakDecayRate:.2,leakMinAvatar:.01,noiseStdK:3.4,minSnr:3.2,noiseMinSamples:90,warmupMs:400,speakingGuardMs:200,minConsecutive:3,hangoverMs:100,minAbsQuiet:.0032,bandpassHz:[350,3400],minDurationWhileSpeakingMs:260,debug:!1};class J{constructor({talkingAvatar:t,avatarOrchestrator:e,config:i}={}){this.talkingAvatar=t,this.avatarOrchestrator=e,this.config={...K,...i||{}},this._audioCtx=null,this._micStream=null,this._micSource=null,this._micBpf=null,this._micAnalyser=null,this._micBuffer=null,this._avatarAnalyser=null,this._avatarBuffer=null,this._avatarAnalyserMissing=!1,this._armed=!1,this._candidateSince=null,this._lastTriggerTime=0,this._rafId=null,this._projectionUnsub=null,this._isDestroyed=!1,this._lastTickLog=0,this._micEnvelope=0,this._avatarEnvelope=0,this._leakEstimate=this.config.leakFloor??0,this._lastAvatarBelowMin=null,this._lastFrameTs=0,this._lastAudioResumeAttempt=0,this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._resetNoiseStats()}async init(){if(this.config.enabled)try{await this._ensureMicAnalyser(),this._subscribeToState()}catch(t){this._teardown()}}destroy(){this._isDestroyed=!0,this._unsubscribe(),this._disarm(),this._teardown()}async _ensureMicAnalyser(){if(this._micAnalyser)return;if("undefined"==typeof navigator||!navigator.mediaDevices?.getUserMedia)throw new Error("Media devices API not available");this._audioCtx=this._audioCtx||new(window.AudioContext||window.webkitAudioContext);const t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1}});this._micStream=t,this._micSource=this._audioCtx.createMediaStreamSource(t),this._micBpf=this._audioCtx.createBiquadFilter(),this._micBpf.type="bandpass";const[e,i]=Array.isArray(this.config.bandpassHz)&&2===this.config.bandpassHz.length?this.config.bandpassHz:[300,3e3],n=Math.max(10,Math.min(e,i||e)),a=Math.max(1.5*n,i||10*n),s=Math.sqrt(n*a);this._micBpf.frequency.value=Number.isFinite(s)?s:1e3;const o=Math.log2(a/n),r=Math.sinh(Math.log(2)/2*Math.max(o,.01)),c=r>0?1/(2*r):1;this._micBpf.Q.value=Math.max(.5,Math.min(4,c||1)),this._micAnalyser=this._audioCtx.createAnalyser(),this._micAnalyser.fftSize=512,this._micAnalyser.smoothingTimeConstant=.4,this._micSource.connect(this._micBpf).connect(this._micAnalyser),this._micBuffer=new Float32Array(this._micAnalyser.fftSize),this._debugEvent("mic-ready",{sampleRate:this._audioCtx.sampleRate,fftSize:this._micAnalyser.fftSize})}_subscribeToState(){this.avatarOrchestrator?.subscribeProjected&&(this._projectionUnsub=this.avatarOrchestrator.subscribeProjected((t=>{if(this._isDestroyed)return;const e=t?.lifecycle?.conversationSubstate;"speaking"===e?this._arm():this._disarm()})))}_unsubscribe(){if("function"==typeof this._projectionUnsub){try{this._projectionUnsub()}catch(t){}this._projectionUnsub=null}}_arm(){if(!this._micAnalyser)return;if(!this._avatarAnalyser&&!this._avatarAnalyserMissing){if(this._avatarAnalyser=this.talkingAvatar?.getSpeechAnalyzerNode?.()??null,!this._avatarAnalyser)return this._debugEvent("avatar-analyser-missing",{}),this._avatarAnalyserMissing=!0,void(this._armed=!1);this._avatarAnalyser.smoothingTimeConstant=Math.min(this._avatarAnalyser.smoothingTimeConstant??.4,.6),this._avatarBuffer=new Float32Array(this._avatarAnalyser.fftSize),this._debugEvent("avatar-analyser-ready",{fftSize:this._avatarAnalyser.fftSize})}if(this._armed)return;this._armed=!0,this._candidateSince=null,this._micEnvelope=0,this._avatarEnvelope=0,this._resetNoiseStats(),this._lastFrameTs=0,this._leakEstimate=Math.max(this.config.leakFloor??0,Math.min(this._leakEstimate,this.config.leakCeil??1));const t="undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now();this._armedAt=t,this._consecHits=0,this._lastQualifyTs=0,this._lastAvatarBelowMin=null,this._rafId||(this._rafId=requestAnimationFrame(this._monitorLoop)),this._debugEvent("armed",{micThreshold:this.config.micThreshold,avatarQuietFloor:this.config.avatarQuietFloor,minSignalRatio:this.config.minSignalRatio,minSignalRatioWhileSpeaking:this.config.minSignalRatioWhileSpeaking,minSignalDelta:this.config.minSignalDelta,absoluteMicOverride:this.config.absoluteMicOverride,minDurationMs:this.config.minDurationMs,cooldownMs:this.config.cooldownMs,warmupMs:this.config.warmupMs,speakingGuardMs:this.config.speakingGuardMs,minConsecutive:this.config.minConsecutive,hangoverMs:this.config.hangoverMs,bandpassHz:this.config.bandpassHz})}_disarm(){(this._armed||this._rafId)&&(this._armed=!1,this._candidateSince=null,this._micEnvelope=0,this._avatarEnvelope=0,this._resetNoiseStats(),this._lastFrameTs=0,this._leakEstimate=Math.max(this.config.leakFloor??0,Math.min(this._leakEstimate,this.config.leakCeil??1)),this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._lastAvatarBelowMin=null,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null),this._debugEvent("disarmed",{}))}_monitorLoop=()=>{if(this._isDestroyed)return;if(!this._armed)return void(this._rafId=null);const t=performance.now(),e=this._lastFrameTs?t-this._lastFrameTs:16.7;this._lastFrameTs=t,"suspended"===this._audioCtx?.state&&(0===this._lastAudioResumeAttempt||t-this._lastAudioResumeAttempt>=1e3)&&(this._lastAudioResumeAttempt=t,this._audioCtx.resume().catch((()=>{})));const i=this._clamp01(this._readRms(this._micAnalyser,this._micBuffer)),n=this._avatarAnalyser?this._readRms(this._avatarAnalyser,this._avatarBuffer):0,a=this._clamp01(n),s=this._updateEnvelope("_micEnvelope",i,e),o=this._updateEnvelope("_avatarEnvelope",a,e),r=this._updateLeakEstimate({micSignal:s,avatarSignal:o,candidateActive:!!this._candidateSince}),c=o>(this.config.leakMinAvatar??.01)?.85*(r+(this.config.leakMargin??.012)):0,l=Math.max(0,s-o*c),h=o>5e-4?l/Math.max(o,5e-4):1/0,d=l-o,u=o<=this.config.avatarQuietFloor,p=l>=this.config.micThreshold,g=s>=this.config.absoluteMicOverride,v=t-(this._armedAt||t),m=v<(this.config.warmupMs??400),_=!u&&v<(this.config.speakingGuardMs??250);!g&&!this._candidateSince&&u&&!m&&0===this._consecHits&&l<1.2*this.config.micThreshold&&this._updateNoiseStats(l);const b=this._noiseCount>=(this.config.noiseMinSamples??90),f=this._noiseMean,y=this._getNoiseStd(),S=b?(l+1e-7)/(f+1e-7):0,k=this.config.noiseStdK??3.2,C=b&&l>=f+k*y,w=b&&S>=(this.config.minSnr??3),A=!!u||g||h>=(this.config.minSignalRatioWhileSpeaking??this.config.minSignalRatio)||d>=this.config.minSignalDelta,x=this.config.minAbsQuiet??0,T=!u||l>=x,I=u?T&&(g||(b?C||w:p)):g||p,E=!m&&!_,M=E&&I&&A,D=this.config.minConsecutive??4;if(M)this._consecHits+=1,this._lastQualifyTs=t;else{const e=this.config.hangoverMs??120,i=t-this._lastQualifyTs<=e;this._consecHits=i?this._consecHits:0}this._debugTick({micLevel:i,avatarLevel:a,micSignal:s,avatarSignal:o,effectiveMic:l,leak:r,leakApply:c,noiseMean:f,noiseStd:y,noiseSamples:this._noiseCount,snr:S,exceedsNoise:C,snrDominates:w,ratio:h,delta:d,meetsMicThreshold:p,avatarQuiet:u,absoluteOverride:g,absQuietOK:T,energyOK:I,energyQualified:I,competitionOK:A,noiseReady:b,warmup:m,speakingGuard:_,frameAllowed:E,frameQualifies:M,qualifies:M,consecutiveHits:this._consecHits,requiredHits:D,candidateDuration:this._candidateSince?t-this._candidateSince:0,cooldownRemaining:Math.max(0,this.config.cooldownMs-(t-this._lastTriggerTime))}),this._consecHits>=D?this._candidateSince||(this._candidateSince=t,this._debugEvent("candidate-start",{micLevel:i,avatarLevel:a,micSignal:s,avatarSignal:o,effectiveMic:l,leak:r,noiseMean:f,noiseStd:y,snr:S,ratio:h,delta:d})):this._candidateSince&&!M&&t-this._lastQualifyTs>(this.config.hangoverMs??120)&&(this._debugEvent("candidate-reset",{micLevel:i,avatarLevel:a,micSignal:s,avatarSignal:o,effectiveMic:l,leak:r,noiseMean:f,noiseStd:y,snr:S,ratio:h,delta:d}),this._candidateSince=null,this._consecHits=0);const R=u?this.config.minDurationMs??200:this.config.minDurationWhileSpeakingMs??(this.config.minDurationMs??200)+60,P=this._candidateSince&&t-this._candidateSince>=R,O=t-this._lastTriggerTime>=this.config.cooldownMs;P&&O?this._emitBargeIn({micLevel:i,avatarLevel:a,micSignal:s,avatarSignal:o,effectiveMic:l,leak:r,noiseMean:f,noiseStd:y,snr:S,ratio:h,delta:d,timestamp:t}):P&&!O&&this._debugEvent("cooldown-block",{micLevel:i,avatarLevel:a,micSignal:s,avatarSignal:o,effectiveMic:l,leak:r,noiseMean:f,noiseStd:y,snr:S,ratio:h,delta:d,cooldownRemaining:Math.max(0,this.config.cooldownMs-(t-this._lastTriggerTime))}),this._rafId=requestAnimationFrame(this._monitorLoop)};_emitBargeIn({micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:n,effectiveMic:a,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:l,delta:h,timestamp:d}){this._lastTriggerTime=d,this._candidateSince=null,this._consecHits=0,this._lastQualifyTs=0,this._debugEvent("trigger",{micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:n,effectiveMic:a,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:l,delta:h,timestamp:d});try{this.avatarOrchestrator?.sendEvent?.("VOICE_BARGE_IN",{micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:n,effectiveMic:a,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:l,delta:h,timestamp:d})}catch(u){}}_readRms(t,e){if(!t)return 0;try{t.getFloatTimeDomainData(e)}catch(n){return 0}let i=0;for(let a=0;a<e.length;a++){const t=e[a];i+=t*t}return Math.sqrt(i/e.length)}_teardown(){if(this._micStream&&(this._micStream.getTracks().forEach((t=>{try{t.stop()}catch(e){}})),this._micStream=null),this._micSource){try{this._micSource.disconnect()}catch(t){}this._micSource=null}if(this._micBpf){try{this._micBpf.disconnect()}catch(t){}this._micBpf=null}if(this._micAnalyser){try{this._micAnalyser.disconnect()}catch(t){}this._micAnalyser=null}if(this._audioCtx){try{this._audioCtx.close()}catch(t){}this._audioCtx=null}this._micBuffer=null,this._avatarAnalyser=null,this._avatarBuffer=null,this._avatarAnalyserMissing=!1,this._lastTickLog=0,this._micEnvelope=0,this._avatarEnvelope=0,this._leakEstimate=this.config.leakFloor??0,this._lastAvatarBelowMin=null,this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._resetNoiseStats(),this._lastFrameTs=0,this._lastAudioResumeAttempt=0}_debugTick(t){if(!this.config.debug)return;const e=performance.now?performance.now():Date.now();e-this._lastTickLog<150||(this._lastTickLog=e)}_debugEvent(t,e){this.config.debug}_updateEnvelope(t,e,i=16.7){const n="number"==typeof this[t]?this[t]:e,a=Math.min(Math.max(this.config.envelopeAttack,0),.999),s=Math.min(Math.max(this.config.envelopeRelease,0),.999),o=e>=n?a:s,r=Math.max(i/16.7,.1),c=n+(e-n)*(1-Math.pow(o,r)),l=this._clamp01(c);return this[t]=l,l}_updateLeakEstimate({micSignal:t,avatarSignal:e,candidateActive:i}){const n=this.config.leakMinAvatar??0,a=this.config.leakAdaptRate??.1,s=this.config.leakFloor??0,o=this.config.leakCeil??1,r="undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now();let c=this._leakEstimate??s;if(i||this._consecHits>0)return c;const l=this._noiseCount>=(this.config.noiseMinSamples??90),h=this._getNoiseStd(),d=this._noiseMean,u=l&&t>=d+(this.config.noiseStdK??3.2)*h;if(e>n&&t<.8*this.config.absoluteMicOverride&&!u){const i=t/Math.max(e,1e-5);c+=(Math.max(s,Math.min(i,o))-c)*a,this._leakEstimate=c,this._debugLeakUpdate({ratio:i,estimate:c}),this._lastAvatarBelowMin=null}else if(e<=n&&c>s){const t=this.config.leakDecayHoldMs??1e3,i=this.config.leakDecayRate??.1*a;null==this._lastAvatarBelowMin&&(this._lastAvatarBelowMin=r),e<=n?r-this._lastAvatarBelowMin>=t&&(c+=(s-c)*i):this._lastAvatarBelowMin=r,this._leakEstimate=Math.max(s,c)}return this._leakEstimate??s}_debugLeakUpdate({ratio:t,estimate:e}){this.config.debug&&this._debugEvent("leak-update",{ratio:t,estimate:e})}_resetNoiseStats(){this._noiseMean=0,this._noiseVar=0,this._noiseCount=0}_updateNoiseStats(t){const e=this._clamp01(t);if(!Number.isFinite(e))return;this._noiseCount>=500&&(this._noiseCount=Math.floor(350),this._noiseMean*=.95,this._noiseVar*=.9),this._noiseCount+=1;const i=e-this._noiseMean;this._noiseMean+=i/this._noiseCount;const n=e-this._noiseMean;this._noiseVar+=i*n}_getNoiseStd(){return this._noiseCount<2?0:Math.sqrt(Math.max(this._noiseVar/(this._noiseCount-1),0))}_clamp01(t){return Number.isFinite(t)?t<=0?0:t>=1?1:t:0}}let Q=null;const Y={setInstance(t){Q=t},getItem:async t=>{if(!Q)throw new Error("Storage instance not initialized");return Q.getItem(t)},setItem:async(t,e)=>{if(!Q)throw new Error("Storage instance not initialized");return Q.setItem(t,e)},removeItem:async t=>{if(!Q)throw new Error("Storage instance not initialized");return Q.removeItem(t)}};class Z extends Error{constructor(t,{statusCode:e=null,reason:i=null}={}){super(t),this.name="LoginError",this.statusCode=e,this.reason=i}}async function X(t){try{const e=await fetch(`${t.serverBaseURL}/api/v1/chatbot/login`,{method:"POST",headers:{"Content-Type":"application/json","X-Sentifyd-Origin":t.targetApp},body:JSON.stringify({avatar_api_key:t.getAvatarAPIKey()})});if(!e.ok){const i=function(t){switch(t){case 404:return{message:"Avatar not found.",reason:"avatar-not-found",shouldStopRetrying:!0};case 401:return{message:"Unauthorized avatar login attempt.",reason:"unauthorized",shouldStopRetrying:!1};case 429:return{message:"Too many login attempts. Please retry later.",reason:"rate-limited",shouldStopRetrying:!1};default:return{message:`Login failed with status code ${t}.`,reason:"login-failed",shouldStopRetrying:!1}}}(e.status);throw i.shouldStopRetrying&&(t.retries=T.auth.maxLoginRetries),new Z(i.message,{statusCode:e.status,reason:i.reason})}const i=await e.json();await async function(t,e){try{const i=e?.data?.avatar_params;if(!i||!i.avatarId)throw new Error("Invalid avatar parameters received in login response.");const n=i.avatarId;t.id=n;const a={accessToken:e.data.access_token,refreshToken:e.data.refresh_token,avatarParameters:i};await t.updateAuthData(a),t.setConnected()}catch(i){throw new Error(`Failed to process login response: ${i.message}`)}}(t,i)}catch(e){throw e}}const tt=new class{constructor(t=1){this.max=t,this._fns=[],this._active=0}get remaining(){return this._fns.length}get active(){return this._active}take(t){this._fns.push(t),this._try()}_done(){this._active-=1,this._try()}_try(){if(this._active===this.max||0===this._fns.length)return;const t=this._fns.shift();this._active+=1,t&&t(this._done.bind(this))}}(1);class et{constructor({serverBaseURL:t,getRefreshToken:e,updateAccessToken:i,onSuccess:n,onError:a}){this.serverBaseURL=t,this.getRefreshToken=e,this.onSuccess=n,this.onError=a,this.tokenRefreshIntervalId=null,this.updateAccessToken=i}startTokenRefreshInterval(){this.tokenRefreshIntervalId&&clearInterval(this.tokenRefreshIntervalId),this.tokenRefreshIntervalId=setInterval((async()=>{try{await this.refreshAccessToken()}catch(t){}}),T.auth.tokenRefreshInterval)}stopTokenRefreshInterval(){this.tokenRefreshIntervalId&&(clearInterval(this.tokenRefreshIntervalId),this.tokenRefreshIntervalId=null)}async refreshAccessToken(){return new Promise(((t,e)=>{tt.take((async i=>{try{const e=this.getRefreshToken();if(!e)throw new Error("No refresh token available");const i=await fetch(`${this.serverBaseURL}/api/v1/chatbot/token_exchange`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e}});if(!i.ok){const t=`Failed to refresh JWT token (Status: ${i.status} ${i.statusText})`;throw"function"==typeof this.onError&&this.onError(new Error(t)),new Error(t)}const n=await i.json();if(!n?.data?.access_token)throw new Error("Invalid token data received during refresh.");this.updateAccessToken&&await this.updateAccessToken(n.data.access_token),"function"==typeof this.onSuccess&&this.onSuccess(n.data.access_token),t(!0)}catch(n){"function"==typeof this.onError&&this.onError(n),e(n)}finally{i()}}))}))}}class it extends V{#t;#e;#i;constructor(t="",e="",i=""){if(it._instance)return it._instance;super("authentication"),it._instance=this,this.#t=t,this.tokenEndpoint=e,this.#e=null,this.#i=null,this.avatarParameters=null,this.id=i,this.serverBaseURL=T.auth.serverBaseURL||"",this.targetApp="",this.lastFailureDetails=null,this.tokenRefresher=new et({serverBaseURL:this.serverBaseURL,getRefreshToken:()=>this.#i,updateAccessToken:async t=>await this.updateAuthData({accessToken:t}),onSuccess:()=>{},onError:t=>{this.handleAuthenticationFailure("Error refreshing access token",t)}})}async init(t="web",e="",i="",n=""){this.id=n,this.targetApp=t,this.#t=e,this.tokenEndpoint=i;try{return await this.authenticate(),this.startTokenRefreshInterval(),!0}catch(a){return this.handleAuthenticationFailure(`Error during authentication initialization: ${a.message}`,a),!1}}async authenticate(){for(this.retries=0,this.setConnecting();this.retries<T.auth.maxLoginRetries;)try{if(this.#t?.trim())await X(this);else{if(!this.tokenEndpoint?.trim()){const t="authenticate: No API key or token endpoint provided for authentication.";throw this.handleAuthenticationFailure(t),new Error(t)}await this.requestDataFromServer()}return void this.clearFailureDetails()}catch(t){if(this.setDisconnected(),this.recordFailure({message:`authenticate: Attempt #${this.retries+1} failed`,reason:t instanceof Z?t.reason:t?.message||null,statusCode:t instanceof Z&&"number"==typeof t.statusCode?t.statusCode:null}),this.retries++,this.retries>=T.auth.maxLoginRetries){const e=`authenticate: All ${T.auth.maxLoginRetries} authentication attempts failed.`;if(this.handleAuthenticationFailure(e,t),t instanceof Error)throw t;throw new Error(`${e} Last error: ${t}`)}await k(T.auth.loginRetryDelay)}}startTokenRefreshInterval(){this.tokenRefresher.startTokenRefreshInterval()}stopTokenRefreshInterval(){this.tokenRefresher.stopTokenRefreshInterval()}isTokenCloseToExpiration(){if(!this.#e)return!0;try{const{exp:t}=l(this.#e);if(!t)return!0;if(1e3*t-Date.now()<=T.auth.closeToExpirationLimit)return!0}catch(t){return!0}return!1}async callSentifydApi(t,e="POST",i=null){if(!this.isConnected())throw new Error("Cannot call the API without active authentication");const n=`${this.serverBaseURL}${t}`,a=new Headers({"Content-Type":"application/json"}),s=this.getAccessToken();if(!s)throw new Error("Cannot call the API without an access token");a.append("Authorization",`Bearer ${s}`);const o={method:e,headers:a,body:i?JSON.stringify(i):void 0};try{let t=await fetch(n,o);if(401===t.status)try{await this.authenticate();const e={...o,headers:{...o.headers,Authorization:`Bearer ${this.getAccessToken()}`}};if(t=await fetch(n,e),401===t.status)throw this.handleAuthenticationFailure("callSentifydApi: Authentication failed in API call. Not authorized."),new Error(`API call failed: ${t.statusText} (Status: ${t.status})`)}catch(r){throw this.handleAuthenticationFailure("callSentifydApi: Authentication failed in API call. Not authorized."),new Error("API call failed")}if(!t.ok)throw new Error(`API call failed: ${t.statusText} (Status: ${t.status})`);return await t.json()}catch(r){throw r}}async isAuthRequired(){const t=this.#n();return!(t&&t.accessToken&&t.refreshToken&&t.avatarParameters&&!this.isTokenCloseToExpiration())}async logout(){this.id&&await async function(t){if(t)try{await Y.removeItem(`authData_${t}`)}catch(e){}}(this.id),this.stopTokenRefreshInterval(),this.#e=null,this.#i=null,this.avatarParameters=null,this.clearFailureDetails(),this.setDisconnected()}async#a(){if(!this.id)return!1;const t=await async function(t){if(!t)return null;try{const e=await Y.getItem(`authData_${t}`);return e?JSON.parse(e):null}catch(e){return null}}(this.id);if(!t)return!1;try{return this.#e=t.accessToken,this.#i=t.refreshToken,this.avatarParameters=t.avatarParameters,await this.isAuthRequired()?(this.setDisconnected(),!1):(this.setConnected(),await this.updateAvatarParametersFromServer(),!0)}catch(e){return this.setDisconnected(),!1}}#n(){return this.id&&this.#e&&this.#i&&this.avatarParameters?{accessToken:this.#e,refreshToken:this.#i,avatarParameters:this.avatarParameters}:null}getAccessToken(){return this.#e||null}getRefreshToken(){return this.#i||null}getAvatarAPIKey(){return this.#t}async updateAccessToken(t){await this.updateAuthData({accessToken:t})}getAvatarParameters(){return this.avatarParameters||null}async updateAuthData({accessToken:t,refreshToken:e,avatarParameters:i}){const n=this.#n()||{};t&&(this.#e=t,n.accessToken=t),e&&(this.#i=e,n.refreshToken=e),i&&(this.avatarParameters=i,n.avatarParameters=i);try{await async function(t,e){if(t)try{await Y.setItem(`authData_${t}`,JSON.stringify(e))}catch(i){}}(this.id,n),this.clearFailureDetails()}catch(a){}}async requestDataFromServer(){if(!this.tokenEndpoint?.trim())throw new Error("requestDataFromServer: Token URL is not specified.");try{const t=await fetch(this.tokenEndpoint,{method:"GET"});if(!t.ok)throw new Error(`requestDataFromServer: Failed to request tokens (Status: ${t.status} ${t.statusText})`);const e=await t.json();if(!this.#s(e))throw new Error("requestDataFromServer: Invalid token response received from server.");await this.updateAuthData({accessToken:e.tokens.accessToken,refreshToken:e.tokens.refreshToken,avatarParameters:e.avatarParameters}),this.setConnected()}catch(t){throw this.setDisconnected(),t}}#s(t){return t?.tokens?.accessToken&&t?.tokens?.refreshToken&&t?.avatarParameters}async updateAvatarParametersFromServer(){try{const t=await this.callSentifydApi("/api/v1/chatbot/get-avatar-params","POST");if(!t||!t.data||!t.data.avatar_params)return;this.avatarParameters=t.data.avatar_params,this.updateAuthData({avatarParameters:this.avatarParameters})}catch(t){}}handleAuthenticationFailure(t,e=null){this.recordFailure({message:t,reason:e instanceof Z?e.reason:e instanceof Error?e.message:null,statusCode:e instanceof Z&&"number"==typeof e.statusCode?e.statusCode:null}),this.setFailed()}recordFailure({message:t,reason:e=null,statusCode:i=null}={}){this.lastFailureDetails={message:t||"Unknown authentication error",reason:e??(t||"Unknown authentication error"),statusCode:i,timestamp:Date.now()}}clearFailureDetails(){this.lastFailureDetails=null}getLastFailureDetails(){return this.lastFailureDetails?{...this.lastFailureDetails}:null}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.stopTokenRefreshInterval(),this.isFailed()?this.setReconnecting():this.setConnecting();try{await this.authenticate(),this.isConnected()?this.startTokenRefreshInterval():this.setFailed()}catch(t){this.handleAuthenticationFailure("Authentication reconnect failed",t)}}}static resetInstance(){it._instance=null}}class nt{constructor(t,e=h){this.avatarId=t,this.conversationData={id:void 0,transcript:[],currentTurnId:0},this.lastDetectedLanguage=null,this.uuidGenerator=e,this.lastStartWasResumeAttempt=!1,this.transcriptLengthBeforeResume=0}get conversationId(){return this.conversationData.id}set conversationId(t){this.conversationData.id=t}get transcript(){return this.conversationData.transcript}set transcript(t){this.conversationData.transcript=t}get currentTurnId(){return this.conversationData.currentTurnId}set currentTurnId(t){this.conversationData.currentTurnId=t}incrementTurnId(){return this.conversationData.currentTurnId++,this.conversationData.currentTurnId}async getConversationData(){if(!this.avatarId)return null;const t=await Y.getItem(`conversationData_${this.avatarId}`),e={id:void 0,transcript:[],currentTurnId:0};return this.conversationData=t?{...e,...JSON.parse(t)}:e,this.conversationData}async saveConversationData(){this.avatarId&&await Y.setItem(`conversationData_${this.avatarId}`,JSON.stringify(this.conversationData))}async notifyConversationInit(){await this.getConversationData(),this.conversationId||(await this.clearOngoingConversation(),await this.generateNewConversationId())}async notifyConversationStart(t=!1){if(t)this.lastStartWasResumeAttempt=!1,this.transcriptLengthBeforeResume=0,await this.clearOngoingConversation(),await this.generateNewConversationId(),this.incrementTurnId();else{await this.getConversationData();const t=!!this.conversationId,e=Array.isArray(this.transcript)&&this.transcript.length>0;this.lastStartWasResumeAttempt=t&&e,this.transcriptLengthBeforeResume=e?this.transcript.length:0,this.conversationId||(await this.clearOngoingConversation(),await this.generateNewConversationId()),this.incrementTurnId()}}async notifyConversationEnd(){this.lastStartWasResumeAttempt=!1,await this.clearOngoingConversation()}async clearOngoingConversation(){this.conversationData={id:void 0,transcript:[],currentTurnId:0};try{await Y.removeItem(`conversationData_${this.avatarId}`)}catch(t){await this.saveConversationData()}}async discardConversationHistory(){const t=this.conversationId,e=this.currentTurnId;this.conversationData={id:t,transcript:[],currentTurnId:e},await this.saveConversationData()}async generateNewConversationId(){const t=this.uuidGenerator();this.conversationId=t,await this.saveConversationData()}async appendMessage(t,e,i){if(!this.conversationId)return null;const n={speaker:i,messageText:C(t),time:e};return this.transcript.push(n),await this.saveConversationData(),n}async handleConversationSuccessfulStart(t){const e=t?.isInProgress,i=t?.conversationId,n=this.conversationId,a=!!this.lastStartWasResumeAttempt;let s=!1;if(!1===e&&(s=!0),i&&n&&i!==n&&(this.conversationId=i,s=!0),a&&s){const t=this.transcript.slice(this.transcriptLengthBeforeResume);this.conversationData.transcript=t,await this.saveConversationData()}return{serverStartedNew:s,resumeAttempt:a,resumeFailed:s&&a}}}class at{constructor(){if(at._instance)return at._instance;this._avatarId=null,this._avatarName="",this._avatarItem=null,this._trainingId=null,this._language="",this._autodetectLanguages=[],this._voice="",this._lipsyncType="words",this._wordsPerMinute=150,this._userData={username:"",phoneNumber:"",email:"",isTermsAccepted:!1},this.conversation=null,at._instance=this,Object.seal(this)}static getInstance(){return at._instance||(at._instance=new at),at._instance}static hasInstance(){return null!==at._instance&&void 0!==at._instance}static resetInstance(){if(at._instance)try{return at._instance.destroy(),at._instance=null,!0}catch(t){return!1}return!0}async init(t,e){const{avatarId:i,avatarName:n,trainingId:a,language:s,autodetectLanguages:o,voice:r,wordsPerMinute:c}=t;if(![i,n,e,s,r].every((t=>null!=t&&""!==t))||!Array.isArray(o))return!1;this._trainingId=null===a||""===a?null:a,this._avatarId=i,this._avatarName=n,this._avatarItem=e,this._language=s,this._autodetectLanguages=o,this._voice=r,this._lipsyncType=e?.lipsyncType||"words",this._wordsPerMinute=c||150;try{return this.conversation=new nt(this._avatarId),!0}catch(l){return!1}}get isUserDataDefined(){return this._userData.username&&!0===this._userData.isTermsAccepted}get avatarId(){return this._avatarId}set avatarId(t){this._avatarId=t,this.conversation&&(this.conversation.avatarId=t)}get avatarName(){return this._avatarName}set avatarName(t){"string"==typeof t&&""!==t.trim()&&(this._avatarName=t)}get avatarItem(){return this._avatarItem}set avatarItem(t){t&&"object"==typeof t&&(this._avatarItem=t)}get trainingId(){return this._trainingId}set trainingId(t){(null==t||"string"==typeof t&&""!==t.trim())&&(this._trainingId=t)}get language(){return this._language}set language(t){"string"==typeof t&&""!==t.trim()&&(this._language=t)}get autodetectLanguages(){return this._autodetectLanguages}set autodetectLanguages(t){Array.isArray(t)&&(this._autodetectLanguages=t)}get voice(){return this._voice}set voice(t){"string"==typeof t&&""!==t.trim()&&(this._voice=t)}get lipsyncType(){return this._lipsyncType}set lipsyncType(t){["words","visemes","blendshapes"].includes(t)&&(this._lipsyncType=t)}get wordsPerMinute(){return this._wordsPerMinute}set wordsPerMinute(t){"number"!=typeof t||t<=0||(this._wordsPerMinute=t)}get username(){return this._userData.username}set username(t){"string"==typeof t&&""!==t.trim()&&(this._userData.username=t)}get phoneNumber(){return this._userData.phoneNumber}set phoneNumber(t){"string"==typeof t&&""!==t.trim()&&(this._userData.phoneNumber=t)}get email(){return this._userData.email}set email(t){"string"==typeof t&&""!==t.trim()&&(this._userData.email=t)}get isTermsAccepted(){return this._userData.isTermsAccepted}set isTermsAccepted(t){"boolean"==typeof t&&(this._userData.isTermsAccepted=t)}destroy(){try{this.conversation&&"function"==typeof this.conversation.destroy&&this.conversation.destroy()}catch(t){}}}function st(t){try{t?.talkingAvatar?.liveCaptions?.clearCaptions?.()}catch(e){}try{t?.bus?.emit?.("event_command_UI_ClearCaptions")}catch(e){}}at._instance=null;const ot=d({id:"avatarOrchestrator",context:({input:t})=>({bus:t?.bus??null,talkingAvatar:t?.talkingAvatar??null,chatSocket:t?.chatSocket??null,voiceBot:t?.voiceBot??null,conversation:t?.conversation??null,eventPayload:null,isPageVisible:!0,currentPage:"LoaderPage",pendingStart:null,userSilenced:!1,initFailed:!1,firstConnectionCompleted:!1}),type:"parallel",states:{lifecycle:{initial:"init",states:{init:{initial:"initializing",states:{initializing:{id:"initializing",on:{READY:{target:"complete",actions:["onLeaveInitializing"]},FAIL:{target:"failed",actions:u({initFailed:!0})}}},failed:{id:"failed",on:{RETRY:{target:"initializing"},CONNECT:{target:"initializing"}}},complete:{always:{target:"#avatarOrchestrator.lifecycle.conversation.stopped"}}}},checkingResume:{id:"checkingResume",invoke:{id:"checkResumeOnStart",src:"checkResumeActor",input:({context:t})=>({conversation:t.conversation,bus:t.bus}),onDone:[{target:"conversation.autoResuming",guard:({event:t})=>!!t.output?.resumable},{target:"conversation.stopped"}],onError:{target:"conversation.stopped"}}},conversation:{initial:"stopped",on:{CONVERSATION_TIMEOUT:{target:".timedOut"}},states:{stopped:{id:"stopped",on:{START_CONVERSATION:[{guard:({context:t})=>!t.isPageVisible,actions:"onDeferStart",target:void 0},{target:"inProgress.startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}],INIT_CONVERSATION:{target:"initializingConversation"},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},RESTORED_CONNECTION:{target:"#checkingResume"},AVATAR_INITIALIZED:{target:"#checkingResume"},CONVERSATION_INIT_SUCCESS:{actions:["onConversationInitSuccess"]},CONVERSATION_INIT_FAILED:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})},CONVERSATION_TIMEOUT:{target:"#avatarOrchestrator.lifecycle.conversation.timedOut"},DISCONNECT:{actions:[]},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},timedOut:{id:"timedOut",entry:[({context:t,event:e})=>{try{const i=e?.payload?.conversationId??t?.conversation?.conversationId;t.bus?.emit?.("event_status_Conversation_TimedOut",{conversationId:i})}catch(i){}}],on:{START_CONVERSATION:[{guard:({context:t})=>!t.isPageVisible,actions:"onDeferStart",target:void 0},{target:"inProgress.startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}],INIT_CONVERSATION:{target:"initializingConversation"},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},RESTORED_CONNECTION:{target:"#checkingResume"},AVATAR_INITIALIZED:{target:"#checkingResume"},CONVERSATION_INIT_SUCCESS:{actions:["onConversationInitSuccess"]},CONVERSATION_INIT_FAILED:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},autoResuming:{id:"autoResuming",tags:["thinking","inputs_blocked"],entry:["onStartingConversation"],invoke:{id:"autoResumeService",src:"startConversationService",input:({context:t})=>({isNew:!1,skipFallback:!0,bus:t.bus,conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar}),onDone:[{guard:({event:t})=>"resume_silent"===t.output?.data?.dataType,target:"inProgress.idle",actions:"onConversationStartSuccess"},{target:"inProgress.thinking",actions:"onConversationStartSuccess"}],onError:{target:"resumeExpired",actions:["onAutoResumeFailed"]}},on:{AI_MESSAGE_RECEIVED:{actions:"handleAiMessage"},AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"inProgress.pendingAudioStart",actions:["onStreamStart"]},IDLE:"inProgress.idle"}},resumeExpired:{id:"resumeExpired",entry:[({context:t})=>{try{const e=t?.conversation?.conversationId;t.bus?.emit?.("event_status_Conversation_ResumeExpired",{conversationId:e})}catch(e){}}],on:{START_NEW_CONVERSATION:{target:"inProgress.startingConversation",actions:u({eventPayload:{fresh:!0}})},DISMISS:{target:"stopped",actions:[({context:t})=>{try{t.conversation?.clearOngoingConversation?.()}catch(e){}}]},CLEAR_CONVERSATION:{target:"clearingConversation"},END_CONVERSATION:{target:"endingConversation"},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},paused:{id:"paused",entry:["onConversationPaused"],tags:["conversation_paused","inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]},RECONNECT:[{target:"inProgress.idle",guard:"hasActiveConversation"},{target:"clearingConversation"}],RESTORED_CONNECTION:[{target:"inProgress.idle",guard:"hasActiveConversation"},{target:"clearingConversation"}],END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},initializingConversation:{id:"initializingConversation",invoke:{id:"initConversationActor",src:"initConversationActor",input:({context:t})=>({conversation:t.conversation,chatSocket:t.chatSocket,bus:t.bus}),onDone:{target:"stopped",actions:"onConversationInitSuccess"},onError:{target:"stopped",actions:[u({initFailed:!0}),"onConversationInitFailed"]}},on:{FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},inProgress:{id:"inProgress",tags:["conversation_in_progress"],on:{STOP:{target:"stopped",actions:["onStop"]},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},DISCONNECT:[{target:"paused",guard:"hasActiveConversation"},{target:"stopped"}],AUDIO_START:{target:"#speaking",actions:["onAudioStarted"]},AI_MESSAGE_RECEIVED:{actions:"handleAiMessage"},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}},initial:"idle",states:{idle:{id:"idle",entry:["onIdle"],on:{STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},LISTEN:"listening",THINK:"thinking",START_CONVERSATION:{target:"startingConversation",actions:u({eventPayload:({event:t})=>t.payload})},SEND_TEXT_MESSAGE:{target:"processingTextMessage"},MIC_BUTTON:[{guard:"isRequestBlocked",actions:["onMicButtonBlocked"]},{target:"listening",actions:["onMicButtonStartListening"]}],AUDIO_END:{actions:["onAudioEnd"]}}},listening:{id:"listening",tags:["listening"],entry:["onListenEntry"],invoke:{id:"listenActor",src:"listenActor",input:({context:t})=>({voiceBot:t.voiceBot,bus:t.bus}),onError:{target:"idle",actions:["onListenFailed"]}},on:{STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},THINK:"thinking",START_CONVERSATION:{target:"startingConversation",actions:["onIdle",u({eventPayload:({event:t})=>t.payload})]},SPEECH_RECOGNITION_COMPLETE:{target:"processingSpeechRecognition"},SEND_TEXT_MESSAGE:{target:"processingTextMessage",actions:[({context:t})=>{if(t.voiceBot){t.voiceBot.stopListening();try{t.talkingAvatar?.liveCaptions?.clearCaptions?.()}catch(e){}try{t.bus.emit("event_command_UI_ClearCaptions")}catch(e){}}}]},MIC_BUTTON:{target:"idle",actions:["setUserSilencedTrue","onMicButtonStopListening"]},IDLE:"idle",AUDIO_END:{actions:["onAudioEnd"]}}},processingSpeechRecognition:{id:"processingSpeechRecognition",invoke:{id:"speechRecognitionActor",src:"speechRecognitionActor",input:({context:t,event:e})=>({chatSocket:t.chatSocket,payload:e.payload,conversation:t.conversation,bus:t.bus}),onDone:{target:"thinking"},onError:{target:"idle",actions:["onSpeechRecognitionFailed"]}},on:{AUDIO_END:{actions:["onAudioEnd"]}}},processingTextMessage:{id:"processingTextMessage",invoke:{id:"sendTextMessageActor",src:"sendTextMessageActor",input:({context:t,event:e})=>({chatSocket:t.chatSocket,payload:e.payload,conversation:t.conversation,bus:t.bus}),onDone:{target:"thinking"},onError:{target:"idle",actions:["onSendTextMessageFailed"]}},on:{AUDIO_END:{actions:["onAudioEnd"]}}},thinking:{id:"thinking",tags:["thinking","inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},IDLE:"idle",START_CONVERSATION:{target:"startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}}},startingConversation:{id:"startingConversation",tags:["thinking","inputs_blocked"],entry:["onStartingConversation"],invoke:{id:"startConversationService",src:"startConversationService",input:({context:t})=>({isNew:t.eventPayload?.fresh||!1,bus:t.bus,conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar}),onDone:[{guard:({event:t})=>"resume_silent"===t.output?.data?.dataType,target:"idle",actions:"onConversationStartSuccess"},{target:"thinking",actions:"onConversationStartSuccess"}],onError:{target:"#avatarOrchestrator.lifecycle.conversation.stopped",actions:[u({initFailed:!0}),"onConversationStartFailed"]}},on:{AI_MESSAGE_RECEIVED:{actions:"handleAiMessage"},AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},IDLE:"idle"}},pendingAudioStart:{id:"pendingAudioStart",tags:["thinking","inputs_blocked"],after:{speechStartTimeout:{guard:"isPendingAudioStart",target:"#speaking",actions:["onAudioStartedFallback"]}},on:{SEND_TEXT_MESSAGE:{target:"#inProgress.processingTextMessage",actions:["onInterruptSpeaking"]},MIC_BUTTON:{target:"#inProgress.listening",actions:["onInterruptSpeaking","onMicButtonInterruptSpeaking"]},INTERRUPT:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},VOICE_BARGE_IN:{target:"#inProgress.listening",actions:["emitVoiceBargeInEvent","onVoiceBargeIn","onInterruptSpeaking"]},AUDIO_END:[{target:"#inProgress.listening",guard:({context:t})=>!!t.isPageVisible&&!!t.voiceBot&&t.voiceBot.isConversationInProgress?.(),actions:["onAudioEnd"]},{target:"#inProgress.idle",actions:["onAudioEnd"]}],IDLE:{target:"#inProgress.idle"},LISTEN:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},START_CONVERSATION:{target:"#inProgress.interruptingForRestart",actions:["onInterruptSpeaking",u({eventPayload:({event:t})=>t.payload})]}}},speaking:{id:"speaking",tags:["speaking"],on:{SEND_TEXT_MESSAGE:{target:"#inProgress.processingTextMessage",actions:["onInterruptSpeaking"]},MIC_BUTTON:{target:"#inProgress.listening",actions:["onInterruptSpeaking","onMicButtonInterruptSpeaking"]},INTERRUPT:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},VOICE_BARGE_IN:{target:"#inProgress.listening",actions:["emitVoiceBargeInEvent","onVoiceBargeIn","onInterruptSpeaking"]},STREAM_END:{actions:["onStreamEnd"],internal:!0},AUDIO_END:[{target:"#inProgress.listening",guard:({context:t})=>!!t.isPageVisible&&!!t.voiceBot&&t.voiceBot.isConversationInProgress?.(),actions:["onAudioEnd"]},{target:"#inProgress.idle",actions:["onAudioEnd"]}],IDLE:{target:"#inProgress.idle"},LISTEN:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},START_CONVERSATION:{target:"#inProgress.interruptingForRestart",actions:["onInterruptSpeaking",u({eventPayload:({event:t})=>t.payload})]}}},interruptingForRestart:{id:"interruptingForRestart",entry:["onEnsureCleanupComplete"],invoke:{src:"cleanupInterruptionActor",input:({context:t})=>({talkingAvatar:t.talkingAvatar,chatSocket:t.chatSocket,voiceBot:t.voiceBot}),onDone:{target:"startingConversation"},onError:{target:"#avatarOrchestrator.lifecycle.conversation.stopped"}},tags:["inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]}}}}},endingConversation:{id:"endingConversation",tags:["inputs_blocked"],invoke:{id:"endConversationActor",src:"endConversationActor",input:({context:t,event:e})=>({conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar,voiceBot:t.voiceBot,payload:e?.payload}),onDone:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_UI_ClearConversation")}catch(e){}}]},onError:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertFailedEndConversation"})}catch(e){}}]}}},clearingConversation:{id:"clearingConversation",tags:["inputs_blocked"],invoke:{id:"clearConversationActor",src:"clearConversationActor",input:({context:t,event:e})=>({conversation:t.conversation,talkingAvatar:t.talkingAvatar,payload:e?.payload}),onDone:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_UI_ClearConversation")}catch(e){}}]},onError:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertFailedClearConversation"})}catch(e){}}]}}}}}}},connection:{initial:"connected",states:{connected:{id:"connected",on:{DISCONNECT:"disconnected"}},disconnected:{id:"disconnected",on:{RECONNECT:{target:"connected",actions:["onLeaveDisconnected",u({firstConnectionCompleted:()=>!0})]},CONNECT:{target:"connected",actions:["onLeaveDisconnected",u({firstConnectionCompleted:()=>!0})]}}}}}},on:{INJECT_MODULES:{actions:[u((({context:t,event:e})=>({talkingAvatar:e.payload?.talkingAvatar??t.talkingAvatar,chatSocket:e.payload?.chatSocket??t.chatSocket,voiceBot:e.payload?.voiceBot??t.voiceBot,conversation:e.payload?.conversation??t.conversation}))),({context:t,self:e})=>{try{const i=e.getSnapshot?.();(i?.matches?.("lifecycle.conversation.stopped")||i?.matches?.("lifecycle.conversation.timedOut"))&&t.conversation&&e.send({type:"AVATAR_INITIALIZED"})}catch(i){}}]},PAGE_CHANGED:{actions:["onPageChanged","setCurrentPage"]},DEFER_START:{actions:["onDeferStart"]},VISIBILITY_CHANGED:{actions:["onVisibilityChanged"]},UI_CHATBOT_MODE:{actions:["onUiChatbotMode"]},CONVERSATION_ERROR:{actions:["onConversationError"]},TTS_ERROR:{actions:["onTtsError"]},INTERRUPT:{actions:[({context:t})=>{try{t.talkingAvatar?.interruptSpeaking?.()}catch{}try{t.chatSocket?.interruptCurrentTurn?.()}catch{}try{t.voiceBot?.stopListening?.()}catch{}try{t.bus?.emit?.("event_command_UI_ClearCaptions")}catch{}}]}}},{actions:{onPageChanged:({context:t,event:e,self:i})=>{try{const a=e?.payload?.newPage;if(!a)return;const s=i.getSnapshot?.(),o=!!s?.hasTag?.("speaking")||s?.matches?.("lifecycle.conversation.inProgress.speaking")||s?.matches?.("lifecycle.conversation.inProgress.pendingAudioStart"),r=!!s?.hasTag?.("listening")||s?.matches?.("lifecycle.conversation.inProgress.listening");if("AvatarPage"!==a&&(o||r)&&(o?i.send({type:"INTERRUPT"}):r&&i.send({type:"IDLE"})),"AvatarPage"===a)try{const e="AVATAR"===t.chatSocket?.chatbotMode,i=!1!==t.chatSocket?.isChatbotShown;e&&i&&t.isPageVisible&&(t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.())}catch(n){}}catch(a){}},setCurrentPage:u((({event:t})=>{const e=t?.payload?.newPage;return e?{currentPage:e}:{}})),onDeferStart:u((({context:t,event:e})=>{if(!t.isPageVisible){const i=e.payload?.fresh??!1;return null!==t.pendingStart&&t.pendingStart,{pendingStart:i}}return null!==t.pendingStart?{pendingStart:null}:{}})),onVisibilityChanged:u((({context:t,event:e,self:i})=>{const n=e&&(e.payload?.isVisible??e.isVisible),a=void 0===n?!!t.isPageVisible:!!n,s=a&&!t.isPageVisible;if(!a&&t.isPageVisible){if(t.voiceBot&&(st(t),t.voiceBot.stopListening?.()),t.talkingAvatar){t.talkingAvatar.interruptSpeaking?.();try{t.talkingAvatar.suspendRendering?.("visibility")}catch(o){}}i.send({type:"IDLE"})}else{if(s&&null!==t.pendingStart){const e=t.pendingStart;return i.send({type:"START_CONVERSATION",payload:{fresh:e}}),{isPageVisible:a,pendingStart:null}}s&&t.voiceBot&&i.getSnapshot().matches("lifecycle.conversation.inProgress.idle")&&i.send({type:"LISTEN"})}try{if(a&&"AvatarPage"===t.currentPage){const e="AVATAR"===t.chatSocket?.chatbotMode,i=!1!==t.chatSocket?.isChatbotShown;e&&i&&(t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.())}}catch(o){}return{isPageVisible:a}})),onListenEntry:({context:t})=>{t.voiceBot&&st(t)},onListenFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertCouldNotStartListening"})}catch(i){}},onIdle:({context:t})=>{t.voiceBot&&(st(t),t.voiceBot.stopListening().success)},onStop:({context:t})=>{t.voiceBot&&(st(t),t.voiceBot.stopListening())},onAudioStarted:({context:t,event:e})=>{const i=e?.payload?.audioStartTime??("undefined"!=typeof performance?performance.now():Date.now());try{t.bus?.emit?.("event_command_UI_PlayCaptions",{audioStartTime:i})}catch(n){}},onAudioStartedFallback:({context:t})=>{const e="undefined"!=typeof performance?performance.now():Date.now();try{t.bus?.emit?.("event_command_UI_PlayCaptions",{audioStartTime:e})}catch(i){}},onStreamStart:({context:t,event:e})=>{const{audioStream:i,lipsyncStream:n,turnId:a}=e.payload||{};t.voiceBot&&void 0!==a&&(t.voiceBot._currentTurnId=a,t.voiceBot._expectedTurnId=a),t.talkingAvatar&&i&&n&&t.talkingAvatar.startStreaming(i,n,a)},onInterruptSpeaking:({context:t,self:e})=>{if(t.voiceBot){const i=Date.now();if(i-t.voiceBot._lastInterruptionTime<t.voiceBot.INTERRUPTION_DEBOUNCE)return;const n=-1!==t.voiceBot._expectedTurnId,a=t.voiceBot._isHandlingAudioEnd,s=e.getSnapshot(),o=s?.hasTag?.("speaking")||s?.matches?.("lifecycle.conversation.inProgress.speaking")||s?.matches?.("lifecycle.conversation.inProgress.pendingAudioStart");n&&o&&!a&&(t.voiceBot._expectedTurnId=-1,t.voiceBot._lastInterruptionTime=i),st(t),t.voiceBot.stopListening().success}t.talkingAvatar&&t.talkingAvatar.interruptSpeaking(),t.chatSocket&&t.chatSocket.interruptCurrentTurn()},onEnsureCleanupComplete:({context:t,self:e})=>{},onSpeechRecognitionFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertCouldNotStartListening"})}catch(i){}},onSendTextMessageFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertSomeErrorOccurred"})}catch(i){}},onUiChatbotMode:({context:t,event:e,self:i})=>{const n=e.payload;if(!n||void 0===n.isShown&&!n.chatbotMode)return;const a=n.chatbotMode;if(t.chatSocket&&(void 0!==a&&(t.chatSocket.chatbotMode=a),void 0!==n.isShown&&(t.chatSocket.isChatbotShown=n.isShown)),"CHAT"===a){const e=i.getSnapshot();if(e.matches("lifecycle.conversation.inProgress.speaking")||e.matches("lifecycle.conversation.inProgress.pendingAudioStart")){try{t.talkingAvatar?.interruptSpeaking()}catch(s){}try{t.chatSocket?.interruptCurrentTurn?.()}catch(s){}t.voiceBot&&(st(t),t.voiceBot.stopListening?.(),t.voiceBot._expectedTurnId=-1),i.send({type:"IDLE"})}else e.matches("lifecycle.conversation.inProgress.listening")&&(t.voiceBot&&(st(t),t.voiceBot.stopListening?.()),i.send({type:"IDLE"}));try{t.talkingAvatar?.suspendRendering?.("chat")}catch(s){}}else if("AVATAR"===a)try{const e=i.getSnapshot(),n=e.matches?.("lifecycle.conversation.inProgress"),a=e.matches?.("lifecycle.conversation.inProgress.idle"),s=!!t.isPageVisible;n&&a&&s&&i.send({type:"LISTEN"})}catch(s){}if(!1===n.isShown)try{const e=i.getSnapshot();if(e.matches?.("lifecycle.conversation.inProgress.speaking")||e.matches?.("lifecycle.conversation.inProgress.pendingAudioStart")){try{t.talkingAvatar?.interruptSpeaking?.()}catch(s){}try{t.chatSocket?.interruptCurrentTurn?.()}catch(s){}t.voiceBot&&(st(t),t.voiceBot.stopListening?.(),t.voiceBot._expectedTurnId=-1),i.send({type:"IDLE"})}else e.matches?.("lifecycle.conversation.inProgress.listening")&&(t.voiceBot&&(st(t),t.voiceBot.stopListening?.()),i.send({type:"IDLE"}));try{t.talkingAvatar?.suspendRendering?.("ui-hidden")}catch(s){}}catch(s){}else if(!0===n.isShown)try{const e=i.getSnapshot(),n=e.matches?.("lifecycle.conversation.inProgress"),s=e.matches?.("lifecycle.conversation.inProgress.idle"),o=!!t.isPageVisible;"AVATAR"===(void 0!==a?a:t.chatSocket?.chatbotMode)&&n&&s&&o&&i.send({type:"LISTEN"})}catch(s){}try{const e=void 0!==a?a:t.chatSocket?.chatbotMode,i=void 0!==n.isShown?n.isShown:!1!==t.chatSocket?.isChatbotShown;if("AVATAR"===e&&i&&t.isPageVisible&&"AvatarPage"===t.currentPage)t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.();else if(t.talkingAvatar?.isRenderingActive?.()&&("CHAT"===e||!i||!t.isPageVisible||"AvatarPage"!==t.currentPage))try{t.talkingAvatar?.suspendRendering?.("conditions-change")}catch(s){}}catch(s){}},onLeaveDisconnected:({self:t})=>t.send({type:"RESTORED_CONNECTION"}),onLeaveInitializing:({self:t})=>t.send({type:"AVATAR_INITIALIZED"}),onStartingConversation:({context:t,event:e})=>{t.voiceBot&&(st(t),t.voiceBot.stopListening(),t.voiceBot._expectedTurnId=-1),t.talkingAvatar&&t.talkingAvatar.interruptSpeaking()},onConversationStartSuccess:({context:t,event:e})=>{},onConversationStartFailed:({context:t,event:e})=>{},onAutoResumeFailed:({context:t,event:e})=>{},onConversationInitFailed:({context:t,event:e})=>{},onConversationInitSuccess:({context:t,event:e})=>{},handleAiMessage:({context:t,event:e,self:i})=>{const{message:n,time:a,structuredResponse:s}=e.payload||{};if("string"==typeof n&&""!==n.trim())try{t.bus.emit("event_command_UI_UpdateCurrentMessage",{speaker:"assistant",messageText:C(n)})}catch(r){}const o=s?.avatar_mood??e.payload?.structuredResponse?.avatar_mood;if(o)try{t.bus.emit("event_command_Avatar_SetAvatarMood",{mood:o})}catch(r){}t.conversation&&n&&Promise.resolve().then((async()=>{try{const i=a||(new Date).toLocaleTimeString(),s=await t.conversation.appendMessage(n,i,"assistant");try{t.bus.emit("event_status_Conversation_MessageAppended",s)}catch(e){}}catch(r){}})),"AVATAR"===t.chatSocket?.chatbotMode||setTimeout((()=>{try{const t=i.getSnapshot?.();(t?.matches?.("lifecycle.conversation.inProgress.thinking")||t?.matches?.("lifecycle.conversation.inProgress.startingConversation")||t?.matches?.("lifecycle.conversation.autoResuming"))&&i?.send?.({type:"IDLE"})}catch(t){}}),0)},onAudioEnd:({context:t,event:e})=>{const{turnId:i}=e.payload||{};if(st(t),t.voiceBot){if(-1===t.voiceBot._expectedTurnId||i!==t.voiceBot._expectedTurnId)return;t.voiceBot._expectedTurnId=-1,t.voiceBot._isHandlingAudioEnd=!0}t.chatSocket?.pendingDelayedActions?.length>0&&(I(t.chatSocket.pendingDelayedActions,t.bus),t.chatSocket.pendingDelayedActions=null),t.voiceBot&&setTimeout((()=>{t.voiceBot._isHandlingAudioEnd=!1}),50)},onStreamEnd:({context:t})=>{try{t.talkingAvatar?.finalizeTurn?.()}catch(e){}if(t.chatSocket?.pendingDelayedActions?.length>0){try{I(t.chatSocket.pendingDelayedActions,t.bus)}catch(e){}t.chatSocket.pendingDelayedActions=null}},onMicButtonBlocked:({context:t})=>{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertWaitForAIResponse"})},onMicButtonStartListening:u((()=>({userSilenced:!1}))),setUserSilencedTrue:u((()=>({userSilenced:!0}))),onMicButtonStopListening:({context:t})=>{},onMicButtonInterruptSpeaking:u((()=>({userSilenced:!1}))),emitVoiceBargeInEvent:({context:t,event:e})=>{const i=e?.payload||{};try{t.bus?.emit?.("event_status_Speech_BargeInTriggered",{micLevel:i.micLevel,avatarLevel:i.avatarLevel,ratio:i.ratio,delta:i.delta,timestamp:i.timestamp})}catch(n){}},onVoiceBargeIn:u((()=>({userSilenced:!1}))),onAssistantMessage:({context:t,event:e})=>{try{t.bus.emit("event_command_UI_AutoScrollChat",{message:e?.payload?.message||e?.message})}catch(i){}},onConversationError:({context:t,event:e,self:i})=>{const{error:n,chatbotMode:a}=e.payload||{};if(!n)return;if((908===n.code||404===n.code||408===n.code)&&void 0!==n.conversationId)return void i.send({type:"CONVERSATION_TIMEOUT",payload:{conversationId:n.conversationId}});const s=n.message?{errorMessage:n.message}:{messageKey:"alertSomeErrorOccurred"};t.bus.emit("event_command_Alerts_ShowDismissableAlert",s);const o=i.getSnapshot();o.matches("lifecycle.conversation.inProgress.thinking")&&i.send({type:"IDLE"}),"AVATAR"===a&&o.matches("lifecycle.conversation.inProgress.idle")&&i.send({type:"LISTEN"})},onTtsError:({context:t,self:e})=>{t.chatSocket?.cleanupActiveStreams();const i=e.getSnapshot();i.matches("lifecycle.conversation.inProgress.speaking")||i.matches("lifecycle.conversation.inProgress.pendingAudioStart")?(t.talkingAvatar?.interruptSpeaking&&t.talkingAvatar.interruptSpeaking(),e.send({type:"IDLE"})):e.send({type:"IDLE"})},onConversationPaused:({context:t})=>{t.voiceBot&&(st(t),t.voiceBot.stopListening()),t.talkingAvatar&&t.talkingAvatar.interruptSpeaking()}},guards:{isRequestBlocked:({self:t})=>{try{const e=t.getSnapshot?.();return!!e?.hasTag?.("thinking")}catch(e){return!1}},isAvatarMode:({context:t})=>{try{return"AVATAR"===t?.chatSocket?.chatbotMode}catch(e){return!1}},hasActiveConversation:({context:t})=>{if(!t.conversation)return!1;try{const e=!!t.conversation.conversationId,i=(t.conversation.conversationData?.currentTurnId||0)>0,n=Array.isArray(t.conversation.conversationData?.transcript)&&t.conversation.conversationData.transcript.length>0;return e&&(i||n)}catch(e){return!1}},isPendingAudioStart:({self:t})=>{try{return t.getSnapshot?.().matches?.("lifecycle.conversation.inProgress.pendingAudioStart")}catch(e){return!1}}},actors:{startConversationService:p((async({input:t})=>{const{isNew:e,skipFallback:i,bus:n,conversation:a,chatSocket:s,talkingAvatar:o}=t||{};if(!a||!s)throw new Error("Conversation or ChatSocket module not available");if(await Promise.resolve(),o?.conversationStreamActive)try{await(o.stopConversationStream?.())}catch(h){}e&&a.conversationId&&await a.notifyConversationEnd(),await a.notifyConversationStart(e),o&&await o.startConversationStream();const r=!e;let c;try{c=await s.sendStartConversationEvent(r)}catch(d){const t=d?.message?.includes("404")||d?.message?.includes("408");if(r&&t&&!i){try{await a.clearOngoingConversation()}catch(h){}await a.notifyConversationStart(!0),c=await s.sendStartConversationEvent(!1);try{n?.emit?.("event_status_Conversation_ResumeFailedAndRestarted",{conversationId:a.conversationId})}catch(h){}return c}throw d}const l=await(a.handleConversationSuccessfulStart?.(c))||{};if(l.resumeFailed)try{n?.emit?.("event_status_Conversation_ResumeFailedAndRestarted",{conversationId:a.conversationId})}catch(h){}else if(l.resumeAttempt&&!l.serverStartedNew)try{n?.emit?.("event_status_Conversation_ResumedSuccessfully",{conversationId:a.conversationId})}catch(h){}return c})),initConversationActor:p((async({input:t})=>{const{conversation:e,chatSocket:i}=t||{};if(!e)throw new Error("Conversation module not available");return await e.notifyConversationInit(),i&&await i.sendInitConversationEvent(),{initialized:!0}})),listenActor:p((async({input:t})=>{const{voiceBot:e}=t||{};if(!e)return{started:!1};const i=await e.startListening();if(!i.success)throw new Error(i.error||"Failed to start listening");return{started:!0}})),speechRecognitionActor:p((async({input:t})=>{const{chatSocket:e,payload:i,conversation:n,bus:a}=t||{};if(!e||!n)throw new Error("Dependencies not available");if(!i||!i.messageText)throw new Error("Invalid speech payload");const s=await n.appendMessage(i.messageText,w(new Date),"user");try{a?.emit("event_status_Conversation_MessageAppended",s)}catch(r){}const o=await e.sendMessage(i,"AVATAR");if(!o.success)throw a?.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertSomeErrorOccurred"}),new Error(o.error||"Failed to process speech input");return{sent:!0}})),sendTextMessageActor:p((async({input:t})=>{const{chatSocket:e,payload:i,conversation:n,bus:a}=t||{};if(!e||!n)throw new Error("Dependencies not available");if(!i||!i.message)throw new Error("Invalid text payload");const s=await n.appendMessage(i.message,w(new Date),"user");try{a?.emit("event_status_Conversation_MessageAppended",s)}catch(l){}const o={messageText:i.message},r=i.chatbotMode||"CHAT",c=await e.sendMessage(o,r);if(!c.success)throw a?.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertSomeErrorOccurred"}),new Error(c.error||"Failed to send text message");return{sent:!0}})),endConversationActor:p((async({input:t})=>{const{conversation:e,chatSocket:i,talkingAvatar:n,voiceBot:a,payload:s}=t||{};if(!e)return!0;const o=e.conversationId,{satisfactionScore:r=0}=s||{};if(await e.notifyConversationEnd(),i&&o)try{i.sendEndConversationEvent(o,r)}catch(c){}try{n?.interruptSpeaking?.()}catch(c){}try{await(n?.stopConversationStream?.())}catch(c){}try{n?.liveCaptions?.clearCaptions?.(),a?.stopListening?.()}catch(c){}return!0})),clearConversationActor:p((async({input:t})=>{const{conversation:e,talkingAvatar:i,payload:n}=t||{};if(!e)return!0;const{conversationId:a}=n||{};if(a===e.conversationId){await e.clearOngoingConversation();try{await(i?.stopConversationStream?.())}catch(s){}}return!0})),checkResumeActor:p((async({input:t})=>{const{conversation:e,bus:i}=t||{};if(!e)return{resumable:!1};try{const t=await(e.getConversationData?.());if(t?.id&&Array.isArray(t.transcript)&&t.transcript.length>0)return{resumable:!0}}catch(n){throw n}return{resumable:!1}})),cleanupInterruptionActor:p((async({input:t})=>{const{talkingAvatar:e,chatSocket:i,voiceBot:n}=t||{};try{try{e?.liveCaptions?.clearCaptions?.()}catch(a){}if(n)try{n.stopListening?.()}catch(a){}try{e?.interruptSpeaking?.()}catch(a){}try{i?.interruptCurrentTurn?.()}catch(a){}return await new Promise((t=>setTimeout(t,10))),!0}catch(s){throw s}}))},delays:{thinkingTimeout:T?.chatbot?.thinkingTimeout,speechStartTimeout:Math.min(Math.max(T?.chatbot?.speechStartTimeout??8e3,2e3),6e4)}});class rt{constructor(t){if(!t)throw new Error("Cannot initialize AvatarOrchestrator: missing bus instance");this.bus=t,this.actor=null,this._pendingEvents=[],this._deferredModules=null,this.diagnostics=null}start(t={}){if(this._deferredModules&&(t={...t,...this._deferredModules},this._deferredModules=null),this.actor)t&&Object.keys(t).length>0&&this.injectModules(t);else if(this.actor=g(ot,{input:{bus:this.bus,...t}}).start(),this.actor.subscribe((t=>{this.handleStateTransition(t)})),this._pendingEvents.length>0){for(const t of this._pendingEvents)this.actor.send(t);this._pendingEvents.length=0}}handleStateTransition(t){t&&this.diagnostics&&t?.changed&&(this.diagnostics.logStateTransition(t.history?.value,t.value),t.matches?.("lifecycle.conversation.stopped")&&this.diagnostics.displayDiagnosticsInConsole())}sendEvent(t,e=null){const i={type:t,payload:e};this.actor?this.actor.send(i):this._pendingEvents.push(i)}is(t){return!!this.actor&&this.actor.getSnapshot().matches(t)}getCurrentState(){return this.actor?.getSnapshot().value}getSnapshot(){return this.actor?this.actor.getSnapshot():null}destroy(){this.actor?.stop(),this.actor=null,this.diagnostics=null,this._pendingEvents=[]}interruptSpeaking(){this.sendEvent("INTERRUPT")}transitionToListening(){this.sendEvent("LISTEN")}transitionToIdle(){this.sendEvent("IDLE")}injectModules(t={}){this.actor?this.actor.send({type:"INJECT_MODULES",payload:t}):this._deferredModules={...this._deferredModules||{},...t}}subscribeProjected(t){if(!this.actor)return()=>{};let e={};const i=this.actor.subscribe((i=>{const n={lifecycle:{initInitializing:i.matches?.("lifecycle.init.initializing")||!1,initFailed:i.matches?.("lifecycle.init.failed")||!1,convoStopped:i.matches?.("lifecycle.conversation.stopped")||!1,convoAutoResuming:i.matches?.("lifecycle.conversation.autoResuming")||!1,convoResumeExpired:i.matches?.("lifecycle.conversation.resumeExpired")||!1,convoInProgress:i.matches?.("lifecycle.conversation.inProgress")||!1,convoStarting:i.matches?.("lifecycle.conversation.inProgress.startingConversation")||!1,convoInitializing:i.matches?.("lifecycle.conversation.initializingConversation")||!1,conversationSubstate:i.matches?.("lifecycle.conversation.inProgress.pendingAudioStart")?"pendingAudioStart":i.matches?.("lifecycle.conversation.inProgress.speaking")?"speaking":i.matches?.("lifecycle.conversation.inProgress.listening")?"listening":i.matches?.("lifecycle.conversation.inProgress.thinking")?"thinking":i.matches?.("lifecycle.conversation.inProgress.startingConversation")?"startingConversation":i.matches?.("lifecycle.conversation.inProgress.idle")?"idle":""},connection:{connected:i.matches?.("connection.connected")||!1,disconnected:i.matches?.("connection.disconnected")||!1},flags:{userSilenced:i.context?.userSilenced||!1,isPageVisible:!!i.context?.isPageVisible,pendingStart:"boolean"==typeof i.context?.pendingStart?i.context.pendingStart:null}};!function(t,e){if(t===e)return!0;if(!t||!e)return!1;const i=t.lifecycle,n=e.lifecycle;if(!i||!n)return!1;if(i.initInitializing!==n.initInitializing||i.initFailed!==n.initFailed||i.convoStopped!==n.convoStopped||i.convoResumable!==n.convoResumable||i.convoInProgress!==n.convoInProgress||i.convoStarting!==n.convoStarting||i.convoInitializing!==n.convoInitializing||i.conversationSubstate!==n.conversationSubstate)return!1;const a=t.connection,s=e.connection;if(!a||!s)return!1;if(a.connected!==s.connected||a.disconnected!==s.disconnected)return!1;const o=t.flags,r=e.flags;return!(!o||!r)&&o.userSilenced===r.userSilenced&&o.isPageVisible===r.isPageVisible&&o.pendingStart===r.pendingStart}(n,e)&&(e=n,t(n,i))}));return()=>i.unsubscribe()}}class ct{constructor(t,e){if(!t||!e)throw new Error("Cannot initialize connectionManager due to missing bus or avatarOrchestrator");this.connectionModules={},this._allConnectionsReady=!1,this._wasAllReady=!1,this.isReconnecting=!1,this.bus=t,this.avatarOrchestrator=e,this._reconnectTimer=null,this._retryDelay=T?.connection?.reconnectInitialDelay,this._maxDelay=T?.connection?.reconnectMaxDelay,this._factor=T?.connection?.reconnectFactor,this._reconnectHandler=async()=>{try{this._resetBackoff(),await this.reconnectFailedModules(!0)}catch(t){}},this.bus.on("event_command_ConnectionManager_ReconnectFailedModules",this._reconnectHandler)}get allConnectionsReady(){return this._allConnectionsReady}set allConnectionsReady(t){this._allConnectionsReady=t}registerNewConnectionModule(t,e=null){try{const i=new V(t);e&&(i.reconnect=e),i.subscribe((()=>this.updateAvatarState())),this.connectionModules[t]=i}catch(i){}}registerConnectionModule(t){try{if(!t||!t.name||"function"!=typeof t.subscribe)throw new Error("Invalid module: must have 'name' property and 'subscribe' method");t.subscribe((()=>this.updateAvatarState())),this.connectionModules[t.name]=t}catch(e){}}setReconnectFunction(t,e){try{const i=this.connectionModules[t];if(!i)return;i.reconnect=e}catch(i){}}waitUntilReady(t=15e3){return new Promise(((e,i)=>{if(this._allConnectionsReady)return e(!0);let n,a;const s=()=>{n&&clearTimeout(n),a&&this.bus.off("connectionStateChanged",a)};n=setTimeout((()=>{s(),i(new Error("Connection timeout"))}),t),a=()=>{this._allConnectionsReady&&(s(),e(!0))},this.bus.on("connectionStateChanged",a)}))}updateAvatarState(){if(!this.avatarOrchestrator)return;const t=Object.values(this.connectionModules).every((t=>t.isConnected()));if(Object.values(this.connectionModules).some((t=>t.isFailed())),this.allConnectionsReady=t,this.bus.emit("connectionStateChanged"),t){if(this._clearReconnectTimer(),!this._wasAllReady)try{const t=this.avatarOrchestrator.getSnapshot?.();t?.matches?.("connection.disconnected"),this.avatarOrchestrator.sendEvent("RECONNECT"),(t?.matches?.("lifecycle.init.failed")||t?.matches?.("lifecycle.init.initializing"))&&this.avatarOrchestrator.sendEvent("CONNECT")}catch(e){}this._wasAllReady=!0}else{if(this._scheduleAutoReconnect(),this._wasAllReady)try{this.avatarOrchestrator.sendEvent("DISCONNECT")}catch(e){}this._wasAllReady=!1}}async reconnectFailedModules(t=!1){if(this.isReconnecting)return;this.isReconnecting=!0;const e=Object.values(this.connectionModules).filter((t=>t.isFailed()||t.isDisconnected())).map((async t=>{try{await(t.reconnect?.())}catch(e){}}));await Promise.allSettled(e),this.isReconnecting=!1,this.updateAvatarState(),t||this._stepBackoff()}async reconnectDisconnectedModules(){if(this.isReconnecting)return;this.isReconnecting=!0;const t=Object.values(this.connectionModules).filter((t=>!t.isConnected())).map((async t=>{try{await(t.reconnect?.())}catch(e){}}));await Promise.allSettled(t),this.isReconnecting=!1,this.updateAvatarState()}getConnectionReport(){let t=`System is ${this.allConnectionsReady?"Ready":"Not Ready"}\n\n`;for(const e of Object.values(this.connectionModules))t+=`${e.name}: ${e.isConnected()?"connected":"disconnected"}, \n`;return t}_scheduleAutoReconnect(){this._reconnectTimer||(this._reconnectTimer=setTimeout((async()=>{this._reconnectTimer=null,await this.reconnectFailedModules()}),this._retryDelay))}_clearReconnectTimer(){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._resetBackoff()}_resetBackoff(){this._retryDelay=T?.connection?.reconnectInitialDelay}_stepBackoff(){this._retryDelay=Math.min(Math.ceil(this._retryDelay*this._factor),this._maxDelay)}destroy(){try{this._reconnectHandler&&(this.bus?.off("event_command_ConnectionManager_ReconnectFailedModules",this._reconnectHandler),this._reconnectHandler=null),this._clearReconnectTimer()}catch(t){}}}const lt={dance:["dance\\M_Dances_007.fbx","dance\\M_Dances_008.fbx","dance\\M_Dances_009.fbx","dance\\M_Dances_011.fbx","dance\\F_Dances_001.fbx","dance\\F_Dances_004.fbx","dance\\F_Dances_005.fbx","dance\\F_Dances_006.fbx","dance\\F_Dances_007.fbx","dance\\M_Dances_001.fbx","dance\\M_Dances_002.fbx","dance\\M_Dances_003.fbx","dance\\M_Dances_004.fbx","dance\\M_Dances_005.fbx","dance\\M_Dances_006.fbx"],expression:["expression\\M_Standing_Expressions_016.fbx","expression\\M_Standing_Expressions_017.fbx","expression\\M_Standing_Expressions_018.fbx","expression\\M_Talking_Variations_001.fbx","expression\\M_Talking_Variations_002.fbx","expression\\M_Talking_Variations_003.fbx","expression\\M_Talking_Variations_004.fbx","expression\\M_Talking_Variations_005.fbx","expression\\M_Talking_Variations_006.fbx","expression\\M_Talking_Variations_007.fbx","expression\\M_Talking_Variations_008.fbx","expression\\M_Talking_Variations_009.fbx","expression\\M_Talking_Variations_010.fbx","expression\\F_Talking_Variations_001.fbx","expression\\F_Talking_Variations_002.fbx","expression\\F_Talking_Variations_003.fbx","expression\\F_Talking_Variations_004.fbx","expression\\F_Talking_Variations_005.fbx","expression\\F_Talking_Variations_006.fbx","expression\\M_Standing_Expressions_001.fbx","expression\\M_Standing_Expressions_002.fbx","expression\\M_Standing_Expressions_004.fbx","expression\\M_Standing_Expressions_005.fbx","expression\\M_Standing_Expressions_006.fbx","expression\\M_Standing_Expressions_007.fbx","expression\\M_Standing_Expressions_008.fbx","expression\\M_Standing_Expressions_009.fbx","expression\\M_Standing_Expressions_010.fbx","expression\\M_Standing_Expressions_011.fbx","expression\\M_Standing_Expressions_012.fbx","expression\\M_Standing_Expressions_013.fbx","expression\\M_Standing_Expressions_014.fbx","expression\\M_Standing_Expressions_015.fbx"],locomotion:["locomotion\\M_CrouchedWalk_Backwards_002.fbx","locomotion\\M_Falling_Idle_002.fbx","locomotion\\M_Jog_001.fbx","locomotion\\M_Jog_003.fbx","locomotion\\M_Jog_Backwards_001.fbx","locomotion\\M_Jog_Jump_001.fbx","locomotion\\M_Jog_Jump_002.fbx","locomotion\\M_Jog_Strafe_Left_001.fbx","locomotion\\M_Jog_Strafe_Right_001.fbx","locomotion\\M_Run_001.fbx","locomotion\\M_Run_Backwards_002.fbx","locomotion\\M_Run_Jump_001.fbx","locomotion\\M_Run_Jump_002.fbx","locomotion\\M_Run_Strafe_Left_002.fbx","locomotion\\M_Run_Strafe_Right_002.fbx","locomotion\\M_Walk_001.fbx","locomotion\\M_Walk_002.fbx","locomotion\\M_Walk_Backwards_001.fbx","locomotion\\M_Walk_Jump_001.fbx","locomotion\\M_Walk_Jump_002.fbx","locomotion\\M_Walk_Jump_003.fbx","locomotion\\M_Walk_Strafe_Left_002.fbx","locomotion\\M_Walk_Strafe_Right_002.fbx","locomotion\\F_Crouch_Strafe_Left.fbx","locomotion\\F_Crouch_Strafe_Right.fbx","locomotion\\F_Crouch_Walk_001.fbx","locomotion\\F_CrouchedWalk_Backwards_001.fbx","locomotion\\F_Falling_Idle_000.fbx","locomotion\\F_Falling_Idle_001.fbx","locomotion\\F_Jog_001.fbx","locomotion\\F_Jog_Backwards_001.fbx","locomotion\\F_Jog_Jump_Small_001.fbx","locomotion\\F_Jog_Strafe_Left_002.fbx","locomotion\\F_Jog_Strafe_Right_002.fbx","locomotion\\F_Run_001.fbx","locomotion\\F_Run_Backwards_001.fbx","locomotion\\F_Run_Jump_001.fbx","locomotion\\F_Run_Strafe_Left_001.fbx","locomotion\\F_Run_Strafe_Right_001.fbx","locomotion\\F_Walk_002.fbx","locomotion\\F_Walk_003.fbx","locomotion\\F_Walk_Backwards_001.fbx","locomotion\\F_Walk_Jump_001.fbx","locomotion\\F_Walk_Jump_002.fbx","locomotion\\F_Walk_Strafe_Left_001.fbx","locomotion\\F_Walk_Strafe_Right_001.fbx","locomotion\\M_Crouch_Strafe_Left_002.fbx","locomotion\\M_Crouch_Strafe_Right_002.fbx","locomotion\\M_Crouch_Walk_003.fbx"],idle:["idle\\M_Standing_Idle_Variations_001.fbx","idle\\M_Standing_Idle_Variations_002.fbx","idle\\M_Standing_Idle_Variations_003.fbx","idle\\M_Standing_Idle_Variations_004.fbx","idle\\M_Standing_Idle_Variations_005.fbx","idle\\M_Standing_Idle_Variations_006.fbx","idle\\M_Standing_Idle_Variations_007.fbx","idle\\M_Standing_Idle_Variations_008.fbx","idle\\M_Standing_Idle_Variations_009.fbx","idle\\M_Standing_Idle_Variations_010.fbx","idle\\F_Standing_Idle_001.fbx","idle\\F_Standing_Idle_Variations_001.fbx","idle\\F_Standing_Idle_Variations_002.fbx","idle\\F_Standing_Idle_Variations_003.fbx","idle\\F_Standing_Idle_Variations_004.fbx","idle\\F_Standing_Idle_Variations_005.fbx","idle\\F_Standing_Idle_Variations_006.fbx","idle\\F_Standing_Idle_Variations_007.fbx","idle\\F_Standing_Idle_Variations_008.fbx","idle\\F_Standing_Idle_Variations_009.fbx","idle\\M_Standing_Idle_001.fbx","idle\\M_Standing_Idle_002.fbx"]};function ht(t){return t&&0!==t.length?t[Math.floor(Math.random()*t.length)]:null}function dt(t,e,...i){return t.filter((t=>!!t.includes(`${e}_`)&&i.every((e=>t.includes(e)))))}const ut={maxChars:T.captions.maxCharactersPerCaption,minChars:T.captions.minCharactersPerCaption,softChars:Math.floor(.75*T.captions.maxCharactersPerCaption),pauseBreakMs:350,preferBreakAfter:/[.!?…]|—|–|;/,softBreakAfter:/,|:/};class pt{constructor(){this.currentCaptions=[],this.currentCaptionIndex=0,this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null,this._playAttemptActive=!1}isBoundaryTypeValid(t){return"SpeechSynthesisBoundaryType.Word"===t.boundaryType||"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType}handleWordBoundaryEvent(t){if(!this.isBoundaryTypeValid(t))return;const e=t.text,i=t.audioOffset,n=t.duration;let a=this.currentCaptions[this.currentCaptions.length-1],s=null;if(a&&Number.isFinite(a._lastEndOffsetMs)&&(s=i-a._lastEndOffsetMs),!a||function(t,e,i){const n=t.text,a=n.length,s=ut.preferBreakAfter.test(n.slice(-1)),o=ut.softBreakAfter.test(n.slice(-1));return!!t.isDisplayed||null!=i&&i>=ut.pauseBreakMs&&a>=ut.minChars||(r=a)+(r?1:0)+e.length>ut.maxChars||!!(s&&a>=ut.minChars)||!!(a>=ut.softChars&&o);var r}(a,e,s)){const t={text:e,audioOffset:i,duration:n,isDisplayed:!1,_lastEndOffsetMs:i+n,get renderText(){return(t=this.text)?` ${t.trim()} `:" ";var t}};this.currentCaptions.push(t)}else a.text=(r=e,((o=a.text).length>0&&!/\s$/.test(o)&&!/^[\s.,!?;:…)]/.test(r)?o+" "+r:o+r).replace(/\s{2,}/g," ")),a.duration+=n,a._lastEndOffsetMs=i+n;var o,r;if(/^[\s.,!?;:…()\[\]{}'"—–-]$/.test(e)){const t=this.currentCaptions[this.currentCaptions.length-1];t&&(t.text=t.text.replace(/\s+([.,!?;:…)\]}])/g,"$1").replace(/([([{])\s+/g,"$1").replace(/\s{2,}/g," ").trim())}}playCaptions(t,e){this._playAttemptActive=!0;const i=async()=>{this._playAttemptActive&&(this.currentCaptions.length>0&&!this.currentCaptions[0].isDisplayed?(this._playAttemptActive=!1,this.startCaptionDisplay(t,e)):(await this.wait(100),i()))};i()}startCaptionDisplay(t,e){this.currentCaptionIndex=0,this.displayTimeoutId&&clearTimeout(this.displayTimeoutId),this.durationTimeoutId&&clearTimeout(this.durationTimeoutId),this.settleTimeoutId&&clearTimeout(this.settleTimeoutId),this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null;const i=()=>{if(this.currentCaptionIndex>=this.currentCaptions.length)return void(this.settleTimeoutId=setTimeout((()=>{this.settleTimeoutId=null,this.currentCaptionIndex>=this.currentCaptions.length?t(!1):i()}),100));const n=this.currentCaptions[this.currentCaptionIndex];if(!n)return void t(!1);const a=Math.max(0,n.audioOffset-(performance.now()-e));this.displayTimeoutId=setTimeout((()=>{this.displayTimeoutId=null,this.currentCaptions[this.currentCaptionIndex]?(n.isDisplayed=!0,t(!0,n.text),this.durationTimeoutId=setTimeout((()=>{this.durationTimeoutId=null,this.currentCaptionIndex++,i()}),n.duration)):t(!1)}),a)};i()}clearCaptions(){this._playAttemptActive=!1,this.displayTimeoutId&&clearTimeout(this.displayTimeoutId),this.durationTimeoutId&&clearTimeout(this.durationTimeoutId),this.settleTimeoutId&&clearTimeout(this.settleTimeoutId),this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null,this.currentCaptions=[],this.currentCaptionIndex=0}wait(t){return new Promise((e=>setTimeout(e,t)))}destroy(){this.clearCaptions()}}const gt=["eyeBlinkLeft","eyeLookDownLeft","eyeLookInLeft","eyeLookOutLeft","eyeLookUpLeft","eyeSquintLeft","eyeWideLeft","eyeBlinkRight","eyeLookDownRight","eyeLookInRight","eyeLookOutRight","eyeLookUpRight","eyeSquintRight","eyeWideRight","jawForward","jawLeft","jawRight","jawOpen","mouthClose","mouthFunnel","mouthPucker","mouthLeft","mouthRight","mouthSmileLeft","mouthSmileRight","mouthFrownLeft","mouthFrownRight","mouthDimpleLeft","mouthDimpleRight","mouthStretchLeft","mouthStretchRight","mouthRollLower","mouthRollUpper","mouthShrugLower","mouthShrugUpper","mouthPressLeft","mouthPressRight","mouthLowerDownLeft","mouthLowerDownRight","mouthUpperUpLeft","mouthUpperUpRight","browDownLeft","browDownRight","browInnerUp","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight","noseSneerLeft","noseSneerRight","tongueOut","headRotateZ"],vt=["sil","aa","aa","O","E","RR","I","U","O","O","O","I","kk","RR","nn","SS","CH","TH","FF","DD","kk","PP"];class mt extends V{constructor(t,e){super("talkingAvatar"),this.bus=t,this.avatarOrchestrator=e,this.talkingAvatar=null,this.isFullBody=!0,this.bodyGender="M",this.resetSpeakData(),this.prevViseme=null,this.frameDuration=1e3/T.constants.FRAME_RATE,this.currentTurnId=null,this.isStoppingSpeaking=!1,this._endedTurns=new Set,this.conversationStreamActive=!1,this._pendingEndReason=null,this._audioStartSent=!1,this._busHandlers=[],this.liveCaptions=new pt}resetSpeakData(){this.speak={audio:[],visemes:[],vtimes:[],vdurations:[],words:[],wtimes:[],wdurations:[],markers:[],mtimes:[],anim:{}},this.azureBlendShapes={frames:[],sbuffer:[],orderBuffer:{}},this.prevViseme=null}finalizeTurn(){this.handlePendingVisemes(),this.talkingAvatar.streamNotifyEnd(),this.resetSpeakData()}async init(t,e){try{this.talkingAvatar=new v(e,{ttsEndpoint:"/gtts/",cameraZoomEnable:!1,cameraPanEnable:!1,cameraRotateEnable:!1,cameraView:"full",avatarMood:"happy"});const i="male"===t.gender?"M":"F";this.bodyGender=i,await this.talkingAvatar.showAvatar({url:t.url,body:i}),this.addEventListeners(),this.setConnected(),this.lipsyncType=t.lipsyncType}catch(i){throw this.setFailed(),new Error("Error initializing TalkingAvatar: "+i)}}isRenderingActive(){return!!this.talkingAvatar?.isRunning}async suspendRendering(t="hidden"){if(this.isRenderingActive()){try{this.talkingAvatar?.streamInterrupt?.()}catch(e){}try{this.audioReader?.cancel()}catch(e){}try{this.lipsyncReader?.cancel()}catch(e){}if(this.conversationStreamActive)try{await this.stopConversationStream()}catch(e){}try{this.talkingAvatar?.stop?.()}catch(e){}try{this.liveCaptions?.clearCaptions?.()}catch(e){}try{this.bus?.emit?.("event_command_UI_ClearCaptions")}catch(e){}try{const e=this.isRenderingActive();this.bus?.emit?.("event_status_Avatar_RenderingStateChanged",{running:e,reason:t})}catch(e){}}}async resumeRendering(){if(!this.isRenderingActive()){try{this.talkingAvatar?.start?.()}catch(t){}try{const t=this.isRenderingActive();this.bus?.emit?.("event_status_Avatar_RenderingStateChanged",{running:t,reason:"resume"})}catch(t){}}}resumeAudioContext(){try{const t=this.talkingAvatar?.audioCtx;if(!t)return;"suspended"!==t.state&&"interrupted"!==t.state||t.resume().then((()=>{})).catch((t=>{}))}catch(t){}}getSpeechAnalyzerNode(){return this.talkingAvatar?.audioAnalyzerNode??null}startStreamPump(t){try{this.audioReader=t.readable.getReader()}catch(i){return}const e=this.currentTurnId;(async()=>{try{for(;;){const{value:i,done:n}=await this.audioReader.read();if(n)return;if(this.currentTurnId!==e){try{this.audioReader.cancel()}catch(t){}return}this._notifyAudioStart(e),this.handleSpeechSynthesizingChunk({audio:i})}}catch(i){"AbortError"===i.name||i.message.includes("cancel")}})().catch((t=>{}))}startLipsyncPump(t){this.lipsyncReader=t.readable.getReader();const e=this.currentTurnId;(async()=>{try{for(;;){const{value:i,done:n}=await this.lipsyncReader.read();if(n)break;if(this.currentTurnId!==e){try{this.lipsyncReader.cancel()}catch(t){}break}switch(i.type){case"viseme":this.handleAddVisemeToStreaming(i);break;case"word":this.handleReceivedWordBoundaryEvent(i);break;case"blend":this.handleAddBlendShapestoStreaming(i)}}}catch(i){"AbortError"===i.name||i.message.includes("cancel")}})().catch((t=>{}))}handleAudioEndOnce(t,e){const i=t??"__null__";this._endedTurns.has(i)||(this._endedTurns.add(i),this.avatarOrchestrator.sendEvent("AUDIO_END",{turnId:t,reason:e}))}async startConversationStream(){if(this.isRenderingActive()&&!this.conversationStreamActive)try{await this.talkingAvatar.streamStart({lipsyncType:this.lipsyncType,sampleRate:24e3},(({turnId:t,audioStartTime:e}={})=>{const i=t??this.currentTurnId;this._notifyAudioStart(i,e)}),(()=>{const t=this._pendingEndReason||"completed";this._pendingEndReason=null,this.handleAudioEndOnce(this.currentTurnId,t),this.currentTurnId&&(this.currentTurnId=null)})),this.conversationStreamActive=!0}catch(t){throw this.conversationStreamActive=!1,t}}async stopConversationStream(){if(this.conversationStreamActive)try{this.talkingAvatar.streamStop(),this.conversationStreamActive=!1}catch(t){this.conversationStreamActive=!1}}addEventListeners(){const t=(t,e)=>{this.bus.on(t,e),this._busHandlers.push([t,e])};t("event_command_Avatar_SetAvatarView",(t=>{this.setView(t.view)})),t("event_command_Avatar_SetAvatarMood",(t=>{this.talkingAvatar.setMood(t.mood)})),t("event_command_Avatar_PlayOrStopGesture",(t=>{"stop"!==t.gesture?this.talkingAvatar.playGesture(t.gesture,t.duration,t.mirror,t.ms):this.talkingAvatar.stopGesture()})),t("event_command_Avatar_PlayOrStopAnimation",(t=>{if("stop"===t.animation)return void this.talkingAvatar.stopAnimation();const e=function(t,e="M"){let i=[];switch(t){case"dance":i=dt(lt.dance,e,"Dances");break;case"expression_talking":i=dt(lt.expression,e,"Talking_Variations");break;case"expression_standing":i=dt(lt.expression,e,"Standing_Expressions");break;case"idle_standing":i=dt(lt.idle,e,"Standing_Idle");break;case"locomotion_walk":i=dt(lt.locomotion,e,"Walk_");break;case"locomotion_walk_backwards":i=dt(lt.locomotion,e,"Walk_Backwards");break;case"locomotion_walk_jump":i=dt(lt.locomotion,e,"Walk_Jump");break;case"locomotion_walk_strafe_left":i=dt(lt.locomotion,e,"Walk_Strafe_Left");break;case"locomotion_walk_strafe_right":i=dt(lt.locomotion,e,"Walk_Strafe_Right");break;case"locomotion_run":i=dt(lt.locomotion,e,"Run_");break;case"locomotion_run_backwards":i=dt(lt.locomotion,e,"Run_Backwards");break;case"locomotion_run_jump":i=dt(lt.locomotion,e,"Run_Jump");break;case"locomotion_run_strafe_left":i=dt(lt.locomotion,e,"Run_Strafe_Left");break;case"locomotion_run_strafe_right":i=dt(lt.locomotion,e,"Run_Strafe_Right");break;case"locomotion_jog":i=dt(lt.locomotion,e,"Jog_");break;case"locomotion_jog_backwards":i=dt(lt.locomotion,e,"Jog_Backwards");break;case"locomotion_jog_jump":i=dt(lt.locomotion,e,"Jog_Jump");break;case"locomotion_jog_strafe_left":i=dt(lt.locomotion,e,"Jog_Strafe_Left");break;case"locomotion_jog_strafe_right":i=dt(lt.locomotion,e,"Jog_Strafe_Right");break;case"locomotion_crouch_walk":i=dt(lt.locomotion,e,"Crouch_Walk");break;case"locomotion_crouch_strafe_left":i=dt(lt.locomotion,e,"Crouch_Strafe_Left");break;case"locomotion_crouch_strafe_right":i=dt(lt.locomotion,e,"Crouch_Strafe_Right");break;case"locomotion_crouchedwalk_backwards":i=dt(lt.locomotion,e,"CrouchedWalk_Backwards");break;case"locomotion_falling_idle":i=dt(lt.locomotion,e,"Falling_Idle");break;default:i=[]}return ht(i)||ht(lt.locomotion.filter((t=>t.includes(`${e}_Walk_`))))||"locomotion\\M_Walk_001.fbx"}(t.animation,this.bodyGender);this.playAnimation(e,t.dur)})),t("event_command_Avatar_ControlAvatarLookAt",(t=>{"ahead"!==t.target?"point"!==t.target?"camera"!==t.target?"eye_contact"!==t.target||this.talkingAvatar.makeEyeContact(t.t):this.talkingAvatar.lookAtCamera(t.t):this.talkingAvatar.lookAt(t.x,t.y,t.t):this.talkingAvatar.lookAhead(t.t)})),t("event_command_UI_ClearCaptions",(()=>{try{this.liveCaptions?.clearCaptions?.()}catch(t){}}))}onResize(){this.talkingAvatar&&this.talkingAvatar.onResize()}handleSpeechSynthesizingChunk(t){switch(this.lipsyncType){case"blendshapes":this.talkingAvatar.streamAudio({audio:t.audio,anims:this.azureBlendShapes?.sbuffer.splice(0,this.azureBlendShapes?.sbuffer.length)});break;case"visemes":this.talkingAvatar.streamAudio({audio:t.audio,visemes:this.speak.visemes.splice(0,this.speak.visemes.length),vtimes:this.speak.vtimes.splice(0,this.speak.vtimes.length),vdurations:this.speak.vdurations.splice(0,this.speak.vdurations.length)});break;case"words":this.talkingAvatar.streamAudio({audio:t.audio,words:this.speak.words.splice(0,this.speak.words.length),wtimes:this.speak.wtimes.splice(0,this.speak.wtimes.length),wdurations:this.speak.wdurations.splice(0,this.speak.wdurations.length)})}}handleAddVisemeToStreaming(t){const e=vt[t?.visemeId||0],i=t?.audioOffset||0;if(this.prevViseme){const t=this.prevViseme;let e=i-t.vtime;e<40&&(e=40),this.speak.visemes.push(t.viseme),this.speak.vtimes.push(t.vtime),this.speak.vdurations.push(e)}this.prevViseme={viseme:e,vtime:i}}handleAddBlendShapestoStreaming(t){const e=t?.BlendShapes;if(!e||0===e.length)return;const i=this._getBlendColumns(),n=e.length,a=Object.create(null);for(let o=0;o<i.length;o++){const[t,s]=i[o],r=new Float32Array(n);for(let i=0;i<n;i++){const n=e[i];r[i]=Array.isArray(n)||ArrayBuffer.isView(n)?n[t]??0:0}a[s]=r}const s=null!=t?.AudioOffset?Math.round(t.AudioOffset/1e4):(t?.FrameIndex||0)*this.frameDuration;this.azureBlendShapes.sbuffer.push({name:"blendshapes",delay:s,dt:this._getDtArray(n),vs:a})}handleReceivedWordBoundaryEvent(t){try{this.liveCaptions.handleWordBoundaryEvent(t)}catch(s){}const e=this.speak,i=t.text,n=t.audioOffset,a=t.duration;"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType&&e.words.length?e.words[e.words.length-1]+=i:"SpeechSynthesisBoundaryType.Word"===t.boundaryType||"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType?(e.words.push(i),e.wtimes.push(n),e.wdurations.push(a)):"SpeechSynthesisBoundaryType.Sentence"===t.boundaryType&&n>500&&(e.markers.push((()=>{this.talkingAvatar.lookAtCamera(500)})),e.mtimes.push(n-500))}handlePendingVisemes(t=null){if("visemes"===this.lipsyncType&&this.prevViseme){const e=this.prevViseme;t||(t=100),this.speak.visemes.push(e.viseme),this.speak.vtimes.push(e.vtime),this.speak.vdurations.push(t),this.prevViseme=null}"visemes"===this.lipsyncType&&this.speak.visemes.length&&this.talkingAvatar.streamAudio({visemes:this.speak.visemes.splice(0,this.speak.visemes.length),vtimes:this.speak.vtimes.splice(0,this.speak.vtimes.length),vdurations:this.speak.vdurations.splice(0,this.speak.vdurations.length)}),"blendshapes"===this.lipsyncType&&this.azureBlendShapes.sbuffer.length&&this.talkingAvatar.streamAudio({anims:this.azureBlendShapes.sbuffer.splice(0,this.azureBlendShapes.sbuffer.length)})}async startStreaming(t,e,i){if(this.currentTurnId=i,this.isStoppingSpeaking=!1,this._audioStartSent=!1,!this.isRenderingActive()){try{t?.cancel?.()}catch(a){}try{e?.cancel?.()}catch(a){}return this.handleAudioEndOnce(i,"suppressed"),void(this.currentTurnId=null)}const n=i;this._endedTurns.delete(n??"__null__");try{this.startStreamPump(t),this.startLipsyncPump(e),this.conversationStreamActive||await this.startConversationStream()}catch(s){this.handleAudioEndOnce(n,"error"),this.currentTurnId===n&&(this.currentTurnId=null),this.isStoppingSpeaking=!1}}_notifyAudioStart(t,e=null){if(this._audioStartSent)return;this._audioStartSent=!0;const i=e??("undefined"!=typeof performance?performance.now():Date.now()),n=t??this.currentTurnId,a=n||0===n?{turnId:n,audioStartTime:i}:{audioStartTime:i},s=()=>{try{this.avatarOrchestrator?.sendEvent("AUDIO_START",a)}catch(t){}};"function"==typeof queueMicrotask?queueMicrotask(s):setTimeout(s,0)}interruptSpeaking(){if(!this.isStoppingSpeaking){this.isStoppingSpeaking=!0,this.conversationStreamActive&&this.talkingAvatar.streamInterrupt(),this.audioReader?.cancel(),this.lipsyncReader?.cancel(),this._pendingEndReason="interrupted";try{this.liveCaptions?.clearCaptions?.()}catch(t){}try{this.bus?.emit?.("event_command_UI_ClearCaptions")}catch(t){}this.isStoppingSpeaking=!1}}setView(t){switch(t){case"full":this.talkingAvatar.setView("full");break;case"mid":this.talkingAvatar.setView("mid");break;case"upper":this.talkingAvatar.setView("upper");break;case"head":this.talkingAvatar.setView("head")}}playAnimation(t,e){const i=`https://sentifydfrontend.blob.core.windows.net/animationclips/${t}`;this.setView("full"),this.talkingAvatar.playAnimation(i,null,e)}reconnect(){}async destroy(){for(const[t,e]of this._busHandlers)try{this.bus.off(t,e)}catch{}this._busHandlers.length=0,this.isStoppingSpeaking=!1,this.conversationStreamActive&&await this.stopConversationStream(),this.talkingAvatar?.stop(),this.talkingAvatar=null}_getBlendColumns(){if(!this._blendCols){this._blendCols=[];for(let t=0;t<gt.length;t++){const e=gt[t];e&&this._blendCols.push([t,e])}}return this._blendCols}_getDtArray(t){this._dtCache||(this._dtCache=new Map);let e=this._dtCache.get(t);return e||(e=new Array(t).fill(this.frameDuration),this._dtCache.set(t,e)),e}}class _t{constructor(t){if(!t)throw new Error("Cannot initialize SpeakingAvatar due to missing bus instance");this.voiceBot=null,this.chatSocket=null,this.bus=t,this.avatarOrchestrator=new rt(t),this.avatarOrchestrator.start(),this.connectionManager=this.createConnectionManager(this.bus,this.avatarOrchestrator),this.sessionData=at.getInstance(),this.auth=new it,this.connectionManager.registerConnectionModule(this.auth),this.voiceBargeInDetector=null}createConnectionManager(t,e){if(!t||!e)throw new Error("Missing dependencies for ConnectionManager creation.");return new ct(t,e)}async init(t){if(!t?.avatarContainer||!t.avatarAPIKey&&!t.tokenEndpoint||!t.avatarId||!t.targetApp)return!1;try{await this.initializeAuthentication(t);const{avatarParameters:e,avatarItem:i}=await this.setupAvatarData();return!(!e||!i||(this.avatarModule=new mt(this.bus,this.avatarOrchestrator),await this.sessionData.init(e,i),await Promise.all([this.initializeChatSocket(),this.initializeVoiceBot(),this.initializeAvatarScene(i,t.avatarContainer)]),this.avatarOrchestrator.injectModules({talkingAvatar:this.avatarModule,chatSocket:this.chatSocket,voiceBot:this.voiceBot,conversation:this.sessionData.conversation}),await this.initializeVoiceBargeInDetector(),await this.connectionManager.waitUntilReady(),this.avatarOrchestrator.sendEvent("READY","SpeakingAAvatar.init"),0))}catch(e){return!1}}async initializeAuthentication(t){if(!(await this.auth.init(t.targetApp,t.avatarAPIKey||"",t.tokenEndpoint||"",t.avatarId)))throw new Error("Authentication initialization failed.")}async setupAvatarData(){const t=await this.auth.getAvatarParameters();if(!t)throw new Error("Failed to retrieve avatar parameters from authentication");return{avatarParameters:t,avatarItem:this.constructAvatarItem(t)}}constructAvatarItem(t){let e=t.avatarUrl;"ReadyPlayerMe"===t.avatarSource&&(e+="?morphTargets=ARKit,Oculus+Visemes,mouthOpen,mouthSmile,eyesClosed,eyesLookUp,eyesLookDown&textureSizeLimit=1024&textureFormat=png");let i=t.lipsyncType||"visemes";return{id:t.avatarSourceId,type:T?.avatar?.type,url:e,source:t.avatarSource,bodyType:t.bodyType,gender:t.gender,lipsyncType:i}}async initializeChatSocket(){try{j.resetInstance?.()}catch{}this.chatSocket=j.getInstance(this.bus,this.auth,this.sessionData,this.avatarOrchestrator),this.connectionManager.registerConnectionModule(this.chatSocket),await this.chatSocket.init()}async initializeVoiceBot(){this.voiceBot=await G.build(this.bus,this.avatarOrchestrator,this.auth,this.sessionData),this.connectionManager.registerConnectionModule(this.voiceBot.speechService)}async initializeVoiceBargeInDetector(){if(!this.voiceBargeInDetector&&!1!==T?.speech?.bargeIn?.enabled)try{this.voiceBargeInDetector=new J({talkingAvatar:this.avatarModule,avatarOrchestrator:this.avatarOrchestrator,config:T?.speech?.bargeIn}),await this.voiceBargeInDetector.init()}catch(t){this.voiceBargeInDetector=null}}async setBargeInEnabled(t){if(T?.speech?.bargeIn&&(T.speech.bargeIn.enabled=t),t)this.voiceBargeInDetector||this.avatarModule&&this.avatarOrchestrator&&await this.initializeVoiceBargeInDetector();else if(this.voiceBargeInDetector){try{this.voiceBargeInDetector.destroy()}catch(e){}this.voiceBargeInDetector=null}}async initializeAvatarScene(t,e){try{if(!this.avatarModule)throw new Error("Avatar module not initialized.");this.connectionManager.registerConnectionModule(this.avatarModule),await this.avatarModule.init(t,e)}catch(i){throw i}}destroy(){try{j.resetInstance?.()}catch{}this.voiceBot?.destroy?.(),this.voiceBargeInDetector?.destroy?.(),this.voiceBargeInDetector=null,this.avatarModule?.destroy?.(),this.connectionManager?.destroy?.(),this.sessionData?.destroy?.(),this.auth?.destroy?.(),this.avatarOrchestrator?.destroy?.()}}class bt extends EventTarget{constructor(){super(),this._listeners=new Map,this._disposers=new Set,this._isDisposed=!1,this._globalListeners=new Set}on(t,e){if(this._isDisposed)return()=>{};if("*"===t)return this.onAll(e);const i=t=>{try{const i=t.detail;e(i)}catch(i){}};this._listeners.has(t)||this._listeners.set(t,new Map),this._listeners.get(t).set(e,i),this.addEventListener(t,i);const n=()=>{this._isDisposed||(this.removeEventListener(t,i),this._listeners.get(t)?.delete(e),this._disposers.delete(n))};return this._disposers.add(n),n}off(t,e){if("*"===t)return this.offAll(e);const i=this._listeners.get(t)?.get(e);i&&(this.removeEventListener(t,i),this._listeners.get(t)?.delete(e))}emit(t,e=void 0){if(this._isDisposed)return;const i=new CustomEvent(t,{detail:e,bubbles:!1,cancelable:!1});this.dispatchEvent(i),this._globalListeners.forEach((i=>{try{i(t,e)}catch(n){}}))}onAll(t){if(this._isDisposed)return()=>{};this._globalListeners.add(t);const e=()=>{this._isDisposed||(this._globalListeners.delete(t),this._disposers.delete(e))};return this._disposers.add(e),e}offAll(t){this._globalListeners.delete(t)}clear(){this._listeners.forEach(((t,e)=>{t.forEach(((t,i)=>{this.removeEventListener(e,t)}))})),this._listeners.clear(),this._globalListeners.clear(),this._disposers.clear()}dispose(){this._isDisposed||(this._disposers.forEach((t=>{try{t()}catch(e){}})),this._listeners.clear(),this._globalListeners.clear(),this._disposers.clear(),this._isDisposed=!0)}get disposerCount(){return this._disposers.size}get isDisposed(){return this._isDisposed}get listenerCount(){let t=this._globalListeners.size;return this._listeners.forEach((e=>{t+=e.size})),t}}const ft="en",yt={en:{start:"Start Conversation",connect:"Connect",endConversation:"End Conversation",restartConversation:"Restart Conversation",hideTyping:"Hide typing input",showTyping:"Show typing input",reconnecting:"Reconnecting...",waitForResponse:"Please wait for response...",typeHere:"Type here.",noMessagesYet:"No messages yet...",conversationStatus:"Conversation Status",conversationInProgress:"Conversation In Progress",conversationStopped:"Conversation Stopped",startConversation:"Start Conversation",downloadConversation:"Download Conversation",liveCaptions:"Live captions",toggleChatbot:"Toggle avatar chatbot",avatar:"Avatar",chat:"Chat",statusInitializing:"Hang tight, we're waking up the assistant!",statusReconnecting:"Connection issue, attempting to reconnect...",statusFailed:"Connection failed. Manual action may be required.",statusInvalidConfiguration:"The avatar is not configured correctly, contact the admin.",close:"Close",lastAssistantMessage:"Last assistant message",fullBodyView:"Full body view",upperBodyView:"Upper body view",previousConversationFound:"Previous conversation found - please choose an option to proceed",secureFormTitle:"Secure Form",secureFormDescription:"Enter your information.",name:"Name*",namePlaceholder:"Enter your name",phoneNumber:"Phone Number",phonePlaceholder:"Enter your phone number",email:"Email",emailPlaceholder:"Enter your email",secureFormNote:"Your information will not be shared with the LLM and will not be stored after this session. By sending you agree to share your info to get additional support.",save:"Save",send:"Send",cancel:"Cancel",conversationEndedPrompt:"Conversation ended. Please rate your satisfaction with the conversation.",submit:"Submit",skip:"Skip",consentTitle:"Consent for AI conversation",consentInfo1:"For general information only — no medical, legal, financial, or safety advice.",consentInfo2:"We use session storage and send your input to provide replies. We don’t keep your conversation or personal info after this session.",consentReadOur:"Read our",consentTermsLabel:"Terms",consentAnd:"and",consentPrivacyLabel:"Privacy Policy",consentMoreDetails:"for more details.",consentInfo4:"(Your consent applies to this session only and clears when you close the tab/window)",consentAccept:"I agree",consentDecline:"Decline",consentAcceptAria:"I agree – start chat",consentDeclineAria:"Decline",interruptSpeaking:"Interrupt speaking avatar",turnOnMic:"Turn on microphone",turnOffMic:"Turn off microphone",tapToSpeak:"Tap to speak",startConversationReminder:"Start a conversation to chat.",chatPlaceholderTitle:"Ready to chat?",chatPlaceholderDescription:"Start a conversation to continue in text mode.",enterInfoOnMobile:"Enter your information in User Information page",waitCurrentResponse:"Please wait for the current response before sending another message.",resumeConversationFailedNewStarted:"We couldn't resume your previous conversation. A new one has been started instead.",end:"End",endConversationPrompt:"Would you like to end the conversation? Ending it will permanently delete the conversation history.",restartConversationPrompt:"Are you sure you want to start a new conversation? Current conversation will be deleted.",newConversation:"New",conversationExpiredPrompt:"This conversation has expired and cannot be resumed. Would you like to download a copy and end or end only?",conversationExpiredResumePrompt:"Your previous conversation has expired and cannot be resumed. Would you like to download a copy of your conversation history?",downloadAndClear:"Download & Clear",downloadAndStartNew:"Download & Start New",startNew:"Start New",ok:"OK",download:"Download",onlyClear:"Only Clear",confirm:"Confirm",alertGenericError:"An error occurred.",alertFailedEndConversation:"Failed to end the conversation. Please try again.",alertFailedClearConversation:"Failed to clear the conversation.",alertCouldNotStartListening:"Could not start listening. Please try again.",alertSomeErrorOccurred:"Some error occurred. Please try again.",alertWaitForAIResponse:"Please wait for the AI response before starting to speak.",alertVoiceServicesUnavailable:"Unable to connect to voice services. Please try again later.",alertServiceTemporarilyUnavailable:"Service is temporarily unavailable. Please try again.",alertTooManyRequests:"Too many simultaneous requests. Please wait a moment and try again.",alertConnectionIssue:"Connection issue detected. Please check your internet connection and try again.",alertResponseTimeout:"Response timeout. Please try again.",alertServiceBusy:"Voice service is currently busy. Please try again in a few minutes.",alertMicrophoneStartFailed:"Failed to start listening. Make sure your microphone is working.",alertMicrophoneCheckSettings:"Failed to start listening. Please check your microphone settings.",alertSpeechRecognitionSetupFailed:"Speech recognition setup failed. Please refresh the page and try again.",alertMicrophoneAccessDenied:"Microphone access denied. Please allow microphone access in your browser settings and refresh the page.",alertNoMicrophoneDetected:"No microphone detected. Please connect a microphone and refresh the page.",alertMicrophoneError:"Microphone error. Please check your microphone."},fr:{start:"DĆ©marrer la conversation",connect:"Se connecter",endConversation:"Terminer la conversation",restartConversation:"RedĆ©marrer la conversation",hideTyping:"Masquer la saisie",showTyping:"Afficher la saisie",reconnecting:"Reconnexion...",waitForResponse:"Veuillez attendre la rĆ©ponse...",typeHere:"Tapez ici.",noMessagesYet:"Pas encore de messages...",conversationStatus:"Ɖtat de la conversation",conversationInProgress:"Conversation en cours",conversationStopped:"Conversation terminĆ©e",startConversation:"Commencer la conversation",downloadConversation:"TĆ©lĆ©charger la conversation",liveCaptions:"Sous-titres en direct",toggleChatbot:"Afficher/Masquer l'avatar",avatar:"Avatar",chat:"Chat",statusInitializing:"Patientez, nous rĆ©veillons l'assistant !",statusReconnecting:"ProblĆØme de connexion, tentative de reconnexion...",statusFailed:"Ɖchec de la connexion. Une action manuelle peut ĆŖtre nĆ©cessaire.",statusInvalidConfiguration:"L'avatar n'est pas configurĆ© correctement, contactez l'administrateur.",close:"Fermer",lastAssistantMessage:"Dernier message de l'assistant",fullBodyView:"Vue du corps entier",upperBodyView:"Vue du haut du corps",previousConversationFound:"Conversation prĆ©cĆ©dente trouvĆ©e - veuillez choisir une option pour continuer.",secureFormTitle:"Formulaire sĆ©curisĆ©",secureFormDescription:"Saisissez vos informations.",name:"Nom*",namePlaceholder:"Entrez votre nom",phoneNumber:"NumĆ©ro de tĆ©lĆ©phone",phonePlaceholder:"Entrez votre numĆ©ro de tĆ©lĆ©phone",email:"E-mail",emailPlaceholder:"Entrez votre e-mail",secureFormNote:"Vos informations ne seront pas partagĆ©es avec le LLM et ne seront pas conservĆ©es aprĆØs cette session. En envoyant, vous acceptez de partager vos informations pour obtenir un support supplĆ©mentaire.",save:"Enregistrer",send:"Envoyer",cancel:"Annuler",conversationEndedPrompt:"Conversation terminĆ©e. Veuillez Ć©valuer votre satisfaction.",submit:"Envoyer",skip:"Ignorer",consentTitle:"Consentement pour la conversation IA",consentInfo1:"ƀ titre informatif uniquement — aucun conseil mĆ©dical, juridique, financier ou de sĆ©curitĆ©.",consentInfo2:"Nous utilisons le stockage de session et envoyons votre saisie pour fournir des rĆ©ponses. Nous ne conservons pas votre conversation ni vos informations personnelles aprĆØs cette session.",consentReadOur:"Lisez nos",consentTermsLabel:"Conditions",consentAnd:"et",consentPrivacyLabel:"Politique de confidentialitĆ©",consentMoreDetails:"pour plus de dĆ©tails.",consentInfo4:"(Votre consentement s'applique uniquement Ć  cette session et est rĆ©initialisĆ© lorsque vous fermez l'onglet ou la fenĆŖtre)",consentAccept:"J'accepte",consentDecline:"Refuser",consentAcceptAria:"J'accepte – dĆ©marrer le chat",consentDeclineAria:"Refuser",interruptSpeaking:"Interrompre l'avatar",turnOnMic:"Activer le microphone",turnOffMic:"DĆ©sactiver le microphone",tapToSpeak:"Appuyez pour parler",startConversationReminder:"DĆ©marrez une conversation pour discuter.",chatPlaceholderTitle:"PrĆŖt Ć  discuter ?",chatPlaceholderDescription:"Lancez une conversation pour continuer en mode texte.",enterInfoOnMobile:"Saisissez vos informations dans la page Informations utilisateur",waitCurrentResponse:"Veuillez attendre la rĆ©ponse en cours avant d'envoyer un autre message.",resumeConversationFailedNewStarted:"Nous n'avons pas pu reprendre votre conversation prĆ©cĆ©dente. Une nouvelle a Ć©tĆ© dĆ©marrĆ©e Ć  la place.",end:"Terminer",endConversationPrompt:"Souhaitez-vous terminer la conversation ? Cela supprimera dĆ©finitivement l'historique de la conversation.",restartConversationPrompt:"Voulez-vous dĆ©marrer une nouvelle conversation ? La conversation actuelle sera supprimĆ©e.",newConversation:"Nouveau",conversationExpiredPrompt:"Cette conversation a expirĆ© et ne peut pas ĆŖtre reprise. Voulez-vous en tĆ©lĆ©charger une copie puis la supprimer, ou simplement la supprimer ?",conversationExpiredResumePrompt:"Votre conversation prĆ©cĆ©dente a expirĆ© et ne peut pas ĆŖtre reprise. Voulez-vous tĆ©lĆ©charger une copie de votre historique de conversation ?",downloadAndClear:"TĆ©lĆ©charger et effacer",downloadAndStartNew:"TĆ©lĆ©charger et dĆ©marrer",startNew:"Nouvelle conv.",onlyClear:"Effacer uniquement",confirm:"Confirmer",ok:"OK",download:"TĆ©lĆ©charger",alertGenericError:"Une erreur s'est produite.",alertFailedEndConversation:"Ɖchec de la fin de la conversation. Veuillez rĆ©essayer.",alertFailedClearConversation:"Ɖchec de l'effacement de la conversation.",alertCouldNotStartListening:"Impossible de dĆ©marrer l'Ć©coute. Veuillez rĆ©essayer.",alertSomeErrorOccurred:"Une erreur s'est produite. Veuillez rĆ©essayer.",alertWaitForAIResponse:"Veuillez attendre la rĆ©ponse de l'IA avant de commencer Ć  parler.",alertVoiceServicesUnavailable:"Impossible de se connecter aux services vocaux. Veuillez rĆ©essayer plus tard.",alertServiceTemporarilyUnavailable:"Service temporairement indisponible. Veuillez rĆ©essayer.",alertTooManyRequests:"Trop de demandes simultanĆ©es. Veuillez patienter un instant et rĆ©essayer.",alertConnectionIssue:"ProblĆØme de connexion dĆ©tectĆ©. Veuillez vĆ©rifier votre connexion internet et rĆ©essayer.",alertResponseTimeout:"DĆ©lai de rĆ©ponse dĆ©passĆ©. Veuillez rĆ©essayer.",alertServiceBusy:"Le service vocal est actuellement occupĆ©. Veuillez rĆ©essayer dans quelques minutes.",alertMicrophoneStartFailed:"Impossible de dĆ©marrer l'Ć©coute. Assurez-vous que votre microphone fonctionne.",alertMicrophoneCheckSettings:"Impossible de dĆ©marrer l'Ć©coute. Veuillez vĆ©rifier les paramĆØtres de votre microphone.",alertSpeechRecognitionSetupFailed:"Ɖchec de la configuration de la reconnaissance vocale. Veuillez actualiser la page et rĆ©essayer.",alertMicrophoneAccessDenied:"AccĆØs au microphone refusĆ©. Veuillez autoriser l'accĆØs au microphone dans les paramĆØtres de votre navigateur et actualiser la page.",alertNoMicrophoneDetected:"Aucun microphone dĆ©tectĆ©. Veuillez connecter un microphone et actualiser la page.",alertMicrophoneError:"Erreur de microphone. Veuillez vĆ©rifier votre microphone."},de:{start:"Starten Sie die Konversation",connect:"Verbinden",endConversation:"GesprƤch beenden",restartConversation:"GesprƤch neu starten",hideTyping:"Eingabefeld ausblenden",showTyping:"Eingabefeld anzeigen",reconnecting:"Verbindung wird wiederhergestellt...",waitForResponse:"Bitte auf die Antwort warten...",typeHere:"Hier eingeben.",noMessagesYet:"Noch keine Nachrichten...",conversationStatus:"GesprƤchsstatus",conversationInProgress:"GesprƤch lƤuft",conversationStopped:"GesprƤch beendet",startConversation:"GesprƤch starten",downloadConversation:"GesprƤch herunterladen",liveCaptions:"Live-Untertitel",toggleChatbot:"Avatar-Chatbot ein-/ausblenden",avatar:"Avatar",chat:"Chat",statusInitializing:"Einen Moment, der Assistent wird gestartet!",statusReconnecting:"Verbindungsproblem, versuche erneut zu verbinden...",statusFailed:"Verbindung fehlgeschlagen. Mƶglicherweise ist ein manueller Eingriff erforderlich.",statusInvalidConfiguration:"Der Avatar ist nicht korrekt konfiguriert, wenden Sie sich an den Administrator.",close:"Schließen",lastAssistantMessage:"Letzte Nachricht des Assistenten",fullBodyView:"Ganzkƶrperansicht",upperBodyView:"Oberkƶrperansicht",previousConversationFound:"Früheres GesprƤch gefunden – bitte wƤhlen Sie eine Option, um fortzufahren",secureFormTitle:"Sicheres Formular",secureFormDescription:"Geben Sie Ihre Informationen ein.",name:"Name*",namePlaceholder:"Geben Sie Ihren Namen ein",phoneNumber:"Telefonnummer",phonePlaceholder:"Geben Sie Ihre Telefonnummer ein",email:"E-Mail",emailPlaceholder:"Geben Sie Ihre E-Mail ein",secureFormNote:"Ihre Informationen werden nicht mit dem LLM geteilt und nach dieser Sitzung nicht gespeichert. Mit dem Absenden erklƤren Sie sich einverstanden, Ihre Daten zu teilen, um zusƤtzliche Unterstützung zu erhalten.",save:"Speichern",send:"Senden",cancel:"Abbrechen",conversationEndedPrompt:"GesprƤch beendet. Bitte bewerten Sie Ihre Zufriedenheit.",submit:"Senden",skip:"Überspringen",consentTitle:"Einwilligung für das KI-GesprƤch",consentInfo1:"Nur zu allgemeinen Informationszwecken – keine medizinischen, rechtlichen, finanziellen oder sicherheitsrelevanten RatschlƤge.",consentInfo2:"Wir verwenden den Sitzungspeicher und senden Ihre Eingaben, um Antworten bereitzustellen. Wir speichern Ihr GesprƤch oder persƶnliche Daten nach dieser Sitzung nicht.",consentReadOur:"Lesen Sie unsere",consentTermsLabel:"Nutzungsbedingungen",consentAnd:"und",consentPrivacyLabel:"DatenschutzerklƤrung",consentMoreDetails:"für weitere Informationen.",consentInfo4:"(Ihre Einwilligung gilt nur für diese Sitzung und wird zurückgesetzt, wenn Sie den Tab oder das Fenster schließen)",consentAccept:"Ich stimme zu",consentDecline:"Ablehnen",consentAcceptAria:"Ich stimme zu – Chat starten",consentDeclineAria:"Ablehnen",interruptSpeaking:"Sprechenden Avatar unterbrechen",turnOnMic:"Mikrofon einschalten",turnOffMic:"Mikrofon ausschalten",tapToSpeak:"Tippen zum Sprechen",startConversationReminder:"Starten Sie ein GesprƤch, um zu chatten.",chatPlaceholderTitle:"Bereit zum Chatten?",chatPlaceholderDescription:"Starten Sie ein GesprƤch, um im Textmodus fortzufahren.",enterInfoOnMobile:"Geben Sie Ihre Daten auf der Seite Benutzerinformationen ein",waitCurrentResponse:"Bitte warten Sie die aktuelle Antwort ab, bevor Sie eine weitere Nachricht senden.",resumeConversationFailedNewStarted:"Wir konnten Ihr vorheriges GesprƤch nicht fortsetzen. Stattdessen wurde ein neues gestartet.",end:"Beenden",endConversationPrompt:"Mƶchten Sie das GesprƤch beenden? Dadurch wird der GesprƤchsverlauf dauerhaft gelƶscht.",restartConversationPrompt:"Mƶchten Sie ein neues GesprƤch beginnen? Das aktuelle GesprƤch wird gelƶscht.",newConversation:"Neu",conversationExpiredPrompt:"Dieses GesprƤch ist abgelaufen und kann nicht fortgesetzt werden. Mƶchten Sie eine Kopie herunterladen und lƶschen oder nur lƶschen?",conversationExpiredResumePrompt:"Ihr vorheriges GesprƤch ist abgelaufen und kann nicht fortgesetzt werden. Mƶchten Sie eine Kopie Ihres GesprƤchsverlaufs herunterladen?",downloadAndClear:"Herunterladen & lƶschen",downloadAndStartNew:"Herunterladen & Neu starten",startNew:"Neu starten",onlyClear:"Nur lƶschen",confirm:"BestƤtigen",ok:"OK",download:"Herunterladen",alertGenericError:"Ein Fehler ist aufgetreten.",alertFailedEndConversation:"Das GesprƤch konnte nicht beendet werden. Bitte versuchen Sie es erneut.",alertFailedClearConversation:"Das GesprƤch konnte nicht gelƶscht werden.",alertCouldNotStartListening:"Zuhƶren konnte nicht gestartet werden. Bitte versuchen Sie es erneut.",alertSomeErrorOccurred:"Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.",alertWaitForAIResponse:"Bitte warten Sie auf die KI-Antwort, bevor Sie zu sprechen beginnen.",alertVoiceServicesUnavailable:"Verbindung zu Sprachdiensten nicht mƶglich. Bitte versuchen Sie es spƤter erneut.",alertServiceTemporarilyUnavailable:"Der Dienst ist vorübergehend nicht verfügbar. Bitte versuchen Sie es erneut.",alertTooManyRequests:"Zu viele gleichzeitige Anfragen. Bitte warten Sie einen Moment und versuchen Sie es erneut.",alertConnectionIssue:"Verbindungsproblem erkannt. Bitte überprüfen Sie Ihre Internetverbindung und versuchen Sie es erneut.",alertResponseTimeout:"Zeitüberschreitung bei der Antwort. Bitte versuchen Sie es erneut.",alertServiceBusy:"Der Sprachdienst ist derzeit ausgelastet. Bitte versuchen Sie es in einigen Minuten erneut.",alertMicrophoneStartFailed:"Zuhƶren konnte nicht gestartet werden. Stellen Sie sicher, dass Ihr Mikrofon funktioniert.",alertMicrophoneCheckSettings:"Zuhƶren konnte nicht gestartet werden. Bitte überprüfen Sie Ihre Mikrofoneinstellungen.",alertSpeechRecognitionSetupFailed:"Einrichtung der Spracherkennung fehlgeschlagen. Bitte aktualisieren Sie die Seite und versuchen Sie es erneut.",alertMicrophoneAccessDenied:"Mikrofonzugriff verweigert. Bitte erlauben Sie den Mikrofonzugriff in Ihren Browsereinstellungen und aktualisieren Sie die Seite.",alertNoMicrophoneDetected:"Kein Mikrofon erkannt. Bitte schließen Sie ein Mikrofon an und aktualisieren Sie die Seite.",alertMicrophoneError:"Mikrofonfehler. Bitte überprüfen Sie Ihr Mikrofon."},es:{start:"Iniciar conversación",connect:"Conectar",endConversation:"Terminar conversación",restartConversation:"Reiniciar conversación",hideTyping:"Ocultar entrada de texto",showTyping:"Mostrar entrada de texto",reconnecting:"Reconectando...",waitForResponse:"Espere la respuesta...",typeHere:"Escriba aquĆ­.",noMessagesYet:"TodavĆ­a no hay mensajes...",conversationStatus:"Estado de la conversación",conversationInProgress:"Conversación en curso",conversationStopped:"Conversación detenida",startConversation:"Iniciar conversación",downloadConversation:"Descargar conversación",liveCaptions:"SubtĆ­tulos en vivo",toggleChatbot:"Mostrar/ocultar avatar",avatar:"Avatar",chat:"Chat",statusInitializing:"Espere, estamos iniciando el asistente",statusReconnecting:"Problema de conexión, intentando reconectar...",statusFailed:"La conexión falló. Puede ser necesaria una acción manual.",statusInvalidConfiguration:"El avatar no estĆ” configurado correctamente, contacte al administrador.",close:"Cerrar",lastAssistantMessage:"Último mensaje del asistente",fullBodyView:"Vista de cuerpo completo",upperBodyView:"Vista de torso",previousConversationFound:"Se encontró una conversación anterior; elija una opción para continuar",secureFormTitle:"Formulario seguro",secureFormDescription:"Ingrese su información.",name:"Nombre*",namePlaceholder:"Ingrese su nombre",phoneNumber:"NĆŗmero de telĆ©fono",phonePlaceholder:"Ingrese su nĆŗmero de telĆ©fono",email:"Correo electrónico",emailPlaceholder:"Ingrese su correo electrónico",secureFormNote:"Su información no se compartirĆ” con el LLM ni se almacenarĆ” despuĆ©s de esta sesión. Al enviar, acepta compartir su información para obtener soporte adicional.",save:"Guardar",send:"Enviar",cancel:"Cancelar",conversationEndedPrompt:"Conversación finalizada. Califique su satisfacción.",submit:"Enviar",skip:"Omitir",consentTitle:"Consentimiento para conversación con IA",consentInfo1:"Solo con fines informativos — sin consejos mĆ©dicos, legales, financieros ni de seguridad.",consentInfo2:"Usamos almacenamiento de sesión y enviamos su entrada para responder. No guardamos su conversación ni datos personales tras esta sesión.",consentReadOur:"Lea nuestros",consentTermsLabel:"TĆ©rminos",consentAnd:"y",consentPrivacyLabel:"PolĆ­tica de privacidad",consentMoreDetails:"para mĆ”s detalles.",consentInfo4:"(Su consentimiento se aplica solo a esta sesión y se borra al cerrar la pestaƱa o ventana)",consentAccept:"Acepto",consentDecline:"Rechazar",consentAcceptAria:"Acepto – iniciar chat",consentDeclineAria:"Rechazar",interruptSpeaking:"Interrumpir avatar que habla",turnOnMic:"Activar micrófono",turnOffMic:"Desactivar micrófono",tapToSpeak:"Toca para hablar",startConversationReminder:"Inicie una conversación para chatear.",chatPlaceholderTitle:"ĀæListo para chatear?",chatPlaceholderDescription:"Inicia una conversación para continuar en modo texto.",enterInfoOnMobile:"Ingrese su información en la pĆ”gina de usuario",waitCurrentResponse:"Espere la respuesta actual antes de enviar otro mensaje.",resumeConversationFailedNewStarted:"No pudimos reanudar su conversación anterior. En su lugar, se ha iniciado una nueva.",end:"Terminar",endConversationPrompt:"ĀæDesea terminar la conversación? Esto eliminarĆ” el historial permanentemente.",restartConversationPrompt:"ĀæSeguro que quiere iniciar una nueva conversación? La conversación actual se eliminarĆ”.",newConversation:"Nueva",conversationExpiredPrompt:"Esta conversación ha expirado y no se puede reanudar. ĀæDesea descargar una copia y borrar o solo borrar?",conversationExpiredResumePrompt:"Su conversación anterior ha expirado y no se puede reanudar. ĀæDesea descargar una copia de su historial de conversación?",downloadAndClear:"Descargar y borrar",downloadAndStartNew:"Descargar e iniciar",startNew:"Iniciar nueva",onlyClear:"Solo borrar",confirm:"Confirmar",ok:"OK",download:"Descargar",alertGenericError:"Se produjo un error.",alertFailedEndConversation:"No se pudo terminar la conversación. Por favor, intĆ©ntelo de nuevo.",alertFailedClearConversation:"No se pudo borrar la conversación.",alertCouldNotStartListening:"No se pudo iniciar la escucha. Por favor, intĆ©ntelo de nuevo.",alertSomeErrorOccurred:"Se produjo un error. Por favor, intĆ©ntelo de nuevo.",alertWaitForAIResponse:"Por favor, espere la respuesta de la IA antes de comenzar a hablar.",alertVoiceServicesUnavailable:"No se puede conectar a los servicios de voz. Por favor, intĆ©ntelo mĆ”s tarde.",alertServiceTemporarilyUnavailable:"El servicio no estĆ” disponible temporalmente. Por favor, intĆ©ntelo de nuevo.",alertTooManyRequests:"Demasiadas solicitudes simultĆ”neas. Por favor, espere un momento e intĆ©ntelo de nuevo.",alertConnectionIssue:"Problema de conexión detectado. Por favor, verifique su conexión a internet e intĆ©ntelo de nuevo.",alertResponseTimeout:"Tiempo de respuesta agotado. Por favor, intĆ©ntelo de nuevo.",alertServiceBusy:"El servicio de voz estĆ” ocupado actualmente. Por favor, intĆ©ntelo en unos minutos.",alertMicrophoneStartFailed:"No se pudo iniciar la escucha. AsegĆŗrese de que su micrófono funcione.",alertMicrophoneCheckSettings:"No se pudo iniciar la escucha. Por favor, verifique la configuración de su micrófono.",alertSpeechRecognitionSetupFailed:"Error en la configuración del reconocimiento de voz. Por favor, actualice la pĆ”gina e intĆ©ntelo de nuevo.",alertMicrophoneAccessDenied:"Acceso al micrófono denegado. Por favor, permita el acceso al micrófono en la configuración de su navegador y actualice la pĆ”gina.",alertNoMicrophoneDetected:"No se detectó ningĆŗn micrófono. Por favor, conecte un micrófono y actualice la pĆ”gina.",alertMicrophoneError:"Error de micrófono. Por favor, verifique su micrófono."},ar:{start:"Ų§ŲØŲÆŲ£ المحادثة",connect:"اتصل",endConversation:"؄نهاؔ المحادثة",restartConversation:"Ų„Ų¹Ų§ŲÆŲ© ŲØŲÆŲ” المحادثة",hideTyping:"؄خفاؔ حقل Ų§Ł„ŁƒŲŖŲ§ŲØŲ©",showTyping:"؄ظهار حقل Ų§Ł„ŁƒŲŖŲ§ŲØŲ©",reconnecting:"Ų¬Ų§Ų±Ł Ų„Ų¹Ų§ŲÆŲ© الاتصال...",waitForResponse:"ŁŠŲ±Ų¬Ł‰ انتظار الرد...",typeHere:"اكتب هنا.",noMessagesYet:"لا توجد رسائل ŲØŲ¹ŲÆ...",conversationStatus:"حالة المحادثة",conversationInProgress:"المحادثة جارية",conversationStopped:"المحادثة Ł…ŲŖŁˆŁ‚ŁŲ©",startConversation:"Ų§ŲØŲÆŲ£ المحادثة",downloadConversation:"ŲŖŁ†Ų²ŁŠŁ„ المحادثة",liveCaptions:"ŲŖŲ¹Ł„ŁŠŁ‚Ų§ŲŖ Ł†ŲµŁŠŲ© Ł…ŲØŲ§Ų“Ų±Ų©",toggleChatbot:"؄ظهار/؄خفاؔ روبوت المحادثة",avatar:"أفاتار",chat:"ŲÆŲ±ŲÆŲ“Ų©",statusInitializing:"ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ų§Ł†ŲŖŲøŲ§Ų±ŲŒ Ł†Ł‚ŁˆŁ… ŲØŲŖŲ“ŲŗŁŠŁ„ الأفاتار!",statusReconnecting:"Ł…Ų“ŁƒŁ„Ų© في Ų§Ł„Ų§ŲŖŲµŲ§Ł„ŲŒ Ų¬Ų§Ų±Ł Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© مجددًا...",statusFailed:"فؓل الاتصال. قد ŁŠŲŖŲ·Ł„ŲØ الأمر تدخلاً ŁŠŲÆŁˆŁŠŁ‹Ų§.",statusInvalidConfiguration:"الأفاتار غير Ł…Ł‡ŁŠŲ£ ŲØŲ“ŁƒŁ„ صحيح، ŁŠŲ±Ų¬Ł‰ Ų§Ł„ŲŖŁˆŲ§ŲµŁ„ Ł…Ų¹ Ų§Ł„Ł…Ų³Ų¤ŁˆŁ„.",close:"؄غلاق",lastAssistantMessage:"Ų¢Ų®Ų± رسالة من الأفاتار",fullBodyView:"Ų¹Ų±Ų¶ ŁƒŲ§Ł…Ł„ للجسم",upperBodyView:"Ų¹Ų±Ų¶ للجزؔ Ų§Ł„Ų¹Ł„ŁˆŁŠ",previousConversationFound:"ŲŖŁ… Ų§Ł„Ų¹Ų«ŁˆŲ± على Ł…Ų­Ų§ŲÆŲ«Ų© سابقة - ŁŠŲ±Ų¬Ł‰ اختيار خيار للمتابعة",secureFormTitle:"Ł†Ł…ŁˆŲ°Ų¬ آمن",secureFormDescription:"أدخل Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ.",name:"الاسم*",namePlaceholder:"أدخل Ų§Ų³Ł…Łƒ",phoneNumber:"رقم الهاتف",phonePlaceholder:"أدخل رقم Ł‡Ų§ŲŖŁŁƒ",email:"Ų§Ł„ŲØŲ±ŁŠŲÆ Ų§Ł„Ų„Ł„ŁƒŲŖŲ±ŁˆŁ†ŁŠ",emailPlaceholder:"أدخل بريدك Ų§Ł„Ų„Ł„ŁƒŲŖŲ±ŁˆŁ†ŁŠ",secureFormNote:"لن ŲŖŲŖŁ… Ł…Ų“Ų§Ų±ŁƒŲ© Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ Ł…Ų¹ Ł†Ł…ŁˆŲ°Ų¬ اللغة ŁˆŁ„Ł† ŁŠŲŖŁ… ŲŖŲ®Ų²ŁŠŁ†Ł‡Ų§ ŲØŲ¹ŲÆ هذه الجلسة. بال؄رسال ŁŲ„Ł†Łƒ ŲŖŁˆŲ§ŁŁ‚ على Ł…Ų“Ų§Ų±ŁƒŲ© Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ Ł„Ł„Ų­ŲµŁˆŁ„ على دعم ؄ضافي.",save:"حفظ",send:"Ų„Ų±Ų³Ų§Ł„",cancel:"؄لغاؔ",conversationEndedPrompt:"انتهت المحادثة. ŁŠŲ±Ų¬Ł‰ ŲŖŁ‚ŁŠŁŠŁ… مدى رضاك.",submit:"Ų„Ų±Ų³Ų§Ł„",skip:"تخطي",consentTitle:"Ł…ŁˆŲ§ŁŁ‚Ų© على Ł…Ų­Ų§ŲÆŲ«Ų© Ų§Ł„Ų°ŁƒŲ§Ų” Ų§Ł„Ų§ŲµŲ·Ł†Ų§Ų¹ŁŠ",consentInfo1:"Ł„Ł„Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖ العامة فقط — ŲØŲÆŁˆŁ† نصائح طبية أو Ł‚Ų§Ł†ŁˆŁ†ŁŠŲ© أو Ł…Ų§Ł„ŁŠŲ© أو Ų£Ł…Ł†ŁŠŲ©.",consentInfo2:"نستخدم ŲŖŲ®Ų²ŁŠŁ† الجلسة ŁˆŁ†Ų±Ų³Ł„ Ł…ŲÆŲ®Ł„Ų§ŲŖŁƒ Ł„ŲŖŁ‚ŲÆŁŠŁ… Ų§Ł„Ų±ŲÆŁˆŲÆ. لا نحتفظ ŲØŁ…Ų­Ų§ŲÆŲ«ŲŖŁƒ أو ŲØŁŠŲ§Ł†Ų§ŲŖŁƒ Ų§Ł„Ų“Ų®ŲµŁŠŲ© ŲØŲ¹ŲÆ هذه الجلسة.",consentReadOur:"اقرأ",consentTermsLabel:"Ų§Ł„Ų“Ų±ŁˆŲ·",consentAnd:"و",consentPrivacyLabel:"سياسة Ų§Ł„Ų®ŲµŁˆŲµŁŠŲ©",consentMoreDetails:"Ł„Ł„Ł…Ų²ŁŠŲÆ من Ų§Ł„ŲŖŁŲ§ŲµŁŠŁ„.",consentInfo4:"(تنطبق Ł…ŁˆŲ§ŁŁ‚ŲŖŁƒ على جلسة التصفح Ų§Ł„Ų­Ų§Ł„ŁŠŲ© فقط ŁˆŁŠŲŖŁ… مسحها عند ؄غلاق الصفحة أو النافذة)",consentAccept:"Ų£ŁˆŲ§ŁŁ‚",consentDecline:"رفض",consentAcceptAria:"Ų£ŁˆŲ§ŁŁ‚ - Ų§ŲØŲÆŲ£ المحادثة",consentDeclineAria:"رفض",interruptSpeaking:"Ų„ŁŠŁ‚Ų§Ł الأفاتار Ų§Ł„Ł…ŲŖŁƒŁ„Ł…",turnOnMic:"ŲŖŲ“ŲŗŁŠŁ„ Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†",turnOffMic:"Ų„ŁŠŁ‚Ų§Ł Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†",tapToSpeak:"انقر للتحدث",startConversationReminder:"Ų§ŲØŲÆŲ£ Ł…Ų­Ų§ŲÆŲ«Ų© للتحدث.",chatPlaceholderTitle:"Ł…Ų³ŲŖŲ¹ŲÆ Ł„Ł„ŲÆŲ±ŲÆŲ“Ų©ŲŸ",chatPlaceholderDescription:"Ų§ŲØŲÆŲ£ Ł…Ų­Ų§ŲÆŲ«Ų© للمتابعة في وضع النص.",enterInfoOnMobile:"أدخل Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ في صفحة Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖ المستخدم",waitCurrentResponse:"ŁŠŲ±Ų¬Ł‰ انتظار الرد Ų§Ł„Ų­Ų§Ł„ŁŠ قبل Ų„Ų±Ų³Ų§Ł„ رسالة أخرى.",resumeConversationFailedNewStarted:"لم Ł†ŲŖŁ…ŁƒŁ† من استئناف Ł…Ų­Ų§ŲÆŲ«ŲŖŁƒ السابقة. ŲŖŁ… ŲØŲÆŲ” Ł…Ų­Ų§ŲÆŲ«Ų© جديدة بدلاً من Ų°Ł„Łƒ. ",end:"؄نهاؔ",endConversationPrompt:"هل ŲŖŲ±ŲŗŲØ في ؄نهاؔ Ų§Ł„Ł…Ų­Ų§ŲÆŲ«Ų©ŲŸ سيؤدي Ų°Ł„Łƒ ؄لى حذف المحادثة Ł†Ł‡Ų§Ų¦ŁŠŁ‹Ų§.",restartConversationPrompt:"هل أنت Ł…ŲŖŲ£ŁƒŲÆ من ŲØŲÆŲ” Ł…Ų­Ų§ŲÆŲ«Ų© جديدة؟ Ų³ŁŠŲŖŁ… حذف المحادثة Ų§Ł„Ų­Ų§Ł„ŁŠŲ©.",newConversation:"جديدة",conversationExpiredPrompt:"انتهت ŲµŁ„Ų§Ų­ŁŠŲ© هذه المحادثة ŁˆŁ„Ų§ ŁŠŁ…ŁƒŁ† استئنافها. هل تريد ŲŖŁ†Ų²ŁŠŁ„ نسخة Ų«Ł… حذفها أو الحذف ŁŁ‚Ų·ŲŸ",conversationExpiredResumePrompt:"انتهت ŲµŁ„Ų§Ų­ŁŠŲ© Ł…Ų­Ų§ŲÆŲ«ŲŖŁƒ السابقة ŁˆŁ„Ų§ ŁŠŁ…ŁƒŁ† استئنافها. هل ŲŖŲ±ŲŗŲØ في ŲŖŁ†Ų²ŁŠŁ„ نسخة من سجل Ų§Ł„Ł…Ų­Ų§ŲÆŲ«Ų©ŲŸ",downloadAndClear:"ŲŖŁ†Ų²ŁŠŁ„ وحذف",downloadAndStartNew:"ŲŖŁ†Ų²ŁŠŁ„ وبدؔ جديدة",startNew:"ŲØŲÆŲ” جديدة",onlyClear:"حذف فقط",confirm:"تأكيد",ok:"Ł…ŁˆŲ§ŁŁ‚",download:"ŲŖŁ†Ų²ŁŠŁ„",alertGenericError:"Ų­ŲÆŲ« Ų®Ų·Ų£.",alertFailedEndConversation:"فؓل في ؄نهاؔ المحادثة. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertFailedClearConversation:"فؓل في Ł…Ų³Ų­ المحادثة.",alertCouldNotStartListening:"ŲŖŲ¹Ų°Ų± ŲØŲÆŲ” الاستماع. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertSomeErrorOccurred:"Ų­ŲÆŲ« Ų®Ų·Ų£ Ł…Ų§. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertWaitForAIResponse:"ŁŠŲ±Ų¬Ł‰ انتظار Ų±ŲÆ Ų§Ł„Ų°ŁƒŲ§Ų” Ų§Ł„Ų§ŲµŲ·Ł†Ų§Ų¹ŁŠ قبل البدؔ في التحدث.",alertVoiceServicesUnavailable:"ŲŖŲ¹Ų°Ų± الاتصال ŲØŲ®ŲÆŁ…Ų§ŲŖ Ų§Ł„ŲµŁˆŲŖ. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© لاحقاً.",alertServiceTemporarilyUnavailable:"الخدمة غير Ł…ŲŖŲ§Ų­Ų© مؤقتاً. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertTooManyRequests:"طلبات متزامنة كثيرة Ų¬ŲÆŲ§Ł‹. ŁŠŲ±Ų¬Ł‰ الانتظار لحظة ŁˆŲ§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertConnectionIssue:"ŲŖŁ… اكتؓاف Ł…Ų“ŁƒŁ„Ų© في الاتصال. ŁŠŲ±Ų¬Ł‰ التحقق من Ų§ŲŖŲµŲ§Ł„Łƒ بال؄نترنت ŁˆŲ§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertResponseTimeout:"انتهت مهلة الاستجابة. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertServiceBusy:"Ų®ŲÆŁ…Ų© Ų§Ł„ŲµŁˆŲŖ Ł…Ų“ŲŗŁˆŁ„Ų© Ų­Ų§Ł„ŁŠŲ§Ł‹. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© ŲØŲ¹ŲÆ ŲØŲ¶Ų¹ دقائق.",alertMicrophoneStartFailed:"ŲŖŲ¹Ų°Ų± ŲØŲÆŲ” الاستماع. تأكد من أن Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ† ŁŠŲ¹Ł…Ł„.",alertMicrophoneCheckSettings:"ŲŖŲ¹Ų°Ų± ŲØŲÆŲ” الاستماع. ŁŠŲ±Ų¬Ł‰ التحقق من Ų„Ų¹ŲÆŲ§ŲÆŲ§ŲŖ Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†.",alertSpeechRecognitionSetupFailed:"فؓل Ų„Ų¹ŲÆŲ§ŲÆ التعرف على Ų§Ł„ŁƒŁ„Ų§Ł…. ŁŠŲ±Ų¬Ł‰ تحديث الصفحة ŁˆŲ§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertMicrophoneAccessDenied:"ŲŖŁ… رفض Ų§Ł„ŁˆŲµŁˆŁ„ ؄لى Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†. ŁŠŲ±Ų¬Ł‰ السماح ŲØŲ§Ł„ŁˆŲµŁˆŁ„ ؄لى Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ† في Ų„Ų¹ŲÆŲ§ŲÆŲ§ŲŖ المتصفح وتحديث الصفحة.",alertNoMicrophoneDetected:"لم ŁŠŲŖŁ… اكتؓاف Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†. ŁŠŲ±Ų¬Ł‰ ŲŖŁˆŲµŁŠŁ„ Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ† وتحديث الصفحة.",alertMicrophoneError:"Ų®Ų·Ų£ في Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†. ŁŠŲ±Ų¬Ł‰ التحقق من Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†."},zh:{start:"å¼€å§‹åÆ¹čÆ",connect:"čæžęŽ„",endConversation:"ē»“ęŸåÆ¹čÆ",restartConversation:"é‡ę–°å¼€å§‹åÆ¹čÆ",hideTyping:"éšč—č¾“å…„ę”†",showTyping:"ę˜¾ē¤ŗč¾“å…„ę”†",reconnecting:"ę­£åœØé‡ę–°čæžęŽ„...",waitForResponse:"čÆ·ē­‰å¾…å›žå¤...",typeHere:"åœØę­¤č¾“å…„ć€‚",noMessagesYet:"ęš‚ę— ę¶ˆęÆ...",conversationStatus:"åÆ¹čÆēŠ¶ę€",conversationInProgress:"åÆ¹čÆčæ›č”Œäø­",conversationStopped:"åÆ¹čÆå·²åœę­¢",startConversation:"å¼€å§‹åÆ¹čÆ",downloadConversation:"äø‹č½½åÆ¹čÆ",liveCaptions:"å®žę—¶å­—å¹•",toggleChatbot:"显示/éšč—č™šę‹Ÿå½¢č±”åŠ©ę‰‹",avatar:"č™šę‹Ÿå½¢č±”",chat:"聊天",statusInitializing:"čÆ·ēØå€™ļ¼Œęˆ‘ä»¬ę­£åœØå”¤é†’åŠ©ę‰‹ļ¼",statusReconnecting:"čæžęŽ„å‡ŗēŽ°é—®é¢˜ļ¼Œę­£åœØå°čÆ•é‡ę–°čæžęŽ„...",statusFailed:"čæžęŽ„å¤±č“„ć€‚åÆčƒ½éœ€č¦ę‰‹åŠØå¤„ē†ć€‚",statusInvalidConfiguration:"č™šę‹Ÿå½¢č±”é…ē½®äøę­£ē”®ļ¼ŒčÆ·č”ē³»ē®”ē†å‘˜ć€‚",close:"关闭",lastAssistantMessage:"åŠ©ę‰‹ēš„äøŠäø€ę”ę¶ˆęÆ",fullBodyView:"全身视图",upperBodyView:"åŠčŗ«č§†å›¾",previousConversationFound:"ę‰¾åˆ°ä¹‹å‰ēš„åÆ¹čÆā€”ā€”čÆ·é€‰ę‹©äø€äøŖé€‰é”¹ē»§ē»­",secureFormTitle:"å®‰å…Øč”Øå•",secureFormDescription:"čÆ·č¾“å…„ę‚Øēš„äæ”ęÆć€‚",name:"姓名*",namePlaceholder:"čÆ·č¾“å…„å§“å",phoneNumber:"ē”µčÆå·ē ",phonePlaceholder:"čÆ·č¾“å…„ē”µčÆå·ē ",email:"电子邮件",emailPlaceholder:"请输兄电子邮件",secureFormNote:"ę‚Øēš„äæ”ęÆäøä¼šäøŽå¤§čÆ­čØ€ęØ”åž‹å…±äŗ«ļ¼Œä¼ščÆē»“ęŸåŽä¹Ÿäøä¼šč¢«å­˜å‚Øć€‚å‘é€å³č”Øē¤ŗę‚ØåŒę„å…±äŗ«ę‚Øēš„äæ”ęÆä»„čŽ·å¾—é¢å¤–ę”ÆęŒć€‚",save:"äæå­˜",send:"发送",cancel:"å–ę¶ˆ",conversationEndedPrompt:"åÆ¹čÆå·²ē»“ęŸć€‚čÆ·čÆ„ä»·ę‚Øēš„ę»”ę„åŗ¦ć€‚",submit:"ęäŗ¤",skip:"跳过",consentTitle:"åŒę„čæ›č”Œäŗŗå·„ę™ŗčƒ½åÆ¹čÆ",consentInfo1:"ä»…ä¾›äø€čˆ¬äæ”ęÆå‚č€ƒā€”ā€”äøęä¾›åŒ»ē–—ć€ę³•å¾‹ć€č“¢åŠ”ęˆ–å®‰å…Øå»ŗč®®ć€‚",consentInfo2:"ęˆ‘ä»¬ä½æē”Øä¼ščÆå­˜å‚Øå¹¶å‘é€ę‚Øēš„č¾“å…„ä»„ęä¾›å›žå¤ć€‚ęœ¬ę¬”ä¼ščÆē»“ęŸåŽęˆ‘ä»¬äøä¼šäæē•™ę‚Øēš„åÆ¹čÆęˆ–äøŖäŗŗäæ”ęÆć€‚",consentReadOur:"é˜…čÆ»ęˆ‘ä»¬ēš„",consentTermsLabel:"ę”ę¬¾",consentAnd:"和",consentPrivacyLabel:"éšē§ę”æē­–",consentMoreDetails:"äŗ†č§£ę›“å¤ščÆ¦ęƒ…ć€‚",consentInfo4:"ļ¼ˆę‚Øēš„åŒę„ä»…é€‚ē”ØäŗŽęœ¬ę¬”ä¼ščÆļ¼Œå…³é—­ę ‡ē­¾é”µęˆ–ēŖ—å£åŽå°†č¢«ęø…é™¤ļ¼‰",consentAccept:"åŒę„",consentDecline:"ę‹’ē»",consentAcceptAria:"åŒę„ā€”ā€”å¼€å§‹čŠå¤©",consentDeclineAria:"ę‹’ē»",interruptSpeaking:"ę‰“ę–­č™šę‹Ÿå½¢č±”č®²čÆ",turnOnMic:"å¼€åÆéŗ¦å…‹é£Ž",turnOffMic:"å…³é—­éŗ¦å…‹é£Ž",tapToSpeak:"ē‚¹å‡»čÆ“čÆ",startConversationReminder:"å¼€å§‹åÆ¹čÆä»„ä¾æčŠå¤©ć€‚",chatPlaceholderTitle:"å‡†å¤‡å„½čŠå¤©äŗ†å—ļ¼Ÿ",chatPlaceholderDescription:"å¼€å§‹åÆ¹čÆä»„ē»§ē»­ä½æē”Øę–‡å­—ęØ”å¼ć€‚",enterInfoOnMobile:"čÆ·åœØē”Øęˆ·äæ”ęÆé”µé¢č¾“å…„ę‚Øēš„äæ”ęÆ",waitCurrentResponse:"čÆ·ē­‰å¾…å½“å‰å›žå¤åŽå†å‘é€ę–°ę¶ˆęÆć€‚",resumeConversationFailedNewStarted:"ęˆ‘ä»¬ę— ę³•ę¢å¤ę‚Øä¹‹å‰ēš„åÆ¹čÆć€‚å·²åÆåŠØäø€äøŖę–°ēš„åÆ¹čÆć€‚",end:"ē»“ęŸ",endConversationPrompt:"ę˜Æå¦ē»“ęŸåÆ¹čÆļ¼Ÿē»“ęŸåŽå°†ę°øä¹…åˆ é™¤åŽ†å²č®°å½•ć€‚",restartConversationPrompt:"ē”®å®šč¦å¼€å§‹ę–°ēš„åÆ¹čÆå—ļ¼Ÿå½“å‰åÆ¹čÆå°†č¢«åˆ é™¤ć€‚",newConversation:"ꖰ",conversationExpiredPrompt:"ę­¤åÆ¹čÆå·²čæ‡ęœŸäø”ę— ę³•ę¢å¤ć€‚ę‚Øč¦äø‹č½½å‰Æęœ¬å¹¶ęø…é™¤ļ¼Œčæ˜ę˜Æä»…ęø…é™¤ļ¼Ÿ",conversationExpiredResumePrompt:"ę‚Øä¹‹å‰ēš„åÆ¹čÆå·²čæ‡ęœŸäø”ę— ę³•ę¢å¤ć€‚ę‚Øę˜Æå¦č¦äø‹č½½åÆ¹čÆč®°å½•ēš„å‰Æęœ¬ļ¼Ÿ",downloadAndClear:"下载并清除",downloadAndStartNew:"äø‹č½½å¹¶å¼€å§‹ę–°åÆ¹čÆ",startNew:"å¼€å§‹ę–°åÆ¹čÆ",onlyClear:"仅清除",confirm:"甮认",ok:"甮定",download:"äø‹č½½",alertGenericError:"å‘ē”Ÿé”™čÆÆć€‚",alertFailedEndConversation:"ę— ę³•ē»“ęŸåÆ¹čÆć€‚čÆ·é‡čÆ•ć€‚",alertFailedClearConversation:"ę— ę³•ęø…é™¤åÆ¹čÆć€‚",alertCouldNotStartListening:"ę— ę³•å¼€å§‹č†å¬ć€‚čÆ·é‡čÆ•ć€‚",alertSomeErrorOccurred:"å‘ē”Ÿäŗ†é”™čÆÆć€‚čÆ·é‡čÆ•ć€‚",alertWaitForAIResponse:"请等待AIå›žå¤åŽå†å¼€å§‹čÆ“čÆć€‚",alertVoiceServicesUnavailable:"ę— ę³•čæžęŽ„åˆ°čÆ­éŸ³ęœåŠ”ć€‚čÆ·ēØåŽé‡čÆ•ć€‚",alertServiceTemporarilyUnavailable:"ęœåŠ”ęš‚ę—¶äøåÆē”Øć€‚čÆ·é‡čÆ•ć€‚",alertTooManyRequests:"åŒę—¶čÆ·ę±‚čæ‡å¤šć€‚čÆ·ēØē­‰ē‰‡åˆ»åŽé‡čÆ•ć€‚",alertConnectionIssue:"ę£€ęµ‹åˆ°čæžęŽ„é—®é¢˜ć€‚čÆ·ę£€ęŸ„ę‚Øēš„ē½‘ē»œčæžęŽ„åŽé‡čÆ•ć€‚",alertResponseTimeout:"å“åŗ”č¶…ę—¶ć€‚čÆ·é‡čÆ•ć€‚",alertServiceBusy:"čÆ­éŸ³ęœåŠ”å½“å‰ē¹åæ™ć€‚čÆ·å‡ åˆ†é’ŸåŽé‡čÆ•ć€‚",alertMicrophoneStartFailed:"ę— ę³•å¼€å§‹č†å¬ć€‚čÆ·ē”®äæę‚Øēš„éŗ¦å…‹é£Žę­£åøøå·„ä½œć€‚",alertMicrophoneCheckSettings:"ę— ę³•å¼€å§‹č†å¬ć€‚čÆ·ę£€ęŸ„ę‚Øēš„éŗ¦å…‹é£Žč®¾ē½®ć€‚",alertSpeechRecognitionSetupFailed:"čÆ­éŸ³čÆ†åˆ«č®¾ē½®å¤±č“„ć€‚čÆ·åˆ·ę–°é”µé¢åŽé‡čÆ•ć€‚",alertMicrophoneAccessDenied:"éŗ¦å…‹é£Žč®æé—®č¢«ę‹’ē»ć€‚čÆ·åœØęµč§ˆå™Øč®¾ē½®äø­å…č®øéŗ¦å…‹é£Žč®æé—®å¹¶åˆ·ę–°é”µé¢ć€‚",alertNoMicrophoneDetected:"ęœŖę£€ęµ‹åˆ°éŗ¦å…‹é£Žć€‚čÆ·čæžęŽ„éŗ¦å…‹é£Žå¹¶åˆ·ę–°é”µé¢ć€‚",alertMicrophoneError:"éŗ¦å…‹é£Žé”™čÆÆć€‚čÆ·ę£€ęŸ„ę‚Øēš„éŗ¦å…‹é£Žć€‚"}};function St(t,e){const i=function(t){if(!t||"string"!=typeof t)return ft;const e=t.toLowerCase();if(yt[e])return e;const i=e.split("-")[0];return yt[i]?i:ft}(t),n=yt[i]?.[e];return void 0!==n?n:yt[ft]?.[e]??e}class kt{constructor(t,e,i){this.bus=t,this.dismissableContainer=e,this._getLanguage=i||(()=>"en"),this.dismissableAlerts=new Map,this.bus.on("event_command_Alerts_ShowDismissableAlert",(t=>{let e;e=t?.messageKey?St(this._getLanguage(),t.messageKey):t?.errorMessage||St(this._getLanguage(),"alertGenericError");const i=t?.className||"alert-danger";this.showDismissableAlert(e,i)}))}showDismissableAlert(t,e){if(this.dismissableAlerts.has(t))return;if(this.dismissableAlerts.size>=T.alerts.maxAlerts){const t=this.dismissableAlerts.keys().next().value,e=this.dismissableAlerts.get(t);e&&(e.hideToast(),this.dismissableAlerts.delete(t))}const i=y({text:t,duration:T.alerts.dismissableAlertDuration,close:!0,gravity:"top",position:"left",stopOnFocus:!0,className:`alert ${e}`,selector:this.dismissableContainer,callback:()=>{this.dismissableAlerts.delete(t)}});i.showToast(),this.dismissableAlerts.set(t,i)}}const Ct=t=>/[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/.test(t);class wt{#o=null;#r="wakeLock"in navigator;get isActive(){return!!this.#o}get isSupported(){return this.#r}async request(){const t="undefined"!=typeof process&&process.env&&"test"===process.env.NODE_ENV,e="undefined"!=typeof document&&"visible"===document.visibilityState;if(this.#r&&!this.isActive&&!t&&e)try{this.#o=await navigator.wakeLock.request("screen"),this.#o.addEventListener("release",(()=>{this.#o=null}))}catch(i){}}async release(){try{await(this.#o?.release())}finally{this.#o=null,this.#r}}}const At=m`
1
+ import{io as t}from"socket.io-client";import{AudioConfig as e,SpeechRecognizer as i,ResultReason as a,CancellationReason as n,CancellationErrorCode as s,SpeechConfig as o,PropertyId as r,AutoDetectSourceLanguageConfig as c}from"microsoft-cognitiveservices-speech-sdk";import"js-cookie";import{jwtDecode as l}from"jwt-decode";import{v4 as h}from"uuid";import{createMachine as d,assign as u,fromPromise as p,createActor as g}from"xstate";import{TalkingHead as m}from"@met4citizen/talkinghead";import{html as v,nothing as _,css as b,LitElement as f}from"lit";import y from"toastify-js";import{styleMap as S}from"lit/directives/style-map.js";const w=t=>new Promise((e=>setTimeout(e,t))),k=t=>{if(t){let e=t;return e=e.replace(/<(prosody|emphasis|say-as|phoneme|sub|voice|lang|p|s|w|audio|mark|desc)[^>]*>([\s\S]*?)<\/\1>/gi,"$2"),e=e.replace(/<(break|mark|audio)[^>]*\/?>/gi,""),e=e.replace(/<\/?[a-zA-Z][^>]*>/g,""),e.replace(/#\*[\s\S]*?\*#/g,"").trim()}return t},C=t=>(t instanceof Date?t:new Date(t)).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});function A(){return"undefined"!=typeof window&&window.VITE_APP_SOCKET_URL?window.VITE_APP_SOCKET_URL:"https://sentifyd-serve.agreeablestone-0bc8c055.swedencentral.azurecontainerapps.io"}const x=A(),T={auth:{tokenRefreshInterval:6e5,speechTokenInterval:42e4,maxLoginRetries:3,loginRetryDelay:5e3,closeToExpirationLimit:6e4,speechTokenRetries:5,serverBaseURL:A()},avatar:{type:"gltf"},constants:{HEADROLL_BLENDSHAPE_INDEX:52,LEFTEYE_BLENDSHAPE_INDEX:53,RIGHTEYE_BLENDSHAPE_INDEX:54,FRAME_RATE:60},dom:{avatarDivId:"#avatar-container",toastifyDivId:"#toastify-container",canvasWidth:400,canvasHeight:500,headerAndFooterHeight:166,controlsHeight:90,smallDisplayWidth:768,smallScreenSafetyPadding:24},renderer:{alpha:!0,antialias:!0},speech:{authorizationEndPoint:"/api/v1/chatbot/get-speech-token",maxDurationTimeout:6e5,vad:{segmentationSilenceMs:1700,initialSilenceMs:12e3,semantic:!0},bargeIn:{enabled:!0,debug:!1}},captions:{wordsPerMinute:140,maxCharactersPerCaption:40,minCharactersPerCaption:15,captionChangeDelay:200,captionTimeout:1500},alerts:{maxAlerts:3,dismissableAlertDuration:4500},chatbot:{streaming:!1,thinkingTimeout:15e3,speakingTimeout:24e4},test:{stateTestMode:!1,enableDiagnostics:!1},connection:{reconnectInitialDelay:2e3,reconnectMaxDelay:3e4,reconnectFactor:1.6}},I=async(t,e)=>{for(const i of t){const{name:t}=i;switch(t){case"RequestUserData":await E(e);break;case"EndConversation":await M(e);break;case"DisableCaptions":await D(e);break;case"EnableCaptions":await R(e);break;case"SwitchToChatMode":await P(e);break;case"SwitchToAvatarMode":await O(e);break;case"SetAvatarView":await L(e,i.view);break;case"SetAvatarMood":await B(e,i.mood);break;case"PlayOrStopAvatarGesture":await N(e,i.gesture,i.dur||3,i.mirror||!1,i.ms||1e3);break;case"PlayOrStopAvatarAnimation":await z(e,i.animation,i.dur||3);break;case"ControlAvatarLookAt":await F(e,i.target,i.t||1e3,i.x||0,i.y||0)}}},E=async t=>{t.emit("event_command_UI_RequestUserData")},M=async t=>{t.emit("event_command_UI_EndConversation")},D=async t=>{t.emit("event_command_UI_DisableCaptions")},R=async t=>{t.emit("event_command_UI_EnableCaptions")},P=async t=>{t.emit("event_command_UI_SwitchToChatMode")},O=async t=>{t.emit("event_command_UI_SwitchToAvatarMode")},L=async(t,e)=>{t.emit("event_command_Avatar_SetAvatarView",{view:e})},B=async(t,e)=>{t.emit("event_command_Avatar_SetAvatarMood",{mood:e})},N=async(t,e,i,a,n)=>{t.emit("event_command_Avatar_PlayOrStopGesture",{gesture:e,duration:i,mirror:a,ms:n})},z=async(t,e,i)=>{t.emit("event_command_Avatar_PlayOrStopAnimation",{animation:e,dur:i})},F=async(t,e,i,a,n)=>{t.emit("event_command_Avatar_ControlAvatarLookAt",{target:e,t:i,x:a,y:n})};class ${constructor(t,e=null){this.validateDependencies({auth:t}),this.socketUrl=x,this.auth=t,this.socket=null,this.isAuthenticating=!1,this.onConnectionStatusChange=e}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize WebSocketManager due to missing dependencies: ${e.join(", ")}`)}async connect(){this.socket?.connected&&this.disconnect();const e=this.auth.getAccessToken();return new Promise(((i,a)=>{this.socket=t(this.socketUrl,{auth:{token:`Bearer ${e}`},path:"/socket.io",reconnection:!0,reconnectionAttempts:5,reconnectionDelay:500,reconnectionDelayMax:1e4}),this.registerWebsocketEventHandlers(i,a)}))}isSocketConnected(){return this.socket?.connected}isInitialised(){return null!==this.socket}disconnect(){this.socket&&(this.socket.disconnect(),this.socket.removeAllListeners(),this.socket=null)}registerWebsocketEventHandlers(t,e){this.socket.removeAllListeners(),this.socket.io.on("error",(t=>{})),this.socket.io.on("reconnect",(()=>{this.onConnectionStatusChange&&this.onConnectionStatusChange("connected")})),this.socket.io.on("reconnect_attempt",(t=>{})),this.socket.io.on("reconnect_error",(t=>{})),this.socket.io.on("reconnect_failed",(()=>{this.onConnectionStatusChange&&this.onConnectionStatusChange("failed"),this.socket=null,e(new Error("Websocket connection failed after maximum retries."))})),this.socket.on("connect",(()=>{this.socket.io.engine,this.onConnectionStatusChange&&this.onConnectionStatusChange("connected"),t()})),this.socket.on("connect_error",(t=>{t.message.includes("Token expired")||t.message.includes("Invalid token")?this.reAuthenticate():(this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected"),e?.(t))})),this.socket.on("disconnect",(t=>{this.socket&&this.socket.active||this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")})),this.socket.onAny(((t,...e)=>{}))}reAuthenticate(){this.isAuthenticating||(this.isAuthenticating=!0,this.auth.authenticate().then((()=>{this.connect(),this.isAuthenticating=!1})).catch((t=>{this.isAuthenticating=!1,this.onConnectionStatusChange("failed")})))}on(t,e){this.socket&&this.socket.on(t,e)}off(t,e){this.socket&&(e?this.socket.off(t,e):this.socket.off(t))}emit(t,e,i){this.isSocketConnected()?i?this.socket.emit(t,e,i):this.socket.emit(t,e):this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")}async emitWithResponse(t,e){return new Promise(((i,a)=>{this.isSocketConnected()?this.socket.emit(t,e,(t=>{i(t)})):(this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected"),a(new Error("Socket not connected")))}))}timeoutEmit(t,e,i,a){this.isSocketConnected()?a?this.socket.timeout(i).emit(t,e,a):this.socket.timeout(i).emit(t,e):this.onConnectionStatusChange&&this.onConnectionStatusChange("disconnected")}destroy(){this.socket&&(this.socket.disconnect(),this.socket.removeAllListeners(),this.socket=null),this.isAuthenticating=!1,this.onConnectionStatusChange=null}}class V{constructor(t){if(!t||"string"!=typeof t)throw new Error("ConnectionModule requires a valid name");this.name=t,this.connectionState="disconnected",this.subscribers=[]}isConnecting(){return"connecting"===this.connectionState}isDisconnected(){return"disconnected"===this.connectionState}isReconnecting(){return"reconnecting"===this.connectionState}isConnected(){return"connected"===this.connectionState}isFailed(){return"failed"===this.connectionState}setConnected(){this.updateConnectionState("connected")}setDisconnected(){this.updateConnectionState("disconnected")}setConnecting(){this.updateConnectionState("connecting")}setReconnecting(){this.updateConnectionState("reconnecting")}setFailed(){this.updateConnectionState("failed")}updateConnectionState(t){return!!["connected","connecting","reconnecting","disconnected","failed"].includes(t)&&this.connectionState!==t&&(this.connectionState,this.connectionState=t,this.notifySubscribers(),!0)}reconnect(){}subscribe(t){return"function"==typeof t&&!this.subscribers.includes(t)&&(this.subscribers.push(t),!0)}unsubscribe(t){if("function"!=typeof t)return!1;const e=this.subscribers.length;return this.subscribers=this.subscribers.filter((e=>e!==t)),this.subscribers.length<e}notifySubscribers(){0!==this.subscribers.length&&[...this.subscribers].forEach(((t,e)=>{try{t(this.connectionState,this.name)}catch(i){}}))}destroy(){try{this.subscribers=[],this.connectionState="disconnected"}catch(t){}}getStateInfo(){return{name:this.name,state:this.connectionState,subscriberCount:this.subscribers.length}}}class U{constructor(t,e,i){this.id=t,this.state="CREATED",this.abortController=new AbortController,this.audio=(t=>{let e,i=!1;return{readable:new ReadableStream({start(a){e=a,t?.addEventListener("abort",(()=>{try{e.error(new DOMException("Aborted","AbortError"))}catch{}i=!0}))}}),push:t=>{if(!i)try{e?.enqueue(t)}catch(a){}},close:()=>{if(!i)try{e?.close(),i=!0}catch(t){}},get isClosed(){return i}}})(this.abortController.signal),this.lipsync=(t=>{let e,i=!1;return{readable:new ReadableStream({start(i){e=i,t?.addEventListener("abort",(()=>{try{e.error(new DOMException("Aborted","AbortError"))}catch{}}))}}),push:t=>{if(!i)try{e?.enqueue(t)}catch(a){}},close:()=>{if(!i)try{e?.close(),i=!0}catch(t){}},get isClosed(){return i}}})(this.abortController.signal),this._watchdog=setTimeout((()=>{this._watchdog=null,i?.(this)}),e)}activate(){this.state="ACTIVE"}finish(){if("FINISHED"!==this.state){this.state="FINISHED",clearTimeout(this._watchdog);try{this.audio.close()}catch{}try{this.lipsync.close()}catch{}this.abortController.abort("turn finished")}}abort(){"FINISHED"!==this.state&&(this.state="STOPPING",this.abortController.abort("turn interrupted"),clearTimeout(this._watchdog))}get isActive(){return"ACTIVE"===this.state}get done(){return"FINISHED"===this.state}}const H=12e4;class j extends V{static _instance=null;constructor(t,e,i,a){if(j._instance)return j._instance;super("chatSocket"),this.validateDependencies({bus:t,auth:e,sessionData:i,avatarOrchestrator:a}),this.socketManager=new $(e,(t=>this.updateConnectionState(t))),this.isChatbotShown=!0,this.chatbotMode="AVATAR",this.bus=t,this.sessionData=i,this.auth=e,this.avatarOrchestrator=a,this.pendingDelayedActions=null,this.turn=null,this.INTERRUPT_WATCHDOG=15e3,j._instance=this}static getInstance(t,e,i,a){return j._instance||(j._instance=new j(t,e,i,a)),j._instance}_isDataForCurrentTurn(){return!!this.turn&&!this.turn.done&&this.turn.id===this.sessionData.conversation.currentTurnId}static resetInstance(){j._instance&&(j._instance._cleanup(),j._instance=null)}_cleanup(){this.cleanupActiveStreams(),this.removeTTSEventHandlers(),this.socketManager?.disconnect(),this.pendingDelayedActions=null,this.turn=null,this.audioStream=null,this.lipsyncStream=null}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize ChatSocket due to missing dependencies: ${e.join(", ")}`)}async init(){if(!this.sessionData||!this.sessionData.avatarName||!this.sessionData.language)throw new Error("Missing required session data for chat connection.");this.sessionData.trainingId;try{this.setConnecting(),await this.socketManager.connect()}catch(t){this.setDisconnected()}this.registerTTSEventHandlers()}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.isFailed()?this.setReconnecting():this.setConnecting();try{if(await this.socketManager.connect(),!this.socketManager.isSocketConnected())throw new Error("Socket still not connected after connect()");this.registerTTSEventHandlers(),this.setConnected()}catch(t){this.setFailed()}}}removeTTSEventHandlers(){this.socketManager&&["conversation_ai_reply","tts_stream_start","tts_viseme","tts_word","tts_blend","tts_error","tts_chunk","tts_stream_end"].forEach((t=>{this.socketManager.off(t)}))}registerTTSEventHandlers(){this.removeTTSEventHandlers(),this.socketManager.on("conversation_ai_reply",(t=>this.handleConversationResponse(t))),this.socketManager.on("tts_stream_start",(t=>{t?.turnId,this.turn&&this.turn.id===this.sessionData.conversation.currentTurnId||this.prepareStreamsForTurn(this.sessionData.conversation.currentTurnId),this.turn.activate(),this.avatarOrchestrator&&this.avatarOrchestrator.sendEvent("STREAM_START",{audioStream:this.audioStream,lipsyncStream:this.lipsyncStream,turnId:this.turn.id})})),this.socketManager.on("tts_viseme",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed&&this.turn&&this.turn.isActive)try{this.lipsyncStream.push({type:"viseme",...t})}catch(e){if(e.message?.includes("closed readable stream"))return}})),this.socketManager.on("tts_word",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed){if(!this.turn||!this.turn.isActive||!this.lipsyncStream)return;try{this.lipsyncStream.push({type:"word",...t})}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_blend",(t=>{if(this._isDataForCurrentTurn()&&this.lipsyncStream&&!this.lipsyncStream.isClosed){if(!this.turn||!this.turn.isActive||!this.lipsyncStream)return;try{this.lipsyncStream.push({type:"blend",...t})}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_error",(t=>{this.avatarOrchestrator&&this.avatarOrchestrator.sendEvent("TTS_ERROR",{error:t})})),this.socketManager.on("tts_chunk",(t=>{if(this._isDataForCurrentTurn()&&this.audioStream&&!this.audioStream.isClosed){if(!this.turn||!this.turn.isActive||!this.audioStream)return;try{this.audioStream.push(t)}catch(e){e.message?.includes("closed readable stream")}}})),this.socketManager.on("tts_stream_end",(t=>{const e=t?.turnId;t?.reason,this.turn&&e===this.turn.id&&(this.turn.finish(),this.avatarOrchestrator.sendEvent("STREAM_END"),this.turn=null)}))}async handleConversationResponse(t){if(this.sessionData?.conversation?.conversationId)if("success"===t?.status)t?.error,await this.processAIResponse(t);else if("error"===t?.status){const e={...t.error};t.conversationId&&!e.conversationId&&(e.conversationId=t.conversationId),this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:e,chatbotMode:this.chatbotMode})}else this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:{message:"No response from server. Please try again."},chatbotMode:this.chatbotMode})}async sendInitConversationEvent(){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");return new Promise(((t,e)=>{this.socketManager.timeoutEmit("init_conversation",{avatarId:this.sessionData.avatarId,trainingId:this.sessionData.trainingId,conversationId:this.sessionData.conversation.conversationId,chatbotMode:this.chatbotMode,streaming:!1},H,((i,a)=>{i||"success"!==a?.status?e(new Error(i||a?.error?.message||"Conversation init failed")):t({initialized:!0})}))}))}async sendStartConversationEvent(t=!1){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");return new Promise(((e,i)=>{this.socketManager.timeoutEmit("start_conversation",{avatarId:this.sessionData.avatarId,trainingId:this.sessionData.trainingId,conversationId:this.sessionData.conversation.conversationId,chatbotMode:this.chatbotMode,detectedLanguage:this.sessionData.language||"en-US",voice:this.sessionData.voice||"",lipsyncType:this.sessionData.lipsyncType,turnId:this.sessionData.conversation.currentTurnId,streaming:!1,isTermsAccepted:!0===this.sessionData.isTermsAccepted,isResume:t},H,(async(t,a)=>{if(t||"success"!==a?.status){const e=a?.error?.code,n=t||a?.error?.message||"Conversation start failed";i(new Error(e?`${e}: ${n}`:n))}else try{await this.processAIResponse(a),e(a)}catch(n){i(n)}}))}))}sendEndConversationEvent(t,e){if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");this.socketManager.emit("end_conversation",{conversationId:t,satisfactionScore:e,chatbotMode:this.chatbotMode},(e=>{"success"===e?.status?this.avatarOrchestrator.sendEvent("CLEAR_CONVERSATION",{conversationId:t}):e?.status}))}prepareStreamsForTurn(t){this.turn&&!this.turn.done&&this.turn.abort(),this.turn=new U(t,this.INTERRUPT_WATCHDOG,(t=>{this.socketManager.emit("interrupt_tts",{turnId:t.id})})),this.audioStream=this.turn.audio,this.lipsyncStream=this.turn.lipsync}async processAIResponse(t){try{const e=t?.data?.actions||[],i=e.filter((t=>!1!==t.immediate)),a=e.filter((t=>!1===t.immediate)),n=i.some((t=>"SwitchToAvatarMode"===t.name));if(i.length>0&&await I(i,this.bus),a.length>0&&(this.pendingDelayedActions=a),"resume_silent"===t.data?.dataType)return;if("message"===t.data?.dataType?await this.receiveMessage(t.data,t.timestamp,{switchedToAvatar:n}):"avatar_structured_response"===t.data?.dataType?await this.receiveAvatarStructuredResponse(t.data,t.timestamp,{switchedToAvatar:n}):t?.data?.messageContent&&await this.receiveMessage(t.data,t.timestamp,{switchedToAvatar:n}),"CHAT"===this.chatbotMode&&this.pendingDelayedActions&&this.pendingDelayedActions.length>0)try{await I(this.pendingDelayedActions,this.bus)}finally{this.pendingDelayedActions=null}}catch(e){this.avatarOrchestrator.sendEvent("CONVERSATION_ERROR",{error:{message:"Error getting a response. Please try again."},chatbotMode:this.chatbotMode})}}async receiveAvatarStructuredResponse(t,e,i={}){if(!t?.structuredResponse)throw new Error("Avatar response is invalid");const a=C(e);this.avatarOrchestrator.sendEvent("AI_MESSAGE_RECEIVED",{message:t.messageContent,time:a,structuredResponse:t.structuredResponse,chatbotMode:this.chatbotMode,switchedToAvatar:i.switchedToAvatar})}async receiveMessage(t,e,i={}){if(!t?.messageContent)throw new Error("Message is invalid");const a=C(e);this.avatarOrchestrator.sendEvent("AI_MESSAGE_RECEIVED",{message:t.messageContent,time:a,chatbotMode:this.chatbotMode,switchedToAvatar:i.switchedToAvatar})}async sendMessage(t,e="CHAT"){if(this.pendingDelayedActions=null,!this.sessionData.trainingId||!t?.messageText)return{success:!1,error:"Missing required field(s)"};if(!this.sessionData.conversation.conversationId)return{success:!1,error:"No conversation found. Start a conversation first."};try{const i=this.sessionData.conversation.incrementTurnId();"AVATAR"===e?this.prepareStreamsForTurn(i):this.turn&&(this.turn.abort(),this.turn=null),this.socketManager.emit("user_chat_message",{trainingId:this.sessionData.trainingId,avatarId:this.sessionData.avatarId,userName:this.sessionData.username,conversationId:this.sessionData.conversation.conversationId,turnId:i,message:t.messageText,messageDuration:t?.messageDuration||0,chatbotMode:e,detectedLanguage:t?.detectedLanguage||this.sessionData.language,voice:this.sessionData.voice||"",lipsyncType:this.sessionData.lipsyncType,streaming:T.chatbot.streaming||!1});const a=C(new Date);return this.avatarOrchestrator.sendEvent("USER_MESSAGE_SENT",{message:t.messageText,time:a,chatbotMode:e}),this.sessionData.conversation.lastDetectedLanguage=t?.detectedLanguage,{success:!0}}catch(i){return{success:!1,error:i.message||"An error occurred while sending the message"}}}sendUserData(){const t=this.sessionData.conversation.incrementTurnId();if(this.prepareStreamsForTurn(t),this.avatarOrchestrator){const t=this.avatarOrchestrator.getSnapshot(),e=t?.matches("lifecycle.conversation.inProgress.thinking");e||this.avatarOrchestrator.sendEvent("USER_MESSAGE_SENT",{message:"[User data update]",time:C(new Date),chatbotMode:this.chatbotMode})}if(!this.socketManager.isSocketConnected())throw new Error("Socket not available.");this.socketManager.emit("update_user_data",{conversationId:this.sessionData.conversation.conversationId,turnId:t,detectedLanguage:this.sessionData.language||"en-US",voice:this.sessionData.voice||"",chatbotMode:this.chatbotMode,lipsyncType:this.sessionData.lipsyncType,userData:{username:this.sessionData.username,phoneNumber:this.sessionData.phoneNumber,email:this.sessionData.email,isTermsAccepted:this.sessionData.isTermsAccepted}},(async t=>{"success"===t?.status?this.processAIResponse(t):t?.status}))}cleanupActiveStreams(){this.turn&&this.turn.abort()}async interruptCurrentTurn(){if(!this.turn)return{status:"warning",message:"No active turn"};try{return this.turn.abort(),await this.socketManager.emitWithResponse("interrupt_tts",{turnId:this.turn.id,chatbotMode:this.chatbotMode})}catch(t){return{status:"error",message:"Interruption failed"}}}destroy(){this.socketManager?.destroy()}}class W{constructor({recognizer:t,speechConfig:e,audioConfig:i,bus:a,avatarOrchestrator:n,autoDetectLanguage:s}={}){this.validateDependencies({recognizer:t,speechConfig:e,audioConfig:i,bus:a,avatarOrchestrator:n}),this.bus=a,this.avatarOrchestrator=n,this.speechConfig=e,this.recognizer=t,this.audioConfig=i,this.messageText="",this.messageDuration=0,this.detectedLanguage="",this.isMessageSent=!1,this.isListening=!1,this.isMicDetected=!0,this.autoDetectLanguage=s,this.languageDurations={},this._isStopping=!1,this.maxDurationTimeoutId=null}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize SpeechRecognition due to missing dependencies: ${e.join(", ")}`)}static async build(t,e,i,a){if(!t)throw new Error("speechConfig is required");const{recognizer:n,audioConfig:s}=await this.init(t,e),o=new W({recognizer:n,speechConfig:t,audioConfig:s,bus:i,avatarOrchestrator:a,autoDetectLanguage:!!e});return o._registerRecognizerEvents(),o}static async init(t,a){try{const n=e.fromDefaultMicrophoneInput();let s=null;return s=a?i.FromConfig(t,a,n):new i(t,n),{recognizer:s,audioConfig:n}}catch(n){throw new Error("Error in SpeechRecognition initialization: "+n)}}static async checkMicrophoneAccess(){try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Media devices not supported");if(0===(await navigator.mediaDevices.enumerateDevices()).filter((t=>"audioinput"===t.kind)).length)throw new Error("No microphone devices found");return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach((t=>t.stop())),!0}catch(t){throw new Error(`Microphone access issue: ${t.message}`)}}start(){try{this._isStopping=!1,clearTimeout(this.maxDurationTimeoutId),this.messageText="",this.messageDuration=0,this.isMessageSent=!1,this.autoDetectLanguage&&(this.languageDurations={}),this.recognizeNewMessage(),this._setMaxDurationTimeout()}catch(t){this.stop()}}stop(){if(!this._isStopping){this._isStopping=!0;try{this.recognizer&&this.recognizer.stopContinuousRecognitionAsync()}catch(t){}finally{this.isListening=!1,this._isStopping=!1}clearTimeout(this.maxDurationTimeoutId)}}sendMessage(){if(!this.isMessageSent&&this.messageText&&this.messageText.trim())try{this.autoDetectLanguage?this.detectedLanguage=this._determineMainLanguage():this.detectedLanguage=this.speechConfig.speechRecognitionLanguage,this.avatarOrchestrator.sendEvent("SPEECH_RECOGNITION_COMPLETE",{messageText:this.messageText,messageDuration:this.messageDuration,detectedLanguage:this.detectedLanguage}),this.isMessageSent=!0}catch(t){}}simulateRecognition(){this.avatarOrchestrator.transitionToListening(),this.messageText="Hello, how are you doing today?",this.avatarOrchestrator.sendEvent("SPEECH_RECOGNITION_COMPLETE",{messageText:this.messageText,messageDuration:3e3,detectedLanguage:"en-US"})}recognizeNewMessage(){try{this._startRecognizer()}catch(t){this._emitAlert("alertMicrophoneStartFailed"),this.stop()}}_startRecognizer(){this.recognizer.startContinuousRecognitionAsync((()=>{this.avatarOrchestrator.is("listening"),this.isListening=!0}),(async t=>{await this._handleRecognitionStartupError(t),this.isMicDetected=!1,this.stop()}))}async _handleRecognitionStartupError(t){let e="alertMicrophoneCheckSettings";try{await W.checkMicrophoneAccess(),e="alertSpeechRecognitionSetupFailed"}catch(i){e=this._isBrowserPermissionError(i)?"alertMicrophoneAccessDenied":this._isBrowserDeviceError(i)?"alertNoMicrophoneDetected":"alertMicrophoneError"}this._emitAlert(e)}_isBrowserPermissionError(t){if(t&&"object"==typeof t)return"NotAllowedError"===t.name||"PermissionDeniedError"===t.name||"SecurityError"===t.name;const e=t.toString().toLowerCase();return e.includes("permission")||e.includes("notallowed")||e.includes("denied")}_isBrowserDeviceError(t){if(t&&"object"==typeof t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name;const e=t.toString().toLowerCase();return e.includes("notfound")||e.includes("device")||e.includes("microphone not found")}close(){this.stop(),this.recognizer&&(this.recognizer.close(),this.recognizer.dispose(!0),this.recognizer=void 0)}_registerRecognizerEvents(){this.recognizer.recognized=(t,e)=>{if(!this._isStopping&&this.isListening&&!this.isMessageSent&&e.result.reason===a.RecognizedSpeech&&""!==e.result.text){if(this.messageText=(this.messageText?this.messageText+" ":"")+e.result.text,this.messageDuration+=e.result.duration,this.autoDetectLanguage){const t=e.result.language,i=e.result.duration;this.languageDurations[t]?this.languageDurations[t]+=i:this.languageDurations[t]=i}this.bus.emit("event_command_UI_UpdateSTTCaption",{STTCaption:this.messageText}),this._completeRecognitionTurn()}},this.recognizer.recognizing=(t,e)=>{this._isStopping||!this.isListening||this.isMessageSent||""!==e.result.text&&this.bus.emit("event_command_UI_UpdateSTTCaption",{STTCaption:this.messageText+" "+e.result.text})},this.recognizer.speechStartDetected=(t,e)=>{},this.recognizer.speechEndDetected=(t,e)=>{this._isStopping||!this.isListening||this.isMessageSent||this.messageText?.trim()&&this._completeRecognitionTurn()},this.recognizer.canceled=(t,e)=>{e.reason===n.Error&&this._handleAzureSpeechError(e),this.stop()}}_handleAzureSpeechError(t){const e=t.errorCode,i=t.errorDetails||"No additional details available";let a="",n=!1;switch(e){case s.NoError:a="alertSomeErrorOccurred";break;case s.AuthenticationFailure:a="alertVoiceServicesUnavailable",n=!0;break;case s.BadRequestParameters:a="alertServiceTemporarilyUnavailable";break;case s.TooManyRequests:a="alertTooManyRequests";break;case s.ConnectionFailure:a="alertConnectionIssue";break;case s.ServiceTimeout:a="alertResponseTimeout";break;case s.ServiceError:a="alertServiceTemporarilyUnavailable";break;case s.RuntimeError:a="alertSomeErrorOccurred";break;case s.Forbidden:a="alertServiceBusy";break;default:a="alertSomeErrorOccurred"}n&&this.bus.emit("event_error_VoiceBot_ExpiredOrInvalidToken",i),this.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:a})}_emitAlert(t,e={}){if("string"!=typeof t||!this.bus)return;if(["alertMicrophoneStartFailed","alertMicrophoneCheckSettings","alertMicrophoneAccessDenied","alertNoMicrophoneDetected","alertMicrophoneError"].includes(t)&&this._isChatModeActive())return;const i={messageKey:t,...e};this.bus.emit("event_command_Alerts_ShowDismissableAlert",i)}_isChatModeActive(){try{const t=this.avatarOrchestrator?.getSnapshot?.(),e=t?.context?.chatSocket?.chatbotMode;return"CHAT"===e}catch(t){return!1}}_setMaxDurationTimeout(){this.maxDurationTimeoutId=setTimeout((()=>{this._completeRecognitionTurn()}),T.speech.maxDurationTimeout)}_completeRecognitionTurn(){this._isStopping||this.stop(),this.sendMessage()}_determineMainLanguage(){let t=null,e=0;for(const[i,a]of Object.entries(this.languageDurations))a>e&&(e=a,t=i);return t}destroy(){try{this.close()}catch(t){}}}class q extends V{constructor(t,e){super("speech-token"),this.auth=t,this.refreshTokenCallback=e,this.tokenRefreshLoop=null}async requestAuthorizationToken(t=T.auth.speechTokenRetries){for(let i=1;i<=t;i++)try{const t=await this.fetchSpeechToken();return this.setConnected(),t}catch(e){if(i===t)throw this.setFailed(),new Error(`Failed to fetch speech token after ${t} attempts`)}}async fetchSpeechToken(){try{const t=await this.auth.callSentifydApi(T.speech.authorizationEndPoint,"POST"),{token:e}=t.data;if(!e)throw new Error("Invalid token structure received from API.");return t.data}catch(t){throw new Error("Failed to fetch data from API.")}}async startTokenRefreshLoop(){await this.stopTokenRefreshLoop(),this.tokenRefreshLoop=setInterval((async()=>{try{const{token:t}=await this.requestAuthorizationToken();this.refreshTokenCallback(t),this.setConnected()}catch(t){this.setDisconnected()}}),T.auth.speechTokenInterval)}async stopTokenRefreshLoop(){this.tokenRefreshLoop&&(clearInterval(this.tokenRefreshLoop),this.tokenRefreshLoop=null)}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.isFailed()?this.setReconnecting():this.setConnecting(),await this.stopTokenRefreshLoop();try{const{token:t}=await this.requestAuthorizationToken();this.refreshTokenCallback(t),await this.startTokenRefreshLoop()}catch(t){this.setFailed()}}}}class G{constructor({speechService:t,speechConfig:e,autoDetectSourceLanguageConfig:i,speechRecognizer:a,bus:n,auth:s,avatarOrchestrator:o,sessionData:r}={}){this.validateDependencies({speechService:t,speechConfig:e,speechRecognizer:a,bus:n,auth:s,avatarOrchestrator:o,sessionData:r}),this.sessionData=r,this.speechService=t,this.speechConfig=e,this.speechRecognizer=a,this.bus=n,this.avatarOrchestrator=o,this.autoDetectSourceLanguageConfig=i,this._currentTurnId=0,this._expectedTurnId=0,this._lastInterruptionTime=0,this.INTERRUPTION_DEBOUNCE=100,this._isHandlingAudioEnd=!1,this.registerEventListeners(),this.speechService.startTokenRefreshLoop()}validateDependencies(t){const e=Object.entries(t).filter((([t,e])=>!e)).map((([t])=>t));if(e.length>0)throw new Error(`Cannot initialize VoiceBot due to missing dependencies: ${e.join(", ")}`)}registerEventListeners(){this._busHandlers=this._busHandlers||[];const t=t=>{this.getNewSpeechToken()};this.bus.on("event_error_VoiceBot_ExpiredOrInvalidToken",t),this._busHandlers.push(["event_error_VoiceBot_ExpiredOrInvalidToken",t])}static async build(t,e,i,a){const{speechService:n,speechConfig:s,autoDetectSourceLanguageConfig:o,speechRecognizer:r}=await this.init(a,t,i,e);return new G({speechService:n,speechConfig:s,autoDetectSourceLanguageConfig:o,speechRecognizer:r,bus:t,auth:i,avatarOrchestrator:e,sessionData:a})}static async init(t,e,i,a){try{const n=t?.language||"en-US",s=(t?.voice,t?.autodetectLanguages||[]);let l=null,h=null;const d=new q(i,(t=>{l&&(l.authorizationToken=t)})),{token:u,region:p}=await d.requestAuthorizationToken();if(!u||!p)throw new Error("Failed to get authorization token");l=o.fromAuthorizationToken(u,p);const g=T?.speech?.vad??{},m=t?.speech?.vad??t?.vad??{},v=m.segmentationSilenceMs??g.segmentationSilenceMs??800,_=m.initialSilenceMs??g.initialSilenceMs??8e3;l.setProperty(r.Speech_SegmentationSilenceTimeoutMs,String(v)),l.setProperty(r.SpeechServiceConnection_InitialSilenceTimeoutMs,String(_));const b=m.strategy??g.strategy,f=m.semantic??g.semantic,y="string"==typeof b?b:!0===f?"Semantic":null;y&&l.setProperty(r.Speech_SegmentationStrategy,y),"multilingual"===n?s.length>0?h=c.fromLanguages(s):l.speechRecognitionLanguage="en-US":l.speechRecognitionLanguage=n;const S=await W.build(l,h,e,a);return{speechService:d,speechConfig:l,autoDetectSourceLanguageConfig:h,speechRecognizer:S}}catch(n){throw new Error("Error in VoiceBot initialization",{cause:n})}}async getNewSpeechToken(){try{const{token:t}=await this.speechService.requestAuthorizationToken();this.speechConfig.authorizationToken=t}catch(t){}}isConversationInProgress(){return!!this.sessionData?.conversation?.conversationId}async startListening(){if(this.speechRecognizer.isListening)return{success:!0,alreadyListening:!0};try{return this.speechRecognizer.isMicDetected||(this.speechRecognizer.close(),this.speechRecognizer=await W.build(this.speechConfig,this.autoDetectSourceLanguageConfig,this.bus,this.avatarOrchestrator),this.speechRecognizer.isMicDetected=!0),this.speechRecognizer.start(),{success:!0,started:!0}}catch(t){return{success:!1,error:t.message||"Failed to start speech recognition"}}}stopListening(){try{return this.speechRecognizer.stop(),{success:!0}}catch(t){return{success:!1,error:t.message||"Failed to stop speech recognition"}}}async updateSpeechLanguage(t){this.speechConfig.speechRecognitionLanguage=t,this.speechRecognizer.close(),this.speechRecognizer=await W.build(this.speechConfig,this.autoDetectSourceLanguageConfig,this.bus,this.avatarOrchestrator)}destroy(){this._busHandlers?.forEach((([t,e])=>this.bus.off(t,e))),this._busHandlers=[],this.speechRecognizer?.destroy(),this.speechService?.stopTokenRefreshLoop()}}const K={enabled:!0,micThreshold:.0033,avatarQuietFloor:.009,minSignalRatio:1.2,minSignalRatioWhileSpeaking:.38,minSignalDelta:.0028,absoluteMicOverride:.012,minDurationMs:200,cooldownMs:1500,envelopeAttack:.6,envelopeRelease:.8,leakAdaptRate:.06,leakFloor:0,leakCeil:.25,leakMargin:.012,leakDecayHoldMs:300,leakDecayRate:.2,leakMinAvatar:.01,noiseStdK:3.4,minSnr:3.2,noiseMinSamples:90,warmupMs:400,speakingGuardMs:200,minConsecutive:3,hangoverMs:100,minAbsQuiet:.0032,bandpassHz:[350,3400],minDurationWhileSpeakingMs:260,debug:!1};class J{constructor({talkingAvatar:t,avatarOrchestrator:e,config:i}={}){this.talkingAvatar=t,this.avatarOrchestrator=e,this.config={...K,...i||{}},this._audioCtx=null,this._micStream=null,this._micSource=null,this._micBpf=null,this._micAnalyser=null,this._micBuffer=null,this._avatarAnalyser=null,this._avatarBuffer=null,this._avatarAnalyserMissing=!1,this._armed=!1,this._candidateSince=null,this._lastTriggerTime=0,this._rafId=null,this._projectionUnsub=null,this._isDestroyed=!1,this._lastTickLog=0,this._micEnvelope=0,this._avatarEnvelope=0,this._leakEstimate=this.config.leakFloor??0,this._lastAvatarBelowMin=null,this._lastFrameTs=0,this._lastAudioResumeAttempt=0,this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._resetNoiseStats()}async init(){if(this.config.enabled)try{await this._ensureMicAnalyser(),this._subscribeToState()}catch(t){this._teardown()}}destroy(){this._isDestroyed=!0,this._unsubscribe(),this._disarm(),this._teardown()}async _ensureMicAnalyser(){if(this._micAnalyser)return;if("undefined"==typeof navigator||!navigator.mediaDevices?.getUserMedia)throw new Error("Media devices API not available");this._audioCtx=this._audioCtx||new(window.AudioContext||window.webkitAudioContext);const t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1}});this._micStream=t,this._micSource=this._audioCtx.createMediaStreamSource(t),this._micBpf=this._audioCtx.createBiquadFilter(),this._micBpf.type="bandpass";const[e,i]=Array.isArray(this.config.bandpassHz)&&2===this.config.bandpassHz.length?this.config.bandpassHz:[300,3e3],a=Math.max(10,Math.min(e,i||e)),n=Math.max(1.5*a,i||10*a),s=Math.sqrt(a*n);this._micBpf.frequency.value=Number.isFinite(s)?s:1e3;const o=Math.log2(n/a),r=Math.sinh(Math.log(2)/2*Math.max(o,.01)),c=r>0?1/(2*r):1;this._micBpf.Q.value=Math.max(.5,Math.min(4,c||1)),this._micAnalyser=this._audioCtx.createAnalyser(),this._micAnalyser.fftSize=512,this._micAnalyser.smoothingTimeConstant=.4,this._micSource.connect(this._micBpf).connect(this._micAnalyser),this._micBuffer=new Float32Array(this._micAnalyser.fftSize),this._debugEvent("mic-ready",{sampleRate:this._audioCtx.sampleRate,fftSize:this._micAnalyser.fftSize})}_subscribeToState(){this.avatarOrchestrator?.subscribeProjected&&(this._projectionUnsub=this.avatarOrchestrator.subscribeProjected((t=>{if(this._isDestroyed)return;const e=t?.lifecycle?.conversationSubstate;"speaking"===e?this._arm():this._disarm()})))}_unsubscribe(){if("function"==typeof this._projectionUnsub){try{this._projectionUnsub()}catch(t){}this._projectionUnsub=null}}_arm(){if(!this._micAnalyser)return;if(!this._avatarAnalyser&&!this._avatarAnalyserMissing){if(this._avatarAnalyser=this.talkingAvatar?.getSpeechAnalyzerNode?.()??null,!this._avatarAnalyser)return this._debugEvent("avatar-analyser-missing",{}),this._avatarAnalyserMissing=!0,void(this._armed=!1);this._avatarAnalyser.smoothingTimeConstant=Math.min(this._avatarAnalyser.smoothingTimeConstant??.4,.6),this._avatarBuffer=new Float32Array(this._avatarAnalyser.fftSize),this._debugEvent("avatar-analyser-ready",{fftSize:this._avatarAnalyser.fftSize})}if(this._armed)return;this._armed=!0,this._candidateSince=null,this._micEnvelope=0,this._avatarEnvelope=0,this._resetNoiseStats(),this._lastFrameTs=0,this._leakEstimate=Math.max(this.config.leakFloor??0,Math.min(this._leakEstimate,this.config.leakCeil??1));const t="undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now();this._armedAt=t,this._consecHits=0,this._lastQualifyTs=0,this._lastAvatarBelowMin=null,this._rafId||(this._rafId=requestAnimationFrame(this._monitorLoop)),this._debugEvent("armed",{micThreshold:this.config.micThreshold,avatarQuietFloor:this.config.avatarQuietFloor,minSignalRatio:this.config.minSignalRatio,minSignalRatioWhileSpeaking:this.config.minSignalRatioWhileSpeaking,minSignalDelta:this.config.minSignalDelta,absoluteMicOverride:this.config.absoluteMicOverride,minDurationMs:this.config.minDurationMs,cooldownMs:this.config.cooldownMs,warmupMs:this.config.warmupMs,speakingGuardMs:this.config.speakingGuardMs,minConsecutive:this.config.minConsecutive,hangoverMs:this.config.hangoverMs,bandpassHz:this.config.bandpassHz})}_disarm(){(this._armed||this._rafId)&&(this._armed=!1,this._candidateSince=null,this._micEnvelope=0,this._avatarEnvelope=0,this._resetNoiseStats(),this._lastFrameTs=0,this._leakEstimate=Math.max(this.config.leakFloor??0,Math.min(this._leakEstimate,this.config.leakCeil??1)),this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._lastAvatarBelowMin=null,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null),this._debugEvent("disarmed",{}))}_monitorLoop=()=>{if(this._isDestroyed)return;if(!this._armed)return void(this._rafId=null);const t=performance.now(),e=this._lastFrameTs?t-this._lastFrameTs:16.7;this._lastFrameTs=t,"suspended"===this._audioCtx?.state&&(0===this._lastAudioResumeAttempt||t-this._lastAudioResumeAttempt>=1e3)&&(this._lastAudioResumeAttempt=t,this._audioCtx.resume().catch((()=>{})));const i=this._clamp01(this._readRms(this._micAnalyser,this._micBuffer)),a=this._avatarAnalyser?this._readRms(this._avatarAnalyser,this._avatarBuffer):0,n=this._clamp01(a),s=this._updateEnvelope("_micEnvelope",i,e),o=this._updateEnvelope("_avatarEnvelope",n,e),r=this._updateLeakEstimate({micSignal:s,avatarSignal:o,candidateActive:!!this._candidateSince}),c=o>(this.config.leakMinAvatar??.01)?.85*(r+(this.config.leakMargin??.012)):0,l=Math.max(0,s-o*c),h=o>5e-4?l/Math.max(o,5e-4):1/0,d=l-o,u=o<=this.config.avatarQuietFloor,p=l>=this.config.micThreshold,g=s>=this.config.absoluteMicOverride,m=t-(this._armedAt||t),v=m<(this.config.warmupMs??400),_=!u&&m<(this.config.speakingGuardMs??250);!g&&!this._candidateSince&&u&&!v&&0===this._consecHits&&l<1.2*this.config.micThreshold&&this._updateNoiseStats(l);const b=this._noiseCount>=(this.config.noiseMinSamples??90),f=this._noiseMean,y=this._getNoiseStd(),S=b?(l+1e-7)/(f+1e-7):0,w=this.config.noiseStdK??3.2,k=b&&l>=f+w*y,C=b&&S>=(this.config.minSnr??3),A=!!u||g||h>=(this.config.minSignalRatioWhileSpeaking??this.config.minSignalRatio)||d>=this.config.minSignalDelta,x=this.config.minAbsQuiet??0,T=!u||l>=x,I=u?T&&(g||(b?k||C:p)):g||p,E=!v&&!_,M=E&&I&&A,D=this.config.minConsecutive??4;if(M)this._consecHits+=1,this._lastQualifyTs=t;else{const e=this.config.hangoverMs??120,i=t-this._lastQualifyTs<=e;this._consecHits=i?this._consecHits:0}this._debugTick({micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:l,leak:r,leakApply:c,noiseMean:f,noiseStd:y,noiseSamples:this._noiseCount,snr:S,exceedsNoise:k,snrDominates:C,ratio:h,delta:d,meetsMicThreshold:p,avatarQuiet:u,absoluteOverride:g,absQuietOK:T,energyOK:I,energyQualified:I,competitionOK:A,noiseReady:b,warmup:v,speakingGuard:_,frameAllowed:E,frameQualifies:M,qualifies:M,consecutiveHits:this._consecHits,requiredHits:D,candidateDuration:this._candidateSince?t-this._candidateSince:0,cooldownRemaining:Math.max(0,this.config.cooldownMs-(t-this._lastTriggerTime))}),this._consecHits>=D?this._candidateSince||(this._candidateSince=t,this._debugEvent("candidate-start",{micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:l,leak:r,noiseMean:f,noiseStd:y,snr:S,ratio:h,delta:d})):this._candidateSince&&!M&&t-this._lastQualifyTs>(this.config.hangoverMs??120)&&(this._debugEvent("candidate-reset",{micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:l,leak:r,noiseMean:f,noiseStd:y,snr:S,ratio:h,delta:d}),this._candidateSince=null,this._consecHits=0);const R=u?this.config.minDurationMs??200:this.config.minDurationWhileSpeakingMs??(this.config.minDurationMs??200)+60,P=this._candidateSince&&t-this._candidateSince>=R,O=t-this._lastTriggerTime>=this.config.cooldownMs;P&&O?this._emitBargeIn({micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:l,leak:r,noiseMean:f,noiseStd:y,snr:S,ratio:h,delta:d,timestamp:t}):P&&!O&&this._debugEvent("cooldown-block",{micLevel:i,avatarLevel:n,micSignal:s,avatarSignal:o,effectiveMic:l,leak:r,noiseMean:f,noiseStd:y,snr:S,ratio:h,delta:d,cooldownRemaining:Math.max(0,this.config.cooldownMs-(t-this._lastTriggerTime))}),this._rafId=requestAnimationFrame(this._monitorLoop)};_emitBargeIn({micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:a,effectiveMic:n,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:l,delta:h,timestamp:d}){this._lastTriggerTime=d,this._candidateSince=null,this._consecHits=0,this._lastQualifyTs=0,this._debugEvent("trigger",{micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:a,effectiveMic:n,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:l,delta:h,timestamp:d});try{this.avatarOrchestrator?.sendEvent?.("VOICE_BARGE_IN",{micLevel:t,avatarLevel:e,micSignal:i,avatarSignal:a,effectiveMic:n,leak:s,noiseMean:o,noiseStd:r,snr:c,ratio:l,delta:h,timestamp:d})}catch(u){}}_readRms(t,e){if(!t)return 0;try{t.getFloatTimeDomainData(e)}catch(a){return 0}let i=0;for(let n=0;n<e.length;n++){const t=e[n];i+=t*t}return Math.sqrt(i/e.length)}_teardown(){if(this._micStream&&(this._micStream.getTracks().forEach((t=>{try{t.stop()}catch(e){}})),this._micStream=null),this._micSource){try{this._micSource.disconnect()}catch(t){}this._micSource=null}if(this._micBpf){try{this._micBpf.disconnect()}catch(t){}this._micBpf=null}if(this._micAnalyser){try{this._micAnalyser.disconnect()}catch(t){}this._micAnalyser=null}if(this._audioCtx){try{this._audioCtx.close()}catch(t){}this._audioCtx=null}this._micBuffer=null,this._avatarAnalyser=null,this._avatarBuffer=null,this._avatarAnalyserMissing=!1,this._lastTickLog=0,this._micEnvelope=0,this._avatarEnvelope=0,this._leakEstimate=this.config.leakFloor??0,this._lastAvatarBelowMin=null,this._armedAt=0,this._consecHits=0,this._lastQualifyTs=0,this._resetNoiseStats(),this._lastFrameTs=0,this._lastAudioResumeAttempt=0}_debugTick(t){if(!this.config.debug)return;const e=performance.now?performance.now():Date.now();e-this._lastTickLog<150||(this._lastTickLog=e)}_debugEvent(t,e){this.config.debug}_updateEnvelope(t,e,i=16.7){const a="number"==typeof this[t]?this[t]:e,n=Math.min(Math.max(this.config.envelopeAttack,0),.999),s=Math.min(Math.max(this.config.envelopeRelease,0),.999),o=e>=a?n:s,r=Math.max(i/16.7,.1),c=a+(e-a)*(1-Math.pow(o,r)),l=this._clamp01(c);return this[t]=l,l}_updateLeakEstimate({micSignal:t,avatarSignal:e,candidateActive:i}){const a=this.config.leakMinAvatar??0,n=this.config.leakAdaptRate??.1,s=this.config.leakFloor??0,o=this.config.leakCeil??1,r="undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now();let c=this._leakEstimate??s;if(i||this._consecHits>0)return c;const l=this._noiseCount>=(this.config.noiseMinSamples??90),h=this._getNoiseStd(),d=this._noiseMean,u=l&&t>=d+(this.config.noiseStdK??3.2)*h;if(e>a&&t<.8*this.config.absoluteMicOverride&&!u){const i=t/Math.max(e,1e-5);c+=(Math.max(s,Math.min(i,o))-c)*n,this._leakEstimate=c,this._debugLeakUpdate({ratio:i,estimate:c}),this._lastAvatarBelowMin=null}else if(e<=a&&c>s){const t=this.config.leakDecayHoldMs??1e3,i=this.config.leakDecayRate??.1*n;null==this._lastAvatarBelowMin&&(this._lastAvatarBelowMin=r),e<=a?r-this._lastAvatarBelowMin>=t&&(c+=(s-c)*i):this._lastAvatarBelowMin=r,this._leakEstimate=Math.max(s,c)}return this._leakEstimate??s}_debugLeakUpdate({ratio:t,estimate:e}){this.config.debug&&this._debugEvent("leak-update",{ratio:t,estimate:e})}_resetNoiseStats(){this._noiseMean=0,this._noiseVar=0,this._noiseCount=0}_updateNoiseStats(t){const e=this._clamp01(t);if(!Number.isFinite(e))return;this._noiseCount>=500&&(this._noiseCount=Math.floor(350),this._noiseMean*=.95,this._noiseVar*=.9),this._noiseCount+=1;const i=e-this._noiseMean;this._noiseMean+=i/this._noiseCount;const a=e-this._noiseMean;this._noiseVar+=i*a}_getNoiseStd(){return this._noiseCount<2?0:Math.sqrt(Math.max(this._noiseVar/(this._noiseCount-1),0))}_clamp01(t){return Number.isFinite(t)?t<=0?0:t>=1?1:t:0}}let Q=null;const Y={setInstance(t){Q=t},getItem:async t=>{if(!Q)throw new Error("Storage instance not initialized");return Q.getItem(t)},setItem:async(t,e)=>{if(!Q)throw new Error("Storage instance not initialized");return Q.setItem(t,e)},removeItem:async t=>{if(!Q)throw new Error("Storage instance not initialized");return Q.removeItem(t)}};class Z extends Error{constructor(t,{statusCode:e=null,reason:i=null}={}){super(t),this.name="LoginError",this.statusCode=e,this.reason=i}}async function X(t){try{const e=await fetch(`${t.serverBaseURL}/api/v1/chatbot/login`,{method:"POST",headers:{"Content-Type":"application/json","X-Sentifyd-Origin":t.targetApp},body:JSON.stringify({avatar_api_key:t.getAvatarAPIKey()})});if(!e.ok){const i=function(t){switch(t){case 404:return{message:"Avatar not found.",reason:"avatar-not-found",shouldStopRetrying:!0};case 401:return{message:"Unauthorized avatar login attempt.",reason:"unauthorized",shouldStopRetrying:!1};case 429:return{message:"Too many login attempts. Please retry later.",reason:"rate-limited",shouldStopRetrying:!1};default:return{message:`Login failed with status code ${t}.`,reason:"login-failed",shouldStopRetrying:!1}}}(e.status);throw i.shouldStopRetrying&&(t.retries=T.auth.maxLoginRetries),new Z(i.message,{statusCode:e.status,reason:i.reason})}const i=await e.json();await async function(t,e){try{const i=e?.data?.avatar_params;if(!i||!i.avatarId)throw new Error("Invalid avatar parameters received in login response.");const a=i.avatarId;t.id=a;const n={accessToken:e.data.access_token,refreshToken:e.data.refresh_token,avatarParameters:i};await t.updateAuthData(n),t.setConnected()}catch(i){throw new Error(`Failed to process login response: ${i.message}`)}}(t,i)}catch(e){throw e}}const tt=new class{constructor(t=1){this.max=t,this._fns=[],this._active=0}get remaining(){return this._fns.length}get active(){return this._active}take(t){this._fns.push(t),this._try()}_done(){this._active-=1,this._try()}_try(){if(this._active===this.max||0===this._fns.length)return;const t=this._fns.shift();this._active+=1,t&&t(this._done.bind(this))}}(1);class et{constructor({serverBaseURL:t,getRefreshToken:e,updateAccessToken:i,onSuccess:a,onError:n}){this.serverBaseURL=t,this.getRefreshToken=e,this.onSuccess=a,this.onError=n,this.tokenRefreshIntervalId=null,this.updateAccessToken=i}startTokenRefreshInterval(){this.tokenRefreshIntervalId&&clearInterval(this.tokenRefreshIntervalId),this.tokenRefreshIntervalId=setInterval((async()=>{try{await this.refreshAccessToken()}catch(t){}}),T.auth.tokenRefreshInterval)}stopTokenRefreshInterval(){this.tokenRefreshIntervalId&&(clearInterval(this.tokenRefreshIntervalId),this.tokenRefreshIntervalId=null)}async refreshAccessToken(){return new Promise(((t,e)=>{tt.take((async i=>{try{const e=this.getRefreshToken();if(!e)throw new Error("No refresh token available");const i=await fetch(`${this.serverBaseURL}/api/v1/chatbot/token_exchange`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e}});if(!i.ok){const t=`Failed to refresh JWT token (Status: ${i.status} ${i.statusText})`;throw"function"==typeof this.onError&&this.onError(new Error(t)),new Error(t)}const a=await i.json();if(!a?.data?.access_token)throw new Error("Invalid token data received during refresh.");this.updateAccessToken&&await this.updateAccessToken(a.data.access_token),"function"==typeof this.onSuccess&&this.onSuccess(a.data.access_token),t(!0)}catch(a){"function"==typeof this.onError&&this.onError(a),e(a)}finally{i()}}))}))}}class it extends V{#t;#e;#i;constructor(t="",e="",i=""){if(it._instance)return it._instance;super("authentication"),it._instance=this,this.#t=t,this.tokenEndpoint=e,this.#e=null,this.#i=null,this.avatarParameters=null,this.id=i,this.serverBaseURL=T.auth.serverBaseURL||"",this.targetApp="",this.lastFailureDetails=null,this.tokenRefresher=new et({serverBaseURL:this.serverBaseURL,getRefreshToken:()=>this.#i,updateAccessToken:async t=>await this.updateAuthData({accessToken:t}),onSuccess:()=>{},onError:t=>{this.handleAuthenticationFailure("Error refreshing access token",t)}})}async init(t="web",e="",i="",a=""){this.id=a,this.targetApp=t,this.#t=e,this.tokenEndpoint=i;try{await this.authenticate();try{await this.updateAvatarParametersFromServer()}catch(n){}return this.startTokenRefreshInterval(),!0}catch(s){return this.handleAuthenticationFailure(`Error during authentication initialization: ${s.message}`,s),!1}}async authenticate(){for(this.retries=0,this.setConnecting();this.retries<T.auth.maxLoginRetries;)try{if(this.#t?.trim())await X(this);else{if(!this.tokenEndpoint?.trim()){const t="authenticate: No API key or token endpoint provided for authentication.";throw this.handleAuthenticationFailure(t),new Error(t)}await this.requestDataFromServer()}return void this.clearFailureDetails()}catch(t){if(this.setDisconnected(),this.recordFailure({message:`authenticate: Attempt #${this.retries+1} failed`,reason:t instanceof Z?t.reason:t?.message||null,statusCode:t instanceof Z&&"number"==typeof t.statusCode?t.statusCode:null}),this.retries++,this.retries>=T.auth.maxLoginRetries){const e=`authenticate: All ${T.auth.maxLoginRetries} authentication attempts failed.`;if(this.handleAuthenticationFailure(e,t),t instanceof Error)throw t;throw new Error(`${e} Last error: ${t}`)}await w(T.auth.loginRetryDelay)}}startTokenRefreshInterval(){this.tokenRefresher.startTokenRefreshInterval()}stopTokenRefreshInterval(){this.tokenRefresher.stopTokenRefreshInterval()}isTokenCloseToExpiration(){if(!this.#e)return!0;try{const{exp:t}=l(this.#e);if(!t)return!0;if(1e3*t-Date.now()<=T.auth.closeToExpirationLimit)return!0}catch(t){return!0}return!1}async callSentifydApi(t,e="POST",i=null){if(!this.isConnected())throw new Error("Cannot call the API without active authentication");const a=`${this.serverBaseURL}${t}`,n=new Headers({"Content-Type":"application/json"}),s=this.getAccessToken();if(!s)throw new Error("Cannot call the API without an access token");n.append("Authorization",`Bearer ${s}`);const o={method:e,headers:n,body:i?JSON.stringify(i):void 0};try{let t=await fetch(a,o);if(401===t.status)try{await this.authenticate();const e={...o,headers:{...o.headers,Authorization:`Bearer ${this.getAccessToken()}`}};if(t=await fetch(a,e),401===t.status)throw this.handleAuthenticationFailure("callSentifydApi: Authentication failed in API call. Not authorized."),new Error(`API call failed: ${t.statusText} (Status: ${t.status})`)}catch(r){throw this.handleAuthenticationFailure("callSentifydApi: Authentication failed in API call. Not authorized."),new Error("API call failed")}if(!t.ok)throw new Error(`API call failed: ${t.statusText} (Status: ${t.status})`);return await t.json()}catch(r){throw r}}async isAuthRequired(){const t=this.#a();return!(t&&t.accessToken&&t.refreshToken&&t.avatarParameters&&!this.isTokenCloseToExpiration())}async logout(){this.id&&await async function(t){if(t)try{await Y.removeItem(`authData_${t}`)}catch(e){}}(this.id),this.stopTokenRefreshInterval(),this.#e=null,this.#i=null,this.avatarParameters=null,this.clearFailureDetails(),this.setDisconnected()}async#n(){if(!this.id)return!1;const t=await async function(t){if(!t)return null;try{const e=await Y.getItem(`authData_${t}`);return e?JSON.parse(e):null}catch(e){return null}}(this.id);if(!t)return!1;try{return this.#e=t.accessToken,this.#i=t.refreshToken,this.avatarParameters=t.avatarParameters,!(await this.isAuthRequired())||(this.setDisconnected(),!1)}catch(e){return this.setDisconnected(),!1}}#a(){return this.id&&this.#e&&this.#i&&this.avatarParameters?{accessToken:this.#e,refreshToken:this.#i,avatarParameters:this.avatarParameters}:null}getAccessToken(){return this.#e||null}getRefreshToken(){return this.#i||null}getAvatarAPIKey(){return this.#t}async updateAccessToken(t){await this.updateAuthData({accessToken:t})}getAvatarParameters(){return this.avatarParameters||null}async updateAuthData({accessToken:t,refreshToken:e,avatarParameters:i}){const a=this.#a()||{};t&&(this.#e=t,a.accessToken=t),e&&(this.#i=e,a.refreshToken=e),i&&(this.avatarParameters=i,a.avatarParameters=i);try{await async function(t,e){if(t)try{await Y.setItem(`authData_${t}`,JSON.stringify(e))}catch(i){}}(this.id,a),this.clearFailureDetails()}catch(n){}}async requestDataFromServer(){if(!this.tokenEndpoint?.trim())throw new Error("requestDataFromServer: Token URL is not specified.");try{const t=await fetch(this.tokenEndpoint,{method:"GET"});if(!t.ok)throw new Error(`requestDataFromServer: Failed to request tokens (Status: ${t.status} ${t.statusText})`);const e=await t.json();if(!this.#s(e))throw new Error("requestDataFromServer: Invalid token response received from server.");await this.updateAuthData({accessToken:e.tokens.accessToken,refreshToken:e.tokens.refreshToken,avatarParameters:e.avatarParameters}),this.setConnected()}catch(t){throw this.setDisconnected(),t}}#s(t){return t?.tokens?.accessToken&&t?.tokens?.refreshToken&&t?.avatarParameters}async updateAvatarParametersFromServer(){try{const t=await this.callSentifydApi("/api/v1/chatbot/get-avatar-params","POST");if(!t||!t.data||!t.data.avatar_params)return;this.avatarParameters=t.data.avatar_params,this.updateAuthData({avatarParameters:this.avatarParameters})}catch(t){}}handleAuthenticationFailure(t,e=null){this.recordFailure({message:t,reason:e instanceof Z?e.reason:e instanceof Error?e.message:null,statusCode:e instanceof Z&&"number"==typeof e.statusCode?e.statusCode:null}),this.setFailed()}recordFailure({message:t,reason:e=null,statusCode:i=null}={}){this.lastFailureDetails={message:t||"Unknown authentication error",reason:e??(t||"Unknown authentication error"),statusCode:i,timestamp:Date.now()}}clearFailureDetails(){this.lastFailureDetails=null}getLastFailureDetails(){return this.lastFailureDetails?{...this.lastFailureDetails}:null}async reconnect(){if(!this.isConnected()&&!this.isReconnecting()){this.stopTokenRefreshInterval(),this.isFailed()?this.setReconnecting():this.setConnecting();try{if(await this.authenticate(),this.isConnected()){try{await this.updateAvatarParametersFromServer()}catch(t){}this.startTokenRefreshInterval()}else this.setFailed()}catch(e){this.handleAuthenticationFailure("Authentication reconnect failed",e)}}}static resetInstance(){it._instance=null}}class at{constructor(t,e=h){this.avatarId=t,this.conversationData={id:void 0,transcript:[],currentTurnId:0},this.lastDetectedLanguage=null,this.uuidGenerator=e,this.lastStartWasResumeAttempt=!1,this.transcriptLengthBeforeResume=0}get conversationId(){return this.conversationData.id}set conversationId(t){this.conversationData.id=t}get transcript(){return this.conversationData.transcript}set transcript(t){this.conversationData.transcript=t}get currentTurnId(){return this.conversationData.currentTurnId}set currentTurnId(t){this.conversationData.currentTurnId=t}incrementTurnId(){return this.conversationData.currentTurnId++,this.conversationData.currentTurnId}async getConversationData(){if(!this.avatarId)return null;const t=await Y.getItem(`conversationData_${this.avatarId}`),e={id:void 0,transcript:[],currentTurnId:0};return this.conversationData=t?{...e,...JSON.parse(t)}:e,this.conversationData}async saveConversationData(){this.avatarId&&await Y.setItem(`conversationData_${this.avatarId}`,JSON.stringify(this.conversationData))}async notifyConversationInit(){await this.getConversationData(),this.conversationId||(await this.clearOngoingConversation(),await this.generateNewConversationId())}async notifyConversationStart(t=!1){if(t)this.lastStartWasResumeAttempt=!1,this.transcriptLengthBeforeResume=0,await this.clearOngoingConversation(),await this.generateNewConversationId(),this.incrementTurnId();else{await this.getConversationData();const t=!!this.conversationId,e=Array.isArray(this.transcript)&&this.transcript.length>0;this.lastStartWasResumeAttempt=t&&e,this.transcriptLengthBeforeResume=e?this.transcript.length:0,this.conversationId||(await this.clearOngoingConversation(),await this.generateNewConversationId()),this.incrementTurnId()}}async notifyConversationEnd(){this.lastStartWasResumeAttempt=!1,await this.clearOngoingConversation()}async clearOngoingConversation(){this.conversationData={id:void 0,transcript:[],currentTurnId:0};try{await Y.removeItem(`conversationData_${this.avatarId}`)}catch(t){await this.saveConversationData()}}async discardConversationHistory(){const t=this.conversationId,e=this.currentTurnId;this.conversationData={id:t,transcript:[],currentTurnId:e},await this.saveConversationData()}async generateNewConversationId(){const t=this.uuidGenerator();this.conversationId=t,await this.saveConversationData()}async appendMessage(t,e,i){if(!this.conversationId)return null;const a={speaker:i,messageText:k(t),time:e};return this.transcript.push(a),await this.saveConversationData(),a}async handleConversationSuccessfulStart(t){const e=t?.isInProgress,i=t?.conversationId,a=this.conversationId,n=!!this.lastStartWasResumeAttempt;let s=!1;if(!1===e&&(s=!0),i&&a&&i!==a&&(this.conversationId=i,s=!0),n&&s){const t=this.transcript.slice(this.transcriptLengthBeforeResume);this.conversationData.transcript=t,await this.saveConversationData()}return{serverStartedNew:s,resumeAttempt:n,resumeFailed:s&&n}}}class nt{constructor(){if(nt._instance)return nt._instance;this._avatarId=null,this._avatarName="",this._avatarItem=null,this._trainingId=null,this._language="",this._autodetectLanguages=[],this._voice="",this._lipsyncType="words",this._wordsPerMinute=150,this._userData={username:"",phoneNumber:"",email:"",isTermsAccepted:!1},this.conversation=null,nt._instance=this,Object.seal(this)}static getInstance(){return nt._instance||(nt._instance=new nt),nt._instance}static hasInstance(){return null!==nt._instance&&void 0!==nt._instance}static resetInstance(){if(nt._instance)try{return nt._instance.destroy(),nt._instance=null,!0}catch(t){return!1}return!0}async init(t,e){const{avatarId:i,avatarName:a,trainingId:n,language:s,autodetectLanguages:o,voice:r,wordsPerMinute:c}=t;if(![i,a,e,s,r].every((t=>null!=t&&""!==t))||!Array.isArray(o))return!1;this._trainingId=null===n||""===n?null:n,this._avatarId=i,this._avatarName=a,this._avatarItem=e,this._language=s,this._autodetectLanguages=o,this._voice=r,this._lipsyncType=e?.lipsyncType||"words",this._wordsPerMinute=c||150;try{return this.conversation=new at(this._avatarId),!0}catch(l){return!1}}get isUserDataDefined(){return this._userData.username&&!0===this._userData.isTermsAccepted}get avatarId(){return this._avatarId}set avatarId(t){this._avatarId=t,this.conversation&&(this.conversation.avatarId=t)}get avatarName(){return this._avatarName}set avatarName(t){"string"==typeof t&&""!==t.trim()&&(this._avatarName=t)}get avatarItem(){return this._avatarItem}set avatarItem(t){t&&"object"==typeof t&&(this._avatarItem=t)}get trainingId(){return this._trainingId}set trainingId(t){(null==t||"string"==typeof t&&""!==t.trim())&&(this._trainingId=t)}get language(){return this._language}set language(t){"string"==typeof t&&""!==t.trim()&&(this._language=t)}get autodetectLanguages(){return this._autodetectLanguages}set autodetectLanguages(t){Array.isArray(t)&&(this._autodetectLanguages=t)}get voice(){return this._voice}set voice(t){"string"==typeof t&&""!==t.trim()&&(this._voice=t)}get lipsyncType(){return this._lipsyncType}set lipsyncType(t){["words","visemes","blendshapes"].includes(t)&&(this._lipsyncType=t)}get wordsPerMinute(){return this._wordsPerMinute}set wordsPerMinute(t){"number"!=typeof t||t<=0||(this._wordsPerMinute=t)}get username(){return this._userData.username}set username(t){"string"==typeof t&&""!==t.trim()&&(this._userData.username=t)}get phoneNumber(){return this._userData.phoneNumber}set phoneNumber(t){"string"==typeof t&&""!==t.trim()&&(this._userData.phoneNumber=t)}get email(){return this._userData.email}set email(t){"string"==typeof t&&""!==t.trim()&&(this._userData.email=t)}get isTermsAccepted(){return this._userData.isTermsAccepted}set isTermsAccepted(t){"boolean"==typeof t&&(this._userData.isTermsAccepted=t)}destroy(){try{this.conversation&&"function"==typeof this.conversation.destroy&&this.conversation.destroy()}catch(t){}}}function st(t){try{t?.talkingAvatar?.liveCaptions?.clearCaptions?.()}catch(e){}try{t?.bus?.emit?.("event_command_UI_ClearCaptions")}catch(e){}}nt._instance=null;const ot=d({id:"avatarOrchestrator",context:({input:t})=>({bus:t?.bus??null,talkingAvatar:t?.talkingAvatar??null,chatSocket:t?.chatSocket??null,voiceBot:t?.voiceBot??null,conversation:t?.conversation??null,eventPayload:null,isPageVisible:!0,currentPage:"LoaderPage",pendingStart:null,userSilenced:!1,initFailed:!1,firstConnectionCompleted:!1}),type:"parallel",states:{lifecycle:{initial:"init",states:{init:{initial:"initializing",states:{initializing:{id:"initializing",on:{READY:{target:"complete",actions:["onLeaveInitializing"]},FAIL:{target:"failed",actions:u({initFailed:!0})}}},failed:{id:"failed",on:{RETRY:{target:"initializing"},CONNECT:{target:"initializing"}}},complete:{always:{target:"#avatarOrchestrator.lifecycle.conversation.stopped"}}}},checkingResume:{id:"checkingResume",invoke:{id:"checkResumeOnStart",src:"checkResumeActor",input:({context:t})=>({conversation:t.conversation,bus:t.bus}),onDone:[{target:"conversation.autoResuming",guard:({event:t})=>!!t.output?.resumable},{target:"conversation.stopped"}],onError:{target:"conversation.stopped"}}},conversation:{initial:"stopped",on:{CONVERSATION_TIMEOUT:{target:".timedOut"}},states:{stopped:{id:"stopped",on:{START_CONVERSATION:[{guard:({context:t})=>!t.isPageVisible,actions:"onDeferStart",target:void 0},{target:"inProgress.startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}],INIT_CONVERSATION:{target:"initializingConversation"},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},RESTORED_CONNECTION:{target:"#checkingResume"},AVATAR_INITIALIZED:{target:"#checkingResume"},CONVERSATION_INIT_SUCCESS:{actions:["onConversationInitSuccess"]},CONVERSATION_INIT_FAILED:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})},CONVERSATION_TIMEOUT:{target:"#avatarOrchestrator.lifecycle.conversation.timedOut"},DISCONNECT:{actions:[]},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},timedOut:{id:"timedOut",entry:[({context:t,event:e})=>{try{const i=e?.payload?.conversationId??t?.conversation?.conversationId;t.bus?.emit?.("event_status_Conversation_TimedOut",{conversationId:i})}catch(i){}}],on:{START_CONVERSATION:[{guard:({context:t})=>!t.isPageVisible,actions:"onDeferStart",target:void 0},{target:"inProgress.startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}],INIT_CONVERSATION:{target:"initializingConversation"},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},RESTORED_CONNECTION:{target:"#checkingResume"},AVATAR_INITIALIZED:{target:"#checkingResume"},CONVERSATION_INIT_SUCCESS:{actions:["onConversationInitSuccess"]},CONVERSATION_INIT_FAILED:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},autoResuming:{id:"autoResuming",tags:["thinking","inputs_blocked"],entry:["onStartingConversation"],invoke:{id:"autoResumeService",src:"startConversationService",input:({context:t})=>({isNew:!1,skipFallback:!0,bus:t.bus,conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar}),onDone:[{guard:({event:t})=>"resume_silent"===t.output?.data?.dataType,target:"inProgress.idle",actions:"onConversationStartSuccess"},{target:"inProgress.thinking",actions:"onConversationStartSuccess"}],onError:{target:"resumeExpired",actions:["onAutoResumeFailed"]}},on:{AI_MESSAGE_RECEIVED:{actions:"handleAiMessage"},AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"inProgress.pendingAudioStart",actions:["onStreamStart"]},IDLE:"inProgress.idle"}},resumeExpired:{id:"resumeExpired",entry:[({context:t})=>{try{const e=t?.conversation?.conversationId;t.bus?.emit?.("event_status_Conversation_ResumeExpired",{conversationId:e})}catch(e){}}],on:{START_NEW_CONVERSATION:{target:"inProgress.startingConversation",actions:u({eventPayload:{fresh:!0}})},DISMISS:{target:"stopped",actions:[({context:t})=>{try{t.conversation?.clearOngoingConversation?.()}catch(e){}}]},CLEAR_CONVERSATION:{target:"clearingConversation"},END_CONVERSATION:{target:"endingConversation"},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},paused:{id:"paused",entry:["onConversationPaused"],tags:["conversation_paused","inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]},RECONNECT:[{target:"inProgress.idle",guard:"hasActiveConversation"},{target:"clearingConversation"}],RESTORED_CONNECTION:[{target:"inProgress.idle",guard:"hasActiveConversation"},{target:"clearingConversation"}],END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},initializingConversation:{id:"initializingConversation",invoke:{id:"initConversationActor",src:"initConversationActor",input:({context:t})=>({conversation:t.conversation,chatSocket:t.chatSocket,bus:t.bus}),onDone:{target:"stopped",actions:"onConversationInitSuccess"},onError:{target:"stopped",actions:[u({initFailed:!0}),"onConversationInitFailed"]}},on:{FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}}},inProgress:{id:"inProgress",tags:["conversation_in_progress"],on:{STOP:{target:"stopped",actions:["onStop"]},END_CONVERSATION:{target:"endingConversation"},CLEAR_CONVERSATION:{target:"clearingConversation"},DISCONNECT:[{target:"paused",guard:"hasActiveConversation"},{target:"stopped"}],AUDIO_START:{target:"#speaking",actions:["onAudioStarted"]},AI_MESSAGE_RECEIVED:{actions:"handleAiMessage"},FAIL:{target:"#avatarOrchestrator.lifecycle.init.failed",actions:u({initFailed:!0})}},initial:"idle",states:{idle:{id:"idle",entry:["onIdle"],on:{STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},LISTEN:"listening",THINK:"thinking",START_CONVERSATION:{target:"startingConversation",actions:u({eventPayload:({event:t})=>t.payload})},SEND_TEXT_MESSAGE:{target:"processingTextMessage"},MIC_BUTTON:[{guard:"isRequestBlocked",actions:["onMicButtonBlocked"]},{target:"listening",actions:["onMicButtonStartListening"]}],AUDIO_END:{actions:["onAudioEnd"]}}},listening:{id:"listening",tags:["listening"],entry:["onListenEntry"],invoke:{id:"listenActor",src:"listenActor",input:({context:t})=>({voiceBot:t.voiceBot,bus:t.bus}),onError:{target:"idle",actions:["onListenFailed"]}},on:{STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},THINK:"thinking",START_CONVERSATION:{target:"startingConversation",actions:["onIdle",u({eventPayload:({event:t})=>t.payload})]},SPEECH_RECOGNITION_COMPLETE:{target:"processingSpeechRecognition"},SEND_TEXT_MESSAGE:{target:"processingTextMessage",actions:[({context:t})=>{if(t.voiceBot){t.voiceBot.stopListening();try{t.talkingAvatar?.liveCaptions?.clearCaptions?.()}catch(e){}try{t.bus.emit("event_command_UI_ClearCaptions")}catch(e){}}}]},MIC_BUTTON:{target:"idle",actions:["setUserSilencedTrue","onMicButtonStopListening"]},IDLE:"idle",AUDIO_END:{actions:["onAudioEnd"]}}},processingSpeechRecognition:{id:"processingSpeechRecognition",invoke:{id:"speechRecognitionActor",src:"speechRecognitionActor",input:({context:t,event:e})=>({chatSocket:t.chatSocket,payload:e.payload,conversation:t.conversation,bus:t.bus}),onDone:{target:"thinking"},onError:{target:"idle",actions:["onSpeechRecognitionFailed"]}},on:{AUDIO_END:{actions:["onAudioEnd"]}}},processingTextMessage:{id:"processingTextMessage",invoke:{id:"sendTextMessageActor",src:"sendTextMessageActor",input:({context:t,event:e})=>({chatSocket:t.chatSocket,payload:e.payload,conversation:t.conversation,bus:t.bus}),onDone:{target:"thinking"},onError:{target:"idle",actions:["onSendTextMessageFailed"]}},on:{AUDIO_END:{actions:["onAudioEnd"]}}},thinking:{id:"thinking",tags:["thinking","inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},IDLE:"idle",START_CONVERSATION:{target:"startingConversation",actions:u({eventPayload:({event:t})=>t.payload})}}},startingConversation:{id:"startingConversation",tags:["thinking","inputs_blocked"],entry:["onStartingConversation"],invoke:{id:"startConversationService",src:"startConversationService",input:({context:t})=>({isNew:t.eventPayload?.fresh||!1,bus:t.bus,conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar}),onDone:[{guard:({event:t})=>"resume_silent"===t.output?.data?.dataType,target:"idle",actions:"onConversationStartSuccess"},{target:"thinking",actions:"onConversationStartSuccess"}],onError:{target:"#avatarOrchestrator.lifecycle.conversation.stopped",actions:[u({initFailed:!0}),"onConversationStartFailed"]}},on:{AI_MESSAGE_RECEIVED:{actions:"handleAiMessage"},AUDIO_END:{actions:["onAudioEnd"]},STREAM_START:{target:"pendingAudioStart",actions:["onStreamStart"]},IDLE:"idle"}},pendingAudioStart:{id:"pendingAudioStart",tags:["thinking","inputs_blocked"],after:{speechStartTimeout:{guard:"isPendingAudioStart",target:"#speaking",actions:["onAudioStartedFallback"]}},on:{SEND_TEXT_MESSAGE:{target:"#inProgress.processingTextMessage",actions:["onInterruptSpeaking"]},MIC_BUTTON:{target:"#inProgress.listening",actions:["onInterruptSpeaking","onMicButtonInterruptSpeaking"]},INTERRUPT:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},VOICE_BARGE_IN:{target:"#inProgress.listening",actions:["emitVoiceBargeInEvent","onVoiceBargeIn","onInterruptSpeaking"]},AUDIO_END:[{target:"#inProgress.listening",guard:({context:t})=>!!t.isPageVisible&&!!t.voiceBot&&t.voiceBot.isConversationInProgress?.(),actions:["onAudioEnd"]},{target:"#inProgress.idle",actions:["onAudioEnd"]}],IDLE:{target:"#inProgress.idle"},LISTEN:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},START_CONVERSATION:{target:"#inProgress.interruptingForRestart",actions:["onInterruptSpeaking",u({eventPayload:({event:t})=>t.payload})]}}},speaking:{id:"speaking",tags:["speaking"],on:{SEND_TEXT_MESSAGE:{target:"#inProgress.processingTextMessage",actions:["onInterruptSpeaking"]},MIC_BUTTON:{target:"#inProgress.listening",actions:["onInterruptSpeaking","onMicButtonInterruptSpeaking"]},INTERRUPT:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},VOICE_BARGE_IN:{target:"#inProgress.listening",actions:["emitVoiceBargeInEvent","onVoiceBargeIn","onInterruptSpeaking"]},STREAM_END:{actions:["onStreamEnd"],internal:!0},AUDIO_END:[{target:"#inProgress.listening",guard:({context:t})=>!!t.isPageVisible&&!!t.voiceBot&&t.voiceBot.isConversationInProgress?.(),actions:["onAudioEnd"]},{target:"#inProgress.idle",actions:["onAudioEnd"]}],IDLE:{target:"#inProgress.idle"},LISTEN:{target:"#inProgress.listening",actions:["onInterruptSpeaking"]},START_CONVERSATION:{target:"#inProgress.interruptingForRestart",actions:["onInterruptSpeaking",u({eventPayload:({event:t})=>t.payload})]}}},interruptingForRestart:{id:"interruptingForRestart",entry:["onEnsureCleanupComplete"],invoke:{src:"cleanupInterruptionActor",input:({context:t})=>({talkingAvatar:t.talkingAvatar,chatSocket:t.chatSocket,voiceBot:t.voiceBot}),onDone:{target:"startingConversation"},onError:{target:"#avatarOrchestrator.lifecycle.conversation.stopped"}},tags:["inputs_blocked"],on:{AUDIO_END:{actions:["onAudioEnd"]}}}}},endingConversation:{id:"endingConversation",tags:["inputs_blocked"],invoke:{id:"endConversationActor",src:"endConversationActor",input:({context:t,event:e})=>({conversation:t.conversation,chatSocket:t.chatSocket,talkingAvatar:t.talkingAvatar,voiceBot:t.voiceBot,payload:e?.payload}),onDone:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_UI_ClearConversation")}catch(e){}}]},onError:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertFailedEndConversation"})}catch(e){}}]}}},clearingConversation:{id:"clearingConversation",tags:["inputs_blocked"],invoke:{id:"clearConversationActor",src:"clearConversationActor",input:({context:t,event:e})=>({conversation:t.conversation,talkingAvatar:t.talkingAvatar,payload:e?.payload}),onDone:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_UI_ClearConversation")}catch(e){}}]},onError:{target:"stopped",actions:[({context:t})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertFailedClearConversation"})}catch(e){}}]}}}}}}},connection:{initial:"connected",states:{connected:{id:"connected",on:{DISCONNECT:"disconnected"}},disconnected:{id:"disconnected",on:{RECONNECT:{target:"connected",actions:["onLeaveDisconnected",u({firstConnectionCompleted:()=>!0})]},CONNECT:{target:"connected",actions:["onLeaveDisconnected",u({firstConnectionCompleted:()=>!0})]}}}}}},on:{INJECT_MODULES:{actions:[u((({context:t,event:e})=>({talkingAvatar:e.payload?.talkingAvatar??t.talkingAvatar,chatSocket:e.payload?.chatSocket??t.chatSocket,voiceBot:e.payload?.voiceBot??t.voiceBot,conversation:e.payload?.conversation??t.conversation}))),({context:t,self:e})=>{try{const i=e.getSnapshot?.();(i?.matches?.("lifecycle.conversation.stopped")||i?.matches?.("lifecycle.conversation.timedOut"))&&t.conversation&&e.send({type:"AVATAR_INITIALIZED"})}catch(i){}}]},PAGE_CHANGED:{actions:["onPageChanged","setCurrentPage"]},DEFER_START:{actions:["onDeferStart"]},VISIBILITY_CHANGED:{actions:["onVisibilityChanged"]},UI_CHATBOT_MODE:{actions:["onUiChatbotMode"]},CONVERSATION_ERROR:{actions:["onConversationError"]},TTS_ERROR:{actions:["onTtsError"]},INTERRUPT:{actions:[({context:t})=>{try{t.talkingAvatar?.interruptSpeaking?.()}catch{}try{t.chatSocket?.interruptCurrentTurn?.()}catch{}try{t.voiceBot?.stopListening?.()}catch{}try{t.bus?.emit?.("event_command_UI_ClearCaptions")}catch{}}]}}},{actions:{onPageChanged:({context:t,event:e,self:i})=>{try{const n=e?.payload?.newPage;if(!n)return;const s=i.getSnapshot?.(),o=!!s?.hasTag?.("speaking")||s?.matches?.("lifecycle.conversation.inProgress.speaking")||s?.matches?.("lifecycle.conversation.inProgress.pendingAudioStart"),r=!!s?.hasTag?.("listening")||s?.matches?.("lifecycle.conversation.inProgress.listening");if("AvatarPage"!==n&&(o||r)&&(o?i.send({type:"INTERRUPT"}):r&&i.send({type:"IDLE"})),"AvatarPage"===n)try{const e="AVATAR"===t.chatSocket?.chatbotMode,i=!1!==t.chatSocket?.isChatbotShown;e&&i&&t.isPageVisible&&(t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.())}catch(a){}}catch(n){}},setCurrentPage:u((({event:t})=>{const e=t?.payload?.newPage;return e?{currentPage:e}:{}})),onDeferStart:u((({context:t,event:e})=>{if(!t.isPageVisible){const i=e.payload?.fresh??!1;return null!==t.pendingStart&&t.pendingStart,{pendingStart:i}}return null!==t.pendingStart?{pendingStart:null}:{}})),onVisibilityChanged:u((({context:t,event:e,self:i})=>{const a=e&&(e.payload?.isVisible??e.isVisible),n=void 0===a?!!t.isPageVisible:!!a,s=n&&!t.isPageVisible;if(!n&&t.isPageVisible){if(t.voiceBot&&(st(t),t.voiceBot.stopListening?.()),t.talkingAvatar){t.talkingAvatar.interruptSpeaking?.();try{t.talkingAvatar.suspendRendering?.("visibility")}catch(o){}}i.send({type:"IDLE"})}else{if(s&&null!==t.pendingStart){const e=t.pendingStart;return i.send({type:"START_CONVERSATION",payload:{fresh:e}}),{isPageVisible:n,pendingStart:null}}s&&t.voiceBot&&i.getSnapshot().matches("lifecycle.conversation.inProgress.idle")&&i.send({type:"LISTEN"})}try{if(n&&"AvatarPage"===t.currentPage){const e="AVATAR"===t.chatSocket?.chatbotMode,i=!1!==t.chatSocket?.isChatbotShown;e&&i&&(t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.())}}catch(o){}return{isPageVisible:n}})),onListenEntry:({context:t})=>{t.voiceBot&&st(t)},onListenFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertCouldNotStartListening"})}catch(i){}},onIdle:({context:t})=>{t.voiceBot&&(st(t),t.voiceBot.stopListening().success)},onStop:({context:t})=>{t.voiceBot&&(st(t),t.voiceBot.stopListening())},onAudioStarted:({context:t,event:e})=>{const i=e?.payload?.audioStartTime??("undefined"!=typeof performance?performance.now():Date.now());try{t.bus?.emit?.("event_command_UI_PlayCaptions",{audioStartTime:i})}catch(a){}},onAudioStartedFallback:({context:t})=>{const e="undefined"!=typeof performance?performance.now():Date.now();try{t.bus?.emit?.("event_command_UI_PlayCaptions",{audioStartTime:e})}catch(i){}},onStreamStart:({context:t,event:e})=>{const{audioStream:i,lipsyncStream:a,turnId:n}=e.payload||{};t.voiceBot&&void 0!==n&&(t.voiceBot._currentTurnId=n,t.voiceBot._expectedTurnId=n),t.talkingAvatar&&i&&a&&t.talkingAvatar.startStreaming(i,a,n)},onInterruptSpeaking:({context:t,self:e})=>{if(t.voiceBot){const i=Date.now();if(i-t.voiceBot._lastInterruptionTime<t.voiceBot.INTERRUPTION_DEBOUNCE)return;const a=-1!==t.voiceBot._expectedTurnId,n=t.voiceBot._isHandlingAudioEnd,s=e.getSnapshot(),o=s?.hasTag?.("speaking")||s?.matches?.("lifecycle.conversation.inProgress.speaking")||s?.matches?.("lifecycle.conversation.inProgress.pendingAudioStart");a&&o&&!n&&(t.voiceBot._expectedTurnId=-1,t.voiceBot._lastInterruptionTime=i),st(t),t.voiceBot.stopListening().success}t.talkingAvatar&&t.talkingAvatar.interruptSpeaking(),t.chatSocket&&t.chatSocket.interruptCurrentTurn()},onEnsureCleanupComplete:({context:t,self:e})=>{},onSpeechRecognitionFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertCouldNotStartListening"})}catch(i){}},onSendTextMessageFailed:({context:t,event:e})=>{try{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertSomeErrorOccurred"})}catch(i){}},onUiChatbotMode:({context:t,event:e,self:i})=>{const a=e.payload;if(!a||void 0===a.isShown&&!a.chatbotMode)return;const n=a.chatbotMode;if(t.chatSocket&&(void 0!==n&&(t.chatSocket.chatbotMode=n),void 0!==a.isShown&&(t.chatSocket.isChatbotShown=a.isShown)),"CHAT"===n){const e=i.getSnapshot();if(e.matches("lifecycle.conversation.inProgress.speaking")||e.matches("lifecycle.conversation.inProgress.pendingAudioStart")){try{t.talkingAvatar?.interruptSpeaking()}catch(s){}try{t.chatSocket?.interruptCurrentTurn?.()}catch(s){}t.voiceBot&&(st(t),t.voiceBot.stopListening?.(),t.voiceBot._expectedTurnId=-1),i.send({type:"IDLE"})}else e.matches("lifecycle.conversation.inProgress.listening")&&(t.voiceBot&&(st(t),t.voiceBot.stopListening?.()),i.send({type:"IDLE"}));try{t.talkingAvatar?.suspendRendering?.("chat")}catch(s){}}else if("AVATAR"===n)try{const e=i.getSnapshot(),a=e.matches?.("lifecycle.conversation.inProgress"),n=e.matches?.("lifecycle.conversation.inProgress.idle"),s=!!t.isPageVisible;a&&n&&s&&i.send({type:"LISTEN"})}catch(s){}if(!1===a.isShown)try{const e=i.getSnapshot();if(e.matches?.("lifecycle.conversation.inProgress.speaking")||e.matches?.("lifecycle.conversation.inProgress.pendingAudioStart")){try{t.talkingAvatar?.interruptSpeaking?.()}catch(s){}try{t.chatSocket?.interruptCurrentTurn?.()}catch(s){}t.voiceBot&&(st(t),t.voiceBot.stopListening?.(),t.voiceBot._expectedTurnId=-1),i.send({type:"IDLE"})}else e.matches?.("lifecycle.conversation.inProgress.listening")&&(t.voiceBot&&(st(t),t.voiceBot.stopListening?.()),i.send({type:"IDLE"}));try{t.talkingAvatar?.suspendRendering?.("ui-hidden")}catch(s){}}catch(s){}else if(!0===a.isShown)try{const e=i.getSnapshot(),a=e.matches?.("lifecycle.conversation.inProgress"),s=e.matches?.("lifecycle.conversation.inProgress.idle"),o=!!t.isPageVisible;"AVATAR"===(void 0!==n?n:t.chatSocket?.chatbotMode)&&a&&s&&o&&i.send({type:"LISTEN"})}catch(s){}try{const e=void 0!==n?n:t.chatSocket?.chatbotMode,i=void 0!==a.isShown?a.isShown:!1!==t.chatSocket?.isChatbotShown;if("AVATAR"===e&&i&&t.isPageVisible&&"AvatarPage"===t.currentPage)t.talkingAvatar?.isRenderingActive?.()||t.talkingAvatar?.resumeRendering?.();else if(t.talkingAvatar?.isRenderingActive?.()&&("CHAT"===e||!i||!t.isPageVisible||"AvatarPage"!==t.currentPage))try{t.talkingAvatar?.suspendRendering?.("conditions-change")}catch(s){}}catch(s){}},onLeaveDisconnected:({self:t})=>t.send({type:"RESTORED_CONNECTION"}),onLeaveInitializing:({self:t})=>t.send({type:"AVATAR_INITIALIZED"}),onStartingConversation:({context:t,event:e})=>{t.voiceBot&&(st(t),t.voiceBot.stopListening(),t.voiceBot._expectedTurnId=-1),t.talkingAvatar&&t.talkingAvatar.interruptSpeaking()},onConversationStartSuccess:({context:t,event:e})=>{},onConversationStartFailed:({context:t,event:e})=>{},onAutoResumeFailed:({context:t,event:e})=>{},onConversationInitFailed:({context:t,event:e})=>{},onConversationInitSuccess:({context:t,event:e})=>{},handleAiMessage:({context:t,event:e,self:i})=>{const{message:a,time:n,structuredResponse:s}=e.payload||{};if("string"==typeof a&&""!==a.trim())try{t.bus.emit("event_command_UI_UpdateCurrentMessage",{speaker:"assistant",messageText:k(a)})}catch(l){}const o=s?.avatar_mood??e.payload?.structuredResponse?.avatar_mood;if(o)try{t.bus.emit("event_command_Avatar_SetAvatarMood",{mood:o})}catch(l){}t.conversation&&a&&Promise.resolve().then((async()=>{try{const i=n||(new Date).toLocaleTimeString(),s=await t.conversation.appendMessage(a,i,"assistant");try{t.bus.emit("event_status_Conversation_MessageAppended",s)}catch(e){}}catch(l){}}));const r="AVATAR"===t.chatSocket?.chatbotMode,c=e.payload?.switchedToAvatar;r&&!c||setTimeout((()=>{try{const t=i.getSnapshot?.();(t?.matches?.("lifecycle.conversation.inProgress.thinking")||t?.matches?.("lifecycle.conversation.inProgress.startingConversation")||t?.matches?.("lifecycle.conversation.autoResuming"))&&i?.send?.({type:"IDLE"})}catch(t){}}),0)},onAudioEnd:({context:t,event:e})=>{const{turnId:i}=e.payload||{};if(st(t),t.voiceBot){if(-1===t.voiceBot._expectedTurnId||i!==t.voiceBot._expectedTurnId)return;t.voiceBot._expectedTurnId=-1,t.voiceBot._isHandlingAudioEnd=!0}t.chatSocket?.pendingDelayedActions?.length>0&&(I(t.chatSocket.pendingDelayedActions,t.bus),t.chatSocket.pendingDelayedActions=null),t.voiceBot&&setTimeout((()=>{t.voiceBot._isHandlingAudioEnd=!1}),50)},onStreamEnd:({context:t})=>{try{t.talkingAvatar?.finalizeTurn?.()}catch(e){}if(t.chatSocket?.pendingDelayedActions?.length>0){try{I(t.chatSocket.pendingDelayedActions,t.bus)}catch(e){}t.chatSocket.pendingDelayedActions=null}},onMicButtonBlocked:({context:t})=>{t.bus.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertWaitForAIResponse"})},onMicButtonStartListening:u((()=>({userSilenced:!1}))),setUserSilencedTrue:u((()=>({userSilenced:!0}))),onMicButtonStopListening:({context:t})=>{},onMicButtonInterruptSpeaking:u((()=>({userSilenced:!1}))),emitVoiceBargeInEvent:({context:t,event:e})=>{const i=e?.payload||{};try{t.bus?.emit?.("event_status_Speech_BargeInTriggered",{micLevel:i.micLevel,avatarLevel:i.avatarLevel,ratio:i.ratio,delta:i.delta,timestamp:i.timestamp})}catch(a){}},onVoiceBargeIn:u((()=>({userSilenced:!1}))),onAssistantMessage:({context:t,event:e})=>{try{t.bus.emit("event_command_UI_AutoScrollChat",{message:e?.payload?.message||e?.message})}catch(i){}},onConversationError:({context:t,event:e,self:i})=>{const{error:a,chatbotMode:n}=e.payload||{};if(!a)return;if((908===a.code||404===a.code||408===a.code)&&void 0!==a.conversationId)return void i.send({type:"CONVERSATION_TIMEOUT",payload:{conversationId:a.conversationId}});const s=a.message?{errorMessage:a.message}:{messageKey:"alertSomeErrorOccurred"};t.bus.emit("event_command_Alerts_ShowDismissableAlert",s);const o=i.getSnapshot();o.matches("lifecycle.conversation.inProgress.thinking")&&i.send({type:"IDLE"}),"AVATAR"===n&&o.matches("lifecycle.conversation.inProgress.idle")&&i.send({type:"LISTEN"})},onTtsError:({context:t,self:e})=>{t.chatSocket?.cleanupActiveStreams();const i=e.getSnapshot();i.matches("lifecycle.conversation.inProgress.speaking")||i.matches("lifecycle.conversation.inProgress.pendingAudioStart")?(t.talkingAvatar?.interruptSpeaking&&t.talkingAvatar.interruptSpeaking(),e.send({type:"IDLE"})):e.send({type:"IDLE"})},onConversationPaused:({context:t})=>{t.voiceBot&&(st(t),t.voiceBot.stopListening()),t.talkingAvatar&&t.talkingAvatar.interruptSpeaking()}},guards:{isRequestBlocked:({self:t})=>{try{const e=t.getSnapshot?.();return!!e?.hasTag?.("thinking")}catch(e){return!1}},isAvatarMode:({context:t})=>{try{return"AVATAR"===t?.chatSocket?.chatbotMode}catch(e){return!1}},hasActiveConversation:({context:t})=>{if(!t.conversation)return!1;try{const e=!!t.conversation.conversationId,i=(t.conversation.conversationData?.currentTurnId||0)>0,a=Array.isArray(t.conversation.conversationData?.transcript)&&t.conversation.conversationData.transcript.length>0;return e&&(i||a)}catch(e){return!1}},isPendingAudioStart:({self:t})=>{try{return t.getSnapshot?.().matches?.("lifecycle.conversation.inProgress.pendingAudioStart")}catch(e){return!1}}},actors:{startConversationService:p((async({input:t})=>{const{isNew:e,skipFallback:i,bus:a,conversation:n,chatSocket:s,talkingAvatar:o}=t||{};if(!n||!s)throw new Error("Conversation or ChatSocket module not available");if(await Promise.resolve(),o?.conversationStreamActive)try{await(o.stopConversationStream?.())}catch(h){}e&&n.conversationId&&await n.notifyConversationEnd(),await n.notifyConversationStart(e),o&&await o.startConversationStream();const r=!e;let c;try{c=await s.sendStartConversationEvent(r)}catch(d){const t=d?.message?.includes("404")||d?.message?.includes("408");if(r&&t&&!i){try{await n.clearOngoingConversation()}catch(h){}await n.notifyConversationStart(!0),c=await s.sendStartConversationEvent(!1);try{a?.emit?.("event_status_Conversation_ResumeFailedAndRestarted",{conversationId:n.conversationId})}catch(h){}return c}throw d}const l=await(n.handleConversationSuccessfulStart?.(c))||{};if(l.resumeFailed)try{a?.emit?.("event_status_Conversation_ResumeFailedAndRestarted",{conversationId:n.conversationId})}catch(h){}else if(l.resumeAttempt&&!l.serverStartedNew)try{a?.emit?.("event_status_Conversation_ResumedSuccessfully",{conversationId:n.conversationId})}catch(h){}return c})),initConversationActor:p((async({input:t})=>{const{conversation:e,chatSocket:i}=t||{};if(!e)throw new Error("Conversation module not available");return await e.notifyConversationInit(),i&&await i.sendInitConversationEvent(),{initialized:!0}})),listenActor:p((async({input:t})=>{const{voiceBot:e}=t||{};if(!e)return{started:!1};const i=await e.startListening();if(!i.success)throw new Error(i.error||"Failed to start listening");return{started:!0}})),speechRecognitionActor:p((async({input:t})=>{const{chatSocket:e,payload:i,conversation:a,bus:n}=t||{};if(!e||!a)throw new Error("Dependencies not available");if(!i||!i.messageText)throw new Error("Invalid speech payload");const s=await a.appendMessage(i.messageText,C(new Date),"user");try{n?.emit("event_status_Conversation_MessageAppended",s)}catch(r){}const o=await e.sendMessage(i,"AVATAR");if(!o.success)throw n?.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertSomeErrorOccurred"}),new Error(o.error||"Failed to process speech input");return{sent:!0}})),sendTextMessageActor:p((async({input:t})=>{const{chatSocket:e,payload:i,conversation:a,bus:n}=t||{};if(!e||!a)throw new Error("Dependencies not available");if(!i||!i.message)throw new Error("Invalid text payload");const s=await a.appendMessage(i.message,C(new Date),"user");try{n?.emit("event_status_Conversation_MessageAppended",s)}catch(l){}const o={messageText:i.message},r=i.chatbotMode||"CHAT",c=await e.sendMessage(o,r);if(!c.success)throw n?.emit("event_command_Alerts_ShowDismissableAlert",{messageKey:"alertSomeErrorOccurred"}),new Error(c.error||"Failed to send text message");return{sent:!0}})),endConversationActor:p((async({input:t})=>{const{conversation:e,chatSocket:i,talkingAvatar:a,voiceBot:n,payload:s}=t||{};if(!e)return!0;const o=e.conversationId,{satisfactionScore:r=0}=s||{};if(await e.notifyConversationEnd(),i&&o)try{i.sendEndConversationEvent(o,r)}catch(c){}try{a?.interruptSpeaking?.()}catch(c){}try{await(a?.stopConversationStream?.())}catch(c){}try{a?.liveCaptions?.clearCaptions?.(),n?.stopListening?.()}catch(c){}return!0})),clearConversationActor:p((async({input:t})=>{const{conversation:e,talkingAvatar:i,payload:a}=t||{};if(!e)return!0;const{conversationId:n}=a||{};if(n===e.conversationId){await e.clearOngoingConversation();try{await(i?.stopConversationStream?.())}catch(s){}}return!0})),checkResumeActor:p((async({input:t})=>{const{conversation:e,bus:i}=t||{};if(!e)return{resumable:!1};try{const t=await(e.getConversationData?.());if(t?.id&&Array.isArray(t.transcript)&&t.transcript.length>0)return{resumable:!0}}catch(a){throw a}return{resumable:!1}})),cleanupInterruptionActor:p((async({input:t})=>{const{talkingAvatar:e,chatSocket:i,voiceBot:a}=t||{};try{try{e?.liveCaptions?.clearCaptions?.()}catch(n){}if(a)try{a.stopListening?.()}catch(n){}try{e?.interruptSpeaking?.()}catch(n){}try{i?.interruptCurrentTurn?.()}catch(n){}return await new Promise((t=>setTimeout(t,10))),!0}catch(s){throw s}}))},delays:{thinkingTimeout:T?.chatbot?.thinkingTimeout,speechStartTimeout:Math.min(Math.max(T?.chatbot?.speechStartTimeout??8e3,2e3),6e4)}});class rt{constructor(t){if(!t)throw new Error("Cannot initialize AvatarOrchestrator: missing bus instance");this.bus=t,this.actor=null,this._pendingEvents=[],this._deferredModules=null,this.diagnostics=null}start(t={}){if(this._deferredModules&&(t={...t,...this._deferredModules},this._deferredModules=null),this.actor)t&&Object.keys(t).length>0&&this.injectModules(t);else if(this.actor=g(ot,{input:{bus:this.bus,...t}}).start(),this.actor.subscribe((t=>{this.handleStateTransition(t)})),this._pendingEvents.length>0){for(const t of this._pendingEvents)this.actor.send(t);this._pendingEvents.length=0}}handleStateTransition(t){t&&this.diagnostics&&t?.changed&&(this.diagnostics.logStateTransition(t.history?.value,t.value),t.matches?.("lifecycle.conversation.stopped")&&this.diagnostics.displayDiagnosticsInConsole())}sendEvent(t,e=null){const i={type:t,payload:e};this.actor?this.actor.send(i):this._pendingEvents.push(i)}is(t){return!!this.actor&&this.actor.getSnapshot().matches(t)}getCurrentState(){return this.actor?.getSnapshot().value}getSnapshot(){return this.actor?this.actor.getSnapshot():null}destroy(){this.actor?.stop(),this.actor=null,this.diagnostics=null,this._pendingEvents=[]}interruptSpeaking(){this.sendEvent("INTERRUPT")}transitionToListening(){this.sendEvent("LISTEN")}transitionToIdle(){this.sendEvent("IDLE")}injectModules(t={}){this.actor?this.actor.send({type:"INJECT_MODULES",payload:t}):this._deferredModules={...this._deferredModules||{},...t}}subscribeProjected(t){if(!this.actor)return()=>{};let e={};const i=this.actor.subscribe((i=>{const a={lifecycle:{initInitializing:i.matches?.("lifecycle.init.initializing")||!1,initFailed:i.matches?.("lifecycle.init.failed")||!1,convoStopped:i.matches?.("lifecycle.conversation.stopped")||!1,convoAutoResuming:i.matches?.("lifecycle.conversation.autoResuming")||!1,convoResumeExpired:i.matches?.("lifecycle.conversation.resumeExpired")||!1,convoInProgress:i.matches?.("lifecycle.conversation.inProgress")||!1,convoStarting:i.matches?.("lifecycle.conversation.inProgress.startingConversation")||!1,convoInitializing:i.matches?.("lifecycle.conversation.initializingConversation")||!1,conversationSubstate:i.matches?.("lifecycle.conversation.inProgress.pendingAudioStart")?"pendingAudioStart":i.matches?.("lifecycle.conversation.inProgress.speaking")?"speaking":i.matches?.("lifecycle.conversation.inProgress.listening")?"listening":i.matches?.("lifecycle.conversation.inProgress.thinking")?"thinking":i.matches?.("lifecycle.conversation.inProgress.startingConversation")?"startingConversation":i.matches?.("lifecycle.conversation.inProgress.idle")?"idle":""},connection:{connected:i.matches?.("connection.connected")||!1,disconnected:i.matches?.("connection.disconnected")||!1},flags:{userSilenced:i.context?.userSilenced||!1,isPageVisible:!!i.context?.isPageVisible,pendingStart:"boolean"==typeof i.context?.pendingStart?i.context.pendingStart:null}};!function(t,e){if(t===e)return!0;if(!t||!e)return!1;const i=t.lifecycle,a=e.lifecycle;if(!i||!a)return!1;if(i.initInitializing!==a.initInitializing||i.initFailed!==a.initFailed||i.convoStopped!==a.convoStopped||i.convoResumable!==a.convoResumable||i.convoInProgress!==a.convoInProgress||i.convoStarting!==a.convoStarting||i.convoInitializing!==a.convoInitializing||i.conversationSubstate!==a.conversationSubstate)return!1;const n=t.connection,s=e.connection;if(!n||!s)return!1;if(n.connected!==s.connected||n.disconnected!==s.disconnected)return!1;const o=t.flags,r=e.flags;return!(!o||!r)&&o.userSilenced===r.userSilenced&&o.isPageVisible===r.isPageVisible&&o.pendingStart===r.pendingStart}(a,e)&&(e=a,t(a,i))}));return()=>i.unsubscribe()}}class ct{constructor(t,e){if(!t||!e)throw new Error("Cannot initialize connectionManager due to missing bus or avatarOrchestrator");this.connectionModules={},this._allConnectionsReady=!1,this._wasAllReady=!1,this.isReconnecting=!1,this.bus=t,this.avatarOrchestrator=e,this._reconnectTimer=null,this._retryDelay=T?.connection?.reconnectInitialDelay,this._maxDelay=T?.connection?.reconnectMaxDelay,this._factor=T?.connection?.reconnectFactor,this._reconnectHandler=async()=>{try{this._resetBackoff(),await this.reconnectFailedModules(!0)}catch(t){}},this.bus.on("event_command_ConnectionManager_ReconnectFailedModules",this._reconnectHandler)}get allConnectionsReady(){return this._allConnectionsReady}set allConnectionsReady(t){this._allConnectionsReady=t}registerNewConnectionModule(t,e=null){try{const i=new V(t);e&&(i.reconnect=e),i.subscribe((()=>this.updateAvatarState())),this.connectionModules[t]=i}catch(i){}}registerConnectionModule(t){try{if(!t||!t.name||"function"!=typeof t.subscribe)throw new Error("Invalid module: must have 'name' property and 'subscribe' method");t.subscribe((()=>this.updateAvatarState())),this.connectionModules[t.name]=t}catch(e){}}setReconnectFunction(t,e){try{const i=this.connectionModules[t];if(!i)return;i.reconnect=e}catch(i){}}waitUntilReady(t=15e3){return new Promise(((e,i)=>{if(this._allConnectionsReady)return e(!0);let a,n;const s=()=>{a&&clearTimeout(a),n&&this.bus.off("connectionStateChanged",n)};a=setTimeout((()=>{s(),i(new Error("Connection timeout"))}),t),n=()=>{this._allConnectionsReady&&(s(),e(!0))},this.bus.on("connectionStateChanged",n)}))}updateAvatarState(){if(!this.avatarOrchestrator)return;const t=Object.values(this.connectionModules).every((t=>t.isConnected()));if(Object.values(this.connectionModules).some((t=>t.isFailed())),this.allConnectionsReady=t,this.bus.emit("connectionStateChanged"),t){if(this._clearReconnectTimer(),!this._wasAllReady)try{const t=this.avatarOrchestrator.getSnapshot?.();t?.matches?.("connection.disconnected"),this.avatarOrchestrator.sendEvent("RECONNECT"),(t?.matches?.("lifecycle.init.failed")||t?.matches?.("lifecycle.init.initializing"))&&this.avatarOrchestrator.sendEvent("CONNECT")}catch(e){}this._wasAllReady=!0}else{if(this._scheduleAutoReconnect(),this._wasAllReady)try{this.avatarOrchestrator.sendEvent("DISCONNECT")}catch(e){}this._wasAllReady=!1}}async reconnectFailedModules(t=!1){if(this.isReconnecting)return;this.isReconnecting=!0;const e=Object.values(this.connectionModules).filter((t=>t.isFailed()||t.isDisconnected())).map((async t=>{try{await(t.reconnect?.())}catch(e){}}));await Promise.allSettled(e),this.isReconnecting=!1,this.updateAvatarState(),t||this._stepBackoff()}async reconnectDisconnectedModules(){if(this.isReconnecting)return;this.isReconnecting=!0;const t=Object.values(this.connectionModules).filter((t=>!t.isConnected())).map((async t=>{try{await(t.reconnect?.())}catch(e){}}));await Promise.allSettled(t),this.isReconnecting=!1,this.updateAvatarState()}getConnectionReport(){let t=`System is ${this.allConnectionsReady?"Ready":"Not Ready"}\n\n`;for(const e of Object.values(this.connectionModules))t+=`${e.name}: ${e.isConnected()?"connected":"disconnected"}, \n`;return t}_scheduleAutoReconnect(){this._reconnectTimer||(this._reconnectTimer=setTimeout((async()=>{this._reconnectTimer=null,await this.reconnectFailedModules()}),this._retryDelay))}_clearReconnectTimer(){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._resetBackoff()}_resetBackoff(){this._retryDelay=T?.connection?.reconnectInitialDelay}_stepBackoff(){this._retryDelay=Math.min(Math.ceil(this._retryDelay*this._factor),this._maxDelay)}destroy(){try{this._reconnectHandler&&(this.bus?.off("event_command_ConnectionManager_ReconnectFailedModules",this._reconnectHandler),this._reconnectHandler=null),this._clearReconnectTimer()}catch(t){}}}const lt={dance:["dance\\M_Dances_007.fbx","dance\\M_Dances_008.fbx","dance\\M_Dances_009.fbx","dance\\M_Dances_011.fbx","dance\\F_Dances_001.fbx","dance\\F_Dances_004.fbx","dance\\F_Dances_005.fbx","dance\\F_Dances_006.fbx","dance\\F_Dances_007.fbx","dance\\M_Dances_001.fbx","dance\\M_Dances_002.fbx","dance\\M_Dances_003.fbx","dance\\M_Dances_004.fbx","dance\\M_Dances_005.fbx","dance\\M_Dances_006.fbx"],expression:["expression\\M_Standing_Expressions_016.fbx","expression\\M_Standing_Expressions_017.fbx","expression\\M_Standing_Expressions_018.fbx","expression\\M_Talking_Variations_001.fbx","expression\\M_Talking_Variations_002.fbx","expression\\M_Talking_Variations_003.fbx","expression\\M_Talking_Variations_004.fbx","expression\\M_Talking_Variations_005.fbx","expression\\M_Talking_Variations_006.fbx","expression\\M_Talking_Variations_007.fbx","expression\\M_Talking_Variations_008.fbx","expression\\M_Talking_Variations_009.fbx","expression\\M_Talking_Variations_010.fbx","expression\\F_Talking_Variations_001.fbx","expression\\F_Talking_Variations_002.fbx","expression\\F_Talking_Variations_003.fbx","expression\\F_Talking_Variations_004.fbx","expression\\F_Talking_Variations_005.fbx","expression\\F_Talking_Variations_006.fbx","expression\\M_Standing_Expressions_001.fbx","expression\\M_Standing_Expressions_002.fbx","expression\\M_Standing_Expressions_004.fbx","expression\\M_Standing_Expressions_005.fbx","expression\\M_Standing_Expressions_006.fbx","expression\\M_Standing_Expressions_007.fbx","expression\\M_Standing_Expressions_008.fbx","expression\\M_Standing_Expressions_009.fbx","expression\\M_Standing_Expressions_010.fbx","expression\\M_Standing_Expressions_011.fbx","expression\\M_Standing_Expressions_012.fbx","expression\\M_Standing_Expressions_013.fbx","expression\\M_Standing_Expressions_014.fbx","expression\\M_Standing_Expressions_015.fbx"],locomotion:["locomotion\\M_CrouchedWalk_Backwards_002.fbx","locomotion\\M_Falling_Idle_002.fbx","locomotion\\M_Jog_001.fbx","locomotion\\M_Jog_003.fbx","locomotion\\M_Jog_Backwards_001.fbx","locomotion\\M_Jog_Jump_001.fbx","locomotion\\M_Jog_Jump_002.fbx","locomotion\\M_Jog_Strafe_Left_001.fbx","locomotion\\M_Jog_Strafe_Right_001.fbx","locomotion\\M_Run_001.fbx","locomotion\\M_Run_Backwards_002.fbx","locomotion\\M_Run_Jump_001.fbx","locomotion\\M_Run_Jump_002.fbx","locomotion\\M_Run_Strafe_Left_002.fbx","locomotion\\M_Run_Strafe_Right_002.fbx","locomotion\\M_Walk_001.fbx","locomotion\\M_Walk_002.fbx","locomotion\\M_Walk_Backwards_001.fbx","locomotion\\M_Walk_Jump_001.fbx","locomotion\\M_Walk_Jump_002.fbx","locomotion\\M_Walk_Jump_003.fbx","locomotion\\M_Walk_Strafe_Left_002.fbx","locomotion\\M_Walk_Strafe_Right_002.fbx","locomotion\\F_Crouch_Strafe_Left.fbx","locomotion\\F_Crouch_Strafe_Right.fbx","locomotion\\F_Crouch_Walk_001.fbx","locomotion\\F_CrouchedWalk_Backwards_001.fbx","locomotion\\F_Falling_Idle_000.fbx","locomotion\\F_Falling_Idle_001.fbx","locomotion\\F_Jog_001.fbx","locomotion\\F_Jog_Backwards_001.fbx","locomotion\\F_Jog_Jump_Small_001.fbx","locomotion\\F_Jog_Strafe_Left_002.fbx","locomotion\\F_Jog_Strafe_Right_002.fbx","locomotion\\F_Run_001.fbx","locomotion\\F_Run_Backwards_001.fbx","locomotion\\F_Run_Jump_001.fbx","locomotion\\F_Run_Strafe_Left_001.fbx","locomotion\\F_Run_Strafe_Right_001.fbx","locomotion\\F_Walk_002.fbx","locomotion\\F_Walk_003.fbx","locomotion\\F_Walk_Backwards_001.fbx","locomotion\\F_Walk_Jump_001.fbx","locomotion\\F_Walk_Jump_002.fbx","locomotion\\F_Walk_Strafe_Left_001.fbx","locomotion\\F_Walk_Strafe_Right_001.fbx","locomotion\\M_Crouch_Strafe_Left_002.fbx","locomotion\\M_Crouch_Strafe_Right_002.fbx","locomotion\\M_Crouch_Walk_003.fbx"],idle:["idle\\M_Standing_Idle_Variations_001.fbx","idle\\M_Standing_Idle_Variations_002.fbx","idle\\M_Standing_Idle_Variations_003.fbx","idle\\M_Standing_Idle_Variations_004.fbx","idle\\M_Standing_Idle_Variations_005.fbx","idle\\M_Standing_Idle_Variations_006.fbx","idle\\M_Standing_Idle_Variations_007.fbx","idle\\M_Standing_Idle_Variations_008.fbx","idle\\M_Standing_Idle_Variations_009.fbx","idle\\M_Standing_Idle_Variations_010.fbx","idle\\F_Standing_Idle_001.fbx","idle\\F_Standing_Idle_Variations_001.fbx","idle\\F_Standing_Idle_Variations_002.fbx","idle\\F_Standing_Idle_Variations_003.fbx","idle\\F_Standing_Idle_Variations_004.fbx","idle\\F_Standing_Idle_Variations_005.fbx","idle\\F_Standing_Idle_Variations_006.fbx","idle\\F_Standing_Idle_Variations_007.fbx","idle\\F_Standing_Idle_Variations_008.fbx","idle\\F_Standing_Idle_Variations_009.fbx","idle\\M_Standing_Idle_001.fbx","idle\\M_Standing_Idle_002.fbx"]};function ht(t){return t&&0!==t.length?t[Math.floor(Math.random()*t.length)]:null}function dt(t,e,...i){return t.filter((t=>!!t.includes(`${e}_`)&&i.every((e=>t.includes(e)))))}const ut={maxChars:T.captions.maxCharactersPerCaption,minChars:T.captions.minCharactersPerCaption,softChars:Math.floor(.75*T.captions.maxCharactersPerCaption),pauseBreakMs:350,preferBreakAfter:/[.!?…]|—|–|;/,softBreakAfter:/,|:/};class pt{constructor(){this.currentCaptions=[],this.currentCaptionIndex=0,this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null,this._playAttemptActive=!1}isBoundaryTypeValid(t){return"SpeechSynthesisBoundaryType.Word"===t.boundaryType||"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType}handleWordBoundaryEvent(t){if(!this.isBoundaryTypeValid(t))return;const e=t.text,i=t.audioOffset,a=t.duration;let n=this.currentCaptions[this.currentCaptions.length-1],s=null;if(n&&Number.isFinite(n._lastEndOffsetMs)&&(s=i-n._lastEndOffsetMs),!n||function(t,e,i){const a=t.text,n=a.length,s=ut.preferBreakAfter.test(a.slice(-1)),o=ut.softBreakAfter.test(a.slice(-1));return!!t.isDisplayed||null!=i&&i>=ut.pauseBreakMs&&n>=ut.minChars||(r=n)+(r?1:0)+e.length>ut.maxChars||!!(s&&n>=ut.minChars)||!!(n>=ut.softChars&&o);var r}(n,e,s)){const t={text:e,audioOffset:i,duration:a,isDisplayed:!1,_lastEndOffsetMs:i+a,get renderText(){return(t=this.text)?` ${t.trim()} `:" ";var t}};this.currentCaptions.push(t)}else n.text=(r=e,((o=n.text).length>0&&!/\s$/.test(o)&&!/^[\s.,!?;:…)]/.test(r)?o+" "+r:o+r).replace(/\s{2,}/g," ")),n.duration+=a,n._lastEndOffsetMs=i+a;var o,r;if(/^[\s.,!?;:…()\[\]{}'"—–-]$/.test(e)){const t=this.currentCaptions[this.currentCaptions.length-1];t&&(t.text=t.text.replace(/\s+([.,!?;:…)\]}])/g,"$1").replace(/([([{])\s+/g,"$1").replace(/\s{2,}/g," ").trim())}}playCaptions(t,e){this._playAttemptActive=!0;const i=async()=>{this._playAttemptActive&&(this.currentCaptions.length>0&&!this.currentCaptions[0].isDisplayed?(this._playAttemptActive=!1,this.startCaptionDisplay(t,e)):(await this.wait(100),i()))};i()}startCaptionDisplay(t,e){this.currentCaptionIndex=0,this.displayTimeoutId&&clearTimeout(this.displayTimeoutId),this.durationTimeoutId&&clearTimeout(this.durationTimeoutId),this.settleTimeoutId&&clearTimeout(this.settleTimeoutId),this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null;const i=()=>{if(this.currentCaptionIndex>=this.currentCaptions.length)return void(this.settleTimeoutId=setTimeout((()=>{this.settleTimeoutId=null,this.currentCaptionIndex>=this.currentCaptions.length?t(!1):i()}),100));const a=this.currentCaptions[this.currentCaptionIndex];if(!a)return void t(!1);const n=Math.max(0,a.audioOffset-(performance.now()-e));this.displayTimeoutId=setTimeout((()=>{this.displayTimeoutId=null,this.currentCaptions[this.currentCaptionIndex]?(a.isDisplayed=!0,t(!0,a.text),this.durationTimeoutId=setTimeout((()=>{this.durationTimeoutId=null,this.currentCaptionIndex++,i()}),a.duration)):t(!1)}),n)};i()}clearCaptions(){this._playAttemptActive=!1,this.displayTimeoutId&&clearTimeout(this.displayTimeoutId),this.durationTimeoutId&&clearTimeout(this.durationTimeoutId),this.settleTimeoutId&&clearTimeout(this.settleTimeoutId),this.displayTimeoutId=null,this.durationTimeoutId=null,this.settleTimeoutId=null,this.currentCaptions=[],this.currentCaptionIndex=0}wait(t){return new Promise((e=>setTimeout(e,t)))}destroy(){this.clearCaptions()}}const gt=["eyeBlinkLeft","eyeLookDownLeft","eyeLookInLeft","eyeLookOutLeft","eyeLookUpLeft","eyeSquintLeft","eyeWideLeft","eyeBlinkRight","eyeLookDownRight","eyeLookInRight","eyeLookOutRight","eyeLookUpRight","eyeSquintRight","eyeWideRight","jawForward","jawLeft","jawRight","jawOpen","mouthClose","mouthFunnel","mouthPucker","mouthLeft","mouthRight","mouthSmileLeft","mouthSmileRight","mouthFrownLeft","mouthFrownRight","mouthDimpleLeft","mouthDimpleRight","mouthStretchLeft","mouthStretchRight","mouthRollLower","mouthRollUpper","mouthShrugLower","mouthShrugUpper","mouthPressLeft","mouthPressRight","mouthLowerDownLeft","mouthLowerDownRight","mouthUpperUpLeft","mouthUpperUpRight","browDownLeft","browDownRight","browInnerUp","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight","noseSneerLeft","noseSneerRight","tongueOut","headRotateZ"],mt=["sil","aa","aa","O","E","RR","I","U","O","O","O","I","kk","RR","nn","SS","CH","TH","FF","DD","kk","PP"];class vt extends V{constructor(t,e){super("talkingAvatar"),this.bus=t,this.avatarOrchestrator=e,this.talkingAvatar=null,this.isFullBody=!0,this.bodyGender="M",this.resetSpeakData(),this.prevViseme=null,this.frameDuration=1e3/T.constants.FRAME_RATE,this.currentTurnId=null,this.isStoppingSpeaking=!1,this._endedTurns=new Set,this.conversationStreamActive=!1,this._pendingEndReason=null,this._audioStartSent=!1,this._busHandlers=[],this.liveCaptions=new pt}resetSpeakData(){this.speak={audio:[],visemes:[],vtimes:[],vdurations:[],words:[],wtimes:[],wdurations:[],markers:[],mtimes:[],anim:{}},this.azureBlendShapes={frames:[],sbuffer:[],orderBuffer:{}},this.prevViseme=null}finalizeTurn(){this.handlePendingVisemes(),this.talkingAvatar.streamNotifyEnd(),this.resetSpeakData()}async init(t,e){try{this.talkingAvatar=new m(e,{ttsEndpoint:"/gtts/",cameraZoomEnable:!1,cameraPanEnable:!1,cameraRotateEnable:!1,cameraView:"full",cameraY:.25,cameraDistance:.5,avatarMood:"happy"});const i="male"===t.gender?"M":"F";this.bodyGender=i,this.currentAvatarConfig={url:t.url,body:i},await this.talkingAvatar.showAvatar(this.currentAvatarConfig),this.addEventListeners(),this.setConnected(),this.lipsyncType=t.lipsyncType}catch(i){throw this.setFailed(),new Error("Error initializing TalkingAvatar: "+i)}}isRenderingActive(){return!!this.talkingAvatar?.isRunning}async suspendRendering(t="hidden"){if(this.isRenderingActive()){this.suspendTime=Date.now();try{this.talkingAvatar?.streamInterrupt?.()}catch(e){}try{this.audioReader?.cancel()}catch(e){}try{this.lipsyncReader?.cancel()}catch(e){}if(this.conversationStreamActive)try{await this.stopConversationStream()}catch(e){}try{this.talkingAvatar?.stop?.()}catch(e){}try{this.liveCaptions?.clearCaptions?.()}catch(e){}try{this.bus?.emit?.("event_command_UI_ClearCaptions")}catch(e){}try{const e=this.isRenderingActive();this.bus?.emit?.("event_status_Avatar_RenderingStateChanged",{running:e,reason:t})}catch(e){}}}async resumeRendering(){if(!this.isRenderingActive()){this.suspendTime&&Date.now()-this.suspendTime>15e3&&this.currentAvatarConfig&&await this.refreshAvatar();try{this.talkingAvatar?.start?.()}catch(t){}try{const t=this.isRenderingActive();this.bus?.emit?.("event_status_Avatar_RenderingStateChanged",{running:t,reason:"resume"})}catch(t){}}}async refreshAvatar(){if(!this.currentAvatarConfig)return!1;try{try{this.talkingAvatar?.streamInterrupt?.()}catch(t){}return await this.talkingAvatar.showAvatar(this.currentAvatarConfig),!0}catch(e){return!1}}resumeAudioContext(){try{const t=this.talkingAvatar?.audioCtx;if(!t)return;"suspended"!==t.state&&"interrupted"!==t.state||t.resume().then((()=>{})).catch((t=>{}))}catch(t){}}getSpeechAnalyzerNode(){return this.talkingAvatar?.audioAnalyzerNode??null}startStreamPump(t){try{this.audioReader=t.readable.getReader()}catch(i){return}const e=this.currentTurnId;(async()=>{try{for(;;){const{value:i,done:a}=await this.audioReader.read();if(a)return;if(this.currentTurnId!==e){try{this.audioReader.cancel()}catch(t){}return}this._notifyAudioStart(e),this.handleSpeechSynthesizingChunk({audio:i})}}catch(i){"AbortError"===i.name||i.message.includes("cancel")}})().catch((t=>{}))}startLipsyncPump(t){this.lipsyncReader=t.readable.getReader();const e=this.currentTurnId;(async()=>{try{for(;;){const{value:i,done:a}=await this.lipsyncReader.read();if(a)break;if(this.currentTurnId!==e){try{this.lipsyncReader.cancel()}catch(t){}break}switch(i.type){case"viseme":this.handleAddVisemeToStreaming(i);break;case"word":this.handleReceivedWordBoundaryEvent(i);break;case"blend":this.handleAddBlendShapestoStreaming(i)}}}catch(i){"AbortError"===i.name||i.message.includes("cancel")}})().catch((t=>{}))}handleAudioEndOnce(t,e){const i=t??"__null__";this._endedTurns.has(i)||(this._endedTurns.add(i),this.avatarOrchestrator.sendEvent("AUDIO_END",{turnId:t,reason:e}))}async startConversationStream(){if(this.isRenderingActive()&&!this.conversationStreamActive)try{await this.talkingAvatar.streamStart({lipsyncType:this.lipsyncType,sampleRate:24e3},(({turnId:t,audioStartTime:e}={})=>{const i=t??this.currentTurnId;this._notifyAudioStart(i,e)}),(()=>{const t=this._pendingEndReason||"completed";this._pendingEndReason=null,this.handleAudioEndOnce(this.currentTurnId,t),this.currentTurnId&&(this.currentTurnId=null)})),this.conversationStreamActive=!0}catch(t){throw this.conversationStreamActive=!1,t}}async stopConversationStream(){if(this.conversationStreamActive)try{this.talkingAvatar.streamStop(),this.conversationStreamActive=!1}catch(t){this.conversationStreamActive=!1}}addEventListeners(){const t=(t,e)=>{this.bus.on(t,e),this._busHandlers.push([t,e])};t("event_command_Avatar_SetAvatarView",(t=>{this.setView(t.view)})),t("event_command_Avatar_SetAvatarMood",(t=>{this.talkingAvatar.setMood(t.mood)})),t("event_command_Avatar_PlayOrStopGesture",(t=>{"stop"!==t.gesture?this.talkingAvatar.playGesture(t.gesture,t.duration,t.mirror,t.ms):this.talkingAvatar.stopGesture()})),t("event_command_Avatar_PlayOrStopAnimation",(t=>{if("stop"===t.animation)return void this.talkingAvatar.stopAnimation();const e=function(t,e="M"){let i=[];switch(t){case"dance":i=dt(lt.dance,e,"Dances");break;case"expression_talking":i=dt(lt.expression,e,"Talking_Variations");break;case"expression_standing":i=dt(lt.expression,e,"Standing_Expressions");break;case"idle_standing":i=dt(lt.idle,e,"Standing_Idle");break;case"locomotion_walk":i=dt(lt.locomotion,e,"Walk_");break;case"locomotion_walk_backwards":i=dt(lt.locomotion,e,"Walk_Backwards");break;case"locomotion_walk_jump":i=dt(lt.locomotion,e,"Walk_Jump");break;case"locomotion_walk_strafe_left":i=dt(lt.locomotion,e,"Walk_Strafe_Left");break;case"locomotion_walk_strafe_right":i=dt(lt.locomotion,e,"Walk_Strafe_Right");break;case"locomotion_run":i=dt(lt.locomotion,e,"Run_");break;case"locomotion_run_backwards":i=dt(lt.locomotion,e,"Run_Backwards");break;case"locomotion_run_jump":i=dt(lt.locomotion,e,"Run_Jump");break;case"locomotion_run_strafe_left":i=dt(lt.locomotion,e,"Run_Strafe_Left");break;case"locomotion_run_strafe_right":i=dt(lt.locomotion,e,"Run_Strafe_Right");break;case"locomotion_jog":i=dt(lt.locomotion,e,"Jog_");break;case"locomotion_jog_backwards":i=dt(lt.locomotion,e,"Jog_Backwards");break;case"locomotion_jog_jump":i=dt(lt.locomotion,e,"Jog_Jump");break;case"locomotion_jog_strafe_left":i=dt(lt.locomotion,e,"Jog_Strafe_Left");break;case"locomotion_jog_strafe_right":i=dt(lt.locomotion,e,"Jog_Strafe_Right");break;case"locomotion_crouch_walk":i=dt(lt.locomotion,e,"Crouch_Walk");break;case"locomotion_crouch_strafe_left":i=dt(lt.locomotion,e,"Crouch_Strafe_Left");break;case"locomotion_crouch_strafe_right":i=dt(lt.locomotion,e,"Crouch_Strafe_Right");break;case"locomotion_crouchedwalk_backwards":i=dt(lt.locomotion,e,"CrouchedWalk_Backwards");break;case"locomotion_falling_idle":i=dt(lt.locomotion,e,"Falling_Idle");break;default:i=[]}return ht(i)||ht(lt.locomotion.filter((t=>t.includes(`${e}_Walk_`))))||"locomotion\\M_Walk_001.fbx"}(t.animation,this.bodyGender);this.playAnimation(e,t.dur)})),t("event_command_Avatar_ControlAvatarLookAt",(t=>{"ahead"!==t.target?"point"!==t.target?"camera"!==t.target?"eye_contact"!==t.target||this.talkingAvatar.makeEyeContact(t.t):this.talkingAvatar.lookAtCamera(t.t):this.talkingAvatar.lookAt(t.x,t.y,t.t):this.talkingAvatar.lookAhead(t.t)})),t("event_command_UI_ClearCaptions",(()=>{try{this.liveCaptions?.clearCaptions?.()}catch(t){}}))}onResize(){this.talkingAvatar&&this.talkingAvatar.onResize()}handleSpeechSynthesizingChunk(t){switch(this.lipsyncType){case"blendshapes":this.talkingAvatar.streamAudio({audio:t.audio,anims:this.azureBlendShapes?.sbuffer.splice(0,this.azureBlendShapes?.sbuffer.length)});break;case"visemes":this.talkingAvatar.streamAudio({audio:t.audio,visemes:this.speak.visemes.splice(0,this.speak.visemes.length),vtimes:this.speak.vtimes.splice(0,this.speak.vtimes.length),vdurations:this.speak.vdurations.splice(0,this.speak.vdurations.length)});break;case"words":this.talkingAvatar.streamAudio({audio:t.audio,words:this.speak.words.splice(0,this.speak.words.length),wtimes:this.speak.wtimes.splice(0,this.speak.wtimes.length),wdurations:this.speak.wdurations.splice(0,this.speak.wdurations.length)})}}handleAddVisemeToStreaming(t){const e=mt[t?.visemeId||0],i=t?.audioOffset||0;if(this.prevViseme){const t=this.prevViseme;let e=i-t.vtime;e<40&&(e=40),this.speak.visemes.push(t.viseme),this.speak.vtimes.push(t.vtime),this.speak.vdurations.push(e)}this.prevViseme={viseme:e,vtime:i}}handleAddBlendShapestoStreaming(t){const e=t?.BlendShapes;if(!e||0===e.length)return;const i=this._getBlendColumns(),a=e.length,n=Object.create(null);for(let o=0;o<i.length;o++){const[t,s]=i[o],r=new Float32Array(a);for(let i=0;i<a;i++){const a=e[i];r[i]=Array.isArray(a)||ArrayBuffer.isView(a)?a[t]??0:0}n[s]=r}const s=null!=t?.AudioOffset?Math.round(t.AudioOffset/1e4):(t?.FrameIndex||0)*this.frameDuration;this.azureBlendShapes.sbuffer.push({name:"blendshapes",delay:s,dt:this._getDtArray(a),vs:n})}handleReceivedWordBoundaryEvent(t){try{this.liveCaptions.handleWordBoundaryEvent(t)}catch(s){}const e=this.speak,i=t.text,a=t.audioOffset,n=t.duration;"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType&&e.words.length?e.words[e.words.length-1]+=i:"SpeechSynthesisBoundaryType.Word"===t.boundaryType||"SpeechSynthesisBoundaryType.Punctuation"===t.boundaryType?(e.words.push(i),e.wtimes.push(a),e.wdurations.push(n)):"SpeechSynthesisBoundaryType.Sentence"===t.boundaryType&&a>500&&(e.markers.push((()=>{this.talkingAvatar.lookAtCamera(500)})),e.mtimes.push(a-500))}handlePendingVisemes(t=null){if("visemes"===this.lipsyncType&&this.prevViseme){const e=this.prevViseme;t||(t=100),this.speak.visemes.push(e.viseme),this.speak.vtimes.push(e.vtime),this.speak.vdurations.push(t),this.prevViseme=null}"visemes"===this.lipsyncType&&this.speak.visemes.length&&this.talkingAvatar.streamAudio({visemes:this.speak.visemes.splice(0,this.speak.visemes.length),vtimes:this.speak.vtimes.splice(0,this.speak.vtimes.length),vdurations:this.speak.vdurations.splice(0,this.speak.vdurations.length)}),"blendshapes"===this.lipsyncType&&this.azureBlendShapes.sbuffer.length&&this.talkingAvatar.streamAudio({anims:this.azureBlendShapes.sbuffer.splice(0,this.azureBlendShapes.sbuffer.length)})}async startStreaming(t,e,i){if(this.currentTurnId=i,this.isStoppingSpeaking=!1,this._audioStartSent=!1,!this.isRenderingActive()){try{t?.cancel?.()}catch(n){}try{e?.cancel?.()}catch(n){}return this.handleAudioEndOnce(i,"suppressed"),void(this.currentTurnId=null)}const a=i;this._endedTurns.delete(a??"__null__");try{this.startStreamPump(t),this.startLipsyncPump(e),this.conversationStreamActive||await this.startConversationStream()}catch(s){this.handleAudioEndOnce(a,"error"),this.currentTurnId===a&&(this.currentTurnId=null),this.isStoppingSpeaking=!1}}_notifyAudioStart(t,e=null){if(this._audioStartSent)return;this._audioStartSent=!0;const i=e??("undefined"!=typeof performance?performance.now():Date.now()),a=t??this.currentTurnId,n=a||0===a?{turnId:a,audioStartTime:i}:{audioStartTime:i},s=()=>{try{this.avatarOrchestrator?.sendEvent("AUDIO_START",n)}catch(t){}};"function"==typeof queueMicrotask?queueMicrotask(s):setTimeout(s,0)}interruptSpeaking(){if(!this.isStoppingSpeaking){this.isStoppingSpeaking=!0,this.conversationStreamActive&&this.talkingAvatar.streamInterrupt(),this.audioReader?.cancel(),this.lipsyncReader?.cancel(),this._pendingEndReason="interrupted";try{this.liveCaptions?.clearCaptions?.()}catch(t){}try{this.bus?.emit?.("event_command_UI_ClearCaptions")}catch(t){}this.isStoppingSpeaking=!1}}setView(t){switch(t){case"full":this.talkingAvatar.setView("full");break;case"mid":this.talkingAvatar.setView("mid");break;case"upper":this.talkingAvatar.setView("upper");break;case"head":this.talkingAvatar.setView("head")}}playAnimation(t,e){const i=`https://sentifydfrontend.blob.core.windows.net/animationclips/${t}`;this.setView("full"),this.talkingAvatar.playAnimation(i,null,e)}reconnect(){}async destroy(){for(const[t,e]of this._busHandlers)try{this.bus.off(t,e)}catch{}this._busHandlers.length=0,this.isStoppingSpeaking=!1,this.conversationStreamActive&&await this.stopConversationStream(),this.talkingAvatar?.stop(),this.talkingAvatar=null}_getBlendColumns(){if(!this._blendCols){this._blendCols=[];for(let t=0;t<gt.length;t++){const e=gt[t];e&&this._blendCols.push([t,e])}}return this._blendCols}_getDtArray(t){this._dtCache||(this._dtCache=new Map);let e=this._dtCache.get(t);return e||(e=new Array(t).fill(this.frameDuration),this._dtCache.set(t,e)),e}}class _t{constructor(t){if(!t)throw new Error("Cannot initialize SpeakingAvatar due to missing bus instance");this.voiceBot=null,this.chatSocket=null,this.bus=t,this.avatarOrchestrator=new rt(t),this.avatarOrchestrator.start(),this.connectionManager=this.createConnectionManager(this.bus,this.avatarOrchestrator),this.sessionData=nt.getInstance(),this.auth=new it,this.connectionManager.registerConnectionModule(this.auth),this.voiceBargeInDetector=null}createConnectionManager(t,e){if(!t||!e)throw new Error("Missing dependencies for ConnectionManager creation.");return new ct(t,e)}async init(t){if(!t?.avatarContainer||!t.avatarAPIKey&&!t.tokenEndpoint||!t.avatarId||!t.targetApp)return!1;try{await this.initializeAuthentication(t);const{avatarParameters:e,avatarItem:i}=await this.setupAvatarData();return!(!e||!i||(this.avatarModule=new vt(this.bus,this.avatarOrchestrator),await this.sessionData.init(e,i),await Promise.all([this.initializeChatSocket(),this.initializeVoiceBot(),this.initializeAvatarScene(i,t.avatarContainer)]),this.avatarOrchestrator.injectModules({talkingAvatar:this.avatarModule,chatSocket:this.chatSocket,voiceBot:this.voiceBot,conversation:this.sessionData.conversation}),await this.initializeVoiceBargeInDetector(),await this.connectionManager.waitUntilReady(),this.avatarOrchestrator.sendEvent("READY","SpeakingAAvatar.init"),0))}catch(e){return!1}}async initializeAuthentication(t){if(!(await this.auth.init(t.targetApp,t.avatarAPIKey||"",t.tokenEndpoint||"",t.avatarId)))throw new Error("Authentication initialization failed.")}async setupAvatarData(){const t=await this.auth.getAvatarParameters();if(!t)throw new Error("Failed to retrieve avatar parameters from authentication");return{avatarParameters:t,avatarItem:this.constructAvatarItem(t)}}constructAvatarItem(t){let e=t.avatarUrl;"ReadyPlayerMe"===t.avatarSource&&e&&e.includes("models.readyplayer.me")&&(e+="?morphTargets=ARKit,Oculus+Visemes,mouthOpen,mouthSmile,eyesClosed,eyesLookUp,eyesLookDown&textureSizeLimit=1024&textureFormat=png");let i=t.lipsyncType||"visemes";return{id:t.avatarSourceId,type:T?.avatar?.type,url:e,source:t.avatarSource,bodyType:t.bodyType,gender:t.gender,lipsyncType:i}}async initializeChatSocket(){try{j.resetInstance?.()}catch{}this.chatSocket=j.getInstance(this.bus,this.auth,this.sessionData,this.avatarOrchestrator),this.connectionManager.registerConnectionModule(this.chatSocket),await this.chatSocket.init()}async initializeVoiceBot(){this.voiceBot=await G.build(this.bus,this.avatarOrchestrator,this.auth,this.sessionData),this.connectionManager.registerConnectionModule(this.voiceBot.speechService)}async initializeVoiceBargeInDetector(){if(!this.voiceBargeInDetector&&!1!==T?.speech?.bargeIn?.enabled)try{this.voiceBargeInDetector=new J({talkingAvatar:this.avatarModule,avatarOrchestrator:this.avatarOrchestrator,config:T?.speech?.bargeIn}),await this.voiceBargeInDetector.init()}catch(t){this.voiceBargeInDetector=null}}async setBargeInEnabled(t){if(T?.speech?.bargeIn&&(T.speech.bargeIn.enabled=t),t)this.voiceBargeInDetector||this.avatarModule&&this.avatarOrchestrator&&await this.initializeVoiceBargeInDetector();else if(this.voiceBargeInDetector){try{this.voiceBargeInDetector.destroy()}catch(e){}this.voiceBargeInDetector=null}}async initializeAvatarScene(t,e){try{if(!this.avatarModule)throw new Error("Avatar module not initialized.");this.connectionManager.registerConnectionModule(this.avatarModule),await this.avatarModule.init(t,e)}catch(i){throw i}}destroy(){try{j.resetInstance?.()}catch{}this.voiceBot?.destroy?.(),this.voiceBargeInDetector?.destroy?.(),this.voiceBargeInDetector=null,this.avatarModule?.destroy?.(),this.connectionManager?.destroy?.(),this.sessionData?.destroy?.(),this.auth?.destroy?.(),this.avatarOrchestrator?.destroy?.()}async refreshAvatar(){return!!this.avatarModule&&this.avatarModule.refreshAvatar()}}class bt extends EventTarget{constructor(){super(),this._listeners=new Map,this._disposers=new Set,this._isDisposed=!1,this._globalListeners=new Set}on(t,e){if(this._isDisposed)return()=>{};if("*"===t)return this.onAll(e);const i=t=>{try{const i=t.detail;e(i)}catch(i){}};this._listeners.has(t)||this._listeners.set(t,new Map),this._listeners.get(t).set(e,i),this.addEventListener(t,i);const a=()=>{this._isDisposed||(this.removeEventListener(t,i),this._listeners.get(t)?.delete(e),this._disposers.delete(a))};return this._disposers.add(a),a}off(t,e){if("*"===t)return this.offAll(e);const i=this._listeners.get(t)?.get(e);i&&(this.removeEventListener(t,i),this._listeners.get(t)?.delete(e))}emit(t,e=void 0){if(this._isDisposed)return;const i=new CustomEvent(t,{detail:e,bubbles:!1,cancelable:!1});this.dispatchEvent(i),this._globalListeners.forEach((i=>{try{i(t,e)}catch(a){}}))}onAll(t){if(this._isDisposed)return()=>{};this._globalListeners.add(t);const e=()=>{this._isDisposed||(this._globalListeners.delete(t),this._disposers.delete(e))};return this._disposers.add(e),e}offAll(t){this._globalListeners.delete(t)}clear(){this._listeners.forEach(((t,e)=>{t.forEach(((t,i)=>{this.removeEventListener(e,t)}))})),this._listeners.clear(),this._globalListeners.clear(),this._disposers.clear()}dispose(){this._isDisposed||(this._disposers.forEach((t=>{try{t()}catch(e){}})),this._listeners.clear(),this._globalListeners.clear(),this._disposers.clear(),this._isDisposed=!0)}get disposerCount(){return this._disposers.size}get isDisposed(){return this._isDisposed}get listenerCount(){let t=this._globalListeners.size;return this._listeners.forEach((e=>{t+=e.size})),t}}const ft="en",yt={en:{start:"Start Conversation",connect:"Connect",endConversation:"End Conversation",restartConversation:"Restart Conversation",hideTyping:"Hide typing input",showTyping:"Show typing input",reconnecting:"Reconnecting...",waitForResponse:"Please wait for response...",typeHere:"Type here.",noMessagesYet:"No messages yet...",conversationStatus:"Conversation Status",conversationInProgress:"Conversation In Progress",conversationStopped:"Conversation Stopped",startConversation:"Start Conversation",downloadConversation:"Download Conversation",liveCaptions:"Live captions",toggleChatbot:"Toggle avatar chatbot",avatar:"Avatar",switchToAvatar:"Back to avatar",switchToChat:"Switch to chat",chat:"Chat",statusInitializing:"Hang tight, we're waking up the avatar!",statusReconnecting:"Connection issue, attempting to reconnect...",statusFailed:"Connection failed. Manual action may be required.",statusInvalidConfiguration:"The avatar is not configured correctly, contact the admin.",close:"Close",lastAssistantMessage:"Last message",fullBodyView:"Full body view",upperBodyView:"Upper body view",secureFormTitle:"Secure Form",secureFormDescription:"Enter your information.",name:"Name*",namePlaceholder:"Enter your name",phoneNumber:"Phone Number",phonePlaceholder:"Enter your phone number",email:"Email",emailPlaceholder:"Enter your email",secureFormNote:"Your information will not be shared with the LLM and will not be stored after this session. By sending you agree to share your info to get additional support.",save:"Save",send:"Send",cancel:"Cancel",conversationEndedPrompt:"Conversation ended. Please rate your satisfaction with the conversation.",submit:"Submit",skip:"Skip and end",consentTitle:"Consent for AI conversation",consentInfo1:"For general information only — no medical, legal, financial, or safety advice.",consentInfo2:"We use session storage and send your input to provide replies. We don’t keep your conversation or personal info after this session.",consentReadOur:"Read our",consentTermsLabel:"Terms",consentAnd:"and",consentPrivacyLabel:"Privacy Policy",consentMoreDetails:"for more details.",consentInfo4:"(Your consent applies to this session only and clears when you close the tab/window)",consentAccept:"I agree",consentDecline:"Decline",consentAcceptAria:"I agree – start chat",consentDeclineAria:"Decline",interruptSpeaking:"Interrupt speaking avatar",turnOnMic:"Turn on microphone",turnOffMic:"Turn off microphone",tapToSpeak:"Tap to speak",thinking:"Thinking...",startConversationReminder:"Start a conversation to chat.",chatPlaceholderTitle:"Ready to chat?",chatPlaceholderDescription:"Start a conversation to continue in text mode.",enterInfoOnMobile:"Enter your information in User Information page",waitCurrentResponse:"Please wait for the current response before sending another message.",resumeConversationFailedNewStarted:"We couldn't resume your previous conversation. A new one has been started instead.",end:"End",endConversationPrompt:"Would you like to end the conversation? Ending it will permanently delete the conversation history.",restartConversationPrompt:"Are you sure you want to start a new conversation? Current conversation will be deleted.",newConversation:"New",conversationExpiredPrompt:"This conversation has expired and cannot be resumed. Would you like to download a copy and end or end only?",conversationExpiredResumePrompt:"Your previous conversation has expired and cannot be resumed. Would you like to download a copy of your conversation history?",downloadAndClear:"Download & Clear",downloadAndStartNew:"Download & Start New",startNew:"Start New",ok:"OK",download:"Download",onlyClear:"Only Clear",confirm:"Confirm",alertGenericError:"An error occurred.",alertFailedEndConversation:"Failed to end the conversation. Please try again.",alertFailedClearConversation:"Failed to clear the conversation.",alertCouldNotStartListening:"Could not start listening. Please try again.",alertSomeErrorOccurred:"Some error occurred. Please try again.",alertWaitForAIResponse:"Please wait for the AI response before starting to speak.",alertVoiceServicesUnavailable:"Unable to connect to voice services. Please try again later.",alertServiceTemporarilyUnavailable:"Service is temporarily unavailable. Please try again.",alertTooManyRequests:"Too many simultaneous requests. Please wait a moment and try again.",alertConnectionIssue:"Connection issue detected. Please check your internet connection and try again.",alertResponseTimeout:"Response timeout. Please try again.",alertServiceBusy:"Voice service is currently busy. Please try again in a few minutes.",alertMicrophoneStartFailed:"Failed to start listening. Make sure your microphone is working.",alertMicrophoneCheckSettings:"Failed to start listening. Please check your microphone settings.",alertSpeechRecognitionSetupFailed:"Speech recognition setup failed. Please refresh the page and try again.",alertMicrophoneAccessDenied:"Microphone access denied. Please allow microphone access in your browser settings and refresh the page.",alertNoMicrophoneDetected:"No microphone detected. Please connect a microphone and refresh the page.",alertMicrophoneError:"Microphone error. Please check your microphone."},fr:{start:"DĆ©marrer la conversation",connect:"Se connecter",endConversation:"Terminer la conversation",restartConversation:"RedĆ©marrer la conversation",hideTyping:"Masquer la saisie",showTyping:"Afficher la saisie",reconnecting:"Reconnexion...",waitForResponse:"Veuillez attendre la rĆ©ponse...",typeHere:"Tapez ici.",noMessagesYet:"Pas encore de messages...",conversationStatus:"Ɖtat de la conversation",conversationInProgress:"Conversation en cours",conversationStopped:"Conversation terminĆ©e",startConversation:"Commencer la conversation",downloadConversation:"TĆ©lĆ©charger la conversation",liveCaptions:"Sous-titres en direct",toggleChatbot:"Afficher/Masquer l'avatar",avatar:"Avatar",switchToAvatar:"Retour Ć  l'avatar",switchToChat:"Passer au chat",chat:"Chat",statusInitializing:"Patientez, nous rĆ©veillons l'avatar !",statusReconnecting:"ProblĆØme de connexion, tentative de reconnexion...",statusFailed:"Ɖchec de la connexion. Une action manuelle peut ĆŖtre nĆ©cessaire.",statusInvalidConfiguration:"L'avatar n'est pas configurĆ© correctement, contactez l'administrateur.",close:"Fermer",lastAssistantMessage:"Dernier message",fullBodyView:"Vue du corps entier",upperBodyView:"Vue du haut du corps",secureFormTitle:"Formulaire sĆ©curisĆ©",secureFormDescription:"Saisissez vos informations.",name:"Nom*",namePlaceholder:"Entrez votre nom",phoneNumber:"NumĆ©ro de tĆ©lĆ©phone",phonePlaceholder:"Entrez votre numĆ©ro de tĆ©lĆ©phone",email:"E-mail",emailPlaceholder:"Entrez votre e-mail",secureFormNote:"Vos informations ne seront pas partagĆ©es avec le LLM et ne seront pas conservĆ©es aprĆØs cette session. En envoyant, vous acceptez de partager vos informations pour obtenir un support supplĆ©mentaire.",save:"Enregistrer",send:"Envoyer",cancel:"Annuler",conversationEndedPrompt:"Conversation terminĆ©e. Veuillez Ć©valuer votre satisfaction.",submit:"Envoyer",skip:"Ignorer et terminer",consentTitle:"Consentement pour la conversation IA",consentInfo1:"ƀ titre informatif uniquement — aucun conseil mĆ©dical, juridique, financier ou de sĆ©curitĆ©.",consentInfo2:"Nous utilisons le stockage de session et envoyons votre saisie pour fournir des rĆ©ponses. Nous ne conservons pas votre conversation ni vos informations personnelles aprĆØs cette session.",consentReadOur:"Lisez nos",consentTermsLabel:"Conditions",consentAnd:"et",consentPrivacyLabel:"Politique de confidentialitĆ©",consentMoreDetails:"pour plus de dĆ©tails.",consentInfo4:"(Votre consentement s'applique uniquement Ć  cette session et est rĆ©initialisĆ© lorsque vous fermez l'onglet ou la fenĆŖtre)",consentAccept:"J'accepte",consentDecline:"Refuser",consentAcceptAria:"J'accepte – dĆ©marrer le chat",consentDeclineAria:"Refuser",interruptSpeaking:"Interrompre l'avatar",turnOnMic:"Activer le microphone",turnOffMic:"DĆ©sactiver le microphone",tapToSpeak:"Appuyez pour parler",thinking:"RĆ©flexion...",startConversationReminder:"DĆ©marrez une conversation pour discuter.",chatPlaceholderTitle:"PrĆŖt Ć  discuter ?",chatPlaceholderDescription:"Lancez une conversation pour continuer en mode texte.",enterInfoOnMobile:"Saisissez vos informations dans la page Informations utilisateur",waitCurrentResponse:"Veuillez attendre la rĆ©ponse en cours avant d'envoyer un autre message.",resumeConversationFailedNewStarted:"Nous n'avons pas pu reprendre votre conversation prĆ©cĆ©dente. Une nouvelle a Ć©tĆ© dĆ©marrĆ©e Ć  la place.",end:"Terminer",endConversationPrompt:"Souhaitez-vous terminer la conversation ? Cela supprimera dĆ©finitivement l'historique de la conversation.",restartConversationPrompt:"Voulez-vous dĆ©marrer une nouvelle conversation ? La conversation actuelle sera supprimĆ©e.",newConversation:"Nouveau",conversationExpiredPrompt:"Cette conversation a expirĆ© et ne peut pas ĆŖtre reprise. Voulez-vous en tĆ©lĆ©charger une copie puis la supprimer, ou simplement la supprimer ?",conversationExpiredResumePrompt:"Votre conversation prĆ©cĆ©dente a expirĆ© et ne peut pas ĆŖtre reprise. Voulez-vous tĆ©lĆ©charger une copie de votre historique de conversation ?",downloadAndClear:"TĆ©lĆ©charger et effacer",downloadAndStartNew:"TĆ©lĆ©charger et dĆ©marrer",startNew:"Nouvelle conv.",onlyClear:"Effacer uniquement",confirm:"Confirmer",ok:"OK",download:"TĆ©lĆ©charger",alertGenericError:"Une erreur s'est produite.",alertFailedEndConversation:"Ɖchec de la fin de la conversation. Veuillez rĆ©essayer.",alertFailedClearConversation:"Ɖchec de l'effacement de la conversation.",alertCouldNotStartListening:"Impossible de dĆ©marrer l'Ć©coute. Veuillez rĆ©essayer.",alertSomeErrorOccurred:"Une erreur s'est produite. Veuillez rĆ©essayer.",alertWaitForAIResponse:"Veuillez attendre la rĆ©ponse de l'IA avant de commencer Ć  parler.",alertVoiceServicesUnavailable:"Impossible de se connecter aux services vocaux. Veuillez rĆ©essayer plus tard.",alertServiceTemporarilyUnavailable:"Service temporairement indisponible. Veuillez rĆ©essayer.",alertTooManyRequests:"Trop de demandes simultanĆ©es. Veuillez patienter un instant et rĆ©essayer.",alertConnectionIssue:"ProblĆØme de connexion dĆ©tectĆ©. Veuillez vĆ©rifier votre connexion internet et rĆ©essayer.",alertResponseTimeout:"DĆ©lai de rĆ©ponse dĆ©passĆ©. Veuillez rĆ©essayer.",alertServiceBusy:"Le service vocal est actuellement occupĆ©. Veuillez rĆ©essayer dans quelques minutes.",alertMicrophoneStartFailed:"Impossible de dĆ©marrer l'Ć©coute. Assurez-vous que votre microphone fonctionne.",alertMicrophoneCheckSettings:"Impossible de dĆ©marrer l'Ć©coute. Veuillez vĆ©rifier les paramĆØtres de votre microphone.",alertSpeechRecognitionSetupFailed:"Ɖchec de la configuration de la reconnaissance vocale. Veuillez actualiser la page et rĆ©essayer.",alertMicrophoneAccessDenied:"AccĆØs au microphone refusĆ©. Veuillez autoriser l'accĆØs au microphone dans les paramĆØtres de votre navigateur et actualiser la page.",alertNoMicrophoneDetected:"Aucun microphone dĆ©tectĆ©. Veuillez connecter un microphone et actualiser la page.",alertMicrophoneError:"Erreur de microphone. Veuillez vĆ©rifier votre microphone."},de:{start:"Starten Sie die Konversation",connect:"Verbinden",endConversation:"GesprƤch beenden",restartConversation:"GesprƤch neu starten",hideTyping:"Eingabefeld ausblenden",showTyping:"Eingabefeld anzeigen",reconnecting:"Verbindung wird wiederhergestellt...",waitForResponse:"Bitte auf die Antwort warten...",typeHere:"Hier eingeben.",noMessagesYet:"Noch keine Nachrichten...",conversationStatus:"GesprƤchsstatus",conversationInProgress:"GesprƤch lƤuft",conversationStopped:"GesprƤch beendet",startConversation:"GesprƤch starten",downloadConversation:"GesprƤch herunterladen",liveCaptions:"Live-Untertitel",toggleChatbot:"Avatar-Chatbot ein-/ausblenden",avatar:"Avatar",switchToAvatar:"Zurück zum Avatar",switchToChat:"Zum Chat wechseln",chat:"Chat",statusInitializing:"Einen Moment, der Avatar wird gestartet!",statusReconnecting:"Verbindungsproblem, versuche erneut zu verbinden...",statusFailed:"Verbindung fehlgeschlagen. Mƶglicherweise ist ein manueller Eingriff erforderlich.",statusInvalidConfiguration:"Der Avatar ist nicht korrekt konfiguriert, wenden Sie sich an den Administrator.",close:"Schließen",lastAssistantMessage:"Letzte Nachricht",fullBodyView:"Ganzkƶrperansicht",upperBodyView:"Oberkƶrperansicht",secureFormTitle:"Sicheres Formular",secureFormDescription:"Geben Sie Ihre Informationen ein.",name:"Name*",namePlaceholder:"Geben Sie Ihren Namen ein",phoneNumber:"Telefonnummer",phonePlaceholder:"Geben Sie Ihre Telefonnummer ein",email:"E-Mail",emailPlaceholder:"Geben Sie Ihre E-Mail ein",secureFormNote:"Ihre Informationen werden nicht mit dem LLM geteilt und nach dieser Sitzung nicht gespeichert. Mit dem Absenden erklƤren Sie sich einverstanden, Ihre Daten zu teilen, um zusƤtzliche Unterstützung zu erhalten.",save:"Speichern",send:"Senden",cancel:"Abbrechen",conversationEndedPrompt:"GesprƤch beendet. Bitte bewerten Sie Ihre Zufriedenheit.",submit:"Senden",skip:"Überspringen und beenden",consentTitle:"Einwilligung für das KI-GesprƤch",consentInfo1:"Nur zu allgemeinen Informationszwecken – keine medizinischen, rechtlichen, finanziellen oder sicherheitsrelevanten RatschlƤge.",consentInfo2:"Wir verwenden den Sitzungspeicher und senden Ihre Eingaben, um Antworten bereitzustellen. Wir speichern Ihr GesprƤch oder persƶnliche Daten nach dieser Sitzung nicht.",consentReadOur:"Lesen Sie unsere",consentTermsLabel:"Nutzungsbedingungen",consentAnd:"und",consentPrivacyLabel:"DatenschutzerklƤrung",consentMoreDetails:"für weitere Informationen.",consentInfo4:"(Ihre Einwilligung gilt nur für diese Sitzung und wird zurückgesetzt, wenn Sie den Tab oder das Fenster schließen)",consentAccept:"Ich stimme zu",consentDecline:"Ablehnen",consentAcceptAria:"Ich stimme zu – Chat starten",consentDeclineAria:"Ablehnen",interruptSpeaking:"Sprechenden Avatar unterbrechen",turnOnMic:"Mikrofon einschalten",turnOffMic:"Mikrofon ausschalten",tapToSpeak:"Tippen zum Sprechen",thinking:"Nachdenken...",startConversationReminder:"Starten Sie ein GesprƤch, um zu chatten.",chatPlaceholderTitle:"Bereit zum Chatten?",chatPlaceholderDescription:"Starten Sie ein GesprƤch, um im Textmodus fortzufahren.",enterInfoOnMobile:"Geben Sie Ihre Daten auf der Seite Benutzerinformationen ein",waitCurrentResponse:"Bitte warten Sie die aktuelle Antwort ab, bevor Sie eine weitere Nachricht senden.",resumeConversationFailedNewStarted:"Wir konnten Ihr vorheriges GesprƤch nicht fortsetzen. Stattdessen wurde ein neues gestartet.",end:"Beenden",endConversationPrompt:"Mƶchten Sie das GesprƤch beenden? Dadurch wird der GesprƤchsverlauf dauerhaft gelƶscht.",restartConversationPrompt:"Mƶchten Sie ein neues GesprƤch beginnen? Das aktuelle GesprƤch wird gelƶscht.",newConversation:"Neu",conversationExpiredPrompt:"Dieses GesprƤch ist abgelaufen und kann nicht fortgesetzt werden. Mƶchten Sie eine Kopie herunterladen und lƶschen oder nur lƶschen?",conversationExpiredResumePrompt:"Ihr vorheriges GesprƤch ist abgelaufen und kann nicht fortgesetzt werden. Mƶchten Sie eine Kopie Ihres GesprƤchsverlaufs herunterladen?",downloadAndClear:"Herunterladen & lƶschen",downloadAndStartNew:"Herunterladen & Neu starten",startNew:"Neu starten",onlyClear:"Nur lƶschen",confirm:"BestƤtigen",ok:"OK",download:"Herunterladen",alertGenericError:"Ein Fehler ist aufgetreten.",alertFailedEndConversation:"Das GesprƤch konnte nicht beendet werden. Bitte versuchen Sie es erneut.",alertFailedClearConversation:"Das GesprƤch konnte nicht gelƶscht werden.",alertCouldNotStartListening:"Zuhƶren konnte nicht gestartet werden. Bitte versuchen Sie es erneut.",alertSomeErrorOccurred:"Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.",alertWaitForAIResponse:"Bitte warten Sie auf die KI-Antwort, bevor Sie zu sprechen beginnen.",alertVoiceServicesUnavailable:"Verbindung zu Sprachdiensten nicht mƶglich. Bitte versuchen Sie es spƤter erneut.",alertServiceTemporarilyUnavailable:"Der Dienst ist vorübergehend nicht verfügbar. Bitte versuchen Sie es erneut.",alertTooManyRequests:"Zu viele gleichzeitige Anfragen. Bitte warten Sie einen Moment und versuchen Sie es erneut.",alertConnectionIssue:"Verbindungsproblem erkannt. Bitte überprüfen Sie Ihre Internetverbindung und versuchen Sie es erneut.",alertResponseTimeout:"Zeitüberschreitung bei der Antwort. Bitte versuchen Sie es erneut.",alertServiceBusy:"Der Sprachdienst ist derzeit ausgelastet. Bitte versuchen Sie es in einigen Minuten erneut.",alertMicrophoneStartFailed:"Zuhƶren konnte nicht gestartet werden. Stellen Sie sicher, dass Ihr Mikrofon funktioniert.",alertMicrophoneCheckSettings:"Zuhƶren konnte nicht gestartet werden. Bitte überprüfen Sie Ihre Mikrofoneinstellungen.",alertSpeechRecognitionSetupFailed:"Einrichtung der Spracherkennung fehlgeschlagen. Bitte aktualisieren Sie die Seite und versuchen Sie es erneut.",alertMicrophoneAccessDenied:"Mikrofonzugriff verweigert. Bitte erlauben Sie den Mikrofonzugriff in Ihren Browsereinstellungen und aktualisieren Sie die Seite.",alertNoMicrophoneDetected:"Kein Mikrofon erkannt. Bitte schließen Sie ein Mikrofon an und aktualisieren Sie die Seite.",alertMicrophoneError:"Mikrofonfehler. Bitte überprüfen Sie Ihr Mikrofon."},es:{start:"Iniciar conversación",connect:"Conectar",endConversation:"Terminar conversación",restartConversation:"Reiniciar conversación",hideTyping:"Ocultar entrada de texto",showTyping:"Mostrar entrada de texto",reconnecting:"Reconectando...",waitForResponse:"Espere la respuesta...",typeHere:"Escriba aquĆ­.",noMessagesYet:"TodavĆ­a no hay mensajes...",conversationStatus:"Estado de la conversación",conversationInProgress:"Conversación en curso",conversationStopped:"Conversación detenida",startConversation:"Iniciar conversación",downloadConversation:"Descargar conversación",liveCaptions:"SubtĆ­tulos en vivo",toggleChatbot:"Mostrar/ocultar avatar",avatar:"Avatar",switchToAvatar:"Volver al avatar",switchToChat:"Cambiar al chat",chat:"Chat",statusInitializing:"Espere, estamos iniciando el avatar",statusReconnecting:"Problema de conexión, intentando reconectar...",statusFailed:"La conexión falló. Puede ser necesaria una acción manual.",statusInvalidConfiguration:"El avatar no estĆ” configurado correctamente, contacte al administrador.",close:"Cerrar",lastAssistantMessage:"Último mensaje",fullBodyView:"Vista de cuerpo completo",upperBodyView:"Vista de torso",secureFormTitle:"Formulario seguro",secureFormDescription:"Ingrese su información.",name:"Nombre*",namePlaceholder:"Ingrese su nombre",phoneNumber:"NĆŗmero de telĆ©fono",phonePlaceholder:"Ingrese su nĆŗmero de telĆ©fono",email:"Correo electrónico",emailPlaceholder:"Ingrese su correo electrónico",secureFormNote:"Su información no se compartirĆ” con el LLM ni se almacenarĆ” despuĆ©s de esta sesión. Al enviar, acepta compartir su información para obtener soporte adicional.",save:"Guardar",send:"Enviar",cancel:"Cancelar",conversationEndedPrompt:"Conversación finalizada. Califique su satisfacción.",submit:"Enviar",skip:"Omitir y terminar",consentTitle:"Consentimiento para conversación con IA",consentInfo1:"Solo con fines informativos — sin consejos mĆ©dicos, legales, financieros ni de seguridad.",consentInfo2:"Usamos almacenamiento de sesión y enviamos su entrada para responder. No guardamos su conversación ni datos personales tras esta sesión.",consentReadOur:"Lea nuestros",consentTermsLabel:"TĆ©rminos",consentAnd:"y",consentPrivacyLabel:"PolĆ­tica de privacidad",consentMoreDetails:"para mĆ”s detalles.",consentInfo4:"(Su consentimiento se aplica solo a esta sesión y se borra al cerrar la pestaƱa o ventana)",consentAccept:"Acepto",consentDecline:"Rechazar",consentAcceptAria:"Acepto – iniciar chat",consentDeclineAria:"Rechazar",interruptSpeaking:"Interrumpir avatar que habla",turnOnMic:"Activar micrófono",turnOffMic:"Desactivar micrófono",tapToSpeak:"Toca para hablar",thinking:"Pensando...",startConversationReminder:"Inicie una conversación para chatear.",chatPlaceholderTitle:"ĀæListo para chatear?",chatPlaceholderDescription:"Inicia una conversación para continuar en modo texto.",enterInfoOnMobile:"Ingrese su información en la pĆ”gina de usuario",waitCurrentResponse:"Espere la respuesta actual antes de enviar otro mensaje.",resumeConversationFailedNewStarted:"No pudimos reanudar su conversación anterior. En su lugar, se ha iniciado una nueva.",end:"Terminar",endConversationPrompt:"ĀæDesea terminar la conversación? Esto eliminarĆ” el historial permanentemente.",restartConversationPrompt:"ĀæSeguro que quiere iniciar una nueva conversación? La conversación actual se eliminarĆ”.",newConversation:"Nueva",conversationExpiredPrompt:"Esta conversación ha expirado y no se puede reanudar. ĀæDesea descargar una copia y borrar o solo borrar?",conversationExpiredResumePrompt:"Su conversación anterior ha expirado y no se puede reanudar. ĀæDesea descargar una copia de su historial de conversación?",downloadAndClear:"Descargar y borrar",downloadAndStartNew:"Descargar e iniciar",startNew:"Iniciar nueva",onlyClear:"Solo borrar",confirm:"Confirmar",ok:"OK",download:"Descargar",alertGenericError:"Se produjo un error.",alertFailedEndConversation:"No se pudo terminar la conversación. Por favor, intĆ©ntelo de nuevo.",alertFailedClearConversation:"No se pudo borrar la conversación.",alertCouldNotStartListening:"No se pudo iniciar la escucha. Por favor, intĆ©ntelo de nuevo.",alertSomeErrorOccurred:"Se produjo un error. Por favor, intĆ©ntelo de nuevo.",alertWaitForAIResponse:"Por favor, espere la respuesta de la IA antes de comenzar a hablar.",alertVoiceServicesUnavailable:"No se puede conectar a los servicios de voz. Por favor, intĆ©ntelo mĆ”s tarde.",alertServiceTemporarilyUnavailable:"El servicio no estĆ” disponible temporalmente. Por favor, intĆ©ntelo de nuevo.",alertTooManyRequests:"Demasiadas solicitudes simultĆ”neas. Por favor, espere un momento e intĆ©ntelo de nuevo.",alertConnectionIssue:"Problema de conexión detectado. Por favor, verifique su conexión a internet e intĆ©ntelo de nuevo.",alertResponseTimeout:"Tiempo de respuesta agotado. Por favor, intĆ©ntelo de nuevo.",alertServiceBusy:"El servicio de voz estĆ” ocupado actualmente. Por favor, intĆ©ntelo en unos minutos.",alertMicrophoneStartFailed:"No se pudo iniciar la escucha. AsegĆŗrese de que su micrófono funcione.",alertMicrophoneCheckSettings:"No se pudo iniciar la escucha. Por favor, verifique la configuración de su micrófono.",alertSpeechRecognitionSetupFailed:"Error en la configuración del reconocimiento de voz. Por favor, actualice la pĆ”gina e intĆ©ntelo de nuevo.",alertMicrophoneAccessDenied:"Acceso al micrófono denegado. Por favor, permita el acceso al micrófono en la configuración de su navegador y actualice la pĆ”gina.",alertNoMicrophoneDetected:"No se detectó ningĆŗn micrófono. Por favor, conecte un micrófono y actualice la pĆ”gina.",alertMicrophoneError:"Error de micrófono. Por favor, verifique su micrófono."},ar:{start:"Ų§ŲØŲÆŲ£ المحادثة",connect:"اتصل",endConversation:"؄نهاؔ المحادثة",restartConversation:"Ų„Ų¹Ų§ŲÆŲ© ŲØŲÆŲ” المحادثة",hideTyping:"؄خفاؔ حقل Ų§Ł„ŁƒŲŖŲ§ŲØŲ©",showTyping:"؄ظهار حقل Ų§Ł„ŁƒŲŖŲ§ŲØŲ©",reconnecting:"Ų¬Ų§Ų±Ł Ų„Ų¹Ų§ŲÆŲ© الاتصال...",waitForResponse:"ŁŠŲ±Ų¬Ł‰ انتظار الرد...",typeHere:"اكتب هنا.",noMessagesYet:"لا توجد رسائل ŲØŲ¹ŲÆ...",conversationStatus:"حالة المحادثة",conversationInProgress:"المحادثة جارية",conversationStopped:"المحادثة Ł…ŲŖŁˆŁ‚ŁŲ©",startConversation:"Ų§ŲØŲÆŲ£ المحادثة",downloadConversation:"ŲŖŁ†Ų²ŁŠŁ„ المحادثة",liveCaptions:"ŲŖŲ¹Ł„ŁŠŁ‚Ų§ŲŖ Ł†ŲµŁŠŲ© Ł…ŲØŲ§Ų“Ų±Ų©",toggleChatbot:"؄ظهار/؄خفاؔ روبوت المحادثة",avatar:"أفاتار",switchToAvatar:"Ų§Ł„Ų¹ŁˆŲÆŲ© ؄لى الأفاتار",switchToChat:"Ų§Ł„ŲŖŲØŲÆŁŠŁ„ ؄لى الدردؓة",chat:"ŲÆŲ±ŲÆŲ“Ų©",statusInitializing:"ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ų§Ł†ŲŖŲøŲ§Ų±ŲŒ Ł†Ł‚ŁˆŁ… ŲØŲŖŲ“ŲŗŁŠŁ„ الأفاتار!",statusReconnecting:"Ł…Ų“ŁƒŁ„Ų© في Ų§Ł„Ų§ŲŖŲµŲ§Ł„ŲŒ Ų¬Ų§Ų±Ł Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© مجددًا...",statusFailed:"فؓل الاتصال. قد ŁŠŲŖŲ·Ł„ŲØ الأمر تدخلاً ŁŠŲÆŁˆŁŠŁ‹Ų§.",statusInvalidConfiguration:"الأفاتار غير Ł…Ł‡ŁŠŲ£ ŲØŲ“ŁƒŁ„ صحيح، ŁŠŲ±Ų¬Ł‰ Ų§Ł„ŲŖŁˆŲ§ŲµŁ„ Ł…Ų¹ Ų§Ł„Ł…Ų³Ų¤ŁˆŁ„.",close:"؄غلاق",lastAssistantMessage:"Ų¢Ų®Ų± رسالة",fullBodyView:"Ų¹Ų±Ų¶ ŁƒŲ§Ł…Ł„ للجسم",upperBodyView:"Ų¹Ų±Ų¶ للجزؔ Ų§Ł„Ų¹Ł„ŁˆŁŠ",secureFormTitle:"Ł†Ł…ŁˆŲ°Ų¬ آمن",secureFormDescription:"أدخل Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ.",name:"الاسم*",namePlaceholder:"أدخل Ų§Ų³Ł…Łƒ",phoneNumber:"رقم الهاتف",phonePlaceholder:"أدخل رقم Ł‡Ų§ŲŖŁŁƒ",email:"Ų§Ł„ŲØŲ±ŁŠŲÆ Ų§Ł„Ų„Ł„ŁƒŲŖŲ±ŁˆŁ†ŁŠ",emailPlaceholder:"أدخل بريدك Ų§Ł„Ų„Ł„ŁƒŲŖŲ±ŁˆŁ†ŁŠ",secureFormNote:"لن ŲŖŲŖŁ… Ł…Ų“Ų§Ų±ŁƒŲ© Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ Ł…Ų¹ Ł†Ł…ŁˆŲ°Ų¬ اللغة ŁˆŁ„Ł† ŁŠŲŖŁ… ŲŖŲ®Ų²ŁŠŁ†Ł‡Ų§ ŲØŲ¹ŲÆ هذه الجلسة. بال؄رسال ŁŲ„Ł†Łƒ ŲŖŁˆŲ§ŁŁ‚ على Ł…Ų“Ų§Ų±ŁƒŲ© Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ Ł„Ł„Ų­ŲµŁˆŁ„ على دعم ؄ضافي.",save:"حفظ",send:"Ų„Ų±Ų³Ų§Ł„",cancel:"؄لغاؔ",conversationEndedPrompt:"انتهت المحادثة. ŁŠŲ±Ų¬Ł‰ ŲŖŁ‚ŁŠŁŠŁ… مدى رضاك.",submit:"Ų„Ų±Ų³Ų§Ł„",skip:"تخطي ŁˆŲ„Ł†Ł‡Ų§Ų”",consentTitle:"Ł…ŁˆŲ§ŁŁ‚Ų© على Ł…Ų­Ų§ŲÆŲ«Ų© Ų§Ł„Ų°ŁƒŲ§Ų” Ų§Ł„Ų§ŲµŲ·Ł†Ų§Ų¹ŁŠ",consentInfo1:"Ł„Ł„Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖ العامة فقط — ŲØŲÆŁˆŁ† نصائح طبية أو Ł‚Ų§Ł†ŁˆŁ†ŁŠŲ© أو Ł…Ų§Ł„ŁŠŲ© أو Ų£Ł…Ł†ŁŠŲ©.",consentInfo2:"نستخدم ŲŖŲ®Ų²ŁŠŁ† الجلسة ŁˆŁ†Ų±Ų³Ł„ Ł…ŲÆŲ®Ł„Ų§ŲŖŁƒ Ł„ŲŖŁ‚ŲÆŁŠŁ… Ų§Ł„Ų±ŲÆŁˆŲÆ. لا نحتفظ ŲØŁ…Ų­Ų§ŲÆŲ«ŲŖŁƒ أو ŲØŁŠŲ§Ł†Ų§ŲŖŁƒ Ų§Ł„Ų“Ų®ŲµŁŠŲ© ŲØŲ¹ŲÆ هذه الجلسة.",consentReadOur:"اقرأ",consentTermsLabel:"Ų§Ł„Ų“Ų±ŁˆŲ·",consentAnd:"و",consentPrivacyLabel:"سياسة Ų§Ł„Ų®ŲµŁˆŲµŁŠŲ©",consentMoreDetails:"Ł„Ł„Ł…Ų²ŁŠŲÆ من Ų§Ł„ŲŖŁŲ§ŲµŁŠŁ„.",consentInfo4:"(تنطبق Ł…ŁˆŲ§ŁŁ‚ŲŖŁƒ على جلسة التصفح Ų§Ł„Ų­Ų§Ł„ŁŠŲ© فقط ŁˆŁŠŲŖŁ… مسحها عند ؄غلاق الصفحة أو النافذة)",consentAccept:"Ų£ŁˆŲ§ŁŁ‚",consentDecline:"رفض",consentAcceptAria:"Ų£ŁˆŲ§ŁŁ‚ - Ų§ŲØŲÆŲ£ المحادثة",consentDeclineAria:"رفض",interruptSpeaking:"Ų„ŁŠŁ‚Ų§Ł الأفاتار Ų§Ł„Ł…ŲŖŁƒŁ„Ł…",turnOnMic:"ŲŖŲ“ŲŗŁŠŁ„ Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†",turnOffMic:"Ų„ŁŠŁ‚Ų§Ł Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†",tapToSpeak:"انقر للتحدث",thinking:"جاري Ų§Ł„ŲŖŁŁƒŁŠŲ±...",startConversationReminder:"Ų§ŲØŲÆŲ£ Ł…Ų­Ų§ŲÆŲ«Ų© للتحدث.",chatPlaceholderTitle:"Ł…Ų³ŲŖŲ¹ŲÆ Ł„Ł„ŲÆŲ±ŲÆŲ“Ų©ŲŸ",chatPlaceholderDescription:"Ų§ŲØŲÆŲ£ Ł…Ų­Ų§ŲÆŲ«Ų© للمتابعة في وضع النص.",enterInfoOnMobile:"أدخل Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖŁƒ في صفحة Ł…Ų¹Ł„ŁˆŁ…Ų§ŲŖ المستخدم",waitCurrentResponse:"ŁŠŲ±Ų¬Ł‰ انتظار الرد Ų§Ł„Ų­Ų§Ł„ŁŠ قبل Ų„Ų±Ų³Ų§Ł„ رسالة أخرى.",resumeConversationFailedNewStarted:"لم Ł†ŲŖŁ…ŁƒŁ† من استئناف Ł…Ų­Ų§ŲÆŲ«ŲŖŁƒ السابقة. ŲŖŁ… ŲØŲÆŲ” Ł…Ų­Ų§ŲÆŲ«Ų© جديدة بدلاً من Ų°Ł„Łƒ. ",end:"؄نهاؔ",endConversationPrompt:"هل ŲŖŲ±ŲŗŲØ في ؄نهاؔ Ų§Ł„Ł…Ų­Ų§ŲÆŲ«Ų©ŲŸ سيؤدي Ų°Ł„Łƒ ؄لى حذف المحادثة Ł†Ł‡Ų§Ų¦ŁŠŁ‹Ų§.",restartConversationPrompt:"هل أنت Ł…ŲŖŲ£ŁƒŲÆ من ŲØŲÆŲ” Ł…Ų­Ų§ŲÆŲ«Ų© جديدة؟ Ų³ŁŠŲŖŁ… حذف المحادثة Ų§Ł„Ų­Ų§Ł„ŁŠŲ©.",newConversation:"جديدة",conversationExpiredPrompt:"انتهت ŲµŁ„Ų§Ų­ŁŠŲ© هذه المحادثة ŁˆŁ„Ų§ ŁŠŁ…ŁƒŁ† استئنافها. هل تريد ŲŖŁ†Ų²ŁŠŁ„ نسخة Ų«Ł… حذفها أو الحذف ŁŁ‚Ų·ŲŸ",conversationExpiredResumePrompt:"انتهت ŲµŁ„Ų§Ų­ŁŠŲ© Ł…Ų­Ų§ŲÆŲ«ŲŖŁƒ السابقة ŁˆŁ„Ų§ ŁŠŁ…ŁƒŁ† استئنافها. هل ŲŖŲ±ŲŗŲØ في ŲŖŁ†Ų²ŁŠŁ„ نسخة من سجل Ų§Ł„Ł…Ų­Ų§ŲÆŲ«Ų©ŲŸ",downloadAndClear:"ŲŖŁ†Ų²ŁŠŁ„ وحذف",downloadAndStartNew:"ŲŖŁ†Ų²ŁŠŁ„ وبدؔ جديدة",startNew:"ŲØŲÆŲ” جديدة",onlyClear:"حذف فقط",confirm:"تأكيد",ok:"Ł…ŁˆŲ§ŁŁ‚",download:"ŲŖŁ†Ų²ŁŠŁ„",alertGenericError:"Ų­ŲÆŲ« Ų®Ų·Ų£.",alertFailedEndConversation:"فؓل في ؄نهاؔ المحادثة. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertFailedClearConversation:"فؓل في Ł…Ų³Ų­ المحادثة.",alertCouldNotStartListening:"ŲŖŲ¹Ų°Ų± ŲØŲÆŲ” الاستماع. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertSomeErrorOccurred:"Ų­ŲÆŲ« Ų®Ų·Ų£ Ł…Ų§. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertWaitForAIResponse:"ŁŠŲ±Ų¬Ł‰ انتظار Ų±ŲÆ Ų§Ł„Ų°ŁƒŲ§Ų” Ų§Ł„Ų§ŲµŲ·Ł†Ų§Ų¹ŁŠ قبل البدؔ في التحدث.",alertVoiceServicesUnavailable:"ŲŖŲ¹Ų°Ų± الاتصال ŲØŲ®ŲÆŁ…Ų§ŲŖ Ų§Ł„ŲµŁˆŲŖ. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© لاحقاً.",alertServiceTemporarilyUnavailable:"الخدمة غير Ł…ŲŖŲ§Ų­Ų© مؤقتاً. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertTooManyRequests:"طلبات متزامنة كثيرة Ų¬ŲÆŲ§Ł‹. ŁŠŲ±Ų¬Ł‰ الانتظار لحظة ŁˆŲ§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertConnectionIssue:"ŲŖŁ… اكتؓاف Ł…Ų“ŁƒŁ„Ų© في الاتصال. ŁŠŲ±Ų¬Ł‰ التحقق من Ų§ŲŖŲµŲ§Ł„Łƒ بال؄نترنت ŁˆŲ§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertResponseTimeout:"انتهت مهلة الاستجابة. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertServiceBusy:"Ų®ŲÆŁ…Ų© Ų§Ł„ŲµŁˆŲŖ Ł…Ų“ŲŗŁˆŁ„Ų© Ų­Ų§Ł„ŁŠŲ§Ł‹. ŁŠŲ±Ų¬Ł‰ Ų§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© ŲØŲ¹ŲÆ ŲØŲ¶Ų¹ دقائق.",alertMicrophoneStartFailed:"ŲŖŲ¹Ų°Ų± ŲØŲÆŲ” الاستماع. تأكد من أن Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ† ŁŠŲ¹Ł…Ł„.",alertMicrophoneCheckSettings:"ŲŖŲ¹Ų°Ų± ŲØŲÆŲ” الاستماع. ŁŠŲ±Ų¬Ł‰ التحقق من Ų„Ų¹ŲÆŲ§ŲÆŲ§ŲŖ Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†.",alertSpeechRecognitionSetupFailed:"فؓل Ų„Ų¹ŲÆŲ§ŲÆ التعرف على Ų§Ł„ŁƒŁ„Ų§Ł…. ŁŠŲ±Ų¬Ł‰ تحديث الصفحة ŁˆŲ§Ł„Ł…Ų­Ų§ŁˆŁ„Ų© Ł…Ų±Ų© أخرى.",alertMicrophoneAccessDenied:"ŲŖŁ… رفض Ų§Ł„ŁˆŲµŁˆŁ„ ؄لى Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†. ŁŠŲ±Ų¬Ł‰ السماح ŲØŲ§Ł„ŁˆŲµŁˆŁ„ ؄لى Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ† في Ų„Ų¹ŲÆŲ§ŲÆŲ§ŲŖ المتصفح وتحديث الصفحة.",alertNoMicrophoneDetected:"لم ŁŠŲŖŁ… اكتؓاف Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†. ŁŠŲ±Ų¬Ł‰ ŲŖŁˆŲµŁŠŁ„ Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ† وتحديث الصفحة.",alertMicrophoneError:"Ų®Ų·Ų£ في Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†. ŁŠŲ±Ų¬Ł‰ التحقق من Ų§Ł„Ł…ŁŠŁƒŲ±ŁˆŁŁˆŁ†."},zh:{start:"å¼€å§‹åÆ¹čÆ",connect:"čæžęŽ„",endConversation:"ē»“ęŸåÆ¹čÆ",restartConversation:"é‡ę–°å¼€å§‹åÆ¹čÆ",hideTyping:"éšč—č¾“å…„ę”†",showTyping:"ę˜¾ē¤ŗč¾“å…„ę”†",reconnecting:"ę­£åœØé‡ę–°čæžęŽ„...",waitForResponse:"čÆ·ē­‰å¾…å›žå¤...",typeHere:"åœØę­¤č¾“å…„ć€‚",noMessagesYet:"ęš‚ę— ę¶ˆęÆ...",conversationStatus:"åÆ¹čÆēŠ¶ę€",conversationInProgress:"åÆ¹čÆčæ›č”Œäø­",conversationStopped:"åÆ¹čÆå·²åœę­¢",startConversation:"å¼€å§‹åÆ¹čÆ",downloadConversation:"äø‹č½½åÆ¹čÆ",liveCaptions:"å®žę—¶å­—å¹•",toggleChatbot:"显示/éšč—č™šę‹Ÿå½¢č±”åŠ©ę‰‹",avatar:"č™šę‹Ÿå½¢č±”",switchToAvatar:"čæ”å›žč™šę‹Ÿå½¢č±”",switchToChat:"åˆ‡ę¢åˆ°čŠå¤©",chat:"聊天",statusInitializing:"čÆ·ēØå€™ļ¼Œęˆ‘ä»¬ę­£åœØå”¤é†’č™šę‹Ÿå½¢č±”ļ¼",statusReconnecting:"čæžęŽ„å‡ŗēŽ°é—®é¢˜ļ¼Œę­£åœØå°čÆ•é‡ę–°čæžęŽ„...",statusFailed:"čæžęŽ„å¤±č“„ć€‚åÆčƒ½éœ€č¦ę‰‹åŠØå¤„ē†ć€‚",statusInvalidConfiguration:"č™šę‹Ÿå½¢č±”é…ē½®äøę­£ē”®ļ¼ŒčÆ·č”ē³»ē®”ē†å‘˜ć€‚",close:"关闭",lastAssistantMessage:"åŠ©ę‰‹ēš„äøŠäø€ę”ę¶ˆęÆ",fullBodyView:"全身视图",upperBodyView:"åŠčŗ«č§†å›¾",secureFormTitle:"å®‰å…Øč”Øå•",secureFormDescription:"čÆ·č¾“å…„ę‚Øēš„äæ”ęÆć€‚",name:"姓名*",namePlaceholder:"čÆ·č¾“å…„å§“å",phoneNumber:"ē”µčÆå·ē ",phonePlaceholder:"čÆ·č¾“å…„ē”µčÆå·ē ",email:"电子邮件",emailPlaceholder:"请输兄电子邮件",secureFormNote:"ę‚Øēš„äæ”ęÆäøä¼šäøŽå¤§čÆ­čØ€ęØ”åž‹å…±äŗ«ļ¼Œä¼ščÆē»“ęŸåŽä¹Ÿäøä¼šč¢«å­˜å‚Øć€‚å‘é€å³č”Øē¤ŗę‚ØåŒę„å…±äŗ«ę‚Øēš„äæ”ęÆä»„čŽ·å¾—é¢å¤–ę”ÆęŒć€‚",save:"äæå­˜",send:"发送",cancel:"å–ę¶ˆ",conversationEndedPrompt:"åÆ¹čÆå·²ē»“ęŸć€‚čÆ·čÆ„ä»·ę‚Øēš„ę»”ę„åŗ¦ć€‚",submit:"ęäŗ¤",skip:"č·³čæ‡å¹¶ē»“ęŸ",consentTitle:"åŒę„čæ›č”Œäŗŗå·„ę™ŗčƒ½åÆ¹čÆ",consentInfo1:"ä»…ä¾›äø€čˆ¬äæ”ęÆå‚č€ƒā€”ā€”äøęä¾›åŒ»ē–—ć€ę³•å¾‹ć€č“¢åŠ”ęˆ–å®‰å…Øå»ŗč®®ć€‚",consentInfo2:"ęˆ‘ä»¬ä½æē”Øä¼ščÆå­˜å‚Øå¹¶å‘é€ę‚Øēš„č¾“å…„ä»„ęä¾›å›žå¤ć€‚ęœ¬ę¬”ä¼ščÆē»“ęŸåŽęˆ‘ä»¬äøä¼šäæē•™ę‚Øēš„åÆ¹čÆęˆ–äøŖäŗŗäæ”ęÆć€‚",consentReadOur:"é˜…čÆ»ęˆ‘ä»¬ēš„",consentTermsLabel:"ę”ę¬¾",consentAnd:"和",consentPrivacyLabel:"éšē§ę”æē­–",consentMoreDetails:"äŗ†č§£ę›“å¤ščÆ¦ęƒ…ć€‚",consentInfo4:"ļ¼ˆę‚Øēš„åŒę„ä»…é€‚ē”ØäŗŽęœ¬ę¬”ä¼ščÆļ¼Œå…³é—­ę ‡ē­¾é”µęˆ–ēŖ—å£åŽå°†č¢«ęø…é™¤ļ¼‰",consentAccept:"åŒę„",consentDecline:"ę‹’ē»",consentAcceptAria:"åŒę„ā€”ā€”å¼€å§‹čŠå¤©",consentDeclineAria:"ę‹’ē»",interruptSpeaking:"ę‰“ę–­č™šę‹Ÿå½¢č±”č®²čÆ",turnOnMic:"å¼€åÆéŗ¦å…‹é£Ž",turnOffMic:"å…³é—­éŗ¦å…‹é£Ž",tapToSpeak:"ē‚¹å‡»čÆ“čÆ",thinking:"ę€č€ƒäø­...",startConversationReminder:"å¼€å§‹åÆ¹čÆä»„ä¾æčŠå¤©ć€‚",chatPlaceholderTitle:"å‡†å¤‡å„½čŠå¤©äŗ†å—ļ¼Ÿ",chatPlaceholderDescription:"å¼€å§‹åÆ¹čÆä»„ē»§ē»­ä½æē”Øę–‡å­—ęØ”å¼ć€‚",enterInfoOnMobile:"čÆ·åœØē”Øęˆ·äæ”ęÆé”µé¢č¾“å…„ę‚Øēš„äæ”ęÆ",waitCurrentResponse:"čÆ·ē­‰å¾…å½“å‰å›žå¤åŽå†å‘é€ę–°ę¶ˆęÆć€‚",resumeConversationFailedNewStarted:"ęˆ‘ä»¬ę— ę³•ę¢å¤ę‚Øä¹‹å‰ēš„åÆ¹čÆć€‚å·²åÆåŠØäø€äøŖę–°ēš„åÆ¹čÆć€‚",end:"ē»“ęŸ",endConversationPrompt:"ę˜Æå¦ē»“ęŸåÆ¹čÆļ¼Ÿē»“ęŸåŽå°†ę°øä¹…åˆ é™¤åŽ†å²č®°å½•ć€‚",restartConversationPrompt:"ē”®å®šč¦å¼€å§‹ę–°ēš„åÆ¹čÆå—ļ¼Ÿå½“å‰åÆ¹čÆå°†č¢«åˆ é™¤ć€‚",newConversation:"ꖰ",conversationExpiredPrompt:"ę­¤åÆ¹čÆå·²čæ‡ęœŸäø”ę— ę³•ę¢å¤ć€‚ę‚Øč¦äø‹č½½å‰Æęœ¬å¹¶ęø…é™¤ļ¼Œčæ˜ę˜Æä»…ęø…é™¤ļ¼Ÿ",conversationExpiredResumePrompt:"ę‚Øä¹‹å‰ēš„åÆ¹čÆå·²čæ‡ęœŸäø”ę— ę³•ę¢å¤ć€‚ę‚Øę˜Æå¦č¦äø‹č½½åÆ¹čÆč®°å½•ēš„å‰Æęœ¬ļ¼Ÿ",downloadAndClear:"下载并清除",downloadAndStartNew:"äø‹č½½å¹¶å¼€å§‹ę–°åÆ¹čÆ",startNew:"å¼€å§‹ę–°åÆ¹čÆ",onlyClear:"仅清除",confirm:"甮认",ok:"甮定",download:"äø‹č½½",alertGenericError:"å‘ē”Ÿé”™čÆÆć€‚",alertFailedEndConversation:"ę— ę³•ē»“ęŸåÆ¹čÆć€‚čÆ·é‡čÆ•ć€‚",alertFailedClearConversation:"ę— ę³•ęø…é™¤åÆ¹čÆć€‚",alertCouldNotStartListening:"ę— ę³•å¼€å§‹č†å¬ć€‚čÆ·é‡čÆ•ć€‚",alertSomeErrorOccurred:"å‘ē”Ÿäŗ†é”™čÆÆć€‚čÆ·é‡čÆ•ć€‚",alertWaitForAIResponse:"请等待AIå›žå¤åŽå†å¼€å§‹čÆ“čÆć€‚",alertVoiceServicesUnavailable:"ę— ę³•čæžęŽ„åˆ°čÆ­éŸ³ęœåŠ”ć€‚čÆ·ēØåŽé‡čÆ•ć€‚",alertServiceTemporarilyUnavailable:"ęœåŠ”ęš‚ę—¶äøåÆē”Øć€‚čÆ·é‡čÆ•ć€‚",alertTooManyRequests:"åŒę—¶čÆ·ę±‚čæ‡å¤šć€‚čÆ·ēØē­‰ē‰‡åˆ»åŽé‡čÆ•ć€‚",alertConnectionIssue:"ę£€ęµ‹åˆ°čæžęŽ„é—®é¢˜ć€‚čÆ·ę£€ęŸ„ę‚Øēš„ē½‘ē»œčæžęŽ„åŽé‡čÆ•ć€‚",alertResponseTimeout:"å“åŗ”č¶…ę—¶ć€‚čÆ·é‡čÆ•ć€‚",alertServiceBusy:"čÆ­éŸ³ęœåŠ”å½“å‰ē¹åæ™ć€‚čÆ·å‡ åˆ†é’ŸåŽé‡čÆ•ć€‚",alertMicrophoneStartFailed:"ę— ę³•å¼€å§‹č†å¬ć€‚čÆ·ē”®äæę‚Øēš„éŗ¦å…‹é£Žę­£åøøå·„ä½œć€‚",alertMicrophoneCheckSettings:"ę— ę³•å¼€å§‹č†å¬ć€‚čÆ·ę£€ęŸ„ę‚Øēš„éŗ¦å…‹é£Žč®¾ē½®ć€‚",alertSpeechRecognitionSetupFailed:"čÆ­éŸ³čÆ†åˆ«č®¾ē½®å¤±č“„ć€‚čÆ·åˆ·ę–°é”µé¢åŽé‡čÆ•ć€‚",alertMicrophoneAccessDenied:"éŗ¦å…‹é£Žč®æé—®č¢«ę‹’ē»ć€‚čÆ·åœØęµč§ˆå™Øč®¾ē½®äø­å…č®øéŗ¦å…‹é£Žč®æé—®å¹¶åˆ·ę–°é”µé¢ć€‚",alertNoMicrophoneDetected:"ęœŖę£€ęµ‹åˆ°éŗ¦å…‹é£Žć€‚čÆ·čæžęŽ„éŗ¦å…‹é£Žå¹¶åˆ·ę–°é”µé¢ć€‚",alertMicrophoneError:"éŗ¦å…‹é£Žé”™čÆÆć€‚čÆ·ę£€ęŸ„ę‚Øēš„éŗ¦å…‹é£Žć€‚"}};function St(t,e){const i=function(t){if(!t||"string"!=typeof t)return ft;const e=t.toLowerCase();if(yt[e])return e;const i=e.split("-")[0];return yt[i]?i:ft}(t),a=yt[i]?.[e];return void 0!==a?a:yt[ft]?.[e]??e}class wt{constructor(t,e,i){this.bus=t,this.dismissableContainer=e,this._getLanguage=i||(()=>"en"),this.dismissableAlerts=new Map,this.bus.on("event_command_Alerts_ShowDismissableAlert",(t=>{let e;e=t?.messageKey?St(this._getLanguage(),t.messageKey):t?.errorMessage||St(this._getLanguage(),"alertGenericError");const i=t?.className||"alert-danger";this.showDismissableAlert(e,i)}))}showDismissableAlert(t,e){if(this.dismissableAlerts.has(t))return;if(this.dismissableAlerts.size>=T.alerts.maxAlerts){const t=this.dismissableAlerts.keys().next().value,e=this.dismissableAlerts.get(t);e&&(e.hideToast(),this.dismissableAlerts.delete(t))}const i=y({text:t,duration:T.alerts.dismissableAlertDuration,close:!0,gravity:"top",position:"left",stopOnFocus:!0,className:`alert ${e}`,selector:this.dismissableContainer,callback:()=>{this.dismissableAlerts.delete(t)}});i.showToast(),this.dismissableAlerts.set(t,i)}}const kt=t=>/[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/.test(t);class Ct{#o=null;#r="wakeLock"in navigator;get isActive(){return!!this.#o}get isSupported(){return this.#r}async request(){const t="undefined"!=typeof process&&process.env&&"test"===process.env.NODE_ENV,e="undefined"!=typeof document&&"visible"===document.visibilityState;if(this.#r&&!this.isActive&&!t&&e)try{this.#o=await navigator.wakeLock.request("screen"),this.#o.addEventListener("release",(()=>{this.#o=null}))}catch(i){}}async release(){try{await(this.#o?.release())}finally{this.#o=null,this.#r}}}const At=v`
2
2
  <svg version="1.0" xmlns="http://www.w3.org/2000/svg"
3
3
  width="25px" height="30.42px" viewBox="0 0 1052.000000 1280.000000"
4
4
  preserveAspectRatio="xMidYMid meet">
@@ -35,7 +35,7 @@ l-27 -54 -215 -119 c-332 -184 -779 -441 -1170 -671 -1067 -630 -1651 -1038
35
35
  38 -116 36 -205 22 -276 -44 -24 -22 -33 -24 -104 -20 -61 3 -82 8 -99 24 -46
36
36
  44 -132 65 -207 52z"/>
37
37
  </g>
38
- </svg>`,xt=m`
38
+ </svg>`,xt=v`
39
39
  <svg version="1.0" xmlns="http://www.w3.org/2000/svg"
40
40
  width="25px" height="50px" viewBox="0 0 640.000000 1280.000000"
41
41
  preserveAspectRatio="xMidYMid meet">
@@ -77,7 +77,7 @@ c94 101 142 246 150 447 4 107 9 144 25 178 19 40 20 50 9 155 -26 245 -121
77
77
  -58 374 -80 470 -16 70 -11 137 41 539 l29 220 6 -230 c4 -126 12 -275 19
78
78
  -330z"/>
79
79
  </g>
80
- </svg>`,Tt=m`
80
+ </svg>`,Tt=v`
81
81
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 304" aria-hidden="true" focusable="false">
82
82
  <path fill="currentColor" opacity="1.000000" stroke="none"
83
83
  d="
@@ -173,7 +173,7 @@ M138.709229,129.454376
173
173
  C109.740639,131.054550 114.375092,127.080360 120.324982,124.957504
174
174
  C127.137169,122.526985 133.365952,123.659859 138.709229,129.454376
175
175
  z"/>
176
- </svg>`,It=m`
176
+ </svg>`,It=v`
177
177
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="80" height="80" aria-hidden="true" focusable="false">
178
178
  <!-- Main chat bubble -->
179
179
  <rect x="10" y="15" width="55" height="40" rx="8" ry="8" fill="currentColor" opacity="0.15"/>
@@ -183,21 +183,21 @@ z"/>
183
183
  <circle cx="25" cy="35" r="4" fill="currentColor" opacity="0.4"/>
184
184
  <circle cx="38" cy="35" r="4" fill="currentColor" opacity="0.4"/>
185
185
  <circle cx="51" cy="35" r="4" fill="currentColor" opacity="0.4"/>
186
- </svg>`,Et=Tt,Mt=m`<span class="material-icons">delete</span>`,Dt=m`<span class="material-icons last-message-icon">chat_bubble</span>`,Rt=m`<span class="material-icons">refresh</span>`,Pt=m`<span class="material-icons">send</span>`,Ot=m`<span class="material-icons chat-bubble-icon">chat_bubble</span>`,Lt=m`<span class="material-icons">close</span>`,Bt=m`<span class="material-icons">menu</span>`,Nt=m`<span class="material-icons error-icon">error</span>`,zt=m`<span class="material-icons"> content_copy</span>`,Ft=m`<span class="material-icons">check</span>`,$t=t=>m`
186
+ </svg>`,Et=Tt,Mt=v`<span class="material-icons">call_end</span>`,Dt=v`<span class="material-icons last-message-icon">history</span>`,Rt=v`<span class="material-icons switch-chat-icon">chat</span>`,Pt=v`<span class="material-icons">refresh</span>`,Ot=v`<span class="material-icons">send</span>`,Lt=v`<span class="material-icons chat-bubble-icon">chat_bubble</span>`,Bt=v`<span class="material-icons">close</span>`,Nt=v`<span class="material-icons">menu</span>`,zt=v`<span class="material-icons error-icon">error</span>`,Ft=v`<span class="material-icons"> content_copy</span>`,$t=v`<span class="material-icons">check</span>`,Vt=v`<span class="material-icons">keyboard</span>`,Ut=t=>v`
187
187
  <div class="button-container">
188
188
  <button @click="${t._handleStartConversationBtn}" type="button" class="btn start-button" id="start_conversation_button" title="${t._t("start")}">${t._t("start")}</button>
189
189
  </div>
190
- `,Vt=t=>m`
190
+ `,Ht=t=>v`
191
191
  <div class="button-container">
192
192
  <button @click="${t._handleConnectBtn}" type="button" class="btn-lg start-button" id="connect_button" title="${t._t("connect")}">${t._t("connect")}</button>
193
- </div>`,Ut=t=>{const e=(t=>t._isConversationPaused?"paused":t._isSpeaking?"speaking":t._isThinking?"thinking":t._isListening?"listening":"idle")(t),i=((t,e)=>{switch(e){case"paused":return t._t("reconnecting");case"speaking":return t._t("interruptSpeaking");case"thinking":return t._t("waitForResponse");case"listening":return t._t("turnOffMic");default:return t._t("turnOnMic")}})(t,e),n=t._inputsBlocked&&"idle"===e,a="paused"===e,s="idle"===e&&!n;return m`
193
+ </div>`,jt=t=>{const e=(t=>t._isConversationPaused?"paused":t._isSpeaking?"speaking":t._isThinking?"thinking":t._isListening?"listening":"idle")(t),i=((t,e)=>{switch(e){case"paused":return t._t("reconnecting");case"speaking":return t._t("interruptSpeaking");case"thinking":return t._t("waitForResponse");case"listening":return t._t("turnOffMic");default:return t._t("turnOnMic")}})(t,e),a=t._inputsBlocked&&"idle"===e,n="paused"===e,s="idle"===e&&!a;return v`
194
194
  <div class="voice-visualizer-wrapper">
195
195
  <div
196
- class="voice-visualizer state-${e} ${n||a?"visualizer-disabled":""}"
197
- @click="${n||a?_:t._handleMicBtn}"
196
+ class="voice-visualizer state-${e} ${a||n?"visualizer-disabled":""}"
197
+ @click="${a||n?_:t._handleMicBtn}"
198
198
  title="${i}"
199
199
  role="button"
200
- tabindex="${n||a?-1:0}"
200
+ tabindex="${a||n?-1:0}"
201
201
  aria-label="${i}"
202
202
  >
203
203
  <div class="audio-bar"></div>
@@ -206,16 +206,141 @@ z"/>
206
206
  <div class="audio-bar"></div>
207
207
  <div class="audio-bar"></div>
208
208
  </div>
209
- ${s?m`<span class="visualizer-hint">${t._t("tapToSpeak")}</span>`:_}
209
+ ${s?v`<span class="visualizer-hint">${t._t("tapToSpeak")}</span>`:_}
210
210
  </div>
211
- `},Ht=t=>{const e=t._isConversationInProgress;return m`
211
+ `},Wt=t=>v`
212
+ <div id="chatbot-container" class="${t._showChatbot||!t.toggler?"show-chatbot":""}${t.toggler?"":" embedded"}">
213
+ ${t.toggler?(t=>v`
214
+ <button id="chatbot-toggler" @click="${t._handleToggleChatbot}" aria-label="${t._t("toggleChatbot")}">
215
+ ${Et}
216
+ ${Bt}
217
+ </button>
218
+ `)(t):_}
219
+ ${t._stateTestMode?(t=>{const e=t._actorSnapshot,i="function"==typeof t.initStatus?t.initStatus():"UNKNOWN",a=!!t._isStartingConversation,n=!!t._isInitializingConversation,s=!!t._isConversationInProgress,o=!!t._isConversationPaused,r=!!t._isAutoResuming,c=!!t._isConversationStopped,l=!!t._isFailed,h=l?"FAILED":a?"STARTING":n?"INITIALIZING":s?"IN_PROGRESS":o?"PAUSED":r?"AUTO_RESUMING":c?"STOPPED":"CLEARED",d=!!t._isSpeaking,u=!!t._isThinking||!!t._isStartingConversation,p=s&&!d&&!u&&!t._isListening,g=!!t._isListening,m=d?"speaking":u?"thinking":g?"listening":p?"idle":a?"startingConversation":"",b=!!t._inputsBlocked||u,f=t._speakingAvatar?.connectionManager,y=!0===f?.allConnectionsReady,S=!!t._isDisconnected,w=y?"connected":S?"disconnected":l?"recovering":"connecting",k=function(t){const e=t?.value;if(!e)return"";const i=(t,e=[])=>{if("string"==typeof t)return[e.concat(t).join(".")];if(t&&"object"==typeof t){const a=[];for(const n of Object.keys(t))a.push(...i(t[n],e.concat(n)));return a}return[]};try{return i(e).join(" | ")}catch(a){try{return JSON.stringify(e)}catch{return String(e)}}}(e),C=!t.toggler||t._showChatbot,A="AvatarPage"===t._shownPage?"AVATAR":"CHAT",x=e?.context?.chatSocket?.chatbotMode||"unknown";return v`
220
+ <div class="test-mode-states">
221
+ <div><b>FSM</b>: ${k||"(no state)"}</div>
222
+ <div><b>UI</b>: Chatbot Visible=${String(C)}, Mode (UI → FSM)=${A} → ${x}</div>
223
+ <div>Initialization: ${i}</div>
224
+ <div>Conversation: ${h}</div>
225
+ <div>Substate: ${m}</div>
226
+ <div>AvatarRunning: ${String(t._avatarRunning)}</div>
227
+ <div>InputsBlocked: ${b}</div>
228
+ <div>isPageVisible: ${t._actorSnapshot?.context?.isPageVisible}</div>
229
+ <div>pendingStart: ${String(t._actorSnapshot?.context?.pendingStart)}</div>
230
+ <div>Connection: ${w}</div>
231
+ <pre style="white-space: pre-wrap; margin: 4px 0;">${f?.getConnectionReport?.()}</pre>
232
+ <div style="display:flex; flex-wrap: wrap; gap: 6px; width:50%;">
233
+ <button @click="${()=>t._testSetAuthConnected("disconnected")}">Disconnect Auth</button>
234
+ <button @click="${()=>t._testSetAuthConnected("failed")}">Fail Auth</button>
235
+ <button @click="${()=>t._testSetAuthConnected()}">Connect Auth</button>
236
+ <button @click="${()=>t._testSetSocketConnected("disconnected")}">Disconnect Socket</button>
237
+ <button @click="${()=>t._testSetSocketConnected("failed")}">Fail Socket</button>
238
+ <button @click="${()=>t._testSetSocketConnected()}">Connect Socket</button>
239
+ <button @click="${()=>t._testSetSpeechConnected("disconnected")}">Disconnect Speech</button>
240
+ <button @click="${()=>t._testSetSpeechConnected("failed")}">Fail Speech</button>
241
+ <button @click="${()=>t._testSetSpeechConnected()}">Connect Speech</button>
242
+ ${f?.reconnectFailedModules?v`<button @click="${()=>f.reconnectFailedModules(!0)}">Reconnect Failed</button>`:_}
243
+ ${f?.reconnectDisconnectedModules?v`<button @click="${()=>f.reconnectDisconnectedModules()}">Reconnect All</button>`:_}
244
+ </div>
245
+ </div>
246
+ `})(t):_}
247
+ ${(()=>_)()}
248
+ <div
249
+ class="chatbot ${t.target_app} ${t.compact?"compact":""}"
250
+ @click="${t._handleChatbotClick}"
251
+ style="
252
+ ${t.toggler||"mobile"===t.target_app?`width: ${t._canvasWidth}px; height: ${"mobile"===t.target_app||t.toggler&&window.innerWidth<768?"calc(var(--chatbot-dynamic-height) - var(--chatbot-bottom-offset, 0px))":`${t._chatbotHeight}px`};`:`width: 100%; height: ${t._chatbotHeight}px;`}
253
+ "
254
+ >
255
+ ${t.compact?_:(t=>v`
256
+ <header @click="${t=>t.stopPropagation()}">
257
+ <div class="header-container">
258
+ <div class="header-left">
259
+ <div class="menu-icon" @click="${t._handleToggleMenu}">
260
+ ${t._showMenu?Bt:Nt}
261
+ </div>
262
+ ${(t=>{const e=t._isConversationInProgress,i=t._isStartingConversation||t._isInitializingConversation,a=t._isConversationStopped,n=t._isAutoResuming;return v`
263
+ ${t._showMenu?v`<div class="menu-backdrop" @click="${t._handleToggleMenu}"></div>`:null}
264
+ <div id="menu" class="${t._showMenu?"show":"hide"}">
265
+ <div class="menu-items" >
266
+ <div class="conversation-details">
267
+ <span class="conversation-status" title="${t._t("conversationStatus")}">${e?v`<small>${t._t("conversationInProgress")}</small>`:v`<small>${t._t("conversationStopped")}</small>`}</span>
268
+ </div>
269
+ <div ?hidden=${!a||e||i||n}>
270
+ <button type="button" class="menu-button" @click="${t._handleStartConversationMenuBtn}">${t._t("startConversation")}</button>
271
+ </div>
272
+ <div ?hidden=${!e}>
273
+ <button type="button" class="menu-button" @click="${t._handleEndConversationBtn}">${t._t("endConversation")}</button>
274
+ </div>
275
+ <hr>
276
+ <div ?hidden=${!t._canDownloadTranscript()}>
277
+ <button type="button" class="menu-button" @click="${t._handleDownloadTranscriptMenuBtn}">${t._t("downloadConversation")}</button>
278
+ </div>
279
+ <div class="labels-container">
280
+ <label>${t._t("liveCaptions")}</label>
281
+ <label class="captions-switch">
282
+ <input type="checkbox" .checked=${t.enable_captions} @click="${t._handleToggleCaptionsSwitch}">
283
+ <span class="captions-slider round"></span>
284
+ </label>
285
+ </div>
286
+ <div class="menu-switch-container">
287
+ ${(t=>"AvatarPage"===t._shownPage||"ChatPage"===t._shownPage?v`
288
+ <div class="switches-container" dir="ltr">
289
+ <input type="radio" id="switchAvatar" name="switchMode" value="Avatar" .checked=${"AvatarPage"===t._shownPage} />
290
+ <input type="radio" id="switchChat" name="switchMode" value="Chat" .checked=${"ChatPage"===t._shownPage}/>
291
+ <label for="switchAvatar" @click="${t._handleShowAvatarPage}">${t._t("avatar")}</label>
292
+ <label for="switchChat" @click="${t._handleShowChatPage}">${t._t("chat")}</label>
293
+ <div class="switch-wrapper">
294
+ <div class="switch">
295
+ <div>${t._t("avatar")}</div>
296
+ <div>${t._t("chat")}</div>
297
+ </div>
298
+ </div>
299
+ </div>
300
+ `:_)(t)}
301
+ </div>
302
+ </div>
303
+ </div>
304
+ `})(t)}
305
+ </div>
306
+ <div class="header-center">
307
+ <h3 id="avatar-name">${t._avatarName}</h3>
308
+ </div>
309
+ <div class="header-right">
310
+ ${t.brand_logo?v`
311
+ <div>
312
+ <img src="${t.brand_logo}" class="logo-image">
313
+ </div>
314
+ `:_}
315
+ </div>
316
+ </div>
317
+ </header>
318
+ `)(t)}
319
+
320
+ <div
321
+ class="chatbot-body ${"ChatPage"===t._shownPage?"chat-mode":""} ${t.target_app} ${t.compact?"compact":""}"
322
+ >
323
+ ${(t=>{const e=t._statusBarStatus;if(!e||"connected"===e)return _;const i={initializing:t._t("statusInitializing"),disconnected:t._t("statusReconnecting"),recovering:t._t("statusReconnecting"),failed:t._t("statusFailed"),invalidConfiguration:t._t("statusInvalidConfiguration")}[e]||"";return i?v`
324
+ <div class="status-bar status--${e}" role="status">
325
+ ${i}
326
+ </div>
327
+ `:_})(t)}
328
+ <div id="toastify-dismissable-alerts"></div>
329
+ ${(t=>"LoaderPage"===t._shownPage?v`
330
+ <div class="page-wrapper" id="loader_page">
331
+ <div class="page-center">
332
+ <div class="lds-dual-ring"></div>
333
+ </div>
334
+ </div>
335
+ `:_)(t)}
336
+ ${(t=>(t._isConversationInProgress,v`
212
337
  <div class="page-wrapper avatar-wrapper" id="avatar-page" ?hidden=${"AvatarPage"!==t._shownPage}>
213
338
  <div class="avatarbox">
214
339
  <div id="avatar-container" style=${S(t._getAvatarBackgroundStyleObj())}></div>
215
- ${(t=>m`
216
- ${t._isLiveCaptionsVisible&&t._liveCaption&&""!==t._liveCaption.trim()?m`
340
+ ${(t=>v`
341
+ ${t._isLiveCaptionsVisible&&t._liveCaption&&""!==t._liveCaption.trim()?v`
217
342
  <div id="captions-wrapper" class="center-aligned">
218
- <div class="${"assistant"===t._liveCaptionSpeaker?"assistant-live-caption":"user-live-caption"}" style="direction: ${Ct(t._liveCaption)?"rtl":"ltr"}" @click="${t._openLastMessage}">
343
+ <div class="${"assistant"===t._liveCaptionSpeaker?"assistant-live-caption":"user-live-caption"}" style="direction: ${kt(t._liveCaption)?"rtl":"ltr"}" @click="${t._openLastMessage}">
219
344
  <div class="caption-content ${t._liveCaption.split(" ").length>5?"long-text":t._liveCaption.length<10?"short-text":""}">
220
345
  <span class="${"assistant"===t._liveCaptionSpeaker?"caption-highlight":""}">${t._liveCaption}</span>
221
346
  </div>
@@ -223,37 +348,40 @@ z"/>
223
348
  </div>
224
349
  `:_}
225
350
  `)(t)}
226
- ${e?(t=>m`
351
+ ${(t=>{const e=t._isConversationInProgress;return v`
227
352
  <div class="conversation-buttons-overlay">
228
- ${(t=>m`
353
+ ${e?(t=>v`
229
354
  <button @click="${t._handleEndConversationBtn}" type="button" title="${t._t("endConversation")}" class="secondary-button stop-button">
230
355
  ${Mt}
231
356
  </button>
232
- `)(t)}
233
- ${(t=>m`
357
+ `)(t):_}
358
+ ${e?(t=>v`
234
359
  <button @click="${t._handleRestartConversation}" type="button" class="secondary-button restart-button" id="restart_button" title="${t._t("restartConversation")}">
235
- ${Rt}
236
- </button>
237
- `)(t)}
238
- ${(t=>m`
239
- <button
240
- @click="${t._handleToggleTyping}"
241
- class="secondary-button input-toggle-button"
242
- >
243
- ${t._showTyping?(t=>m`<span title="${t._t("hideTyping")}" class="material-icons">keyboard_hide</span>`)(t):(t=>m`<span title="${t._t("showTyping")}" class="material-icons">keyboard</span>`)(t)}
360
+ ${Pt}
244
361
  </button>
245
- `)(t)}
246
- ${(t=>{const e=t._currentMessage,i=e&&"string"==typeof e.messageText&&""!==e.messageText.trim();return m`
247
- ${i?m`
362
+ `)(t):_}
363
+ ${e?(t=>{const e=t._currentMessage,i=e&&"string"==typeof e.messageText&&""!==e.messageText.trim();return v`
364
+ ${i?v`
248
365
  <div @click="${t._openLastMessage}" class="last-message-button" title="${t._t("lastAssistantMessage")}">
249
366
  ${Dt}
250
367
  </div>
251
368
  `:_}
252
- `})(t)}
369
+ `})(t):_}
370
+ ${(t=>v`
371
+ <div
372
+ @click="${t._handleSwitchToChat}"
373
+ class="switch-chat-button"
374
+ title="${t._t("switchToChat")}"
375
+ aria-label="${t._t("switchToChat")}"
376
+ role="button"
377
+ tabindex="0">
378
+ ${Rt}
379
+ </div>
380
+ `)(t)}
253
381
  </div>
254
- `)(t):_}
382
+ `})(t)}
255
383
  <div class="body-icons-overlay">
256
- ${t._isFullBody?(t=>m`
384
+ ${t._isFullBody?(t=>v`
257
385
  <div id="body-icons-wrapper" class="button-container vertical-icons">
258
386
  <div class="icon-button" @click="${t._handleFullBodyIcon}" title="${t._t("fullBodyView")}">
259
387
  ${xt}
@@ -264,22 +392,38 @@ z"/>
264
392
  </div>
265
393
  `)(t):_}
266
394
  </div>
267
- </div>
268
- <div class="voice-controls-container">
269
- ${(t=>{if(t._isConversationPaused)return m`
270
- <div class="button-container">
395
+ <div class="voice-controls-container">
396
+ ${(t=>{if(t._isConversationPaused)return v`
397
+ <div class="button-container active-conversation">
271
398
  <div class="state-control">
272
- ${Ut(t)}
399
+ ${jt(t)}
273
400
  </div>
274
401
  </div>
275
- `;if(t._isConversationInProgress)return m`
276
- <div class="button-container">
402
+ `;if(t._isConversationInProgress)return v`
403
+ <div class="button-container active-conversation">
277
404
  <div class="state-control">
278
- ${Ut(t)}
405
+ ${jt(t)}
279
406
  </div>
407
+ ${t._showTyping?_:v`
408
+ <div
409
+ class="state-control"
410
+ @click="${t._handleToggleTyping}"
411
+ @keydown="${e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),t._handleToggleTyping(e))}}"
412
+ title="${t._t("showTyping")}"
413
+ role="button"
414
+ tabindex="0"
415
+ aria-label="${t._t("showTyping")}"
416
+ style="cursor: pointer;"
417
+ >
418
+ ${Vt}
419
+ </div>
420
+ `}
280
421
  </div>
281
- ${t._showTyping?(t=>{const e=t._isConversationPaused?t._t("reconnecting"):t._inputsBlocked?t._t("waitForResponse"):t._t("typeHere");return m`
422
+ ${t._showTyping?(t=>{const e=t._isConversationPaused?t._t("reconnecting"):t._inputsBlocked?t._t("waitForResponse"):t._t("typeHere");return v`
282
423
  <div class="typing-input ${t._inputsBlocked?"input-blocked":""}">
424
+ <div class="close-input-button" @click="${t._handleToggleTyping}" aria-label="Close typing input" role="button">
425
+ ${Bt}
426
+ </div>
283
427
  <textarea
284
428
  @keyup="${t._handleTypingKeyUp}"
285
429
  type="text"
@@ -292,202 +436,405 @@ z"/>
292
436
  id="typing_send_button"
293
437
  class="${t._inputsBlocked?"send-button-disabled":""}"
294
438
  >
295
- ${Pt}
439
+ ${Ot}
296
440
  </div>
297
441
  </div>
298
442
  `})(t):_}
299
- `;const e=t._speakingAvatar?.connectionManager;return e?.connectionModules&&Object.values(e.connectionModules).some((t=>t.isFailed()))?Vt(t):$t(t)})(t)}
443
+ `;if(t._isCheckingResume||t._isAutoResuming)return _;const e=t._speakingAvatar?.connectionManager;return e?.connectionModules&&Object.values(e.connectionModules).some((t=>t.isFailed()))?Ht(t):Ut(t)})(t)}
444
+ </div>
300
445
  </div>
301
446
  </div>
302
- `},jt=b`
303
-
304
- :host {
305
- --z-chatbot: 100; /* the widget panel */
306
- --z-toggler: 110; /* floating open/close button (outside .chatbot) */
307
-
308
- --z-controls: 200; /* in-widget controls over the canvas (buttons/icons) */
309
- --z-status: 600; /* inline status bar at top of .chatbot-body */
310
- --z-toasts: 700; /* dismissable alerts above status, below menus/modals */
311
-
312
- --z-menu-backdrop: 1100; /* menu scrim (header) - below modal */
313
- --z-menu: 1150; /* menu panel - below modal */
314
-
315
- --z-overlay: 1200; /* modal backdrops (last-message, dialogs) - topmost */
316
- /* modal content uses overlay+1 */
317
-
318
- width: 100%;
319
- height: 100%;
320
- display: block;
321
-
322
- font-size: 16px;
323
- }
324
-
325
- /* Prevent flash of icon text (FOUT) for ligature-based Material Icons */
326
- :host(:not(.icons-ready)) .material-icons {
327
- /* Keep layout space but hide fallback text until the icon font loads */
328
- visibility: hidden;
329
- }
330
-
331
- .material-icons {
332
- font-family: 'Material Icons';
333
- font-weight: normal;
334
- font-style: normal;
335
- font-size: 24px;
336
- display: inline-block;
337
- line-height: 1;
338
- text-transform: none;
339
- letter-spacing: normal;
340
- word-wrap: normal;
341
- white-space: nowrap;
342
- direction: ltr;
343
-
344
- /* Optional: use this for better rendering */
345
- -webkit-font-smoothing: antialiased;
346
- text-rendering: optimizeLegibility;
347
- -moz-osx-font-smoothing: grayscale;
348
- }
349
-
350
- * {
351
- margin: 0;
352
- padding: 0;
353
- box-sizing: border-box;
354
- font-family: "Poppins", sans-serif;
355
- }
356
-
357
- [hidden] {
358
- display: none;
359
- }
360
-
361
- .center-text {
362
- text-align: center;
363
- }
364
-
365
- .center-aligned {
366
- display: flex;
367
- justify-content: center;
368
- align-items: center;
369
- }
370
-
371
- .btn {
372
- margin-right: 10px;
373
- }
374
-
375
- .page-wrapper {
376
- width: 100%;
377
- height: 100%;
378
- }
379
-
380
- .page-wrapper[hidden] {
381
- display: none !important;
382
- }
383
-
384
-
385
- .page-center {
386
- margin-top: 150px;
387
- text-align: center;
388
- }
389
-
390
- .lds-dual-ring {
391
- display: inline-block;
392
- width: 80px;
393
- height: 80px;
394
- margin-left: auto;
395
- margin-right: auto;
396
- }
397
-
398
- .lds-dual-ring:after {
399
- content: " ";
400
- display: block;
401
- width: 64px;
402
- height: 64px;
403
- margin: 8px;
404
- border-radius: 50%;
405
- border: 6px solid var(--secondary-color, #801bea);
406
- border-color: var(--secondary-color, #801bea) transparent var(--secondary-color, #801bea) transparent;
407
- animation: lds-dual-ring 1.2s linear infinite;
408
- }
409
-
410
- .lds-dual-ring.small {
411
- width: 40px;
412
- height: 40px;
413
- }
414
-
415
- .lds-dual-ring.small:after {
416
- width: 32px;
417
- height: 32px;
418
- margin: 4px;
419
- border-width: 4px;
420
- }
421
-
422
- @keyframes lds-dual-ring {
423
- 0% {
424
- transform: rotate(0deg);
425
- }
426
-
427
- 100% {
428
- transform: rotate(360deg);
429
- }
430
- }
431
-
432
- .error-icon {
433
- color: #f8d7da;
434
- font-size: 96px;
435
- }
447
+ `))(t)}
448
+ ${t.compact?_:(t=>{let e,i="";const a=t._isStartingConversation,n=t._isInitializingConversation,s=t._isConversationInProgress,o=t._isConversationPaused,r=t._isAutoResuming;return a||n||r?(e=v`
449
+ <div class="chat-start-container center-aligned">
450
+ <div class="lds-dual-ring small"></div>
451
+ </div>`,i="center-aligned"):s||o?e=v`
452
+ <ul class="chatbox">
453
+ ${t._conversationTranscript.length?t._conversationTranscript.map((t=>((t,{speaker:e,messageText:i,time:a})=>{const n=kt(i)?"rtl":"ltr";return v`
454
+ <li class="chat ${e}">
455
+ ${"assistant"===e?Lt:""}
456
+ <div style="direction: ${n}; text-align: ${"rtl"===n?"right":"left"}" class="message-container">
457
+ <p class="message-bubble" style="word-wrap: break-word; word-break: break-word;">${i}</p>
458
+ <small class="message-time ${"rtl"===n?"time-left":"time-right"}">${a}</small>
459
+ </div>
460
+ </li>
461
+ `})(0,t))):(t=>v`<h3 id="no-msgs-head">${t._t("noMessagesYet")}</h3>`)(t)}
462
+ </ul>
463
+ ${(t=>{const e=t._isConversationPaused?t._t("reconnecting"):t._inputsBlocked?t._t("waitForResponse"):t._t("typeHere");return v`
464
+ <div class="chat-input ${t._inputsBlocked?"input-blocked":""}">
465
+ ${t._inputsBlocked?v`
466
+ <div class="input-loading-dots">
467
+ <div class="dot"></div>
468
+ <div class="dot"></div>
469
+ <div class="dot"></div>
470
+ </div>
471
+ `:_}
472
+ <textarea
473
+ @keyup="${t._handleChatKeyUp}"
474
+ type="text"
475
+ id="message_input"
476
+ placeholder="${e}"
477
+ ?disabled="${t._inputsBlocked}"
478
+ ></textarea>
479
+ <div
480
+ @click="${t._handleSendTextMessage}"
481
+ id="chat_send_button"
482
+ class="${t._inputsBlocked?"send-button-disabled":""}"
483
+ >
484
+ ${Ot}
485
+ </div>
486
+ </div>
487
+ `})(t)}
488
+ `:(e=v`
489
+ <div class="chat-placeholder-container">
490
+ <div class="chat-placeholder-content">
491
+ <div class="chat-placeholder-icon">
492
+ ${It}
493
+ </div>
494
+ <h3 class="chat-placeholder-title">${t._t("chatPlaceholderTitle")}</h3>
495
+ <p class="chat-placeholder-description">${t._t("chatPlaceholderDescription")}</p>
496
+ </div>
497
+ <div class="chat-placeholder-button">
498
+ ${Ut(t)}
499
+ </div>
500
+ </div>`,i="placeholder-mode"),v`
501
+ <div class="page-wrapper" id="chat-page" ?hidden=${"ChatPage"!==t._shownPage}>
502
+ <div class="chat-wrapper ${i}">
503
+ ${(t=>v`
504
+ <button
505
+ @click="${t._handleBackToAvatar}"
506
+ class="floating-avatar-button"
507
+ title="${t._t("switchToAvatar")}"
508
+ aria-label="${t._t("switchToAvatar")}"
509
+ >
510
+ ${xt}
511
+ </button>
512
+ `)(t)}
513
+ ${e}
514
+ </div>
515
+ </div>
516
+ `})(t)}
517
+ ${(t=>"ErrorPage"===t._shownPage?v`
518
+ <div class="page-wrapper" id="error_page">
519
+ <div class="page-center">
520
+ ${zt}
521
+ </div>
522
+ </div>
523
+ `:_)(t)}
524
+ ${(t=>"DisconnectedPage"===t._shownPage?v`
525
+ <div class="page-wrapper" id="disconnected_page">
526
+ <div class="page-center">
527
+ ${Ht(t)}
528
+ </div>
529
+ </div>
530
+ `:_)(t)}
531
+ </div>
532
+ ${"mobile"===t.target_app||t.compact?_:(t=>{const e=t.brand_name||"Sentifyd",i=!!t.brand_name;return v`
533
+ <footer>
534
+ ${i?v`<small>${e}</small>`:v`<small><a href="https://sentifyd.io" target="_blank">Sentifyd</a></small>`}
535
+ </footer>
536
+ `})(t)}
537
+ ${(t=>t._showLastMessage?v`
538
+ <div class="last-message" @click="${t._closeLastMessage}">
539
+ <div class="last-message-content">
540
+ <div style="direction: ${kt(t._lastMessageText)?"rtl":"ltr"}" class="last-message-scrollable">
541
+ ${t._lastMessageText}
542
+ <button class="last-message-copy-button" @click="${e=>((t,e)=>{t.stopPropagation();const i=e._lastMessageText;i&&navigator.clipboard.writeText(i).then((()=>{e._showCopyTick=!0,setTimeout((()=>{e._showCopyTick=!1}),1500)})).catch((t=>{}))})(e,t)}">
543
+ ${t._showCopyTick?$t:Ft}
544
+ </button>
545
+ </div>
546
+ </div>
547
+ </div>
548
+ `:_)(t)}
549
+ ${(t=>t._showConfirmationDialog?v`
550
+ <div class="dialog-overlay">
551
+ <div class="dialog">
552
+
553
+ <p>${t._dialogMessage}</p>
554
+ <div class="dialog-button-wrapper">
555
+ <button class="confirm-button" @click="${t._handleConfirm}">${t._confirmButtonLabel}</button>
556
+ <button class="cancel-button" @click="${t._handleCancel}">${t._cancelButtonLabel}</button>
557
+ </div>
558
+ </div>
559
+ </div>
560
+ `:_)(t)}
561
+ ${(t=>t._showUserData?v`
562
+ <div class="dialog-overlay">
563
+ <div class="dialog">
564
+ <h3>${t._t("secureFormTitle")}</h3>
565
+ <p>${t._t("secureFormDescription")}</p>
566
+ <div class="form-group">
567
+ <label for="username">${t._t("name")}</label>
568
+ <input @input="${e=>t.username=e.target.value}" type="text" id="username" placeholder="${t._t("namePlaceholder")}" .value=${t.username} required>
569
+ </div>
570
+ <div class="form-group">
571
+ <label for="email">${t._t("email")}*</label>
572
+ <input @input="${e=>t.email=e.target.value}" type="email" id="email" placeholder="${t._t("emailPlaceholder")}" .value=${t.email} required>
573
+ </div>
574
+ <div class="form-group">
575
+ <label for="phoneNumber">${t._t("phoneNumber")}</label>
576
+ <input @input="${e=>t.phoneNumber=e.target.value}" type="tel" id="phoneNumber" placeholder="${t._t("phonePlaceholder")}" .value=${t.phoneNumber}>
577
+ </div>
578
+ <div> <p style="font-size: 0.8em;">${t._t("secureFormNote")}</p></div>
579
+ <div class="dialog-button-group" style="text-align: start;">
580
+ <button class="button-save" @click="${t._handleSaveClick}" type="button" ?disabled="${!t.username?.trim()||!t.email?.trim()}">${t._t("send")}</button>
581
+ <button class="button-cancel" @click="${t._handleCancelClick}">${t._t("cancel")}</button>
582
+ </div>
583
+ </div>
584
+ </div>
585
+ `:_)(t)}
586
+ ${(t=>t._showSatisfactionScore?v`
587
+ <div class="dialog-overlay">
588
+ <div class="dialog">
589
+ <p>${t._t("conversationEndedPrompt")}</p>
590
+ <div class="radio-group">
591
+ ${[1,2,3,4,5].map((e=>v`
592
+ <label class="radio-label">
593
+ <input
594
+ class="radio-input"
595
+ type="radio"
596
+ name="satisfactionScore"
597
+ value="${e}"
598
+ @change="${e=>t._satisfactionScore=parseInt(e.target.value)}"
599
+ ?checked="${t._satisfactionScore===e}"
600
+ />
601
+ ${e}
602
+ </label>
603
+ `))}
604
+ </div>
605
+ <div class="dialog-button-group">
606
+ <button
607
+ class="button-save"
608
+ @click="${t._handleSubmitScoreClick}"
609
+ type="button"
610
+ ?disabled="${null==t._satisfactionScore}"
611
+ >
612
+ ${t._t("submit")}
613
+ </button>
614
+ <button class="button-cancel" @click="${t._handleCancelScoreClick}">
615
+ ${t._t("skip")}
616
+ </button>
617
+ </div>
618
+ </div>
619
+ </div>
620
+ `:_)(t)}
621
+ ${(t=>t._showChatConsentDialog?v`
622
+ <div class="dialog-overlay">
623
+ <div class="dialog consent-dialog" role="dialog" aria-modal="true" aria-labelledby="chat-consent-title">
624
+ <p id="chat-consent-title" class="label"><b>${t._t("consentTitle")}</b></p>
625
+ <div class="consent-text scrollable" tabindex="0" aria-label="${t._t("consentScrollableAria")||t._t("consentTitle")}">
626
+ <p>${t._t("consentInfo1")}</p>
627
+ <p>${t._t("consentInfo2")}</p>
628
+ <p>
629
+ ${t._t("consentReadOur")}
630
+ <a href="${t.terms_href}" target="_blank" rel="noopener noreferrer">${t._t("consentTermsLabel")}</a>
631
+ ${t._t("consentAnd")}
632
+ <a href="${t.privacy_href}" target="_blank" rel="noopener noreferrer">${t._t("consentPrivacyLabel")}</a>
633
+ ${t._t("consentMoreDetails")}
634
+ </p>
635
+ <p><small>${t._t("consentInfo4")}</small></p>
636
+ </div>
637
+ <div class="dialog-button-group" style="text-align: center;">
638
+ <button class="button-save" aria-label="${t._t("consentAcceptAria")}" @click="${t._handleConsentAccept}" type="button">${t._t("consentAccept")}</button>
639
+ <button class="button-cancel" aria-label="${t._t("consentDeclineAria")}" @click="${t._handleConsentDecline}" type="button">${t._t("consentDecline")}</button>
640
+ </div>
641
+ </div>
642
+ </div>`:_)(t)}
643
+ </div>
644
+ </div>
645
+ `,qt=b`
436
646
 
437
- .test-mode-states {
438
- display: flex;
439
- flex-direction: column;
440
- justify-content: center;
647
+ :host {
648
+ --z-chatbot: 100; /* the widget panel */
649
+ --z-toggler: 110; /* floating open/close button (outside .chatbot) */
650
+
651
+ --z-controls: 200; /* in-widget controls over the canvas (buttons/icons) */
652
+ --z-status: 600; /* inline status bar at top of .chatbot-body */
653
+ --z-toasts: 700; /* dismissable alerts above status, below menus/modals */
654
+
655
+ --z-menu-backdrop: 1100; /* menu scrim (header) - below modal */
656
+ --z-menu: 1150; /* menu panel - below modal */
657
+
658
+ --z-overlay: 1200; /* modal backdrops (last-message, dialogs) - topmost */
659
+ /* modal content uses overlay+1 */
660
+
661
+ width: 100%;
441
662
  height: 100%;
442
- margin: 20px;
663
+ display: block;
664
+
665
+ font-size: 16px;
443
666
  }
444
667
 
445
- `,Wt=b`
446
- #chatbot-container {
447
- height: 100%;
448
- width: 100%;
449
- max-height: 100vh;
450
- max-width: 100vw;
451
- margin: 0;
452
- padding: 0;
668
+ /* Prevent flash of icon text (FOUT) for ligature-based Material Icons */
669
+ :host(:not(.icons-ready)) .material-icons {
670
+ /* Keep layout space but hide fallback text until the icon font loads */
671
+ visibility: hidden;
453
672
  }
454
673
 
455
- #chatbot-toggler {
456
- position: fixed;
457
- bottom: 30px;
458
- right: 35px;
459
- outline: none;
460
- border: none;
461
- height: 72px; /* slightly larger for better visibility */
462
- width: 72px; /* slightly larger for better visibility */
463
- display: flex;
464
- cursor: pointer;
465
- align-items: center;
466
- justify-content: center;
467
- border-radius: 50%;
468
- background: var(--secondary-color, #801bea);
469
- color: var(--text-color-secondary-bg, #fff); /* controls inline SVG/logo and close icon color */
470
- transition: all 0.2s ease;
471
- z-index: var(--z-toggler);
472
- user-select: none; /* avoid text selection */
473
- -webkit-user-select: none;
474
- -ms-user-select: none;
475
- -moz-user-select: none;
476
- caret-color: transparent; /* hide blinking caret when focused */
477
- -webkit-tap-highlight-color: transparent; /* remove mobile tap highlight */
478
- -webkit-appearance: none;
479
- -moz-appearance: none;
480
- appearance: none;
674
+ .material-icons {
675
+ font-family: 'Material Icons';
676
+ font-weight: normal;
677
+ font-style: normal;
678
+ font-size: 24px;
679
+ display: inline-block;
680
+ line-height: 1;
681
+ text-transform: none;
682
+ letter-spacing: normal;
683
+ word-wrap: normal;
684
+ white-space: nowrap;
685
+ direction: ltr;
686
+
687
+ /* Optional: use this for better rendering */
688
+ -webkit-font-smoothing: antialiased;
689
+ text-rendering: optimizeLegibility;
690
+ -moz-osx-font-smoothing: grayscale;
481
691
  }
482
692
 
483
- #chatbot-container.show-chatbot #chatbot-toggler {
484
- transform: rotate(90deg);
693
+ * {
694
+ margin: 0;
695
+ padding: 0;
696
+ box-sizing: border-box;
697
+ font-family: "Poppins", sans-serif;
485
698
  }
486
699
 
487
- /* Center immediate children (icon and close glyph) and disable pointer events on them */
488
- #chatbot-toggler > * {
489
- position: absolute;
490
- pointer-events: none; /* ensure clicks hit the button, not the icon/svg */
700
+ [hidden] {
701
+ display: none;
702
+ }
703
+
704
+ .center-text {
705
+ text-align: center;
706
+ }
707
+
708
+ .center-aligned {
709
+ display: flex;
710
+ justify-content: center;
711
+ align-items: center;
712
+ }
713
+
714
+ .btn {
715
+ margin-right: 10px;
716
+ }
717
+
718
+ .page-wrapper {
719
+ width: 100%;
720
+ height: 100%;
721
+ flex-grow: 1;
722
+ min-height: 0;
723
+ display: flex;
724
+ flex-direction: column;
725
+ }
726
+
727
+ .page-wrapper[hidden] {
728
+ display: none !important;
729
+ }
730
+
731
+
732
+ .page-center {
733
+ margin-top: 150px;
734
+ text-align: center;
735
+ }
736
+
737
+ .lds-dual-ring {
738
+ display: inline-block;
739
+ width: 80px;
740
+ height: 80px;
741
+ margin-left: auto;
742
+ margin-right: auto;
743
+ }
744
+
745
+ .lds-dual-ring:after {
746
+ content: " ";
747
+ display: block;
748
+ width: 64px;
749
+ height: 64px;
750
+ margin: 8px;
751
+ border-radius: 50%;
752
+ border: 6px solid var(--secondary-color, #801bea);
753
+ border-color: var(--secondary-color, #801bea) transparent var(--secondary-color, #801bea) transparent;
754
+ animation: lds-dual-ring 1.2s linear infinite;
755
+ }
756
+
757
+ .lds-dual-ring.small {
758
+ width: 40px;
759
+ height: 40px;
760
+ }
761
+
762
+ .lds-dual-ring.small:after {
763
+ width: 32px;
764
+ height: 32px;
765
+ margin: 4px;
766
+ border-width: 4px;
767
+ }
768
+
769
+ @keyframes lds-dual-ring {
770
+ 0% {
771
+ transform: rotate(0deg);
772
+ }
773
+
774
+ 100% {
775
+ transform: rotate(360deg);
776
+ }
777
+ }
778
+
779
+ .error-icon {
780
+ color: #f8d7da;
781
+ font-size: 96px;
782
+ }
783
+
784
+ .test-mode-states {
785
+ display: flex;
786
+ flex-direction: column;
787
+ justify-content: center;
788
+ height: 100%;
789
+ margin: 20px;
790
+ }
791
+
792
+ `,Gt=b`
793
+ #chatbot-container {
794
+ height: 100%;
795
+ width: 100%;
796
+ max-height: 100vh;
797
+ max-width: 100vw;
798
+ margin: 0;
799
+ padding: 0;
800
+ }
801
+
802
+ #chatbot-toggler {
803
+ position: fixed;
804
+ bottom: 30px;
805
+ right: 35px;
806
+ outline: none;
807
+ border: none;
808
+ height: 72px; /* slightly larger for better visibility */
809
+ width: 72px; /* slightly larger for better visibility */
810
+ display: flex;
811
+ cursor: pointer;
812
+ align-items: center;
813
+ justify-content: center;
814
+ border-radius: 50%;
815
+ background: var(--secondary-color, #801bea);
816
+ color: var(--text-color-secondary-bg, #fff); /* controls inline SVG/logo and close icon color */
817
+ transition: all 0.2s ease;
818
+ z-index: var(--z-toggler);
819
+ user-select: none; /* avoid text selection */
820
+ -webkit-user-select: none;
821
+ -ms-user-select: none;
822
+ -moz-user-select: none;
823
+ caret-color: transparent; /* hide blinking caret when focused */
824
+ -webkit-tap-highlight-color: transparent; /* remove mobile tap highlight */
825
+ -webkit-appearance: none;
826
+ -moz-appearance: none;
827
+ appearance: none;
828
+ }
829
+
830
+ #chatbot-container.show-chatbot #chatbot-toggler {
831
+ transform: rotate(90deg);
832
+ }
833
+
834
+ /* Center immediate children (icon and close glyph) and disable pointer events on them */
835
+ #chatbot-toggler > * {
836
+ position: absolute;
837
+ pointer-events: none; /* ensure clicks hit the button, not the icon/svg */
491
838
  }
492
839
 
493
840
  /* Material icon sizing (close icon) */
@@ -684,7 +1031,7 @@ z"/>
684
1031
 
685
1032
  }
686
1033
 
687
- `,qt=b`
1034
+ `,Kt=b`
688
1035
  .chatbot header {
689
1036
  padding: 16px 0;
690
1037
  text-align: center;
@@ -731,13 +1078,11 @@ z"/>
731
1078
 
732
1079
  .header-right .close-icon {
733
1080
  cursor: pointer;
734
- transform: translateY(-50%);
735
1081
  }
736
1082
 
737
1083
  .header-left .menu-icon {
738
1084
  display: block;
739
1085
  cursor: pointer;
740
- transform: translateY(-50%);
741
1086
  }
742
1087
 
743
1088
 
@@ -829,6 +1174,26 @@ z"/>
829
1174
  white-space: nowrap;
830
1175
  }
831
1176
 
1177
+ /* Menu button styling - matches anchor tag appearance */
1178
+ #menu .menu-items .menu-button {
1179
+ color: black;
1180
+ padding: 12px 8px;
1181
+ text-decoration: none;
1182
+ display: block;
1183
+ text-align: start;
1184
+ white-space: nowrap;
1185
+ background: none;
1186
+ border: none;
1187
+ cursor: pointer;
1188
+ font-size: inherit;
1189
+ font-family: inherit;
1190
+ width: 100%;
1191
+ }
1192
+
1193
+ #menu .menu-items .menu-button:hover {
1194
+ background-color: rgba(0, 0, 0, 0.05);
1195
+ }
1196
+
832
1197
  #menu .menu-items hr {
833
1198
  border: none;
834
1199
  border-top: 1px solid #d3d3d3;
@@ -849,6 +1214,7 @@ z"/>
849
1214
  border-radius: 12px;
850
1215
  padding: 4px 12px;
851
1216
  margin-top: 2px;
1217
+ margin-bottom: 8px;
852
1218
  }
853
1219
 
854
1220
  .conversation-status small {
@@ -890,6 +1256,10 @@ z"/>
890
1256
  z-index: 1;
891
1257
  }
892
1258
 
1259
+ .menu-switch-container .switches-container label {
1260
+ color: #333; /* Dark text for light menu background */
1261
+ }
1262
+
893
1263
  /* switch highlighters wrapper (sliding left / right)
894
1264
  - need wrapper to enable the even margins around the highlight box
895
1265
  */
@@ -915,6 +1285,10 @@ z"/>
915
1285
  pointer-events: none;
916
1286
  }
917
1287
 
1288
+ .menu-switch-container .switch {
1289
+ background: var(--secondary-color, #801bea); /* Colored highlight for menu */
1290
+ }
1291
+
918
1292
  /* switch box labels
919
1293
  - default setup
920
1294
  - toggle afterwards based on radio:checked status
@@ -932,6 +1306,10 @@ z"/>
932
1306
  left: 0;
933
1307
  }
934
1308
 
1309
+ .menu-switch-container .switch div {
1310
+ color: white; /* White text on colored highlight */
1311
+ }
1312
+
935
1313
  /* slide the switch box from right to left */
936
1314
  .switches-container input:nth-of-type(1):checked~.switch-wrapper {
937
1315
  transform: translateX(0%);
@@ -963,6 +1341,15 @@ z"/>
963
1341
  white-space: nowrap;
964
1342
  }
965
1343
 
1344
+ .menu-switch-container {
1345
+ padding: 12px 8px;
1346
+ }
1347
+
1348
+ .menu-switch-container .switches-container {
1349
+ background: #eee; /* Light background for the track in menu */
1350
+ border: 1px solid #ddd;
1351
+ }
1352
+
966
1353
  .captions-switch {
967
1354
  position: relative;
968
1355
  display: inline-block;
@@ -1021,7 +1408,7 @@ z"/>
1021
1408
  .captions-slider.round:before {
1022
1409
  border-radius: 50%;
1023
1410
  }
1024
- `,Gt=b`
1411
+ `,Jt=b`
1025
1412
 
1026
1413
  .avatar-wrapper {
1027
1414
  position: relative;
@@ -1031,6 +1418,8 @@ z"/>
1031
1418
  height: 100%;
1032
1419
  width: 100%;
1033
1420
  overflow: hidden;
1421
+ flex-grow: 1;
1422
+ min-height: 0;
1034
1423
  }
1035
1424
 
1036
1425
  .chatbot .avatarbox {
@@ -1173,7 +1562,15 @@ z"/>
1173
1562
  align-items: center;
1174
1563
  justify-content: center;
1175
1564
  flex-shrink: 0;
1176
- position: relative;
1565
+ position: absolute;
1566
+ bottom: 10px;
1567
+ left: 0;
1568
+ right: 0;
1569
+ pointer-events: none; /* Allow clicks through to canvas */
1570
+ }
1571
+
1572
+ .voice-controls-container > * {
1573
+ pointer-events: auto; /* Re-enable clicks on actual controls */
1177
1574
  }
1178
1575
 
1179
1576
  .button-container {
@@ -1181,15 +1578,24 @@ z"/>
1181
1578
  justify-content: center;
1182
1579
  align-items: center;
1183
1580
  position: relative;
1184
- min-height: 70px;
1581
+ min-height: 40px;
1582
+ }
1583
+
1584
+ /* Only show glass background when conversation is active (has visualizer) */
1585
+ .button-container.active-conversation {
1586
+ background: rgba(255, 255, 255, 1);
1587
+ backdrop-filter: blur(8px);
1588
+ border-radius: 35px;
1589
+ padding: 4px 16px;
1590
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
1185
1591
  }
1186
1592
 
1187
1593
  .state-control {
1188
1594
  display: flex;
1189
1595
  justify-content: center;
1190
1596
  align-items: center;
1191
- margin: 10px 20px;
1192
- min-height: 70px;
1597
+ margin: 2px 12px;
1598
+ min-height: 40px;
1193
1599
  }
1194
1600
 
1195
1601
  .btn-lg {
@@ -1226,26 +1632,28 @@ z"/>
1226
1632
  }
1227
1633
 
1228
1634
  .start-button {
1229
- margin-top: .6rem;
1230
1635
  background-color: var(--secondary-color, #801bea);
1231
- border-radius: 12px;
1636
+ border-radius: 25px;
1232
1637
  border: none;
1233
1638
  color: var(--text-color-secondary-bg, white);
1234
- padding: .5rem 1.25rem;
1235
- line-height: 1.5;
1639
+ padding: .65rem 1.5rem;
1640
+ line-height: 1.4;
1236
1641
  cursor: pointer;
1237
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
1642
+ box-shadow: 0 4px 16px rgba(128, 27, 234, 0.3);
1238
1643
  position: relative;
1239
1644
  transition: transform 0.3s, box-shadow 0.3s, background-color 0.3s;
1240
- max-width: 200px;
1645
+ max-width: 220px;
1646
+ font-weight: 500;
1241
1647
  }
1242
1648
 
1243
1649
  .start-button:hover {
1244
- filter: brightness(85%);
1650
+ filter: brightness(90%);
1651
+ transform: scale(1.02);
1652
+ box-shadow: 0 6px 20px rgba(128, 27, 234, 0.4);
1245
1653
  }
1246
1654
 
1247
1655
  .voice-controls-container {
1248
- /* sits over the canvas */
1656
+ /* sits over the canvas as an overlay */
1249
1657
  z-index: var(--z-controls);
1250
1658
  }
1251
1659
 
@@ -1275,16 +1683,14 @@ z"/>
1275
1683
  user-select: none;
1276
1684
  margin-top: 0.5rem;
1277
1685
  }
1278
-
1279
- .input-toggle-button {
1686
+
1687
+ .switch-chat-button {
1280
1688
  z-index: var(--z-controls);
1281
1689
  cursor: pointer;
1282
1690
  outline: none;
1283
1691
  user-select: none;
1284
- background: transparent;
1285
- border: none;
1286
1692
  margin-top: 0.5rem;
1287
- }
1693
+ }
1288
1694
 
1289
1695
  .time-right,
1290
1696
  .time-left {
@@ -1306,7 +1712,7 @@ z"/>
1306
1712
 
1307
1713
  .captions-overlay {
1308
1714
  position: absolute;
1309
- bottom: 0;
1715
+ bottom: 100px; /* Above voice controls */
1310
1716
  width: 100%;
1311
1717
  z-index: var(--z-controls);
1312
1718
  }
@@ -1314,7 +1720,7 @@ z"/>
1314
1720
  /* Position captions overlay over the canvas without affecting layout */
1315
1721
  #captions-wrapper {
1316
1722
  position: absolute;
1317
- bottom: 10px;
1723
+ bottom: 100px; /* Above voice controls */
1318
1724
  left: 0;
1319
1725
  right: 0;
1320
1726
  margin-left: auto;
@@ -1398,6 +1804,11 @@ z"/>
1398
1804
  top: 50px;
1399
1805
  right: 5%;
1400
1806
  z-index: var(--z-controls);
1807
+ background: rgba(255, 255, 255, 0.85);
1808
+ backdrop-filter: blur(8px);
1809
+ border-radius: 12px;
1810
+ padding: 8px;
1811
+ box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
1401
1812
  }
1402
1813
 
1403
1814
  .last-message {
@@ -1449,6 +1860,11 @@ z"/>
1449
1860
  top: 50px;
1450
1861
  left: 3%;
1451
1862
  z-index: var(--z-controls);
1863
+ background: rgba(255, 255, 255, 0.85);
1864
+ backdrop-filter: blur(8px);
1865
+ border-radius: 12px;
1866
+ padding: 8px;
1867
+ box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
1452
1868
  }
1453
1869
 
1454
1870
  .vertical-icons {
@@ -1465,24 +1881,46 @@ z"/>
1465
1881
  display: flex;
1466
1882
  gap: 5px;
1467
1883
  position: relative;
1468
- bottom: 0;
1469
- width: 100%;
1470
- background: #fff;
1471
- padding: 3px 10px;
1472
- border-top: 1px solid #ddd;
1884
+ width: 90%;
1885
+ max-width: 400px;
1886
+ background: rgba(255, 255, 255, 0.95);
1887
+ padding: 6px 12px;
1888
+ border-radius: 25px;
1889
+ box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
1473
1890
  overflow: hidden;
1891
+ margin-top: 8px;
1892
+ }
1893
+
1894
+ .typing-input .close-input-button {
1895
+ display: flex;
1896
+ align-items: center;
1897
+ justify-content: center;
1898
+ cursor: pointer;
1899
+ color: #999;
1900
+ padding-right: 5px;
1901
+ }
1902
+
1903
+ .typing-input .close-input-button:hover {
1904
+ color: #666;
1474
1905
  }
1475
1906
 
1476
1907
  .typing-input textarea {
1477
- height: 50px;
1908
+ height: 36px;
1478
1909
  width: 100%;
1479
1910
  border: none;
1480
1911
  outline: none;
1481
1912
  resize: none;
1482
- padding: 10px 10px 10px 0;
1483
- font-size: 0.95em;
1913
+ padding: 8px 10px 8px 4px;
1914
+ font-size: 0.9em;
1484
1915
  cursor: text;
1485
1916
  caret-color: auto;
1917
+ background: transparent;
1918
+ overflow-y: auto;
1919
+ scrollbar-width: none;
1920
+ }
1921
+
1922
+ .typing-input textarea::-webkit-scrollbar {
1923
+ display: none;
1486
1924
  }
1487
1925
 
1488
1926
  .typing-input #typing_send_button {
@@ -1527,24 +1965,22 @@ z"/>
1527
1965
  display: flex;
1528
1966
  justify-content: center;
1529
1967
  align-items: center;
1530
- width: 80px;
1531
- height: 50px;
1532
- background: rgba(0, 0, 0, 0.15);
1533
- border-radius: 25px;
1534
- padding: 8px;
1968
+ width: 70px;
1969
+ height: 40px;
1970
+ background: transparent;
1971
+ border-radius: 22px;
1972
+ padding: 6px;
1535
1973
  cursor: pointer;
1536
- transition: background-color 0.3s ease;
1537
- }
1538
-
1539
- .voice-visualizer:hover {
1540
- background: rgba(0, 0, 0, 0.25);
1974
+ transition: background 0.3s ease;
1541
1975
  }
1542
1976
 
1543
1977
  .voice-visualizer-wrapper {
1544
1978
  display: flex;
1545
1979
  flex-direction: column;
1546
1980
  align-items: center;
1547
- gap: 6px;
1981
+ gap: 4px;
1982
+ position: relative;
1983
+ min-height: 40px; /* Compact height for overlay */
1548
1984
  }
1549
1985
 
1550
1986
  .voice-visualizer.visualizer-disabled {
@@ -1553,8 +1989,17 @@ z"/>
1553
1989
  pointer-events: none;
1554
1990
  }
1555
1991
 
1992
+ .visualizer-hint,
1993
+ .thinking-label {
1994
+ position: absolute;
1995
+ bottom: -2px;
1996
+ left: 50%;
1997
+ transform: translateX(-50%);
1998
+ white-space: nowrap;
1999
+ }
2000
+
1556
2001
  .visualizer-hint {
1557
- font-size: 0.7rem;
2002
+ font-size: 0.6rem;
1558
2003
  color: var(--text-color-muted, #888);
1559
2004
  opacity: 0.8;
1560
2005
  text-align: center;
@@ -1562,8 +2007,23 @@ z"/>
1562
2007
  }
1563
2008
 
1564
2009
  @keyframes fadeInHint {
1565
- from { opacity: 0; transform: translateY(-5px); }
1566
- to { opacity: 0.8; transform: translateY(0); }
2010
+ from { opacity: 0; transform: translateX(-50%) translateY(-5px); }
2011
+ to { opacity: 0.8; transform: translateX(-50%) translateY(0); }
2012
+ }
2013
+
2014
+ /* Thinking label shown below visualizer during processing */
2015
+ .thinking-label {
2016
+ font-size: 0.6rem;
2017
+ color: var(--primary-color, #00bfdb);
2018
+ text-align: center;
2019
+ animation: thinkingPulse 1.5s infinite ease-in-out;
2020
+ letter-spacing: 0.5px;
2021
+ font-weight: 400;
2022
+ }
2023
+
2024
+ @keyframes thinkingPulse {
2025
+ 0%, 100% { opacity: 0.6; }
2026
+ 50% { opacity: 1; }
1567
2027
  }
1568
2028
 
1569
2029
  .audio-bar {
@@ -1598,19 +2058,29 @@ z"/>
1598
2058
  .state-listening .audio-bar:nth-child(5) { animation-delay: 0.0s; }
1599
2059
 
1600
2060
  /* --- STATE: THINKING (Processing) --- */
1601
- @keyframes think-wave {
1602
- 0% { height: 8px; opacity: 0.5; }
1603
- 50% { height: 28px; opacity: 1; }
1604
- 100% { height: 8px; opacity: 0.5; }
2061
+ /* Distinct "loading" style: sequential pulse sweep left-to-right with glow */
2062
+ @keyframes think-pulse {
2063
+ 0%, 100% {
2064
+ height: 8px;
2065
+ opacity: 0.4;
2066
+ background: linear-gradient(180deg, var(--primary-color, #00bfdb), var(--secondary-color, #801bea));
2067
+ }
2068
+ 40%, 60% {
2069
+ height: 24px;
2070
+ opacity: 1;
2071
+ background: linear-gradient(180deg, #00e5ff, #aa55ff);
2072
+ box-shadow: 0 0 8px rgba(0, 229, 255, 0.6);
2073
+ }
1605
2074
  }
1606
2075
  .state-thinking .audio-bar {
1607
- animation: think-wave 1s infinite;
2076
+ animation: think-pulse 1.2s infinite ease-in-out;
1608
2077
  }
2078
+ /* Sequential cascade from left to right */
1609
2079
  .state-thinking .audio-bar:nth-child(1) { animation-delay: 0.0s; }
1610
- .state-thinking .audio-bar:nth-child(2) { animation-delay: 0.1s; }
1611
- .state-thinking .audio-bar:nth-child(3) { animation-delay: 0.2s; }
1612
- .state-thinking .audio-bar:nth-child(4) { animation-delay: 0.3s; }
1613
- .state-thinking .audio-bar:nth-child(5) { animation-delay: 0.4s; }
2080
+ .state-thinking .audio-bar:nth-child(2) { animation-delay: 0.15s; }
2081
+ .state-thinking .audio-bar:nth-child(3) { animation-delay: 0.30s; }
2082
+ .state-thinking .audio-bar:nth-child(4) { animation-delay: 0.45s; }
2083
+ .state-thinking .audio-bar:nth-child(5) { animation-delay: 0.60s; }
1614
2084
 
1615
2085
  /* --- STATE: SPEAKING (Voice Output) --- */
1616
2086
  @keyframes speak-wave {
@@ -1666,21 +2136,57 @@ z"/>
1666
2136
  height: 100%;
1667
2137
  touch-action: pan-y pinch-zoom !important;
1668
2138
  }
1669
- }
1670
2139
 
1671
- `,Kt=b`
2140
+ /* Compact voice controls on mobile */
2141
+ .voice-controls-container {
2142
+ bottom: 10px;
2143
+ }
1672
2144
 
1673
- #chat-page {
1674
- height: 100%;
1675
- width: 100%;
1676
- }
2145
+ .button-container {
2146
+ padding: 6px 12px;
2147
+ border-radius: 28px;
2148
+ }
1677
2149
 
1678
- .chat-wrapper {
1679
- display: flex;
1680
- flex-direction: column;
1681
- justify-content: space-between;
1682
- height: 100%;
1683
- }
2150
+ .typing-input {
2151
+ width: 85%;
2152
+ max-width: 320px;
2153
+ padding: 4px 10px;
2154
+ }
2155
+
2156
+ .typing-input textarea {
2157
+ height: 32px;
2158
+ font-size: 0.85em;
2159
+ }
2160
+
2161
+ #captions-wrapper {
2162
+ bottom: 85px; /* Adjust for mobile voice controls */
2163
+ }
2164
+
2165
+ .captions-overlay {
2166
+ bottom: 85px;
2167
+ }
2168
+ }
2169
+
2170
+ /* Ensure conversation buttons are visible on mobile */
2171
+ .chatbot.mobile .conversation-buttons-overlay {
2172
+ top: 10px;
2173
+ right: 10px;
2174
+ z-index: 1000;
2175
+ }
2176
+ `,Qt=b`
2177
+
2178
+ #chat-page {
2179
+ height: 100%;
2180
+ width: 100%;
2181
+ }
2182
+
2183
+ .chat-wrapper {
2184
+ display: flex;
2185
+ flex-direction: column;
2186
+ justify-content: space-between;
2187
+ height: 100%;
2188
+ position: relative;
2189
+ }
1684
2190
 
1685
2191
  .chat-start-container {
1686
2192
  padding: 20px;
@@ -2018,7 +2524,46 @@ z"/>
2018
2524
  font-size: 0.9rem;
2019
2525
  }
2020
2526
  }
2021
- `,Jt=b`
2527
+
2528
+ .floating-avatar-button {
2529
+ position: absolute;
2530
+ bottom: 80px;
2531
+ right: 16px;
2532
+ width: 40px;
2533
+ height: 40px;
2534
+ border-radius: 50%;
2535
+ background-color: var(--secondary-color, #801bea);
2536
+ color: white;
2537
+ border: none;
2538
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
2539
+ display: flex;
2540
+ align-items: center;
2541
+ justify-content: center;
2542
+ cursor: pointer;
2543
+ z-index: 100;
2544
+ transition: transform 0.2s, box-shadow 0.2s;
2545
+ }
2546
+
2547
+ .floating-avatar-button:hover {
2548
+ transform: scale(1.05);
2549
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
2550
+ }
2551
+
2552
+ .floating-avatar-button svg,
2553
+ .floating-avatar-button svg g,
2554
+ .floating-avatar-button svg path {
2555
+ width: 24px;
2556
+ height: 24px;
2557
+ fill: currentColor;
2558
+ }
2559
+
2560
+ /* Ensure floating button is visible on mobile */
2561
+ .chatbot.mobile .floating-avatar-button {
2562
+ bottom: 100px;
2563
+ right: 20px;
2564
+ z-index: 1000;
2565
+ }
2566
+ `,Yt=b`
2022
2567
  .chatbot footer {
2023
2568
  text-align: center;
2024
2569
  padding: 5px;
@@ -2036,14 +2581,7 @@ z"/>
2036
2581
  border-bottom-left-radius: 0px;
2037
2582
  border-bottom-right-radius: 0px;
2038
2583
  }
2039
-
2040
- @media (max-width: 768px) {
2041
-
2042
- #chatbot-container.show-chatbot:not(.embedded) footer {
2043
- display: none;
2044
- }
2045
- }
2046
- `,Qt=b`
2584
+ `,Zt=b`
2047
2585
  .form-group {
2048
2586
  display: flex;
2049
2587
  flex-direction: column;
@@ -2261,323 +2799,4 @@ z"/>
2261
2799
  margin-top: 0;
2262
2800
  padding-top: 0.25rem;
2263
2801
  }
2264
- `,Yt=document.createElement("link");Yt.rel="preconnect",Yt.href="https://fonts.googleapis.com",Yt.crossOrigin="anonymous",document.head.appendChild(Yt);const Zt=document.createElement("link");Zt.rel="preconnect",Zt.href="https://fonts.gstatic.com",Zt.crossOrigin="anonymous",document.head.appendChild(Zt);const Xt=document.createElement("link");Xt.href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block",Xt.rel="stylesheet",document.head.appendChild(Xt);const te=document.createElement("link");te.href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap",te.rel="stylesheet",document.head.appendChild(te);class ee extends(function(t=Object){return class extends t{constructor(...t){super(...t),this._eventBus=new bt,this._domDisposers=[]}get bus(){return this._eventBus}_onBus(t,e){return this._eventBus.on(t,e)}_onDom(t,e,i,n){t.addEventListener(e,i,n);const a=()=>t.removeEventListener(e,i,n);return this._domDisposers.push(a),a}pushDisposer(t){if("function"!=typeof t)throw new TypeError("Disposer must be a function");this._domDisposers.push(t)}_disposeListeners(){this._eventBus.dispose(),this._domDisposers.forEach((t=>{try{t()}catch(e){}})),this._domDisposers.length=0}_createChildBus(){return new bt}}}(f)){static get properties(){return{api_key:{type:String,attribute:"api-key"},token_endpoint:{type:String,attribute:"token-endpoint"},avatar_id:{type:String,attribute:"avatar-id"},toggler:{type:Boolean,reflect:!0,converter:t=>"false"!==t},barge_in:{type:Boolean,reflect:!0,attribute:"barge-in",converter:t=>"false"!==t},terms_href:{type:String,attribute:"terms-href"},privacy_href:{type:String,attribute:"privacy-href"},brand_name:{type:String,attribute:"brand-name"},brand_logo:{type:String,attribute:"brand-logo"},username:{type:String},phoneNumber:{type:String},email:{type:String},isTermsAccepted:{type:Boolean,attribute:"terms-accepted"},compact:{type:Boolean,reflect:!0,converter:t=>"false"!==t},target_app:{type:String,attribute:"target-app"},enable_captions:{type:Boolean,reflect:!0,attribute:"enable-captions",converter:t=>"false"!==t},uiLanguage:{type:String,attribute:"ui-language"},canvasWidth:{type:Number,reflect:!0,attribute:"canvas-width"},canvasHeight:{type:Number,reflect:!0,attribute:"canvas-height"},chatbotHeight:{type:Number,reflect:!0,attribute:"chatbot-height"},avatarBackground:{type:String,reflect:!0,attribute:"avatar-background"},cornerRadius:{type:String,reflect:!0,attribute:"corner-radius"},_canvasWidth:{type:Number,attribute:!1},_canvasHeight:{type:Number,attribute:!1},_chatbotHeight:{type:Number,attribute:!1},_language:{type:String,attribute:!1},_avatarName:{type:String,attribute:!1},_currentMessage:{type:Object,attribute:!1},_actorSnapshot:{type:Object,attribute:!1},_conversationTranscript:{type:Array,attribute:!1},_showConversationPanel:{type:Boolean,attribute:!1},_showChatbot:{type:Boolean,attribute:!1},_showMenu:{type:Boolean,attribute:!1},_shownPage:{type:String,attribute:!1},_showUserData:{type:Boolean,attribute:!1},_showSatisfactionScore:{type:Boolean,attribute:!1},_showLastMessage:{type:Boolean,attribute:!1},_satisfactionScore:{type:Number,attribute:!1},_lastMessageText:{type:String,attribute:!1},_liveCaption:{type:String,attribute:!1},_liveCaptionSpeaker:{type:String,attribute:!1},_isLiveCaptionsVisible:{type:Boolean,attribute:!1,reflect:!1},_showConfirmationDialog:{type:Boolean,attribute:!1},_dialogMessage:{type:String,attribute:!1},_confirmButtonLabel:{type:String,attribute:!1},_cancelButtonLabel:{type:String,attribute:!1},_showCopyTick:{type:Boolean,attribute:!1},_isFullBody:{type:Boolean,attribute:!1},_showTyping:{type:Boolean,attribute:!1},_statusBarStatus:{type:String,attribute:!1},_inputsBlocked:{type:Boolean,attribute:!1},_isThinking:{type:Boolean,attribute:!1},_isListening:{type:Boolean,attribute:!1},_isSpeaking:{type:Boolean,attribute:!1},_isConversationInProgress:{type:Boolean,attribute:!1},_isConversationPaused:{type:Boolean,attribute:!1},_isAutoResuming:{type:Boolean,attribute:!1},_isResumeExpired:{type:Boolean,attribute:!1},_isInitializingConversation:{type:Boolean,attribute:!1},_isConversationTimedOut:{type:Boolean,attribute:!1},_isStartingConversation:{type:Boolean,attribute:!1},_isConversationStopped:{type:Boolean,attribute:!1},_isDisconnected:{type:Boolean,attribute:!1},_isFailed:{type:Boolean,attribute:!1},_avatarRunning:{type:Boolean,attribute:!1},_showChatConsentDialog:{type:Boolean,attribute:!1}}}static get observedAttributes(){const t=super.observedAttributes??[];return[...new Set([...t,"api_key","token_endpoint","avatar_id","terms_href","privacy_href","brand_name","brand_logo","target_app","enable_captions","barge_in"])]}attributeChangedCallback(t,e,i){if(super.attributeChangedCallback&&super.attributeChangedCallback(t,e,i),t in{api_key:"api-key",token_endpoint:"token-endpoint",avatar_id:"avatar-id",terms_href:"terms-href",privacy_href:"privacy-href",brand_name:"brand-name",brand_logo:"brand-logo",target_app:"target-app",enable_captions:"enable-captions",barge_in:"barge-in",avatar_background:"avatar-background"}){try{this._deprecatedAttrWarnings=this._deprecatedAttrWarnings||new Set,this._deprecatedAttrWarnings.has(t)||this._deprecatedAttrWarnings.add(t)}catch(n){}switch(t){case"enable_captions":case"barge_in":{const e=null!==i&&"false"!==i;this[t]=e;break}case"avatar_background":this.avatarBackground=i;break;default:this[t]=i}}}static styles=[jt,Wt,qt,Kt,Gt,Qt,Jt];constructor(){super(),this.api_key="",this.token_endpoint="",this.avatar_id="",this.toggler=!0,this.barge_in=!1,this.terms_href="",this.privacy_href="",this.brand_name="",this.brand_logo="",this.compact=!1,this.target_app="web",this.enable_captions=!0,this.uiLanguage=ft,this.canvasWidth=T.dom.canvasWidth,this.canvasHeight=T.dom.canvasHeight,this.chatbotHeight=T.dom.canvasHeight+T.dom.headerAndFooterHeight,this._canvasWidth=T.dom.canvasWidth,this._canvasHeight=T.dom.canvasHeight,this._chatbotHeight=T.dom.canvasHeight+T.dom.headerAndFooterHeight,this._speakingAvatar=null,this._language="",this.username="",this.phoneNumber="",this.email="",this.isTermsAccepted=!1,this._avatarName="Assistant",this._conversationTranscript=[],this._currentMessage=null,this._actorSnapshot={value:"initializing",context:{transcript:[]},matches:()=>!1},this._showConversationPanel=!1,this._showChatbot=!1,this._showMenu=!1,this._shownPage="LoaderPage",this._savedChatbotMode=null,(this.api_key||this.token_endpoint)&&this.avatar_id?this._statusBarStatus="initializing":(this._shownPage="ErrorPage",this._statusBarStatus="invalidConfiguration"),this._showUserData=!1,this._showSatisfactionScore=!1,this._showLastMessage=!1,this._satisfactionScore=null,this._lastMessageText="",this._liveCaption="",this._liveCaptionSpeaker="",this._isLiveCaptionsVisible=!0,this._alerts=null,this._showConfirmationDialog=!1,this._dialogMessage="",this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel"),this._stateTestMode=T.test.stateTestMode,this._showCopyTick=!1,this._isFullBody=!0,this._showTyping=!1,this._wakeLock=new wt,this._focusTimeoutId=null,this.captionsTimeoutId=null,this._userCaptionClearTimeoutId=null,this._connection="unknown",this._initTriggered=!1,this._initInProgress=!1,this._initPromise=null,this._inputsBlocked=!1,this._isThinking=!1,this._isListening=!1,this._isSpeaking=!1,this._isConversationInProgress=!1,this._isConversationPaused=!1,this._isAutoResuming=!1,this._isResumeExpired=!1,this._isInitializingConversation=!1,this._isConversationTimedOut=!1,this._isStartingConversation=!1,this._isConversationStopped=!1,this._isDisconnected=!1,this._isFailed=!1,this._avatarRunning=!1,this._showChatConsentDialog=!1,this.avatarBackground="",this.cornerRadius=void 0,this._dirManagedByUiLanguage=!1,this._lastUiChatbotMode={isShown:null,chatbotMode:null},this._speakingAvatar=new _t(this.bus),this._applyBargeInPreference(),this._setupAvatarStateSubscription()}_t(t){return St(this.uiLanguage,t)}_applyUiLanguage(){this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel")}_applyDirectionFromUiLanguage(){const t=!0===this._dirManagedByUiLanguage,e=this.getAttribute("dir");if(!t&&("rtl"===e||"ltr"===e||"auto"===e))return;const i=(this.uiLanguage||ft).toLowerCase().split("-")[0],n=["ar","he","fa","ur"].includes(i)?"rtl":"ltr";this.dir!==n?(this.dir=n,this._dirManagedByUiLanguage=!0):t||(this._dirManagedByUiLanguage=!0)}_getAvatarBackgroundStyleObj(){const t=(this.avatarBackground??"").toString().trim();if(!t)return{};const e=t.toLowerCase();if(e.includes("url(")||e.includes("expression(")||e.includes("@import")||e.includes("@supports")||e.includes("@media"))return{};if(this._bgTestEl??="undefined"!=typeof document&&document?.createElement?document.createElement("div"):null,!this._bgTestEl)return{};const i=this._bgTestEl;if(/^(linear-gradient|radial-gradient|conic-gradient)\(/i.test(t)){if("undefined"!=typeof CSS&&CSS.supports?.("background-image",t))return i.style.backgroundImage="",i.style.backgroundImage=t,i.style.backgroundImage?{backgroundImage:i.style.backgroundImage}:{};try{return i.style.backgroundImage="",i.style.backgroundImage=t,i.style.backgroundImage?{backgroundImage:i.style.backgroundImage}:{}}catch(n){return{}}}if("undefined"!=typeof CSS&&CSS.supports?.("color",t))return i.style.backgroundColor="",i.style.backgroundColor=t,i.style.backgroundColor?{backgroundColor:i.style.backgroundColor}:{};try{return i.style.backgroundColor="",i.style.backgroundColor=t,i.style.backgroundColor?{backgroundColor:i.style.backgroundColor}:{}}catch(n){return{}}}_applyBargeInPreference(){const t=!1!==this.barge_in;try{T?.speech?.bargeIn&&(T.speech.bargeIn.enabled=t)}catch(e){}if(this._speakingAvatar?.setBargeInEnabled)try{const e=this._speakingAvatar.setBargeInEnabled(t);e&&"function"==typeof e.catch&&e.catch((t=>{}))}catch(e){}}firstUpdated(){const t=this.renderRoot.querySelector("#toastify-dismissable-alerts");this._alerts=new kt(this.bus,t,(()=>this.uiLanguage));try{const t=()=>this.classList.add("icons-ready");document.fonts&&document.fonts.ready?document.fonts.ready.then(t).catch((()=>t())):setTimeout(t,300)}catch(e){}}_setupAvatarStateSubscription(){if(this._speakingAvatar?.avatarOrchestrator){if(this._orchestratorUnsub){try{this._orchestratorUnsub()}catch{}this._orchestratorUnsub=null}this._orchestratorUnsub=this._speakingAvatar.avatarOrchestrator.subscribeProjected(((t,e)=>{if(!e)return;const i=this._actorSnapshot;this._actorSnapshot=e;let n=!1;const a=(t,e)=>{this[t]!==e&&(this[t]=e,n=!0)};try{a("_isConversationInProgress",!!e.hasTag?.("conversation_in_progress")),a("_isConversationPaused",!!e.hasTag?.("conversation_paused")),a("_isSpeaking",!!e.hasTag?.("speaking")),a("_isListening",!!e.hasTag?.("listening")),a("_isThinking",!!e.hasTag?.("thinking")),a("_inputsBlocked",!!e.hasTag?.("inputs_blocked")),a("_isAutoResuming",!!e.matches?.("lifecycle.conversation.autoResuming")),a("_isResumeExpired",!!e.matches?.("lifecycle.conversation.resumeExpired")),a("_isInitializingConversation",!(!e.matches?.("lifecycle.conversation.initializingConversation")&&!e.matches?.("lifecycle.conversation.initializing"))),a("_isConversationTimedOut",!!e.matches?.("lifecycle.conversation.timedOut")),a("_isStartingConversation",!!(e.matches?.("lifecycle.conversation.inProgress.startingConversation")||e.matches?.("lifecycle.conversation.starting")||e.matches?.("lifecycle.conversation.autoResuming"))),a("_isConversationStopped",!!e.matches?.("lifecycle.conversation.stopped")),a("_isDisconnected",!!e.matches?.("connection.disconnected")),a("_isFailed",!(!e.matches?.("lifecycle.init.failed")&&!e.matches?.("lifecycle.failed")))}catch(s){}(n||i!==e)&&this.updateAlertStatus()}))}}updated(t){if(this.__postUpdateQueue||(this.__postUpdateQueue=[]),(t.has("toggler")||t.has("compact"))&&this.toggler&&this.compact&&(this.compact=!1),(t.has("target_app")||t.has("toggler"))&&"mobile"===this.target_app&&this.toggler&&(this.toggler=!1),t.has("compact")&&this.compact&&this.isInitialized()&&(this._shownPage="AvatarPage"),t.has("uiLanguage")&&(this._applyUiLanguage(),this._applyDirectionFromUiLanguage()),t.has("barge_in")&&this.__postUpdateQueue.push((()=>this._applyBargeInPreference())),this.isInitialized()&&this._speakingAvatar?.sessionData&&(t.has("username")&&this.username!==this._speakingAvatar.sessionData.username&&(this._speakingAvatar.sessionData.username=this.username),t.has("phoneNumber")&&this.phoneNumber!==this._speakingAvatar.sessionData.phoneNumber&&(this._speakingAvatar.sessionData.phoneNumber=this.phoneNumber),t.has("email")&&this.email!==this._speakingAvatar.sessionData.email&&(this._speakingAvatar.sessionData.email=this.email),t.has("isTermsAccepted")&&this.isTermsAccepted!==this._speakingAvatar.sessionData.isTermsAccepted&&(this._speakingAvatar.sessionData.isTermsAccepted=this.isTermsAccepted)),t.has("api_key")||t.has("token_endpoint")||t.has("avatar_id")){const t=!(!this.api_key&&!this.token_endpoint||!this.avatar_id);t&&!this._initTriggered?(this._initTriggered=!0,this.__postUpdateQueue.push((()=>this._initialize()))):t||(this._initTriggered=!1,this.__postUpdateQueue.push((()=>this.updateAlertStatus("ErrorPage"))))}if((t.has("_showChatbot")||t.has("_shownPage"))&&(this.__postUpdateQueue.push((()=>{this._speakingAvatar?.chatSocket&&this._syncUiChatbotMode()})),t.has("_shownPage")&&this.__postUpdateQueue.push((()=>this._speakingAvatar?.avatarOrchestrator?.sendEvent("PAGE_CHANGED",{newPage:this._shownPage}))),t.has("_showChatbot")&&this.__postUpdateQueue.push((()=>{if(!("mobile"===this.target_app||this.toggler&&window.innerWidth<768))try{this.style.removeProperty("--chatbot-dynamic-height")}catch(t){}requestAnimationFrame((()=>{this.updateSize(),requestAnimationFrame((()=>{try{this._speakingAvatar?.avatarModule?.onResize?.()}catch(t){}}))}))}))),this.toggler&&t.has("_showChatbot")&&this._showChatbot&&!this._isConversationInProgress&&!this._isAutoResuming&&!this._isResumeExpired&&this._startOrResumeConversation(!0),t.has("_shownPage")&&("ChatPage"===this._shownPage?(this._scheduleInputFocus("chat"),this._scheduleChatScroll(),setTimeout((()=>this._scheduleChatScroll()),80)):"AvatarPage"===this._shownPage&&this._showTyping&&this._scheduleInputFocus("typing")),t.has("_showTyping")&&"AvatarPage"===this._shownPage&&this._showTyping&&this._scheduleInputFocus("typing"),t.has("_inputsBlocked")&&!this._inputsBlocked&&!0===t.get("_inputsBlocked")&&this._scheduleInputFocus(),t.has("canvasWidth")||t.has("canvasHeight")||t.has("chatbotHeight")){const t=()=>this.updateSize();this.__postUpdateQueue.push((()=>requestAnimationFrame(t)))}if(this.__postUpdateQueue.length){const t=this.__postUpdateQueue.splice(0);Promise.resolve().then((()=>{for(const i of t)try{i()}catch(e){}}))}if(t.has("_showChatConsentDialog")&&(this._showChatConsentDialog?this._activateConsentFocusTrap():this._deactivateConsentFocusTrap()),t.has("cornerRadius"))try{const t=this.cornerRadius;if(null==t||""===t)this.style.removeProperty("--corner-radius");else{const e=String(t).trim(),i=/^-?\d+(?:\.\d+)?$/.test(e)?`${e}px`:e;this.style.setProperty("--corner-radius",i)}}catch(e){}}render(){return m`
2265
- <div id="chatbot-container" class="${(t=this)._showChatbot||!t.toggler?"show-chatbot":""}${t.toggler?"":" embedded"}">
2266
- ${t.toggler?(t=>m`
2267
- <button id="chatbot-toggler" @click="${t._handleToggleChatbot}" aria-label="${t._t("toggleChatbot")}">
2268
- ${Et}
2269
- ${Lt}
2270
- </button>
2271
- `)(t):_}
2272
- ${t._stateTestMode?(t=>{const e=t._actorSnapshot,i="function"==typeof t.initStatus?t.initStatus():"UNKNOWN",n=!!t._isStartingConversation,a=!!t._isInitializingConversation,s=!!t._isConversationInProgress,o=!!t._isConversationPaused,r=!!t._isConversationResumable,c=!!t._isConversationStopped,l=!!t._isFailed,h=l?"FAILED":n?"STARTING":a?"INITIALIZING":s?"IN_PROGRESS":o?"PAUSED":r?"RESUMABLE":c?"STOPPED":"CLEARED",d=!!t._isSpeaking,u=!!t._isThinking||!!t._isStartingConversation,p=s&&!d&&!u&&!t._isListening,g=!!t._isListening,v=d?"speaking":u?"thinking":g?"listening":p?"idle":n?"startingConversation":"",b=!!t._inputsBlocked||u,f=t._speakingAvatar?.connectionManager,y=!0===f?.allConnectionsReady,S=!!t._isDisconnected,k=y?"connected":S?"disconnected":l?"recovering":"connecting",C=function(t){const e=t?.value;if(!e)return"";const i=(t,e=[])=>{if("string"==typeof t)return[e.concat(t).join(".")];if(t&&"object"==typeof t){const n=[];for(const a of Object.keys(t))n.push(...i(t[a],e.concat(a)));return n}return[]};try{return i(e).join(" | ")}catch(n){try{return JSON.stringify(e)}catch{return String(e)}}}(e),w=!t.toggler||t._showChatbot,A="AvatarPage"===t._shownPage?"AVATAR":"CHAT",x=e?.context?.chatSocket?.chatbotMode||"unknown";return m`
2273
- <div class="test-mode-states">
2274
- <div><b>FSM</b>: ${C||"(no state)"}</div>
2275
- <div><b>UI</b>: Chatbot Visible=${String(w)}, Mode (UI → FSM)=${A} → ${x}</div>
2276
- <div>Initialization: ${i}</div>
2277
- <div>Conversation: ${h}</div>
2278
- <div>Substate: ${v}</div>
2279
- <div>AvatarRunning: ${String(t._avatarRunning)}</div>
2280
- <div>InputsBlocked: ${b}</div>
2281
- <div>isPageVisible: ${t._actorSnapshot?.context?.isPageVisible}</div>
2282
- <div>pendingStart: ${String(t._actorSnapshot?.context?.pendingStart)}</div>
2283
- <div>Connection: ${k}</div>
2284
- <pre style="white-space: pre-wrap; margin: 4px 0;">${f?.getConnectionReport?.()}</pre>
2285
- <div style="display:flex; flex-wrap: wrap; gap: 6px; width:50%;">
2286
- <button @click="${()=>t._testSetAuthConnected("disconnected")}">Disconnect Auth</button>
2287
- <button @click="${()=>t._testSetAuthConnected("failed")}">Fail Auth</button>
2288
- <button @click="${()=>t._testSetAuthConnected()}">Connect Auth</button>
2289
- <button @click="${()=>t._testSetSocketConnected("disconnected")}">Disconnect Socket</button>
2290
- <button @click="${()=>t._testSetSocketConnected("failed")}">Fail Socket</button>
2291
- <button @click="${()=>t._testSetSocketConnected()}">Connect Socket</button>
2292
- <button @click="${()=>t._testSetSpeechConnected("disconnected")}">Disconnect Speech</button>
2293
- <button @click="${()=>t._testSetSpeechConnected("failed")}">Fail Speech</button>
2294
- <button @click="${()=>t._testSetSpeechConnected()}">Connect Speech</button>
2295
- ${f?.reconnectFailedModules?m`<button @click="${()=>f.reconnectFailedModules(!0)}">Reconnect Failed</button>`:_}
2296
- ${f?.reconnectDisconnectedModules?m`<button @click="${()=>f.reconnectDisconnectedModules()}">Reconnect All</button>`:_}
2297
- </div>
2298
- </div>
2299
- `})(t):_}
2300
- ${(()=>_)()}
2301
- <div
2302
- class="chatbot ${t.target_app} ${t.compact?"compact":""}"
2303
- @click="${t._handleChatbotClick}"
2304
- style="
2305
- ${t.toggler||"mobile"===t.target_app?`width: ${t._canvasWidth}px; height: ${"mobile"===t.target_app||t.toggler&&window.innerWidth<768?"calc(var(--chatbot-dynamic-height) - var(--chatbot-bottom-offset, 0px))":`${t._chatbotHeight}px`};`:`width: 100%; height: ${t._chatbotHeight}px;`}
2306
- "
2307
- >
2308
- ${t.compact?_:(t=>m`
2309
- <header @click="${t=>t.stopPropagation()}">
2310
- <div class="header-container">
2311
- <div class="header-left">
2312
- <div class="menu-icon" @click="${t._handleToggleMenu}">
2313
- ${t._showMenu?Lt:Bt}
2314
- </div>
2315
- ${(t=>{const e=t._isConversationInProgress,i=t._isStartingConversation||t._isInitializingConversation,n=t._isConversationStopped,a=t._isConversationResumable;return m`
2316
- ${t._showMenu?m`<div class="menu-backdrop" @click="${t._handleToggleMenu}"></div>`:null}
2317
- <div id="menu" class="${t._showMenu?"show":"hide"}">
2318
- <div class="menu-items" >
2319
- <div class="conversation-details">
2320
- <span class="conversation-status" title="${t._t("conversationStatus")}">${e?m`<small>${t._t("conversationInProgress")}</small>`:m`<small>${t._t("conversationStopped")}</small>`}</span>
2321
- </div>
2322
- <div ?hidden=${!n||e||i||a}>
2323
- <a type="button" @click="${t._handleStartConversationMenuBtn}" href="#">${t._t("startConversation")}</a>
2324
- </div>
2325
- <div ?hidden=${!e}>
2326
- <a type="button" @click="${t._handleEndConversationBtn}" href="#">${t._t("endConversation")}</a>
2327
- </div>
2328
- <hr>
2329
- <div ?hidden=${!t._canDownloadTranscript()}>
2330
- <a type="button" @click="${t._handleDownloadTranscriptMenuBtn}" href="#">${t._t("downloadConversation")}</a>
2331
- </div>
2332
- <div class="labels-container">
2333
- <label>${t._t("liveCaptions")}</label>
2334
- <label class="captions-switch">
2335
- <input type="checkbox" .checked=${t.enable_captions} @click="${t._handleToggleCaptionsSwitch}">
2336
- <span class="captions-slider round"></span>
2337
- </label>
2338
- </div>
2339
- </div>
2340
- </div>
2341
- `})(t)}
2342
- </div>
2343
- <div class="header-center">
2344
- <h3 id="avatar-name">${t._avatarName}</h3>
2345
- ${(t=>"AvatarPage"===t._shownPage||"ChatPage"===t._shownPage?m`
2346
- <div class="switches-container" dir="ltr">
2347
- <input type="radio" id="switchAvatar" name="switchMode" value="Avatar" .checked=${"AvatarPage"===t._shownPage} />
2348
- <input type="radio" id="switchChat" name="switchMode" value="Chat" .checked=${"ChatPage"===t._shownPage}/>
2349
- <label for="switchAvatar" @click="${t._handleShowAvatarPage}">${t._t("avatar")}</label>
2350
- <label for="switchChat" @click="${t._handleShowChatPage}">${t._t("chat")}</label>
2351
- <div class="switch-wrapper">
2352
- <div class="switch">
2353
- <div>${t._t("avatar")}</div>
2354
- <div>${t._t("chat")}</div>
2355
- </div>
2356
- </div>
2357
- </div>
2358
- `:_)(t)}
2359
- </div>
2360
- <div class="header-right">
2361
- ${"mobile"!==t.target_app&&t.toggler?m`
2362
- <div @click="${t._closeChatbot}" class="close-icon" title="${t._t("close")}">
2363
- ${Lt}
2364
- </div>
2365
- `:_}
2366
- ${t.brand_logo?m`
2367
- <div>
2368
- <img src="${t.brand_logo}" class="logo-image">
2369
- </div>
2370
- `:_}
2371
- </div>
2372
- </div>
2373
- </header>
2374
- `)(t)}
2375
-
2376
- <div
2377
- class="chatbot-body ${"ChatPage"===t._shownPage?"chat-mode":""} ${t.target_app} ${t.compact?"compact":""}"
2378
- >
2379
- ${(t=>{const e=t._statusBarStatus;if(!e||"connected"===e)return _;const i={initializing:t._t("statusInitializing"),disconnected:t._t("statusReconnecting"),recovering:t._t("statusReconnecting"),failed:t._t("statusFailed"),invalidConfiguration:t._t("statusInvalidConfiguration")}[e]||"";return i?m`
2380
- <div class="status-bar status--${e}" role="status">
2381
- ${i}
2382
- </div>
2383
- `:_})(t)}
2384
- <div id="toastify-dismissable-alerts"></div>
2385
- ${(t=>"LoaderPage"===t._shownPage?m`
2386
- <div class="page-wrapper" id="loader_page">
2387
- <div class="page-center">
2388
- <div class="lds-dual-ring"></div>
2389
- </div>
2390
- </div>
2391
- `:_)(t)}
2392
- ${Ht(t)}
2393
- ${t.compact?_:(t=>{let e,i="";const n=t._isStartingConversation,a=t._isInitializingConversation,s=t._isConversationInProgress,o=t._isConversationPaused,r=t._isConversationResumable;return n||a?(e=m`
2394
- <div class="chat-start-container center-aligned">
2395
- <div class="lds-dual-ring small"></div>
2396
- </div>`,i="center-aligned"):r?(e=m`
2397
- <div class="chat-start-container center-aligned">
2398
- <small>${t._t("previousConversationFound")}</small>
2399
- </div>`,i="center-aligned"):s||o?e=m`
2400
- <ul class="chatbox">
2401
- ${t._conversationTranscript.length?t._conversationTranscript.map((t=>((t,{speaker:e,messageText:i,time:n})=>{const a=Ct(i)?"rtl":"ltr";return m`
2402
- <li class="chat ${e}">
2403
- ${"assistant"===e?Ot:""}
2404
- <div style="direction: ${a}; text-align: ${"rtl"===a?"right":"left"}" class="message-container">
2405
- <p class="message-bubble" style="word-wrap: break-word; word-break: break-word;">${i}</p>
2406
- <small class="message-time ${"rtl"===a?"time-left":"time-right"}">${n}</small>
2407
- </div>
2408
- </li>
2409
- `})(0,t))):(t=>m`<h3 id="no-msgs-head">${t._t("noMessagesYet")}</h3>`)(t)}
2410
- </ul>
2411
- ${(t=>{const e=t._isConversationPaused?t._t("reconnecting"):t._inputsBlocked?t._t("waitForResponse"):t._t("typeHere");return m`
2412
- <div class="chat-input ${t._inputsBlocked?"input-blocked":""}">
2413
- ${t._inputsBlocked?m`
2414
- <div class="input-loading-dots">
2415
- <div class="dot"></div>
2416
- <div class="dot"></div>
2417
- <div class="dot"></div>
2418
- </div>
2419
- `:_}
2420
- <textarea
2421
- @keyup="${t._handleChatKeyUp}"
2422
- type="text"
2423
- id="message_input"
2424
- placeholder="${e}"
2425
- ?disabled="${t._inputsBlocked}"
2426
- ></textarea>
2427
- <div
2428
- @click="${t._handleSendTextMessage}"
2429
- id="chat_send_button"
2430
- class="${t._inputsBlocked?"send-button-disabled":""}"
2431
- >
2432
- ${Pt}
2433
- </div>
2434
- </div>
2435
- `})(t)}
2436
- `:(e=m`
2437
- <div class="chat-placeholder-container">
2438
- <div class="chat-placeholder-content">
2439
- <div class="chat-placeholder-icon">
2440
- ${It}
2441
- </div>
2442
- <h3 class="chat-placeholder-title">${t._t("chatPlaceholderTitle")}</h3>
2443
- <p class="chat-placeholder-description">${t._t("chatPlaceholderDescription")}</p>
2444
- </div>
2445
- <div class="chat-placeholder-button">
2446
- ${$t(t)}
2447
- </div>
2448
- </div>`,i="placeholder-mode"),m`
2449
- <div class="page-wrapper" id="chat-page" ?hidden=${"ChatPage"!==t._shownPage}>
2450
- <div class="chat-wrapper ${i}">
2451
- ${e}
2452
- </div>
2453
- </div>
2454
- `})(t)}
2455
- ${(t=>"ErrorPage"===t._shownPage?m`
2456
- <div class="page-wrapper" id="error_page">
2457
- <div class="page-center">
2458
- ${Nt}
2459
- </div>
2460
- </div>
2461
- `:_)(t)}
2462
- ${(t=>"DisconnectedPage"===t._shownPage?m`
2463
- <div class="page-wrapper" id="disconnected_page">
2464
- <div class="page-center">
2465
- ${Vt(t)}
2466
- </div>
2467
- </div>
2468
- `:_)(t)}
2469
- </div>
2470
- ${"mobile"===t.target_app||t.compact?_:(t=>{const e=t.brand_name||"Sentifyd",i=!!t.brand_name;return m`
2471
- <footer>
2472
- ${i?m`<small>${e}</small>`:m`<small><a href="https://sentifyd.io" target="_blank">Sentifyd</a></small>`}
2473
- </footer>
2474
- `})(t)}
2475
- ${(t=>t._showLastMessage?m`
2476
- <div class="last-message" @click="${t._closeLastMessage}">
2477
- <div class="last-message-content">
2478
- <div style="direction: ${Ct(t._lastMessageText)?"rtl":"ltr"}" class="last-message-scrollable">
2479
- ${t._lastMessageText}
2480
- <button class="last-message-copy-button" @click="${e=>((t,e)=>{t.stopPropagation();const i=e._lastMessageText;i&&navigator.clipboard.writeText(i).then((()=>{e._showCopyTick=!0,setTimeout((()=>{e._showCopyTick=!1}),1500)})).catch((t=>{}))})(e,t)}">
2481
- ${t._showCopyTick?Ft:zt}
2482
- </button>
2483
- </div>
2484
- </div>
2485
- </div>
2486
- `:_)(t)}
2487
- ${(t=>t._showConfirmationDialog?m`
2488
- <div class="dialog-overlay">
2489
- <div class="dialog">
2490
-
2491
- <p>${t._dialogMessage}</p>
2492
- <div class="dialog-button-wrapper">
2493
- <button class="confirm-button" @click="${t._handleConfirm}">${t._confirmButtonLabel}</button>
2494
- <button class="cancel-button" @click="${t._handleCancel}">${t._cancelButtonLabel}</button>
2495
- </div>
2496
- </div>
2497
- </div>
2498
- `:_)(t)}
2499
- ${(t=>t._showUserData?m`
2500
- <div class="dialog-overlay">
2501
- <div class="dialog">
2502
- <h3>${t._t("secureFormTitle")}</h3>
2503
- <p>${t._t("secureFormDescription")}</p>
2504
- <div class="form-group">
2505
- <label for="username">${t._t("name")}</label>
2506
- <input @input="${e=>t.username=e.target.value}" type="text" id="username" placeholder="${t._t("namePlaceholder")}" .value=${t.username} required>
2507
- </div>
2508
- <div class="form-group">
2509
- <label for="email">${t._t("email")}*</label>
2510
- <input @input="${e=>t.email=e.target.value}" type="email" id="email" placeholder="${t._t("emailPlaceholder")}" .value=${t.email} required>
2511
- </div>
2512
- <div class="form-group">
2513
- <label for="phoneNumber">${t._t("phoneNumber")}</label>
2514
- <input @input="${e=>t.phoneNumber=e.target.value}" type="tel" id="phoneNumber" placeholder="${t._t("phonePlaceholder")}" .value=${t.phoneNumber}>
2515
- </div>
2516
- <div> <p style="font-size: 0.8em;">${t._t("secureFormNote")}</p></div>
2517
- <div class="dialog-button-group" style="text-align: start;">
2518
- <button class="button-save" @click="${t._handleSaveClick}" type="button" ?disabled="${!t.username?.trim()||!t.email?.trim()}">${t._t("send")}</button>
2519
- <button class="button-cancel" @click="${t._handleCancelClick}">${t._t("cancel")}</button>
2520
- </div>
2521
- </div>
2522
- </div>
2523
- `:_)(t)}
2524
- ${(t=>t._showSatisfactionScore?m`
2525
- <div class="dialog-overlay">
2526
- <div class="dialog">
2527
- <p>${t._t("conversationEndedPrompt")}</p>
2528
- <div class="radio-group">
2529
- ${[1,2,3,4,5].map((e=>m`
2530
- <label class="radio-label">
2531
- <input
2532
- class="radio-input"
2533
- type="radio"
2534
- name="satisfactionScore"
2535
- value="${e}"
2536
- @change="${e=>t._satisfactionScore=parseInt(e.target.value)}"
2537
- ?checked="${t._satisfactionScore===e}"
2538
- />
2539
- ${e}
2540
- </label>
2541
- `))}
2542
- </div>
2543
- <div class="dialog-button-group">
2544
- <button
2545
- class="button-save"
2546
- @click="${t._handleSubmitScoreClick}"
2547
- type="button"
2548
- ?disabled="${null==t._satisfactionScore}"
2549
- >
2550
- ${t._t("submit")}
2551
- </button>
2552
- <button class="button-cancel" @click="${t._handleCancelScoreClick}">
2553
- ${t._t("skip")}
2554
- </button>
2555
- </div>
2556
- </div>
2557
- </div>
2558
- `:_)(t)}
2559
- ${(t=>t._showChatConsentDialog?m`
2560
- <div class="dialog-overlay">
2561
- <div class="dialog consent-dialog" role="dialog" aria-modal="true" aria-labelledby="chat-consent-title">
2562
- <p id="chat-consent-title" class="label"><b>${t._t("consentTitle")}</b></p>
2563
- <div class="consent-text scrollable" tabindex="0" aria-label="${t._t("consentScrollableAria")||t._t("consentTitle")}">
2564
- <p>${t._t("consentInfo1")}</p>
2565
- <p>${t._t("consentInfo2")}</p>
2566
- <p>
2567
- ${t._t("consentReadOur")}
2568
- <a href="${t.terms_href}" target="_blank" rel="noopener noreferrer">${t._t("consentTermsLabel")}</a>
2569
- ${t._t("consentAnd")}
2570
- <a href="${t.privacy_href}" target="_blank" rel="noopener noreferrer">${t._t("consentPrivacyLabel")}</a>
2571
- ${t._t("consentMoreDetails")}
2572
- </p>
2573
- <p><small>${t._t("consentInfo4")}</small></p>
2574
- </div>
2575
- <div class="dialog-button-group" style="text-align: center;">
2576
- <button class="button-save" aria-label="${t._t("consentAcceptAria")}" @click="${t._handleConsentAccept}" type="button">${t._t("consentAccept")}</button>
2577
- <button class="button-cancel" aria-label="${t._t("consentDeclineAria")}" @click="${t._handleConsentDecline}" type="button">${t._t("consentDecline")}</button>
2578
- </div>
2579
- </div>
2580
- </div>`:_)(t)}
2581
- </div>
2582
- </div>
2583
- `;var t}_scheduleInputFocus(t=null){this._focusTimeoutId&&(cancelAnimationFrame(this._focusTimeoutId),this._focusTimeoutId=null),this._focusTimeoutId=requestAnimationFrame((()=>{try{const e=t||this._getCurrentInputType();if(!e)return void(this._focusTimeoutId=null);const i="chat"===e?"#message_input":"#typed_input",n=this.shadowRoot.querySelector(i);n&&!n.disabled&&this._isElementFocusable(n)&&document.activeElement!==n&&n.focus()}catch(e){}finally{this._focusTimeoutId=null}}))}_getCurrentInputType(){return"ChatPage"===this._shownPage?"chat":"AvatarPage"===this._shownPage&&this._showTyping?"typing":null}_isElementFocusable(t){if(!t)return!1;if(null===t.offsetParent)return!1;if("none"===t.style.display||"hidden"===t.style.visibility)return!1;try{const e=window.getComputedStyle(t);return"none"!==e.display&&"hidden"!==e.visibility}catch(e){return!0}}async connectedCallback(){super.connectedCallback(),["visibilitychange","pagehide","freeze"].forEach((t=>{this._onDom(document,t,(t=>this._handleVisibilityChange(t)))})),this._onDom(window,"focus",(t=>this._handleVisibilityChange(t))),this._onDom(window,"pageshow",(t=>this._handleVisibilityChange(t))),this._handleVisibilityChange({type:"init"}),requestAnimationFrame((()=>{this.updateSize(),requestAnimationFrame((()=>this.updateSize()))})),this._onBus("event_command_UI_UpdateCurrentMessage",(t=>{this._currentMessage={speaker:t.speaker,messageText:t.messageText,time:(new Date).toLocaleTimeString("en-US",{hour12:!1})}})),this._onBus("event_command_UI_UpdateSTTCaption",(t=>{if(this.enable_captions){const e=(t=>{if(t.length<=40)return t;const e=t.length-40,i=t.indexOf(" ",e);return-1!==i?t.slice(i).trim():t.slice(0,e).trim()})(t.STTCaption);this._updateLiveCaption(!0,e,"user")}})),this._onBus("event_command_UI_PlayCaptions",(t=>{if(this.enable_captions){const e=this._speakingAvatar?.avatarModule?.liveCaptions;e&&e.playCaptions(((t,e="",i=!1)=>{this._updateLiveCaption(t,e,"assistant",i)}),t.audioStartTime)}})),this._onBus("event_command_UI_ClearCaptions",(()=>{this._updateLiveCaption(!1,"","")})),this._onBus("event_command_UI_ClearConversation",(()=>{document.hidden||this._idleSpeakingAvatar(),this._speakingAvatar?.sessionData?.conversation?.transcript&&(this._conversationTranscript=[...this._speakingAvatar.sessionData.conversation.transcript]),this._updateLiveCaption(!1),this._currentMessage=null})),this._onBus("event_status_Conversation_MessageAppended",(t=>{try{this._speakingAvatar?.sessionData?.conversation?.transcript&&(this._conversationTranscript=[...this._speakingAvatar.sessionData.conversation.transcript])}catch(e){}if("user"===t?.speaker){this._userCaptionClearTimeoutId&&clearTimeout(this._userCaptionClearTimeoutId);const t=T?.captions?.captionTimeout;this._userCaptionClearTimeoutId=setTimeout((()=>{try{"user"===this._liveCaptionSpeaker&&this._updateLiveCaption(!1,"","")}finally{this._userCaptionClearTimeoutId=null}}),t)}this._scheduleChatScroll(),setTimeout((()=>this._scheduleChatScroll()),80)})),this._onBus("event_status_Conversation_TimedOut",(t=>{this.showConfirmationDialog(this._t("conversationExpiredPrompt"),(()=>{this._callDownloadTranscript(),this._speakingAvatar.avatarOrchestrator.sendEvent("CLEAR_CONVERSATION",{conversationId:t.conversationId})}),(()=>{this._speakingAvatar.avatarOrchestrator.sendEvent("CLEAR_CONVERSATION",{conversationId:t.conversationId})}),this._t("downloadAndClear"),this._t("onlyClear"))})),this._onBus("event_status_Conversation_ResumedSuccessfully",(()=>{try{const t=this._speakingAvatar?.sessionData?.conversation;this._conversationTranscript=Array.isArray(t?.transcript)?t.transcript:[]}catch(t){this._conversationTranscript=[]}})),this._onBus("event_status_Conversation_ResumeFailedAndRestarted",(()=>{try{const t=this._speakingAvatar?.sessionData?.conversation;this._conversationTranscript=Array.isArray(t?.transcript)?t.transcript:[]}catch(t){this._conversationTranscript=[]}this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("resumeConversationFailedNewStarted"),className:"alert-warning"})})),this._onBus("event_status_Conversation_ResumeExpired",(()=>{this.showConfirmationDialog(this._t("conversationExpiredResumePrompt"),(()=>{this._callDownloadTranscript(),this._speakingAvatar.avatarOrchestrator.sendEvent("DISMISS")}),(()=>{this._speakingAvatar.avatarOrchestrator.sendEvent("DISMISS")}),this._t("download"),this._t("ok"))})),this._onBus("event_command_UI_RequestUserData",(()=>{"mobile"===this.target_app?this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("enterInfoOnMobile"),className:"alert-warning"}):this._showUserData=!0})),this._onBus("event_command_UI_EnableCaptions",(()=>{this.enable_captions=!0})),this._onBus("event_command_UI_DisableCaptions",(()=>{this.enable_captions=!1})),this._onBus("event_status_Avatar_RenderingStateChanged",(t=>{const e=!!t?.running;this._avatarRunning!==e&&(this._avatarRunning=e)})),this._onBus("event_command_UI_SwitchToChatMode",(()=>{"ChatPage"!==this._shownPage?this._shownPage="ChatPage":this._syncUiChatbotMode()})),this._onBus("event_command_UI_SwitchToAvatarMode",(()=>{"AvatarPage"!==this._shownPage?this._shownPage="AvatarPage":this._syncUiChatbotMode();try{this._startListening()}catch(t){}})),this._onBus("event_command_UI_EndConversation",(()=>{this._endConversation()})),this._onDom(window,"resize",this.handleWindowResize.bind(this));try{const t="undefined"!=typeof window&&window.visualViewport?window.visualViewport:null;t&&(this._onDom(t,"resize",this.handleWindowResize.bind(this)),this._onDom(t,"scroll",this.handleWindowResize.bind(this)))}catch(e){}this.resizeObserver=new ResizeObserver((t=>{if(!t||!t.length)return;const i=t[0],{width:n,height:a}=i.contentRect||{};if((!this.toggler||!1!==this._showChatbot)&&n>120&&a>120&&(T.dom.canvasWidth=Math.round(n),T.dom.canvasHeight=Math.round(a),this._speakingAvatar&&this._speakingAvatar.avatarModule))try{this._speakingAvatar.avatarModule.onResize()}catch(e){}}));const t=this.renderRoot.querySelector("#avatar-container");t&&this.resizeObserver.observe(t);try{this.hostResizeObserver=new ResizeObserver((()=>{requestAnimationFrame((()=>this.updateSize()))})),this.hostResizeObserver.observe(this)}catch(e){}}disconnectedCallback(){if(super.disconnectedCallback(),this._disposeListeners(),this.captionsTimeoutId&&(clearTimeout(this.captionsTimeoutId),this.captionsTimeoutId=null),this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),this._focusTimeoutId&&(cancelAnimationFrame(this._focusTimeoutId),this._focusTimeoutId=null),this._speakingAvatar?.destroy?.(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.hostResizeObserver){try{this.hostResizeObserver.disconnect()}catch(t){}this.hostResizeObserver=null}}updateSize(){const t="undefined"!=typeof window&&window.visualViewport?window.visualViewport:null,e=t?Math.round(t.width):window.innerWidth,i=t?Math.round(t.height):window.innerHeight,n=t?Math.round(t.offsetTop):0,a=e<T.dom.smallDisplayWidth;let s,o;const r=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:null},c=r(this.canvasWidth),l=r(this.canvasHeight),h=r(this.chatbotHeight),d=(this.compact?0:T.dom.headerAndFooterHeight)+T.dom.controlsHeight;if("mobile"===this.target_app){s=e,o=i;try{this.style.setProperty("--chatbot-dynamic-height",`${i}px`),this.style.setProperty("--chatbot-dynamic-top",`${n}px`)}catch(u){}}else if(this.toggler)if(a){s=e,o=i;try{this.style.setProperty("--chatbot-dynamic-height",`${i}px`),this.style.setProperty("--chatbot-dynamic-top",`${n}px`)}catch(u){}}else{const t=Math.max(120,c??(T.dom.canvasWidth||400)),e=Math.max(120,l??(T.dom.canvasHeight||500));s=t,o=Math.max(120,h??e+d)}else{const t=this.getBoundingClientRect?.()||{},n=Math.round(t.width||this.offsetWidth||this.clientWidth||e),a=Math.round(t.height||this.offsetHeight||this.clientHeight||i),r=Math.max(120,c??n),u=Math.max(120,l??(T.dom.canvasHeight||a));s=r;const p=a>=120?a:u+d;o=Math.max(120,h??(l?u+d:p))}this._canvasWidth===s&&this._chatbotHeight===o||(this._canvasWidth=s,this._chatbotHeight=o)}async _initialize(){if(this._initInProgress)return this._initPromise;this._initInProgress=!0,this._initPromise=(async()=>{if(""===this.api_key&&""===this.token_endpoint||""===this.avatar_id)this.updateAlertStatus("ErrorPage");else{this.updateAlertStatus("LoaderPage");try{const t=await this._getChatbotState();this._showChatbot=t.isVisible,this._savedChatbotMode=t.mode,null!==t.enableCaptions&&(this.enable_captions=t.enableCaptions),await this.updateComplete,await this._initializeSpeakingAvatar()}catch(t){this.updateAlertStatus("DisconnectedPage")}}})();try{await this._initPromise}finally{this._initInProgress=!1,this._initPromise=null}}async _initializeSpeakingAvatar(){const t={avatarAPIKey:this.api_key,avatarId:this.avatar_id,avatarContainer:this.renderRoot.querySelector("#avatar-container"),tokenEndpoint:this.token_endpoint,targetApp:this.target_app};this._wakeLock.request();try{if(!(await this._speakingAvatar.init(t)))throw new Error("Initialization failed");this._avatarName=this._speakingAvatar.sessionData.avatarName,this._language=this._speakingAvatar.sessionData.language,this.username=this._speakingAvatar.sessionData.username,this.phoneNumber=this._speakingAvatar.sessionData.phoneNumber,this.email=this._speakingAvatar.sessionData.email,!0===this.isTermsAccepted?this._speakingAvatar.sessionData.isTermsAccepted=!0:this.isTermsAccepted=this._speakingAvatar.sessionData.isTermsAccepted,this._isFullBody=this._speakingAvatar?.avatarModule?.isFullBody,this._setupAvatarStateSubscription();const e=null!==this._speakingAvatar?.sessionData?.trainingId;e&&(this._initConversation(),this._syncUiChatbotMode()),e?this.compact?this._shownPage="AvatarPage":"CHAT"===this._savedChatbotMode?this._shownPage="ChatPage":this._shownPage="AvatarPage":this._shownPage="ErrorPage"}catch(e){throw e}}handleWindowResize(){this.updateSize()}_handleVisibilityChange(t){let e=!0;try{const i="string"==typeof t?t:t?.type;e=!(document.hidden||"hidden"===document.visibilityState),"pagehide"!==i&&"freeze"!==i||(e=!1),"pageshow"!==i&&"focus"!==i||(e=!0)}catch(n){e=!0}const i=this._speakingAvatar?.avatarOrchestrator;i&&"function"==typeof i.sendEvent?i.sendEvent("VISIBILITY_CHANGED",{isVisible:e}):e?this._resumeAfterForeground():this._pauseAvatarForBackground()}_pauseAvatarForBackground(){this._speakingAvatar?.avatarOrchestrator?(this._speakingAvatar.avatarOrchestrator.is("speaking")&&this._speakingAvatar.avatarOrchestrator.sendEvent("INTERRUPT"),this._speakingAvatar.avatarOrchestrator.is("listening")&&this._speakingAvatar.avatarOrchestrator.sendEvent("IDLE"),this._speakingAvatar.avatarOrchestrator.is("idle")||this._speakingAvatar.avatarOrchestrator.is("stopped")||this._idleSpeakingAvatar(),this._wakeLock.release()):this._wakeLock.release()}_resumeAfterForeground(){}_idleSpeakingAvatar(){this._speakingAvatar&&this._speakingAvatar.avatarOrchestrator&&(this._speakingAvatar.avatarOrchestrator.is("idle")||this._speakingAvatar.avatarOrchestrator.is("stopped")||this._speakingAvatar.avatarOrchestrator.sendEvent("IDLE"))}_startListening(){this._inputsBlocked||this._isConversationInProgress&&this._speakingAvatar?.avatarOrchestrator?.is("idle")&&this._speakingAvatar.avatarOrchestrator.sendEvent("LISTEN")}_initConversation(){this.isInitialized()&&this._speakingAvatar.avatarOrchestrator.sendEvent("INIT_CONVERSATION")}_startOrResumeConversation(t=!1){Promise.resolve(this._hasChatConsent()).then((e=>{e?this._proceedStartConversation(t):this._showChatConsentDialog=!0})).catch((()=>{this._showChatConsentDialog=!0}))}_proceedStartConversation(t){try{const t=!(document.hidden||"hidden"===document.visibilityState);this._speakingAvatar?.avatarOrchestrator?.sendEvent("VISIBILITY_CHANGED",{isVisible:t})}catch(e){}this._speakingAvatar?.sessionData&&!0===this.isTermsAccepted&&(this._speakingAvatar.sessionData.isTermsAccepted=!0),this._speakingAvatar.avatarOrchestrator.sendEvent("START_CONVERSATION",{fresh:t,termsAccepted:!0===this.isTermsAccepted})}_endConversation(t=!0){t?this._showSatisfactionScore=!0:this._speakingAvatar.avatarOrchestrator.sendEvent("END_CONVERSATION",{satisfactionScore:0})}_updateLiveCaption(t,e="",i="",n=!1,a=!1){const s=T?.captions??{},o=s.captionChangeDelay??200,r=s.captionTimeout??1500,c=this._liveCaptionSpeaker;t&&"user"===i&&this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),a?(this._isLiveCaptionsVisible=!1,setTimeout((()=>{this._isLiveCaptionsVisible=t,this._liveCaption=e,this._liveCaptionSpeaker=i}),o)):(this.captionsTimeoutId&&(clearTimeout(this.captionsTimeoutId),this.captionsTimeoutId=null),this._isLiveCaptionsVisible=t,this._liveCaption=e,this._liveCaptionSpeaker=i),t||"user"===(i||c)&&this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),n&&(this.captionsTimeoutId=setTimeout((()=>{this._isLiveCaptionsVisible=!1,this._liveCaption="",this._liveCaptionSpeaker="",this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),this.captionsTimeoutId=null}),r))}updateAlertStatus(t=null){const e=this._actorSnapshot;e?.context;const i=!(!this.api_key&&!this.token_endpoint||!this.avatar_id),n=this._speakingAvatar?.sessionData&&null===this._speakingAvatar.sessionData.trainingId;let a=null;a=i?e?.matches?.("lifecycle.init.initializing")?"initializing":e?.matches?.("lifecycle.init.failed")?"failed":n?"invalidConfiguration":e?.matches?.("connection.connected")?"connected":"recovering":"invalidConfiguration","initializing"!==a||"connected"!==this._statusBarStatus&&"recovering"!==this._statusBarStatus||(a=this._statusBarStatus),this._statusBarStatus!==a&&(this._statusBarStatus=a),null!==t&&this._shownPage!==t&&(this._shownPage=t)}get initStatusValue(){return this.initStatus()}initStatus(){const t=this._actorSnapshot;if(!t)return"INITIALIZING";if(!this.api_key&&!this.token_endpoint||!this.avatar_id)return"INVALID";if(t.matches?.("lifecycle.init.failed"))return"FAILED";if(t.context?.initFailed&&t.matches?.("lifecycle.init.initializing"))return"FAILED";if(t.matches?.("lifecycle.init.initializing"))return"INITIALIZING";const e=this._speakingAvatar?.sessionData;return e&&e.avatarId&&null===e.trainingId?"INVALID":"COMPLETED"}isInitialized(){return"COMPLETED"===this.initStatus()}isInitializing(){return"INITIALIZING"===this.initStatus()}_handleToggleChatbot(){this._showChatbot||this._isConversationInProgress||this._isInitializingConversation?this._updateChatbotVisibility(!this._showChatbot):(this._updateChatbotVisibility(!0),this.isInitialized()&&this._startOrResumeConversation())}_updateChatbotVisibility(t){this._showChatbot=t,this._saveChatbotState()}_saveChatbotState(){const t="ChatPage"===this._shownPage?"CHAT":"AVATAR",e={isVisible:this._showChatbot,mode:t,enableCaptions:this.enable_captions};Y.setItem("chatbotState_"+this.avatar_id,JSON.stringify(e))}async _getChatbotState(){try{const t=await Y.getItem("chatbotState_"+this.avatar_id);if(t){const e=JSON.parse(t);return{isVisible:!0===e.isVisible,mode:e.mode||"AVATAR",enableCaptions:void 0!==e.enableCaptions?e.enableCaptions:null}}}catch(t){}return{isVisible:!1,mode:"AVATAR",enableCaptions:null}}_openLastMessage(t){this._lastMessageText=this._currentMessage.messageText,this._showLastMessage=!0}_closeLastMessage(){this._showLastMessage=!1}_showMenuOnHover(){window.matchMedia("(hover: hover)").matches&&(this._showMenu=!0,this.shadowRoot.getElementById("menu").classList.remove("hidden"))}_handleChatbotClick(){if(!this.compact){const t=this.shadowRoot.getElementById("menu");t?.classList.add("hide"),setTimeout((()=>{t?.classList.contains("hide")&&(this._showMenu=!1)}),500)}}_closeChatbot(){this._updateChatbotVisibility(!1)}_handleToggleMenu(){this._showMenu=!this._showMenu}_handleMicBtn(){const t=this._speakingAvatar?.avatarOrchestrator;t&&(this._isConversationInProgress||this._isStartingConversation)?(this._speakingAvatar?.avatarModule?.resumeAudioContext?.(),t.sendEvent("MIC_BUTTON")):this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("startConversationReminder")})}_handleShowChatPage(){if(this.isInitialized()){if(this.compact)return;this._shownPage="ChatPage",this._showMenu=!1,this._saveChatbotState()}}_handleShowAvatarPage(){this.isInitialized()&&(this._shownPage="AvatarPage",this._startListening(),this._showMenu=!1,this._saveChatbotState())}_handleShowUserData(t){t.preventDefault(),this._showUserData=!0,this._showMenu=!1}_handleEndConversationBtn(){this.showConfirmationDialog(this._t("endConversationPrompt"),(()=>{this._endConversation()}),(()=>{}),this._t("end"),this._t("cancel")),this._showMenu=!1}_handleStartConversationMenuBtn(t){t.preventDefault(),t.stopPropagation(),this._shouldConfirmRestart()?this._handleRestartConversation():(this._startOrResumeConversation(!0),this._showMenu=!1)}_handleStartConversationBtn(t){t.preventDefault(),this._shouldConfirmRestart()?this._handleRestartConversation():this._startOrResumeConversation(!0)}_handleRestartConversation(){this.showConfirmationDialog(this._t("restartConversationPrompt"),(()=>{this._idleSpeakingAvatar(),this._startOrResumeConversation(!0)}),(()=>{}),this._t("newConversation"),this._t("cancel"))}_consentStorageKey(){return`chatConsent_${this.avatar_id||"unknown"}`}async _hasChatConsent(){if(!0===this.isTermsAccepted)return!0;try{return"accepted"===await Y.getItem(this._consentStorageKey())}catch(t){return!1}}async _handleConsentAccept(){try{await Y.setItem(this._consentStorageKey(),"accepted")}catch(t){}this._showChatConsentDialog=!1;try{this.isTermsAccepted=!0,this._speakingAvatar?.sessionData&&(this._speakingAvatar.sessionData.isTermsAccepted=!0)}catch(t){}this._shouldConfirmRestart()?this._handleRestartConversation():this._startOrResumeConversation(!0)}async _handleConsentDecline(){try{await Y.setItem(this._consentStorageKey(),"declined")}catch(t){}this._showChatConsentDialog=!1}_activateConsentFocusTrap(){requestAnimationFrame((()=>{try{this.shadowRoot?.querySelector(".dialog .button-save")?.focus()}catch(t){}}));const t=t=>{if(this._showChatConsentDialog&&("Escape"===t.key&&(this._showChatConsentDialog=!1,t.stopPropagation()),"Tab"===t.key)){const e=Array.from(this.shadowRoot.querySelectorAll(".dialog button"));if(!e.length)return;const i=e.indexOf(document.activeElement);t.preventDefault(),(t.shiftKey?i<=0?e[e.length-1]:e[i-1]:i===e.length-1?e[0]:e[i+1]).focus()}};this._consentKeyHandler=t,this.addEventListener("keydown",t)}_deactivateConsentFocusTrap(){this._consentKeyHandler&&(this.removeEventListener("keydown",this._consentKeyHandler),this._consentKeyHandler=null)}_canDownloadTranscript(){return this._conversationTranscript.length>0}_handleDownloadTranscriptMenuBtn(t){t.preventDefault(),this._callDownloadTranscript(),this._showMenu=!1}_callDownloadTranscript(){((t,e,i,n)=>{const a=(new Date).toLocaleString().replace(/[/:, ]/g,"-");let s=`\ufeff\nCONVERSATION TRANSCRIPT\n\n\nšŸ“… Date: ${(new Date).toLocaleString()}\nšŸ¤– Assistant: ${e}\nšŸ‘¤ User: ${i||"User"}${t?`\n⚔ Powered by ${t}`:""}\n\n`;n.forEach((t=>{const{speaker:n,messageText:a,time:o}=t;let r,c;if("user"===n)r=i||"User",c="šŸ‘¤";else{if("assistant"!==n)return;r=e,c="šŸ¤–"}s+=`${c} ${r} [${o}]\n${a}\n\n─────────────────────\n\n`}));const o=new Blob([s],{type:"text/plain;charset=utf-8"}),r=document.createElement("a");r.href=URL.createObjectURL(o),r.download=`transcript-${e}-${a}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r)})(this.brand_name,this._speakingAvatar.sessionData.avatarName,this._speakingAvatar.sessionData.username,this._conversationTranscript)}async _handleSaveClick(){this._speakingAvatar.sessionData.username=this.username,this._speakingAvatar.sessionData.phoneNumber=this.phoneNumber,this._speakingAvatar.sessionData.email=this.email,this._speakingAvatar.sessionData.isTermsAccepted=this.isTermsAccepted,this._speakingAvatar?.chatSocket?.sendUserData(),this._showUserData=!1}_handleCancelClick(){this._showUserData=!1}_handleChatKeyUp(t){"Enter"!==t.key&&13!==t.keyCode||(t.preventDefault(),this._handleSendTextMessage())}_handleSendTextMessage(){if(this._inputsBlocked)return void this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("waitCurrentResponse")});const t=this.renderRoot.querySelector("#message_input"),e=t.value;e&&""!==e.trim()&&(this._speakingAvatar?.avatarModule?.resumeAudioContext?.(),t.value="",this._speakingAvatar.avatarOrchestrator.sendEvent("SEND_TEXT_MESSAGE",{message:e}))}_handleTypingKeyUp(t){"Enter"!==t.key&&13!==t.keyCode||(t.preventDefault(),this._handleSendTypedInput())}_handleSendTypedInput(){if(this._inputsBlocked)return void this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("waitCurrentResponse")});const t=this.renderRoot.querySelector("#typed_input"),e=t.value;e&&""!==e.trim()&&(this._speakingAvatar?.avatarModule?.resumeAudioContext?.(),t.value="",this._speakingAvatar.avatarOrchestrator.sendEvent("SEND_TEXT_MESSAGE",{message:e,chatbotMode:"AVATAR"}))}showConfirmationDialog(t,e,i,n,a){this._dialogMessage=t,this._confirmDialog=e,this._cancelDialog=i,this._confirmButtonLabel=n??this._t("confirm"),this._cancelButtonLabel=a??this._t("cancel"),this._showConfirmationDialog=!0}_handleConfirm(){this._confirmDialog&&this._confirmDialog(),this._resetDialog()}_handleCancel(){this._cancelDialog&&this._cancelDialog(),this._resetDialog()}_resetDialog(){this._showConfirmationDialog=!1,this._confirmDialog=()=>{},this._cancelDialog=()=>{},this._dialogMessage="",this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel")}_handleToggleCaptionsSwitch(t){this.enable_captions=t.target.checked,this._saveChatbotState()}_handleVisemeButtonClick(t){this.bus.emit("event_command_visemeButtonClick",{visemeId:t.target.getAttribute("data-viseme-id")})}_handleFacialButtonClick(t){this.bus.emit("event_command_facialButtonClick",{facialId:t.target.getAttribute("data-facial-id")})}_handleConnectBtn(){"COMPLETED"!==this.initStatus()?this._initialize():this.bus.emit("event_command_ConnectionManager_ReconnectFailedModules")}_handleUpperBodyIcon(){this._speakingAvatar?.avatarModule?.setView("upper")}_handleFullBodyIcon(){this._speakingAvatar?.avatarModule?.setView("full")}_handleMidBodyIcon(){this._speakingAvatar?.avatarModule?.setView("mid")}_handleHeadBodyIcon(){this._speakingAvatar?.avatarModule?.setView("head")}_handleSubmitScoreClick(){this._speakingAvatar.avatarOrchestrator.sendEvent("END_CONVERSATION",{satisfactionScore:this._satisfactionScore}),this._showSatisfactionScore=!1}_handleCancelScoreClick(){this._speakingAvatar.avatarOrchestrator.sendEvent("END_CONVERSATION",{satisfactionScore:0}),this._showSatisfactionScore=!1}_scheduleChatScroll(){try{if("ChatPage"!==this._shownPage)return;requestAnimationFrame((()=>{try{const t=this.shadowRoot?.querySelector(".chatbox");t&&(t.scrollTop=t.scrollHeight)}catch(t){}}))}catch(t){}}_syncUiChatbotMode(){if(!this._speakingAvatar?.avatarOrchestrator||!this._speakingAvatar?.chatSocket)return;const t={isShown:!this.toggler||this._showChatbot,chatbotMode:"AvatarPage"===this._shownPage?"AVATAR":"CHAT"};t.isShown===this._lastUiChatbotMode.isShown&&t.chatbotMode===this._lastUiChatbotMode.chatbotMode||(this._speakingAvatar.avatarOrchestrator.sendEvent("UI_CHATBOT_MODE",t),this._lastUiChatbotMode=t)}_handleToggleTyping(){this._showTyping=!this._showTyping}_testSetAuthConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules.authentication.updateConnectionState(t)}_testSetSocketConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules.chatSocket.updateConnectionState(t)}_testSetSpeechConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules["speech-token"].updateConnectionState(t)}_shouldConfirmRestart(){return!!(this._isConversationInProgress||this._isConversationPaused||this._isConversationResumable||this._isConversationTimedOut||this._isInitializingConversation)}}const ie="undefined"!=typeof window&&void 0!==window.sessionStorage,ne={getItem:t=>Promise.resolve(ie?window.sessionStorage.getItem(t):null),setItem:(t,e)=>Promise.resolve(ie?window.sessionStorage.setItem(t,e):void 0),removeItem:t=>Promise.resolve(ie?window.sessionStorage.removeItem(t):void 0)};function ae(t){Y.setInstance(t)}function se(){"undefined"!=typeof window&&void 0!==window.customElements&&(customElements.get("sentifyd-bot")||customElements.define("sentifyd-bot",ee))}function oe(t){if(se(),t.containerId&&document.querySelector(`#${t.containerId} sentifyd-bot`))return document.querySelector(`#${t.containerId} sentifyd-bot`);let e=document.body;if(t.containerId){const i=document.getElementById(t.containerId);i&&(e=i)}const i=document.createElement("sentifyd-bot");return Object.keys(t).forEach((e=>{if("containerId"===e||"customAttributes"===e)return;const n=t[e];if(null!=n&&""!==n){const t=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();i.setAttribute(t,"boolean"==typeof n?String(n):n)}})),t.customAttributes&&Object.keys(t.customAttributes).forEach((e=>{const n=t.customAttributes[e];null!=n&&""!==n&&i.setAttribute(e,String(n))})),e.appendChild(i),i}Y.setInstance(ne),"undefined"!=typeof window&&se();export{ee as SentifydBot,oe as createSentifydBot,ae as initializeStorage,se as registerSentifydBot};
2802
+ `;class Xt extends(function(t=Object){return class extends t{constructor(...t){super(...t),this._eventBus=new bt,this._domDisposers=[]}get bus(){return this._eventBus}_onBus(t,e){return this._eventBus.on(t,e)}_onDom(t,e,i,a){t.addEventListener(e,i,a);const n=()=>t.removeEventListener(e,i,a);return this._domDisposers.push(n),n}pushDisposer(t){if("function"!=typeof t)throw new TypeError("Disposer must be a function");this._domDisposers.push(t)}_disposeListeners(){this._eventBus.dispose(),this._domDisposers.forEach((t=>{try{t()}catch(e){}})),this._domDisposers.length=0}_createChildBus(){return new bt}}}(f)){static#c=!1;static _injectFontLinks(){if(Xt.#c)return;if("undefined"==typeof document||!document.head)return;Xt.#c=!0;const t=document.createElement("link");t.rel="preconnect",t.href="https://fonts.googleapis.com",t.crossOrigin="anonymous",document.head.appendChild(t);const e=document.createElement("link");e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="anonymous",document.head.appendChild(e);const i=document.createElement("link");i.href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block",i.rel="stylesheet",document.head.appendChild(i);const a=document.createElement("link");a.href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap",a.rel="stylesheet",document.head.appendChild(a)}static get properties(){return{api_key:{type:String,attribute:"api-key"},token_endpoint:{type:String,attribute:"token-endpoint"},avatar_id:{type:String,attribute:"avatar-id"},toggler:{type:Boolean,reflect:!0,converter:t=>"false"!==t},barge_in:{type:Boolean,reflect:!0,attribute:"barge-in",converter:t=>"false"!==t},terms_href:{type:String,attribute:"terms-href"},privacy_href:{type:String,attribute:"privacy-href"},brand_name:{type:String,attribute:"brand-name"},brand_logo:{type:String,attribute:"brand-logo"},username:{type:String},phoneNumber:{type:String},email:{type:String},isTermsAccepted:{type:Boolean,attribute:"terms-accepted"},compact:{type:Boolean,reflect:!0,converter:t=>"false"!==t},target_app:{type:String,attribute:"target-app"},enable_captions:{type:Boolean,reflect:!0,attribute:"enable-captions",converter:t=>"false"!==t},uiLanguage:{type:String,attribute:"ui-language"},canvasWidth:{type:Number,reflect:!0,attribute:"canvas-width"},canvasHeight:{type:Number,reflect:!0,attribute:"canvas-height"},chatbotHeight:{type:Number,reflect:!0,attribute:"chatbot-height"},avatarBackground:{type:String,reflect:!0,attribute:"avatar-background"},cornerRadius:{type:String,reflect:!0,attribute:"corner-radius"},_canvasWidth:{type:Number,attribute:!1},_canvasHeight:{type:Number,attribute:!1},_chatbotHeight:{type:Number,attribute:!1},_language:{type:String,attribute:!1},_avatarName:{type:String,attribute:!1},_currentMessage:{type:Object,attribute:!1},_actorSnapshot:{type:Object,attribute:!1},_conversationTranscript:{type:Array,attribute:!1},_showConversationPanel:{type:Boolean,attribute:!1},_showChatbot:{type:Boolean,attribute:!1},_showMenu:{type:Boolean,attribute:!1},_shownPage:{type:String,attribute:!1},_showUserData:{type:Boolean,attribute:!1},_showSatisfactionScore:{type:Boolean,attribute:!1},_showLastMessage:{type:Boolean,attribute:!1},_satisfactionScore:{type:Number,attribute:!1},_lastMessageText:{type:String,attribute:!1},_liveCaption:{type:String,attribute:!1},_liveCaptionSpeaker:{type:String,attribute:!1},_isLiveCaptionsVisible:{type:Boolean,attribute:!1,reflect:!1},_showConfirmationDialog:{type:Boolean,attribute:!1},_dialogMessage:{type:String,attribute:!1},_confirmButtonLabel:{type:String,attribute:!1},_cancelButtonLabel:{type:String,attribute:!1},_showCopyTick:{type:Boolean,attribute:!1},_isFullBody:{type:Boolean,attribute:!1},_showTyping:{type:Boolean,attribute:!1},_statusBarStatus:{type:String,attribute:!1},_inputsBlocked:{type:Boolean,attribute:!1},_isThinking:{type:Boolean,attribute:!1},_isListening:{type:Boolean,attribute:!1},_isSpeaking:{type:Boolean,attribute:!1},_isConversationInProgress:{type:Boolean,attribute:!1},_isConversationPaused:{type:Boolean,attribute:!1},_isAutoResuming:{type:Boolean,attribute:!1},_isCheckingResume:{type:Boolean,attribute:!1},_isResumeExpired:{type:Boolean,attribute:!1},_isInitializingConversation:{type:Boolean,attribute:!1},_isConversationTimedOut:{type:Boolean,attribute:!1},_isStartingConversation:{type:Boolean,attribute:!1},_isConversationStopped:{type:Boolean,attribute:!1},_isDisconnected:{type:Boolean,attribute:!1},_isFailed:{type:Boolean,attribute:!1},_avatarRunning:{type:Boolean,attribute:!1},_showChatConsentDialog:{type:Boolean,attribute:!1}}}static get observedAttributes(){const t=super.observedAttributes??[];return[...new Set([...t,"api_key","token_endpoint","avatar_id","terms_href","privacy_href","brand_name","brand_logo","target_app","enable_captions","barge_in"])]}attributeChangedCallback(t,e,i){if(super.attributeChangedCallback&&super.attributeChangedCallback(t,e,i),t in{api_key:"api-key",token_endpoint:"token-endpoint",avatar_id:"avatar-id",terms_href:"terms-href",privacy_href:"privacy-href",brand_name:"brand-name",brand_logo:"brand-logo",target_app:"target-app",enable_captions:"enable-captions",barge_in:"barge-in",avatar_background:"avatar-background"}){try{this._deprecatedAttrWarnings=this._deprecatedAttrWarnings||new Set,this._deprecatedAttrWarnings.has(t)||this._deprecatedAttrWarnings.add(t)}catch(a){}switch(t){case"enable_captions":case"barge_in":{const e=null!==i&&"false"!==i;this[t]=e;break}case"avatar_background":this.avatarBackground=i;break;default:this[t]=i}}}static styles=[qt,Gt,Kt,Qt,Jt,Zt,Yt];constructor(){super(),this.api_key="",this.token_endpoint="",this.avatar_id="",this.toggler=!0,this.barge_in=!1,this.terms_href="",this.privacy_href="",this.brand_name="",this.brand_logo="",this.compact=!1,this.target_app="web",this.enable_captions=!0,this.uiLanguage=ft,this.canvasWidth=T.dom.canvasWidth,this.canvasHeight=T.dom.canvasHeight,this.chatbotHeight=T.dom.canvasHeight+T.dom.headerAndFooterHeight,this._canvasWidth=T.dom.canvasWidth,this._canvasHeight=T.dom.canvasHeight,this._chatbotHeight=T.dom.canvasHeight+T.dom.headerAndFooterHeight,this._speakingAvatar=null,this._language="",this.username="",this.phoneNumber="",this.email="",this.isTermsAccepted=!1,this._avatarName="Assistant",this._conversationTranscript=[],this._currentMessage=null,this._actorSnapshot={value:"initializing",context:{transcript:[]},matches:()=>!1},this._showConversationPanel=!1,this._showChatbot=!1,this._showMenu=!1,this._shownPage="LoaderPage",this._savedChatbotMode=null,(this.api_key||this.token_endpoint)&&this.avatar_id?this._statusBarStatus="initializing":(this._shownPage="ErrorPage",this._statusBarStatus="invalidConfiguration"),this._showUserData=!1,this._showSatisfactionScore=!1,this._showLastMessage=!1,this._satisfactionScore=null,this._lastMessageText="",this._liveCaption="",this._liveCaptionSpeaker="",this._isLiveCaptionsVisible=!0,this._alerts=null,this._showConfirmationDialog=!1,this._dialogMessage="",this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel"),this._stateTestMode=T.test.stateTestMode,this._showCopyTick=!1,this._isFullBody=!0,this._showTyping=!1,this._wakeLock=new Ct,this._focusTimeoutId=null,this.captionsTimeoutId=null,this._userCaptionClearTimeoutId=null,this._fontRevealTimeoutId=null,this._captionSwitchTimeoutId=null,this._menuHideTimeoutId=null,this._connection="unknown",this._initTriggered=!1,this._initInProgress=!1,this._initPromise=null,this._inputsBlocked=!1,this._isThinking=!1,this._isListening=!1,this._isSpeaking=!1,this._isConversationInProgress=!1,this._isConversationPaused=!1,this._isAutoResuming=!1,this._isResumeExpired=!1,this._isInitializingConversation=!1,this._isConversationTimedOut=!1,this._isStartingConversation=!1,this._isConversationStopped=!1,this._isDisconnected=!1,this._isFailed=!1,this._avatarRunning=!1,this._showChatConsentDialog=!1,this.avatarBackground="",this.cornerRadius=void 0,this._dirManagedByUiLanguage=!1,this._lastUiChatbotMode={isShown:null,chatbotMode:null},this._chatScrollTimeoutId=null,this._speakingAvatar=new _t(this.bus),this._applyBargeInPreference(),this._setupAvatarStateSubscription()}_t(t){return St(this.uiLanguage,t)}_applyUiLanguage(){this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel")}_applyDirectionFromUiLanguage(){const t=!0===this._dirManagedByUiLanguage,e=this.getAttribute("dir");if(!t&&("rtl"===e||"ltr"===e||"auto"===e))return;const i=(this.uiLanguage||ft).toLowerCase().split("-")[0],a=["ar","he","fa","ur"].includes(i)?"rtl":"ltr";this.dir!==a?(this.dir=a,this._dirManagedByUiLanguage=!0):t||(this._dirManagedByUiLanguage=!0)}_getAvatarBackgroundStyleObj(){const t=(this.avatarBackground??"").toString().trim();if(!t)return{};const e=t.toLowerCase();if(e.includes("url(")||e.includes("expression(")||e.includes("@import")||e.includes("@supports")||e.includes("@media"))return{};if(this._bgTestEl??="undefined"!=typeof document&&document?.createElement?document.createElement("div"):null,!this._bgTestEl)return{};const i=this._bgTestEl;if(/^(linear-gradient|radial-gradient|conic-gradient)\(/i.test(t)){if("undefined"!=typeof CSS&&CSS.supports?.("background-image",t))return i.style.backgroundImage="",i.style.backgroundImage=t,i.style.backgroundImage?{backgroundImage:i.style.backgroundImage}:{};try{return i.style.backgroundImage="",i.style.backgroundImage=t,i.style.backgroundImage?{backgroundImage:i.style.backgroundImage}:{}}catch(a){return{}}}if("undefined"!=typeof CSS&&CSS.supports?.("color",t))return i.style.backgroundColor="",i.style.backgroundColor=t,i.style.backgroundColor?{backgroundColor:i.style.backgroundColor}:{};try{return i.style.backgroundColor="",i.style.backgroundColor=t,i.style.backgroundColor?{backgroundColor:i.style.backgroundColor}:{}}catch(a){return{}}}_applyBargeInPreference(){const t=!1!==this.barge_in;try{T?.speech?.bargeIn&&(T.speech.bargeIn.enabled=t)}catch(e){}if(this._speakingAvatar?.setBargeInEnabled)try{const e=this._speakingAvatar.setBargeInEnabled(t);e&&"function"==typeof e.catch&&e.catch((t=>{}))}catch(e){}}firstUpdated(){const t=this.renderRoot.querySelector("#toastify-dismissable-alerts");this._alerts=new wt(this.bus,t,(()=>this.uiLanguage));try{const t=()=>{this._fontRevealTimeoutId=null,this.classList.add("icons-ready")};document.fonts&&document.fonts.ready?document.fonts.ready.then(t).catch((()=>t())):this._fontRevealTimeoutId=setTimeout(t,300)}catch(e){}}_setupAvatarStateSubscription(){if(this._speakingAvatar?.avatarOrchestrator){if(this._orchestratorUnsub){try{this._orchestratorUnsub()}catch{}this._orchestratorUnsub=null}this._orchestratorUnsub=this._speakingAvatar.avatarOrchestrator.subscribeProjected(((t,e)=>{if(!e)return;const i=this._actorSnapshot;this._actorSnapshot=e;let a=!1;const n=(t,e)=>{this[t]!==e&&(this[t]=e,a=!0)};try{n("_isConversationInProgress",!!e.hasTag?.("conversation_in_progress")),n("_isConversationPaused",!!e.hasTag?.("conversation_paused")),n("_isSpeaking",!!e.hasTag?.("speaking")),n("_isListening",!!e.hasTag?.("listening")),n("_isThinking",!!e.hasTag?.("thinking")),n("_inputsBlocked",!!e.hasTag?.("inputs_blocked")),n("_isAutoResuming",!!e.matches?.("lifecycle.conversation.autoResuming")),n("_isCheckingResume",!!e.matches?.("lifecycle.checkingResume")),n("_isResumeExpired",!!e.matches?.("lifecycle.conversation.resumeExpired")),n("_isInitializingConversation",!(!e.matches?.("lifecycle.conversation.initializingConversation")&&!e.matches?.("lifecycle.conversation.initializing"))),n("_isConversationTimedOut",!!e.matches?.("lifecycle.conversation.timedOut")),n("_isStartingConversation",!!(e.matches?.("lifecycle.conversation.inProgress.startingConversation")||e.matches?.("lifecycle.conversation.starting")||e.matches?.("lifecycle.conversation.autoResuming"))),n("_isConversationStopped",!!e.matches?.("lifecycle.conversation.stopped")),n("_isDisconnected",!!e.matches?.("connection.disconnected")),n("_isFailed",!(!e.matches?.("lifecycle.init.failed")&&!e.matches?.("lifecycle.failed")))}catch(s){}(a||i!==e)&&this.updateAlertStatus()}))}}updated(t){if(this.__postUpdateQueue||(this.__postUpdateQueue=[]),(t.has("toggler")||t.has("compact"))&&this.toggler&&this.compact&&(this.compact=!1),(t.has("target_app")||t.has("toggler"))&&"mobile"===this.target_app&&this.toggler&&(this.toggler=!1),t.has("compact")&&this.compact&&this.isInitialized()&&(this._shownPage="AvatarPage"),t.has("uiLanguage")&&(this._applyUiLanguage(),this._applyDirectionFromUiLanguage()),t.has("barge_in")&&this.__postUpdateQueue.push((()=>this._applyBargeInPreference())),this.isInitialized()&&this._speakingAvatar?.sessionData&&(t.has("username")&&this.username!==this._speakingAvatar.sessionData.username&&(this._speakingAvatar.sessionData.username=this.username),t.has("phoneNumber")&&this.phoneNumber!==this._speakingAvatar.sessionData.phoneNumber&&(this._speakingAvatar.sessionData.phoneNumber=this.phoneNumber),t.has("email")&&this.email!==this._speakingAvatar.sessionData.email&&(this._speakingAvatar.sessionData.email=this.email),t.has("isTermsAccepted")&&this.isTermsAccepted!==this._speakingAvatar.sessionData.isTermsAccepted&&(this._speakingAvatar.sessionData.isTermsAccepted=this.isTermsAccepted)),t.has("api_key")||t.has("token_endpoint")||t.has("avatar_id")){const t=!(!this.api_key&&!this.token_endpoint||!this.avatar_id);t&&!this._initTriggered?(this._initTriggered=!0,this.__postUpdateQueue.push((()=>this._initialize()))):t||(this._initTriggered=!1,this.__postUpdateQueue.push((()=>this.updateAlertStatus("ErrorPage"))))}if((t.has("_showChatbot")||t.has("_shownPage"))&&(this.__postUpdateQueue.push((()=>{this._speakingAvatar?.chatSocket&&this._syncUiChatbotMode()})),t.has("_shownPage")&&this.__postUpdateQueue.push((()=>this._speakingAvatar?.avatarOrchestrator?.sendEvent("PAGE_CHANGED",{newPage:this._shownPage}))),t.has("_showChatbot")&&this.__postUpdateQueue.push((()=>{if(!("mobile"===this.target_app||this.toggler&&window.innerWidth<768))try{this.style.removeProperty("--chatbot-dynamic-height")}catch(t){}requestAnimationFrame((()=>{this.updateSize(),requestAnimationFrame((()=>{try{this._speakingAvatar?.avatarModule?.onResize?.()}catch(t){}}))}))}))),this.toggler&&t.has("_showChatbot")&&this._showChatbot&&!this._isConversationInProgress&&!this._isAutoResuming&&!this._isResumeExpired&&this._startOrResumeConversation(!0),t.has("_shownPage")&&("ChatPage"===this._shownPage?(this._scheduleInputFocus("chat"),this._scheduleChatScroll(),this._chatScrollTimeoutId&&clearTimeout(this._chatScrollTimeoutId),this._chatScrollTimeoutId=setTimeout((()=>{this._chatScrollTimeoutId=null,this._scheduleChatScroll()}),80)):"AvatarPage"===this._shownPage&&this._showTyping&&this._scheduleInputFocus("typing")),t.has("_showTyping")&&"AvatarPage"===this._shownPage&&this._showTyping&&this._scheduleInputFocus("typing"),t.has("_inputsBlocked")&&!this._inputsBlocked&&!0===t.get("_inputsBlocked")&&this._scheduleInputFocus(),t.has("canvasWidth")||t.has("canvasHeight")||t.has("chatbotHeight")){const t=()=>this.updateSize();this.__postUpdateQueue.push((()=>requestAnimationFrame(t)))}if(this.__postUpdateQueue.length){const t=this.__postUpdateQueue.splice(0);Promise.resolve().then((()=>{for(const i of t)try{i()}catch(e){}}))}if(t.has("_showChatConsentDialog")&&(this._showChatConsentDialog?this._activateConsentFocusTrap():this._deactivateConsentFocusTrap()),t.has("cornerRadius"))try{const t=this.cornerRadius;if(null==t||""===t)this.style.removeProperty("--corner-radius");else{const e=String(t).trim(),i=/^-?\d+(?:\.\d+)?$/.test(e)?`${e}px`:e;this.style.setProperty("--corner-radius",i)}}catch(e){}}render(){return Wt(this)}_scheduleInputFocus(t=null){this._focusTimeoutId&&(cancelAnimationFrame(this._focusTimeoutId),this._focusTimeoutId=null),this._focusTimeoutId=requestAnimationFrame((()=>{try{const e=t||this._getCurrentInputType();if(!e)return void(this._focusTimeoutId=null);const i="chat"===e?"#message_input":"#typed_input",a=this.shadowRoot.querySelector(i);a&&!a.disabled&&this._isElementFocusable(a)&&document.activeElement!==a&&a.focus()}catch(e){}finally{this._focusTimeoutId=null}}))}_getCurrentInputType(){return"ChatPage"===this._shownPage?"chat":"AvatarPage"===this._shownPage&&this._showTyping?"typing":null}_isElementFocusable(t){if(!t)return!1;if(null===t.offsetParent)return!1;if("none"===t.style.display||"hidden"===t.style.visibility)return!1;try{const e=window.getComputedStyle(t);return"none"!==e.display&&"hidden"!==e.visibility}catch(e){return!0}}async connectedCallback(){super.connectedCallback(),Xt._injectFontLinks(),["visibilitychange","pagehide","freeze"].forEach((t=>{this._onDom(document,t,(t=>this._handleVisibilityChange(t)))})),this._onDom(window,"focus",(t=>this._handleVisibilityChange(t))),this._onDom(window,"pageshow",(t=>this._handleVisibilityChange(t))),this._handleVisibilityChange({type:"init"}),requestAnimationFrame((()=>{this.updateSize(),requestAnimationFrame((()=>this.updateSize()))})),this._onBus("event_command_UI_UpdateCurrentMessage",(t=>{this._currentMessage={speaker:t.speaker,messageText:t.messageText,time:(new Date).toLocaleTimeString("en-US",{hour12:!1})}})),this._onBus("event_command_UI_UpdateSTTCaption",(t=>{if(this.enable_captions){const e=(t=>{if(t.length<=40)return t;const e=t.length-40,i=t.indexOf(" ",e);return-1!==i?t.slice(i).trim():t.slice(0,e).trim()})(t.STTCaption);this._updateLiveCaption(!0,e,"user")}})),this._onBus("event_command_UI_PlayCaptions",(t=>{if(this.enable_captions){const e=this._speakingAvatar?.avatarModule?.liveCaptions;e&&e.playCaptions(((t,e="",i=!1)=>{this._updateLiveCaption(t,e,"assistant",i)}),t.audioStartTime)}})),this._onBus("event_command_UI_ClearCaptions",(()=>{this._updateLiveCaption(!1,"","")})),this._onBus("event_command_UI_ClearConversation",(()=>{document.hidden||this._idleSpeakingAvatar(),this._speakingAvatar?.sessionData?.conversation?.transcript&&(this._conversationTranscript=[...this._speakingAvatar.sessionData.conversation.transcript]),this._updateLiveCaption(!1),this._currentMessage=null})),this._onBus("event_status_Conversation_MessageAppended",(t=>{try{this._speakingAvatar?.sessionData?.conversation?.transcript&&(this._conversationTranscript=[...this._speakingAvatar.sessionData.conversation.transcript])}catch(e){}if("user"===t?.speaker){this._userCaptionClearTimeoutId&&clearTimeout(this._userCaptionClearTimeoutId);const t=T?.captions?.captionTimeout;this._userCaptionClearTimeoutId=setTimeout((()=>{try{"user"===this._liveCaptionSpeaker&&this._updateLiveCaption(!1,"","")}finally{this._userCaptionClearTimeoutId=null}}),t)}this._scheduleChatScroll(),this._chatScrollTimeoutId&&clearTimeout(this._chatScrollTimeoutId),this._chatScrollTimeoutId=setTimeout((()=>{this._chatScrollTimeoutId=null,this._scheduleChatScroll()}),80)})),this._onBus("event_status_Conversation_TimedOut",(t=>{this.showConfirmationDialog(this._t("conversationExpiredPrompt"),(()=>{this._callDownloadTranscript(),this._speakingAvatar?.avatarOrchestrator?.sendEvent("CLEAR_CONVERSATION",{conversationId:t.conversationId})}),(()=>{this._speakingAvatar?.avatarOrchestrator?.sendEvent("CLEAR_CONVERSATION",{conversationId:t.conversationId})}),this._t("downloadAndClear"),this._t("onlyClear"))})),this._onBus("event_status_Conversation_ResumedSuccessfully",(()=>{try{const t=this._speakingAvatar?.sessionData?.conversation;this._conversationTranscript=Array.isArray(t?.transcript)?t.transcript:[]}catch(t){this._conversationTranscript=[]}})),this._onBus("event_status_Conversation_ResumeFailedAndRestarted",(()=>{try{const t=this._speakingAvatar?.sessionData?.conversation;this._conversationTranscript=Array.isArray(t?.transcript)?t.transcript:[]}catch(t){this._conversationTranscript=[]}this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("resumeConversationFailedNewStarted"),className:"alert-warning"})})),this._onBus("event_status_Conversation_ResumeExpired",(()=>{this.showConfirmationDialog(this._t("conversationExpiredResumePrompt"),(()=>{this._callDownloadTranscript(),this._speakingAvatar?.avatarOrchestrator?.sendEvent("DISMISS")}),(()=>{this._speakingAvatar?.avatarOrchestrator?.sendEvent("DISMISS")}),this._t("download"),this._t("ok"))})),this._onBus("event_command_UI_RequestUserData",(()=>{"mobile"===this.target_app?this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("enterInfoOnMobile"),className:"alert-warning"}):this._showUserData=!0})),this._onBus("event_command_UI_EnableCaptions",(()=>{this.enable_captions=!0})),this._onBus("event_command_UI_DisableCaptions",(()=>{this.enable_captions=!1})),this._onBus("event_status_Avatar_RenderingStateChanged",(t=>{const e=!!t?.running;this._avatarRunning!==e&&(this._avatarRunning=e)})),this._onBus("event_command_UI_SwitchToChatMode",(()=>{"ChatPage"!==this._shownPage?this._shownPage="ChatPage":this._syncUiChatbotMode()})),this._onBus("event_command_UI_SwitchToAvatarMode",(()=>{"AvatarPage"!==this._shownPage?this._shownPage="AvatarPage":this._syncUiChatbotMode();try{this._startListening()}catch(t){}})),this._onBus("event_command_UI_EndConversation",(()=>{this._endConversation()})),this._onDom(window,"resize",this.handleWindowResize.bind(this));try{const t="undefined"!=typeof window&&window.visualViewport?window.visualViewport:null;t&&(this._onDom(t,"resize",this.handleWindowResize.bind(this)),this._onDom(t,"scroll",this.handleWindowResize.bind(this)))}catch(e){}this.resizeObserver=new ResizeObserver((t=>{if(!t||!t.length)return;const i=t[0],{width:a,height:n}=i.contentRect||{};if((!this.toggler||!1!==this._showChatbot)&&a>120&&n>120&&(T.dom.canvasWidth=Math.round(a),T.dom.canvasHeight=Math.round(n),this._speakingAvatar&&this._speakingAvatar.avatarModule))try{this._speakingAvatar.avatarModule.onResize()}catch(e){}}));const t=this.renderRoot.querySelector("#avatar-container");t&&this.resizeObserver.observe(t);try{this.hostResizeObserver=new ResizeObserver((()=>{requestAnimationFrame((()=>this.updateSize()))})),this.hostResizeObserver.observe(this)}catch(e){}}disconnectedCallback(){if(super.disconnectedCallback(),this._disposeListeners(),this.captionsTimeoutId&&(clearTimeout(this.captionsTimeoutId),this.captionsTimeoutId=null),this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),this._fontRevealTimeoutId&&(clearTimeout(this._fontRevealTimeoutId),this._fontRevealTimeoutId=null),this._captionSwitchTimeoutId&&(clearTimeout(this._captionSwitchTimeoutId),this._captionSwitchTimeoutId=null),this._menuHideTimeoutId&&(clearTimeout(this._menuHideTimeoutId),this._menuHideTimeoutId=null),this._chatScrollTimeoutId&&(clearTimeout(this._chatScrollTimeoutId),this._chatScrollTimeoutId=null),this._orchestratorUnsub){try{this._orchestratorUnsub()}catch{}this._orchestratorUnsub=null}if(this._focusTimeoutId&&(cancelAnimationFrame(this._focusTimeoutId),this._focusTimeoutId=null),this._bgTestEl=null,this._speakingAvatar?.destroy?.(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.hostResizeObserver){try{this.hostResizeObserver.disconnect()}catch(t){}this.hostResizeObserver=null}this._deactivateConsentFocusTrap()}updateSize(){const t="undefined"!=typeof window&&window.visualViewport?window.visualViewport:null,e=t?Math.round(t.width):window.innerWidth,i=t?Math.round(t.height):window.innerHeight,a=t?Math.round(t.offsetTop):0,n=e<T.dom.smallDisplayWidth;let s,o;const r=t=>{const e=Number(t);return Number.isFinite(e)&&e>0?e:null},c=r(this.canvasWidth),l=r(this.canvasHeight),h=r(this.chatbotHeight),d=(this.compact?0:T.dom.headerAndFooterHeight)+T.dom.controlsHeight;if("mobile"===this.target_app){s=e,o=i;try{this.style.setProperty("--chatbot-dynamic-height",`${i}px`),this.style.setProperty("--chatbot-dynamic-top",`${a}px`)}catch(u){}}else if(this.toggler)if(n){s=e,o=i;try{this.style.setProperty("--chatbot-dynamic-height",`${i}px`),this.style.setProperty("--chatbot-dynamic-top",`${a}px`)}catch(u){}}else{const t=Math.max(120,c??(T.dom.canvasWidth||400)),e=Math.max(120,l??(T.dom.canvasHeight||500));s=t,o=Math.max(120,h??e+d)}else{const t=this.getBoundingClientRect?.()||{},a=Math.round(t.width||this.offsetWidth||this.clientWidth||e),n=Math.round(t.height||this.offsetHeight||this.clientHeight||i),r=Math.max(120,c??a),u=Math.max(120,l??(T.dom.canvasHeight||n));s=r;const p=n>=120?n:u+d;o=Math.max(120,h??(l?u+d:p))}this._canvasWidth===s&&this._chatbotHeight===o||(this._canvasWidth=s,this._chatbotHeight=o)}async _initialize(){if(this._initInProgress&&this._initPromise)return this._initPromise;this._initInProgress=!0;const t=(async()=>{if(""===this.api_key&&""===this.token_endpoint||""===this.avatar_id)this.updateAlertStatus("ErrorPage");else{this.updateAlertStatus("LoaderPage");try{const t=await this._getChatbotState();this._showChatbot=t.isVisible,this._savedChatbotMode=t.mode,null!==t.enableCaptions&&(this.enable_captions=t.enableCaptions),await this.updateComplete,await this._initializeSpeakingAvatar()}catch(t){this.updateAlertStatus("DisconnectedPage")}}})();this._initPromise=t;try{await this._initPromise}finally{this._initInProgress=!1,this._initPromise=null}}async _initializeSpeakingAvatar(){const t={avatarAPIKey:this.api_key,avatarId:this.avatar_id,avatarContainer:this.renderRoot.querySelector("#avatar-container"),tokenEndpoint:this.token_endpoint,targetApp:this.target_app};this._wakeLock.request();try{if(!(await this._speakingAvatar.init(t)))throw new Error("Initialization failed");this._avatarName=this._speakingAvatar.sessionData.avatarName,this._language=this._speakingAvatar.sessionData.language,this.username=this._speakingAvatar.sessionData.username,this.phoneNumber=this._speakingAvatar.sessionData.phoneNumber,this.email=this._speakingAvatar.sessionData.email,!0===this.isTermsAccepted?this._speakingAvatar.sessionData.isTermsAccepted=!0:this.isTermsAccepted=this._speakingAvatar.sessionData.isTermsAccepted,this._isFullBody=this._speakingAvatar?.avatarModule?.isFullBody,this._setupAvatarStateSubscription();const e=null!==this._speakingAvatar?.sessionData?.trainingId;e&&(this._initConversation(),this._syncUiChatbotMode()),e?this.compact?this._shownPage="AvatarPage":"CHAT"===this._savedChatbotMode?this._shownPage="ChatPage":this._shownPage="AvatarPage":this._shownPage="ErrorPage"}catch(e){throw e}}handleWindowResize(){this.updateSize()}_handleVisibilityChange(t){let e=!0;try{const i="string"==typeof t?t:t?.type;e=!(document.hidden||"hidden"===document.visibilityState),"pagehide"!==i&&"freeze"!==i||(e=!1),"pageshow"!==i&&"focus"!==i||(e=!0)}catch(a){e=!0}const i=this._speakingAvatar?.avatarOrchestrator;i&&"function"==typeof i.sendEvent?i.sendEvent("VISIBILITY_CHANGED",{isVisible:e}):e?this._resumeAfterForeground():this._pauseAvatarForBackground()}_pauseAvatarForBackground(){this._speakingAvatar?.avatarOrchestrator?(this._speakingAvatar.avatarOrchestrator.is("speaking")&&this._speakingAvatar.avatarOrchestrator.sendEvent("INTERRUPT"),this._speakingAvatar.avatarOrchestrator.is("listening")&&this._speakingAvatar.avatarOrchestrator.sendEvent("IDLE"),this._speakingAvatar.avatarOrchestrator.is("idle")||this._speakingAvatar.avatarOrchestrator.is("stopped")||this._idleSpeakingAvatar(),this._wakeLock.release()):this._wakeLock.release()}_resumeAfterForeground(){}_idleSpeakingAvatar(){this._speakingAvatar&&this._speakingAvatar.avatarOrchestrator&&(this._speakingAvatar.avatarOrchestrator.is("idle")||this._speakingAvatar.avatarOrchestrator.is("stopped")||this._speakingAvatar.avatarOrchestrator.sendEvent("IDLE"))}_startListening(){this._inputsBlocked||this._isConversationInProgress&&this._speakingAvatar?.avatarOrchestrator?.is("idle")&&this._speakingAvatar?.avatarOrchestrator?.sendEvent("LISTEN")}_initConversation(){this.isInitialized()&&this._speakingAvatar?.avatarOrchestrator?.sendEvent("INIT_CONVERSATION")}_startOrResumeConversation(t=!1){Promise.resolve(this._hasChatConsent()).then((e=>{e?this._proceedStartConversation(t):this._showChatConsentDialog=!0})).catch((()=>{this._showChatConsentDialog=!0}))}_proceedStartConversation(t){try{const t=!(document.hidden||"hidden"===document.visibilityState);this._speakingAvatar?.avatarOrchestrator?.sendEvent("VISIBILITY_CHANGED",{isVisible:t})}catch(e){}this._speakingAvatar?.sessionData&&!0===this.isTermsAccepted&&(this._speakingAvatar.sessionData.isTermsAccepted=!0),this._speakingAvatar?.avatarOrchestrator?.sendEvent("START_CONVERSATION",{fresh:t,termsAccepted:!0===this.isTermsAccepted})}_endConversation(t=!0){t?this._showSatisfactionScore=!0:this._speakingAvatar?.avatarOrchestrator?.sendEvent("END_CONVERSATION",{satisfactionScore:0})}_updateLiveCaption(t,e="",i="",a=!1,n=!1){const s=T?.captions??{},o=s.captionChangeDelay??200,r=s.captionTimeout??1500,c=this._liveCaptionSpeaker;t&&"user"===i&&this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),n?(this._isLiveCaptionsVisible=!1,this._captionSwitchTimeoutId&&clearTimeout(this._captionSwitchTimeoutId),this._captionSwitchTimeoutId=setTimeout((()=>{this._captionSwitchTimeoutId=null,this._isLiveCaptionsVisible=t,this._liveCaption=e,this._liveCaptionSpeaker=i}),o)):(this.captionsTimeoutId&&(clearTimeout(this.captionsTimeoutId),this.captionsTimeoutId=null),this._isLiveCaptionsVisible=t,this._liveCaption=e,this._liveCaptionSpeaker=i),t||"user"===(i||c)&&this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),a&&(this.captionsTimeoutId=setTimeout((()=>{this._isLiveCaptionsVisible=!1,this._liveCaption="",this._liveCaptionSpeaker="",this._userCaptionClearTimeoutId&&(clearTimeout(this._userCaptionClearTimeoutId),this._userCaptionClearTimeoutId=null),this.captionsTimeoutId=null}),r))}updateAlertStatus(t=null){const e=this._actorSnapshot;e?.context;const i=!(!this.api_key&&!this.token_endpoint||!this.avatar_id),a=this._speakingAvatar?.sessionData&&null===this._speakingAvatar.sessionData.trainingId;let n=null;n=i?e?.matches?.("lifecycle.init.initializing")?"initializing":e?.matches?.("lifecycle.init.failed")?"failed":a?"invalidConfiguration":e?.matches?.("connection.connected")?"connected":"recovering":"invalidConfiguration","initializing"!==n||"connected"!==this._statusBarStatus&&"recovering"!==this._statusBarStatus||(n=this._statusBarStatus),this._statusBarStatus!==n&&(this._statusBarStatus=n),null!==t&&this._shownPage!==t&&(this._shownPage=t)}get initStatusValue(){return this.initStatus()}initStatus(){const t=this._actorSnapshot;if(!t)return"INITIALIZING";if(!this.api_key&&!this.token_endpoint||!this.avatar_id)return"INVALID";if(t.matches?.("lifecycle.init.failed"))return"FAILED";if(t.context?.initFailed&&t.matches?.("lifecycle.init.initializing"))return"FAILED";if(t.matches?.("lifecycle.init.initializing"))return"INITIALIZING";const e=this._speakingAvatar?.sessionData;return e&&e.avatarId&&null===e.trainingId?"INVALID":"COMPLETED"}isInitialized(){return"COMPLETED"===this.initStatus()}isInitializing(){return"INITIALIZING"===this.initStatus()}_handleToggleChatbot(){this._showChatbot||this._isConversationInProgress||this._isInitializingConversation?this._updateChatbotVisibility(!this._showChatbot):(this._updateChatbotVisibility(!0),this.isInitialized()&&this._startOrResumeConversation())}_updateChatbotVisibility(t){this._showChatbot=t,this._saveChatbotState()}_saveChatbotState(){const t="ChatPage"===this._shownPage?"CHAT":"AVATAR",e={isVisible:this._showChatbot,mode:t,enableCaptions:this.enable_captions};Y.setItem("chatbotState_"+this.avatar_id,JSON.stringify(e))}async _getChatbotState(){try{const t=await Y.getItem("chatbotState_"+this.avatar_id);if(t){const e=JSON.parse(t);return{isVisible:!0===e.isVisible,mode:e.mode||"AVATAR",enableCaptions:void 0!==e.enableCaptions?e.enableCaptions:null}}}catch(t){}return{isVisible:!1,mode:"AVATAR",enableCaptions:null}}_openLastMessage(t){this._lastMessageText=this._currentMessage.messageText,this._showLastMessage=!0}_closeLastMessage(){this._showLastMessage=!1}_showMenuOnHover(){window.matchMedia("(hover: hover)").matches&&(this._showMenu=!0,this.shadowRoot.getElementById("menu").classList.remove("hidden"))}_handleChatbotClick(){if(!this.compact){const t=this.shadowRoot.getElementById("menu");t?.classList.add("hide"),this._menuHideTimeoutId&&clearTimeout(this._menuHideTimeoutId),this._menuHideTimeoutId=setTimeout((()=>{this._menuHideTimeoutId=null,t?.classList.contains("hide")&&(this._showMenu=!1)}),500)}}_closeChatbot(){this._updateChatbotVisibility(!1)}_handleToggleMenu(){this._showMenu=!this._showMenu}_handleMicBtn(){const t=this._speakingAvatar?.avatarOrchestrator;t&&(this._isConversationInProgress||this._isStartingConversation)?(this._speakingAvatar?.avatarModule?.resumeAudioContext?.(),t.sendEvent("MIC_BUTTON")):this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("startConversationReminder")})}_handleShowChatPage(){if(this.isInitialized()){if(this.compact)return;this._shownPage="ChatPage",this._showMenu=!1,this._saveChatbotState()}}_handleShowAvatarPage(){this.isInitialized()&&(this._shownPage="AvatarPage",this._startListening(),this._showMenu=!1,this._saveChatbotState())}_handleBackToAvatar(){this._handleShowAvatarPage()}_handleSwitchToChat(){this._handleShowChatPage()}_handleShowUserData(t){t.preventDefault(),this._showUserData=!0,this._showMenu=!1}_handleEndConversationBtn(t){t&&(t.preventDefault(),t.stopPropagation()),this.showConfirmationDialog(this._t("endConversationPrompt"),(()=>{this._endConversation()}),(()=>{}),this._t("end"),this._t("cancel")),this._showMenu=!1}_handleStartConversationMenuBtn(t){t.preventDefault(),t.stopPropagation(),this._shouldConfirmRestart()?this._handleRestartConversation():(this._startOrResumeConversation(!0),this._showMenu=!1)}_handleStartConversationBtn(t){t.preventDefault(),this._shouldConfirmRestart()?this._handleRestartConversation():this._startOrResumeConversation(!0)}_handleRestartConversation(){this.showConfirmationDialog(this._t("restartConversationPrompt"),(()=>{this._idleSpeakingAvatar(),this._startOrResumeConversation(!0)}),(()=>{}),this._t("newConversation"),this._t("cancel"))}_consentStorageKey(){return`chatConsent_${this.avatar_id||"unknown"}`}async _hasChatConsent(){if(!0===this.isTermsAccepted)return!0;try{return"accepted"===await Y.getItem(this._consentStorageKey())}catch(t){return!1}}async _handleConsentAccept(){try{await Y.setItem(this._consentStorageKey(),"accepted")}catch(t){}this._showChatConsentDialog=!1;try{this.isTermsAccepted=!0,this._speakingAvatar?.sessionData&&(this._speakingAvatar.sessionData.isTermsAccepted=!0)}catch(t){}this._shouldConfirmRestart()?this._handleRestartConversation():this._startOrResumeConversation(!0)}async _handleConsentDecline(){try{await Y.setItem(this._consentStorageKey(),"declined")}catch(t){}this._showChatConsentDialog=!1}_activateConsentFocusTrap(){requestAnimationFrame((()=>{try{this.shadowRoot?.querySelector(".dialog .button-save")?.focus()}catch(t){}}));const t=t=>{if(this._showChatConsentDialog&&("Escape"===t.key&&(this._showChatConsentDialog=!1,t.stopPropagation()),"Tab"===t.key)){const e=Array.from(this.shadowRoot.querySelectorAll(".dialog button"));if(!e.length)return;const i=e.indexOf(document.activeElement);t.preventDefault(),(t.shiftKey?i<=0?e[e.length-1]:e[i-1]:i===e.length-1?e[0]:e[i+1]).focus()}};this._consentKeyHandler=t,this.addEventListener("keydown",t)}_deactivateConsentFocusTrap(){this._consentKeyHandler&&(this.removeEventListener("keydown",this._consentKeyHandler),this._consentKeyHandler=null)}_canDownloadTranscript(){return this._conversationTranscript.length>0}_handleDownloadTranscriptMenuBtn(t){t.preventDefault(),this._callDownloadTranscript(),this._showMenu=!1}_callDownloadTranscript(){((t,e,i,a)=>{const n=(new Date).toLocaleString().replace(/[/:, ]/g,"-");let s=`\ufeff\nCONVERSATION TRANSCRIPT\n\n\nšŸ“… Date: ${(new Date).toLocaleString()}\nšŸ¤– Assistant: ${e}\nšŸ‘¤ User: ${i||"User"}${t?`\n⚔ Powered by ${t}`:""}\n\n`;a.forEach((t=>{const{speaker:a,messageText:n,time:o}=t;let r,c;if("user"===a)r=i||"User",c="šŸ‘¤";else{if("assistant"!==a)return;r=e,c="šŸ¤–"}s+=`${c} ${r} [${o}]\n${n}\n\n─────────────────────\n\n`}));const o=new Blob([s],{type:"text/plain;charset=utf-8"}),r=document.createElement("a");r.href=URL.createObjectURL(o),r.download=`transcript-${e}-${n}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r)})(this.brand_name,this._speakingAvatar.sessionData.avatarName,this._speakingAvatar.sessionData.username,this._conversationTranscript)}async _handleSaveClick(){this._speakingAvatar.sessionData.username=this.username,this._speakingAvatar.sessionData.phoneNumber=this.phoneNumber,this._speakingAvatar.sessionData.email=this.email,this._speakingAvatar.sessionData.isTermsAccepted=this.isTermsAccepted,this._speakingAvatar?.chatSocket?.sendUserData(),this._showUserData=!1}_handleCancelClick(){this._showUserData=!1}_handleChatKeyUp(t){"Enter"!==t.key&&13!==t.keyCode||(t.preventDefault(),this._handleSendTextMessage())}_handleSendTextMessage(){if(this._inputsBlocked)return void this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("waitCurrentResponse")});const t=this.renderRoot.querySelector("#message_input"),e=t.value;e&&""!==e.trim()&&(this._speakingAvatar?.avatarModule?.resumeAudioContext?.(),t.value="",this._speakingAvatar?.avatarOrchestrator?.sendEvent("SEND_TEXT_MESSAGE",{message:e}))}_handleTypingKeyUp(t){"Enter"!==t.key&&13!==t.keyCode||(t.preventDefault(),this._handleSendTypedInput())}_handleSendTypedInput(){if(this._inputsBlocked)return void this.bus.emit("event_command_Alerts_ShowDismissableAlert",{errorMessage:this._t("waitCurrentResponse")});const t=this.renderRoot.querySelector("#typed_input"),e=t.value;e&&""!==e.trim()&&(this._speakingAvatar?.avatarModule?.resumeAudioContext?.(),t.value="",this._speakingAvatar?.avatarOrchestrator?.sendEvent("SEND_TEXT_MESSAGE",{message:e,chatbotMode:"AVATAR"}))}showConfirmationDialog(t,e,i,a,n){this._dialogMessage=t,this._confirmDialog=e,this._cancelDialog=i,this._confirmButtonLabel=a??this._t("confirm"),this._cancelButtonLabel=n??this._t("cancel"),this._showConfirmationDialog=!0}_handleConfirm(){this._confirmDialog&&this._confirmDialog(),this._resetDialog()}_handleCancel(){this._cancelDialog&&this._cancelDialog(),this._resetDialog()}_resetDialog(){this._showConfirmationDialog=!1,this._confirmDialog=()=>{},this._cancelDialog=()=>{},this._dialogMessage="",this._confirmButtonLabel=this._t("confirm"),this._cancelButtonLabel=this._t("cancel")}_handleToggleCaptionsSwitch(t){this.enable_captions=t.target.checked,this._saveChatbotState()}_handleVisemeButtonClick(t){this.bus.emit("event_command_visemeButtonClick",{visemeId:t.target.getAttribute("data-viseme-id")})}_handleFacialButtonClick(t){this.bus.emit("event_command_facialButtonClick",{facialId:t.target.getAttribute("data-facial-id")})}_handleConnectBtn(){"COMPLETED"!==this.initStatus()?this._initialize():this.bus.emit("event_command_ConnectionManager_ReconnectFailedModules")}_handleUpperBodyIcon(){this._speakingAvatar?.avatarModule?.setView("upper")}_handleFullBodyIcon(){this._speakingAvatar?.avatarModule?.setView("full")}_handleMidBodyIcon(){this._speakingAvatar?.avatarModule?.setView("mid")}_handleHeadBodyIcon(){this._speakingAvatar?.avatarModule?.setView("head")}_handleSubmitScoreClick(){this._speakingAvatar?.avatarOrchestrator?.sendEvent("END_CONVERSATION",{satisfactionScore:this._satisfactionScore}),this._showSatisfactionScore=!1}_handleCancelScoreClick(){this._speakingAvatar?.avatarOrchestrator?.sendEvent("END_CONVERSATION",{satisfactionScore:0}),this._showSatisfactionScore=!1}_scheduleChatScroll(){try{if("ChatPage"!==this._shownPage)return;requestAnimationFrame((()=>{try{const t=this.shadowRoot?.querySelector(".chatbox");t&&(t.scrollTop=t.scrollHeight)}catch(t){}}))}catch(t){}}_syncUiChatbotMode(){if(!this._speakingAvatar?.avatarOrchestrator||!this._speakingAvatar?.chatSocket)return;const t={isShown:!this.toggler||this._showChatbot,chatbotMode:"AvatarPage"===this._shownPage?"AVATAR":"CHAT"};t.isShown===this._lastUiChatbotMode.isShown&&t.chatbotMode===this._lastUiChatbotMode.chatbotMode||(this._speakingAvatar.avatarOrchestrator.sendEvent("UI_CHATBOT_MODE",t),this._lastUiChatbotMode=t)}_handleToggleTyping(){this._showTyping=!this._showTyping}_testSetAuthConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules.authentication.updateConnectionState(t)}_testSetSocketConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules.chatSocket.updateConnectionState(t)}_testSetSpeechConnected(t="connected"){this._speakingAvatar?.connectionManager?.connectionModules["speech-token"].updateConnectionState(t)}_shouldConfirmRestart(){return!!(this._isConversationInProgress||this._isConversationPaused||this._isAutoResuming||this._isConversationTimedOut||this._isInitializingConversation)}}const te="undefined"!=typeof window&&void 0!==window.sessionStorage,ee={getItem:t=>Promise.resolve(te?window.sessionStorage.getItem(t):null),setItem:(t,e)=>Promise.resolve(te?window.sessionStorage.setItem(t,e):void 0),removeItem:t=>Promise.resolve(te?window.sessionStorage.removeItem(t):void 0)};function ie(t){Y.setInstance(t)}function ae(){"undefined"!=typeof window&&void 0!==window.customElements&&(customElements.get("sentifyd-bot")||customElements.define("sentifyd-bot",Xt))}function ne(t){if(ae(),t.containerId&&document.querySelector(`#${t.containerId} sentifyd-bot`))return document.querySelector(`#${t.containerId} sentifyd-bot`);let e=document.body;if(t.containerId){const i=document.getElementById(t.containerId);i&&(e=i)}const i=document.createElement("sentifyd-bot");return Object.keys(t).forEach((e=>{if("containerId"===e||"customAttributes"===e)return;const a=t[e];if(null!=a&&""!==a){const t=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();i.setAttribute(t,"boolean"==typeof a?String(a):a)}})),t.customAttributes&&Object.keys(t.customAttributes).forEach((e=>{const a=t.customAttributes[e];null!=a&&""!==a&&i.setAttribute(e,String(a))})),e.appendChild(i),i}Y.setInstance(ee),"undefined"!=typeof window&&ae();export{Xt as SentifydBot,ne as createSentifydBot,ie as initializeStorage,ae as registerSentifydBot};