ttp-agent-sdk 2.27.0 â 2.28.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/agent-widget.esm.js +1 -1
- package/dist/agent-widget.esm.js.map +1 -1
- package/dist/agent-widget.js +1 -1
- package/dist/agent-widget.js.map +1 -1
- package/dist/demos/index.html +15 -0
- package/dist/examples/test-index.html +15 -0
- package/examples/test-index.html +15 -0
- package/package.json +1 -1
package/dist/agent-widget.esm.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/*! For license information please see agent-widget.esm.js.LICENSE.txt */
|
|
2
|
-
import{useEffect as e,useRef as t,useState as n}from"react";var o={698:(e,t)=>{var n=Symbol.for("react.transitional.element");function o(e,t,o){var i=null;if(void 0!==o&&(i=""+o),void 0!==t.key&&(i=""+t.key),"key"in t)for(var r in o={},t)"key"!==r&&(o[r]=t[r]);else o=t;return t=o.ref,{$$typeof:n,type:e,key:i,ref:void 0!==t?t:null,props:o}}Symbol.for("react.fragment"),t.jsx=o,t.jsxs=o},848:(e,t,n)=>{e.exports=n(698)}},i={};function r(e){var t=i[e];if(void 0!==t)return t.exports;var n=i[e]={exports:{}};return o[e](n,n.exports,r),n.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var a={};r.r(a),r.d(a,{checkPermissionState:()=>xe,getDeviceInfo:()=>ye,getPermissionInstructions:()=>we,openSettings:()=>Se});var s={};r.r(s),r.d(s,{showBlockedModal:()=>Pe,showNoMicrophoneModal:()=>Te,showPrePromptModal:()=>ke});const c=class{constructor(){this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this}off(e,t){return this.events[e]?(this.events[e]=this.events[e].filter(e=>e!==t),this):this}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return!!this.events[e]&&(this.events[e].forEach(e=>{e(...n)}),!0)}once(e,t){var n=this,o=function(){t(...arguments),n.off(e,o)};return this.on(e,o)}removeAllListeners(e){return e?delete this.events[e]:this.events={},this}},l=class{constructor(){this.name="PCM"}decode(e){if(e instanceof ArrayBuffer)return e;if(e instanceof Uint8Array)return e.buffer;throw new Error("Invalid PCM data type")}encode(e){return e}},d=class{constructor(){this.name="PCMU"}decode(e){for(var t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Int16Array(t.length),o=0;o<t.length;o++)n[o]=this.mulawToLinear(t[o]);return n.buffer}encode(e){for(var t=e instanceof Int16Array?e:new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=this.linearToMulaw(t[o]);return n}mulawToLinear(e){var t=1<<3+(e>>4&7);return(128&e?-1:1)*(132+(15&e)*t+(t>>1)-4)}linearToMulaw(e){var t=e>>8&128;t&&(e=-e),e>32635&&(e=32635),e+=132;for(var n=7,o=16384;0===(e&o)&&n>0;n--,o>>=1);return 255&~(t|n<<4|e>>n+3&15)}},u=class{constructor(){this.name="PCMA"}decode(e){for(var t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Int16Array(t.length),o=0;o<t.length;o++)n[o]=this.alawToLinear(t[o]);return n.buffer}encode(e){for(var t=e instanceof Int16Array?e:new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=this.linearToAlaw(t[o]);return n}alawToLinear(e){var t=(e^=85)>>4&7,n=15&e;return(128&e?-1:1)*(0===t?8+(n<<4):264+(n<<4)<<t-1)}linearToAlaw(e){var t,n,o=e>>8&128;if(o&&(e=-e),e>32635&&(e=32635),e<256)t=0,n=e>>4;else{t=7;for(var i=16384;0===(e&i)&&t>0;t--,i>>=1);n=e>>t+3&15}return 85^(o|t<<4|n)}};function h(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function p(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){h(r,o,i,a,s,"next",e)}function s(e){h(r,o,i,a,s,"throw",e)}a(void 0)})}}const g=class extends c{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.config=e,this.audioContext=null,this.audioQueue=[],this.isPlaying=!1,this.isProcessingQueue=!1,this.currentSource=null,this.outputFormat=null,this.nextStartTime=0,this.scheduledBuffers=0,this.scheduledSources=new Set,this.pcmChunkQueue=[],this.preparedBuffer=[],this.isProcessingPcmQueue=!1,this.isSchedulingFrames=!1,this.MAX_LOOKAHEAD_SECONDS=.02,this.pendingSentenceText=null,this.sentenceTimings=[],this.isCheckingTranscripts=!1,this.codecs={pcm:new l,pcmu:new d,pcma:new u},this.SUPPORTED_CONTAINERS=["wav","raw"],this.SUPPORTED_ENCODINGS=["pcm","pcmu","pcma"],this.SUPPORTED_SAMPLE_RATES=[8e3,16e3,22050,24e3,44100,48e3],this.SUPPORTED_BIT_DEPTHS=[8,16,24],this.SUPPORTED_CHANNELS=[1],console.log("đĩ AudioPlayer v2 initialized")}setOutputFormat(e){var t;this.validateFormat(e)||(console.warn("â ī¸ AudioPlayer: Invalid format, using defaults:",e),e=this.getDefaultFormat());var n=null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate,o=e.sampleRate;this.outputFormat=e,console.log("â
AudioPlayer v2: Format set:",e),this.audioContext&&n&&n!==o&&(console.warn("â ī¸ AudioPlayer: Sample rate changed, recreating AudioContext"),console.warn(" Old: ".concat(n,"Hz â New: ").concat(o,"Hz")),this.stopImmediate(),"closed"!==this.audioContext.state&&this.audioContext.close(),this.audioContext=null,console.log("âšī¸ AudioContext will be recreated on next audio chunk with correct sample rate")),this.audioContext||(this.initializeAudioContext(),this.audioContext&&"suspended"===this.audioContext.state&&this.audioContext.resume().then(()=>{console.log("â
AudioPlayer v2: AudioContext resumed and ready")}).catch(e=>{console.warn("â ī¸ AudioPlayer v2: Could not resume AudioContext:",e)}))}validateFormat(e){var t,n;if(!e)return!1;var o=null===(t=e.container)||void 0===t?void 0:t.toLowerCase(),i=null===(n=e.encoding)||void 0===n?void 0:n.toLowerCase();return o&&i&&this.SUPPORTED_CONTAINERS.includes(o)&&this.SUPPORTED_ENCODINGS.includes(i)&&this.SUPPORTED_SAMPLE_RATES.includes(e.sampleRate)&&this.SUPPORTED_BIT_DEPTHS.includes(e.bitDepth)&&(!e.channels||this.SUPPORTED_CHANNELS.includes(e.channels))}getDefaultFormat(){return{container:"raw",encoding:"pcm",sampleRate:16e3,channels:1,bitDepth:16}}playAudio(e){try{var t=this.createAudioBlob(e);this.audioQueue.push(t),this.isPlaying||this.isProcessingQueue||this.currentSource||setTimeout(()=>this.processQueue(),50)}catch(e){console.error("â AudioPlayer v2: Playback error:",e),this.emit("playbackError",e)}}playChunk(e){var t=this;return p(function*(){var n,o=t.prepareChunk(e);o?(t.preparedBuffer.push(o),t.isSchedulingFrames?setTimeout(()=>{t.preparedBuffer.length>0&&!t.isSchedulingFrames&&t.schedulePreparedFrames()},5):t.schedulePreparedFrames(),t.pcmChunkQueue.length>0&&!t.isProcessingPcmQueue&&t.processPcmQueue()):(console.error("â AudioPlayer: playChunk failed - prepareChunk returned null"),console.error(" pcmData length:",(null==e?void 0:e.byteLength)||"undefined"),console.error(" outputFormat:",t.outputFormat),console.error(" audioContext:",t.audioContext?"initialized":"not initialized"),console.error(" audioContext state:",(null===(n=t.audioContext)||void 0===n?void 0:n.state)||"N/A"),t.emit("playbackError",new Error("Failed to prepare PCM chunk for playback")))})()}prepareChunk(e){try{var t;if(!this.outputFormat)return console.error("â AudioPlayer: Cannot prepare chunk - outputFormat not set"),console.error(" Call setOutputFormat() before playing audio chunks"),null;if(this.audioContext||this.initializeAudioContext(),!this.audioContext)return console.error("â AudioPlayer: Cannot prepare chunk - AudioContext not available"),null;var n=e;if(e.byteLength%2!=0){console.warn("â ī¸ Odd PCM chunk size, padding:",e.byteLength);var o=new Uint8Array(e.byteLength+1);o.set(new Uint8Array(e),0),o[e.byteLength]=0,n=o.buffer}for(var i=new Int16Array(n),r=new Float32Array(i.length),a=1/32768,s=i.length,c=0;c<s;c++)r[c]=i[c]*a;var l=(null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate)||this.audioContext.sampleRate,d=this.audioContext.sampleRate,u=this.audioContext.createBuffer(1,r.length,l);u.getChannelData(0).set(r);var h=u.duration,p=r.length,g=h;return d!==l&&(g=p/d),{buffer:u,duration:g,sampleRate:l,contextSampleRate:d}}catch(e){return console.error("â AudioPlayer: Error preparing chunk:",e),null}}applyFadeOut(e){return e}schedulePreparedFrames(){var e=this;return p(function*(){if(!e.isSchedulingFrames){e.isSchedulingFrames=!0;var t=e.preparedBuffer.length,n=Math.min(t,5);0===n&&t>0&&(n=1);try{e.audioContext||e.initializeAudioContext();var o=0===e.scheduledBuffers&&!e.isPlaying;"suspended"===e.audioContext.state&&(yield e.audioContext.resume(),o&&(yield new Promise(e=>setTimeout(e,50)))),"running"!==e.audioContext.state&&(console.warn("AudioPlayer v2: AudioContext not in running state:",e.audioContext.state),"suspended"===e.audioContext.state&&(yield e.audioContext.resume(),o?yield new Promise(e=>setTimeout(e,50)):yield new Promise(e=>setTimeout(e,10))));for(var i=0,r=function*(){var t=e.preparedBuffer.shift();if(!t)return 1;var n=e.audioContext.createBufferSource();n.buffer=t.buffer,n.connect(e.audioContext.destination),e.scheduledSources.add(n);var o=e.audioContext.currentTime;if(0===e.scheduledBuffers)e.nextStartTime<o&&(e.nextStartTime=o+e.MAX_LOOKAHEAD_SECONDS),console.log("đĩ Starting playback with minimal delay:",e.nextStartTime);else{var r=o+e.MAX_LOOKAHEAD_SECONDS;e.nextStartTime<r&&(e.nextStartTime=r,console.warn("â ī¸ AudioPlayer: Fell behind schedule, adjusting nextStartTime to ".concat(e.nextStartTime.toFixed(4),"s")))}e.pendingSentenceText&&(e.sentenceTimings.push({startTime:e.nextStartTime,text:e.pendingSentenceText,displayed:!1}),console.log("đ AudioPlayer: Sentence scheduled at ".concat(e.nextStartTime.toFixed(3),'s: "').concat(e.pendingSentenceText.substring(0,40),'..."')),e.pendingSentenceText=null,e.isCheckingTranscripts||e.startTranscriptChecker()),n.start(e.nextStartTime),e.nextStartTime+=t.duration,e.nextStartTime=Math.round(1e6*e.nextStartTime)/1e6;var a=e.nextStartTime-t.duration;e.scheduledBuffers<5&&(console.log("đĩ AudioPlayer: Scheduled frame ".concat(e.scheduledBuffers+1," at ").concat(a.toFixed(4),"s, next at ").concat(e.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(t.duration.toFixed(4),"s (").concat((1e3*t.duration).toFixed(2),"ms), Queued: ").concat(e.preparedBuffer.length,", Scheduled: ").concat(e.scheduledBuffers))),e.scheduledBuffers++,i++,n.onended=()=>{if(e.scheduledSources.delete(n),e.scheduledBuffers--,0===e.scheduledBuffers&&0===e.preparedBuffer.length&&0===e.pcmChunkQueue.length)e.isPlaying=!1,e.isSchedulingFrames=!1,console.log("đ AudioPlayer: Emitting playbackStopped event (all buffers finished)"),e.emit("playbackStopped");else if(e.preparedBuffer.length>0)setTimeout(()=>{e.preparedBuffer.length>0&&!e.isSchedulingFrames&&e.schedulePreparedFrames()},0);else if(e.scheduledBuffers>0){var t=()=>{e.preparedBuffer.length>0&&!e.isSchedulingFrames&&e.scheduledBuffers>0?e.schedulePreparedFrames():e.scheduledBuffers>0&&setTimeout(t,10)};setTimeout(t,10)}},e.isPlaying||(e.isPlaying=!0,console.log("đĩ AudioPlayer: Emitting playbackStarted event"),e.emit("playbackStarted"))};e.preparedBuffer.length>0&&i<n&&!(yield*r()););e.isSchedulingFrames=!1,e.preparedBuffer.length>0&&requestAnimationFrame(()=>{e.preparedBuffer.length>0&&!e.isSchedulingFrames&&e.schedulePreparedFrames()}),e.scheduledBuffers>0&&setTimeout(()=>{e.preparedBuffer.length>0&&!e.isSchedulingFrames&&e.scheduledBuffers>0?e.schedulePreparedFrames():e.scheduledBuffers>0&&setTimeout(()=>{e.preparedBuffer.length>0&&!e.isSchedulingFrames&&e.scheduledBuffers>0&&e.schedulePreparedFrames()},10)},10)}catch(t){console.error("â AudioPlayer v2: Error scheduling frames:",t),e.emit("playbackError",t),e.isSchedulingFrames=!1}}})()}processPcmQueue(){var e=this;return p(function*(){if(!e.isProcessingPcmQueue){e.isProcessingPcmQueue=!0;try{e.audioContext||e.initializeAudioContext();var t=0===e.scheduledBuffers&&!e.isPlaying;for("suspended"===e.audioContext.state&&(yield e.audioContext.resume(),t&&(yield new Promise(e=>setTimeout(e,50)))),"running"!==e.audioContext.state&&(console.warn("AudioPlayer v2: AudioContext not in running state:",e.audioContext.state),"suspended"===e.audioContext.state&&(yield e.audioContext.resume(),t?yield new Promise(e=>setTimeout(e,50)):yield new Promise(e=>setTimeout(e,10))));e.pcmChunkQueue.length>0;){var n,o,i=e.pcmChunkQueue.shift();if(i){var r=i;if(i.byteLength%2!=0){console.warn("â ī¸ Odd PCM chunk size, padding:",i.byteLength);var a=new Uint8Array(i.byteLength+1);a.set(new Uint8Array(i),0),a[i.byteLength]=0,r=a.buffer}for(var s=new Int16Array(r),c=new Float32Array(s.length),l=1/32768,d=s.length,u=0;u<d;u++)c[u]=s[u]*l;var h=(null===(n=e.outputFormat)||void 0===n?void 0:n.sampleRate)||e.audioContext.sampleRate,p=e.audioContext.sampleRate;null!==(o=e.outputFormat)&&void 0!==o&&o.sampleRate?e.scheduledBuffers<3&&console.log("đĩ AudioPlayer: Creating buffer at ".concat(h,"Hz (AudioContext: ").concat(p,"Hz)")):console.warn("â ī¸ AudioPlayer: outputFormat.sampleRate not set! Using AudioContext sample rate:",p);var g=e.audioContext.createBuffer(1,c.length,h);g.getChannelData(0).set(c);var m=e.audioContext.createBufferSource();m.buffer=g,m.connect(e.audioContext.destination);var v=e.audioContext.currentTime;e.nextStartTime<v&&(e.nextStartTime=v,0===e.scheduledBuffers&&console.log("đĩ Starting playback at current time:",v));var f=g.duration,y=c.length,x=f;if(p!==h&&(x=y/p,e.scheduledBuffers<3&&(console.log("đ Resampling detected: ".concat(h,"Hz â ").concat(p,"Hz")),console.log(" Buffer duration: ".concat(f.toFixed(4),"s, Calculated: ").concat(x.toFixed(4),"s")))),m.start(e.nextStartTime),e.nextStartTime+=x,e.nextStartTime=Math.round(1e6*e.nextStartTime)/1e6,e.scheduledBuffers<3){var b=e.nextStartTime-x;console.log("đĩ AudioPlayer: Scheduled chunk ".concat(e.scheduledBuffers+1," at ").concat(b.toFixed(4),"s, next at ").concat(e.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(x.toFixed(4),"s (").concat((1e3*x).toFixed(2),"ms)"))}e.scheduledBuffers++,m.onended=()=>{e.scheduledBuffers--,0===e.scheduledBuffers&&0===e.pcmChunkQueue.length&&(e.isPlaying=!1,e.isProcessingPcmQueue=!1,e.emit("playbackStopped"))},e.isPlaying||(e.isPlaying=!0,e.emit("playbackStarted"))}}e.isProcessingPcmQueue=!1}catch(t){console.error("â AudioPlayer v2: Error playing chunk:",t),e.emit("playbackError",t),e.isProcessingPcmQueue=!1}}})()}createAudioBlob(e){var t=new Uint8Array(e);console.log("đĩ AudioPlayer: Processing ".concat(t.length," bytes")),console.log("đĩ AudioPlayer: Negotiated format:",this.outputFormat);var n=this.outputFormat&&this.outputFormat.container&&"wav"===this.outputFormat.container.toLowerCase(),o=this.outputFormat&&this.outputFormat.container&&"raw"===this.outputFormat.container.toLowerCase(),i=this.isWavFile(t);if(i&&console.log("đĩ AudioPlayer: Data has WAV header (RIFF)"),o&&i)return console.error("â AudioPlayer: CRITICAL MISMATCH!"),console.error(" Negotiated format: RAW"),console.error(" Actual data: WAV (RIFF header detected)"),console.error(" Backend is ignoring format request and sending WAV anyway."),console.warn("â ī¸ AudioPlayer: Processing as WAV to avoid playback failure, but UI configuration was bypassed."),this.handleWavFile(t);if(o&&!i)console.log("đĩ AudioPlayer: Processing as RAW data (as negotiated)");else{if(n&&i)return console.log("â
AudioPlayer: Processing as WAV file (matches negotiation)"),this.handleWavFile(t);if(n&&!i)return console.warn("â ī¸ AudioPlayer: Negotiated WAV but data lacks WAV header. Attempting WAV processing anyway."),this.handleWavFile(t);if(!this.outputFormat&&i)return console.log("đĩ AudioPlayer: No format negotiated, auto-detecting WAV"),this.handleWavFile(t);this.outputFormat||i||(console.warn("â ī¸ AudioPlayer: No format negotiated and data not WAV, using defaults"),this.outputFormat=this.getDefaultFormat())}return this.outputFormat||(console.warn("â ī¸ AudioPlayer: No format set, using defaults"),this.outputFormat=this.getDefaultFormat()),console.log("đĩ AudioPlayer: Processing as RAW data with encoding:",this.outputFormat.encoding),this.handleRawData(t)}isWavFile(e){return e.length>=44&&82===e[0]&&73===e[1]&&70===e[2]&&70===e[3]}handleWavFile(e){var t=this.parseWavHeader(e);if(console.log("đĩ WAV file detected:",{format:t.audioFormat,encoding:this.getEncodingName(t.audioFormat),sampleRate:t.sampleRate,channels:t.channels,bitDepth:t.bitsPerSample}),1===t.audioFormat)return console.log("â
PCM WAV - using directly"),new Blob([e],{type:"audio/wav"});var n=this.getCodecForWavFormat(t.audioFormat);if(!n)throw new Error("Unsupported WAV format code: ".concat(t.audioFormat));console.log("đ Non-PCM WAV - converting to PCM WAV");var o=e.slice(44),i=n.decode(o),r=this.createWavHeader(i.byteLength,t.sampleRate,t.channels,16);return new Blob([r,i],{type:"audio/wav"})}handleRawData(e){var t,n,o=this.outputFormat.encoding.toLowerCase(),i=this.getCodec(o);if(!i)throw new Error("No codec found for encoding: ".concat(o));if(console.log("đĩ AudioPlayer: Decoding ".concat(o.toUpperCase()," to PCM")),console.log("đĩ AudioPlayer: Input format - bitDepth: ".concat(this.outputFormat.bitDepth,", sampleRate: ").concat(this.outputFormat.sampleRate)),"pcm"===o){var r=this.outputFormat.bitDepth||16;e.length,24===r?(console.warn("â ī¸ AudioPlayer: Format says 24-bit PCM, but browser support is limited."),console.warn(" Treating as 16-bit PCM. If audio sounds wrong, backend should send 16-bit instead."),t=this.convert24BitTo16Bit(e),n=16):8===r?(console.log("đ AudioPlayer: Converting 8-bit PCM to 16-bit PCM"),t=this.convert8BitTo16Bit(e),n=16):(t=e.buffer,n=r,console.log("â
AudioPlayer: Using native ".concat(r,"-bit PCM (no conversion needed)")))}else t=i.decode(e),n=16,console.log("đ AudioPlayer: Decoded ".concat(o.toUpperCase()," to 16-bit PCM"));var a=this.createWavHeader(t.byteLength,this.outputFormat.sampleRate,this.outputFormat.channels,n);return new Blob([a,t],{type:"audio/wav"})}convert24BitTo16Bit(e){for(var t=Math.floor(e.length/3),n=new Int16Array(t),o=0;o<t;o++){var i=e[3*o],r=e[3*o+1],a=e[3*o+2],s=i|r<<8|(255&a)<<16;128&a&&(s|=4278190080),n[o]=Math.max(-32768,Math.min(32767,Math.round(s/256)))}return n.buffer}convert8BitTo16Bit(e){for(var t=e.length,n=new Int16Array(t),o=0;o<t;o++){var i=e[o];n[o]=256*(i-128)}return n.buffer}getCodec(e){var t={pcm:"pcm",linear:"pcm",l16:"pcm",pcmu:"pcmu",ulaw:"pcmu",mulaw:"pcmu",g711u:"pcmu",pcma:"pcma",alaw:"pcma",g711a:"pcma"}[e.toLowerCase()];return this.codecs[t]}getCodecForWavFormat(e){switch(e){case 1:return this.codecs.pcm;case 6:return this.codecs.pcma;case 7:return this.codecs.pcmu;default:return null}}getEncodingName(e){switch(e){case 1:return"PCM";case 6:return"A-law";case 7:return"Îŧ-law";default:return"Unknown (".concat(e,")")}}parseWavHeader(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{audioFormat:t.getUint16(20,!0),channels:t.getUint16(22,!0),sampleRate:t.getUint32(24,!0),byteRate:t.getUint32(28,!0),blockAlign:t.getUint16(32,!0),bitsPerSample:t.getUint16(34,!0)}}createWavHeader(e,t,n,o){var i=new ArrayBuffer(44),r=new DataView(i);return r.setUint32(0,1380533830,!1),r.setUint32(4,36+e,!0),r.setUint32(8,1463899717,!1),r.setUint32(12,1718449184,!1),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,n,!0),r.setUint32(24,t,!0),r.setUint32(28,t*n*o/8,!0),r.setUint16(32,n*o/8,!0),r.setUint16(34,o,!0),r.setUint32(36,1684108385,!1),r.setUint32(40,e,!0),i}initializeAudioContext(){var e,t,n=(null===(e=this.outputFormat)||void 0===e?void 0:e.sampleRate)||44100;if(48e3!==n&&44100!==n&&(console.log("âšī¸ AudioPlayer: Backend requested ".concat(n,"Hz, but browser may resample")),console.log(" Consider requesting 44100Hz or 48000Hz from backend to avoid resampling and improve quality")),this.audioContext){var o=this.audioContext.sampleRate;if(!(Math.abs(o-n)>100))return;console.warn("â ī¸ AudioPlayer: AudioContext sample rate (".concat(o,"Hz) doesn't match format (").concat(n,"Hz), recreating...")),this.stopImmediate(),"closed"!==this.audioContext.state&&this.audioContext.close(),this.audioContext=null}console.log("đĩ AudioPlayer: Creating AudioContext at ".concat(n,"Hz (from outputFormat: ").concat((null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate)||"not set",")"));try{this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:n,latencyHint:"playback"}),console.log("â
AudioContext created at ".concat(this.audioContext.sampleRate,"Hz (requested: ").concat(n,"Hz)")),Math.abs(this.audioContext.sampleRate-n)>100?(console.error("â CRITICAL: Browser sample rate mismatch!"),console.error(" Requested: ".concat(n,"Hz")),console.error(" Got: ".concat(this.audioContext.sampleRate,"Hz")),console.error(" This WILL cause audio distortion/noise!"),console.error(" Solution: Backend should send ".concat(this.audioContext.sampleRate,"Hz audio instead"))):this.audioContext.sampleRate!==n&&(console.warn("â ī¸ Browser adjusted sample rate: ".concat(n,"Hz â ").concat(this.audioContext.sampleRate,"Hz")),console.warn(" Browser will automatically resample audio."))}catch(e){console.error("â Failed to create AudioContext:",e),this.audioContext=new(window.AudioContext||window.webkitAudioContext),console.log("âšī¸ Using browser default: ".concat(this.audioContext.sampleRate,"Hz"))}}processQueue(){var e=this;return p(function*(){if(!e.isProcessingQueue&&0!==e.audioQueue.length){e.isProcessingQueue=!0;var t=e.audioQueue.shift();if(t)try{var n=!e.isPlaying&&null===e.currentSource;e.audioContext||e.initializeAudioContext();var o=e.audioContext;"suspended"===o.state&&(yield o.resume(),n&&(yield new Promise(e=>setTimeout(e,50)))),"running"!==o.state&&(console.warn("AudioPlayer v2: AudioContext not in running state:",o.state),"suspended"===o.state&&(yield o.resume(),n?yield new Promise(e=>setTimeout(e,50)):yield new Promise(e=>setTimeout(e,10))));var i=yield t.arrayBuffer(),r=yield o.decodeAudioData(i),a=n&&!e.isPlaying&&null===e.currentSource,s=o.createBufferSource();s.buffer=r,s.connect(o.destination),e.currentSource=s,e.isPlaying=!0,a&&e.emit("playbackStarted"),s.onended=()=>{e.currentSource=null,e.isProcessingQueue=!1,e.audioQueue.length>0?setTimeout(()=>e.processQueue(),50):setTimeout(()=>{0!==e.audioQueue.length||e.currentSource||(e.isPlaying=!1,e.emit("playbackStopped"))},100)},s.start()}catch(t){console.error("â AudioPlayer v2: Error processing queue:",t),e.currentSource=null,e.emit("playbackError",t),e.audioQueue.length>0?(e.isProcessingQueue=!1,setTimeout(()=>e.processQueue(),100)):(e.isPlaying=!1,e.isProcessingQueue=!1,e.emit("playbackStopped"))}else e.isProcessingQueue=!1}})()}stop(){this.stopImmediate()}reset(){this.stop(),this.audioQueue=[],this.pcmChunkQueue=[]}stopImmediate(){var e=this.isPlaying||null!==this.currentSource||this.scheduledSources.size>0;if(console.log("đ AudioPlayer.stopImmediate() called"),console.log(" isPlaying:",this.isPlaying),console.log(" currentSource:",null!==this.currentSource),console.log(" scheduledSources.size:",this.scheduledSources.size),console.log(" scheduledBuffers:",this.scheduledBuffers),this.currentSource){try{console.log(" Stopping currentSource..."),this.currentSource.stop()}catch(e){console.log(" currentSource already stopped or error:",e.message)}this.currentSource=null}if(this.scheduledSources.size>0){console.log(" Stopping ".concat(this.scheduledSources.size," scheduled sources..."));var t=0;for(var n of this.scheduledSources)try{n.stop(),t++}catch(e){console.log(" Source already stopped or not started:",e.message)}console.log(" Stopped ".concat(t," sources")),this.scheduledSources.clear()}this.isPlaying=!1,this.isProcessingQueue=!1,this.audioQueue=[],this.pcmChunkQueue=[],this.preparedBuffer=[],this.isProcessingPcmQueue=!1,this.isSchedulingFrames=!1,this.nextStartTime=0,this.scheduledBuffers=0,this.clearTranscriptState(),e&&(console.log("đ AudioPlayer: Emitting playbackStopped event (stopImmediate called)"),this.emit("playbackStopped"))}markNewSentence(e){this.pendingSentenceText=e,console.log('đ AudioPlayer: New sentence marked: "'.concat(e.substring(0,40),'..."'))}startTranscriptChecker(){if(!this.isCheckingTranscripts){this.isCheckingTranscripts=!0,console.log("đ AudioPlayer: Transcript checker started");var e=()=>{if(this.isCheckingTranscripts&&this.audioContext){var t=this.audioContext.currentTime;for(var n of this.sentenceTimings)!n.displayed&&t>=n.startTime&&(n.displayed=!0,console.log("đ AudioPlayer: Display transcript at ".concat(t.toFixed(3),'s: "').concat(n.text.substring(0,40),'..."')),this.emit("transcriptDisplay",{text:n.text}));this.isPlaying||this.scheduledBuffers>0?requestAnimationFrame(e):(this.isCheckingTranscripts=!1,console.log("đ AudioPlayer: Transcript checker stopped"))}};requestAnimationFrame(e)}}clearTranscriptState(){this.pendingSentenceText=null,this.sentenceTimings=[],this.isCheckingTranscripts=!1,console.log("đ AudioPlayer: Transcript state cleared")}resumeAudioContext(){var e=this;return p(function*(){if(e.audioContext&&"closed"!==e.audioContext.state){if("suspended"===e.audioContext.state)try{yield e.audioContext.resume(),console.log("â
AudioPlayer v2: AudioContext resumed after mic permission")}catch(e){console.warn("â ī¸ AudioPlayer v2: Failed to resume AudioContext:",e)}}else yield e.initializeAudioContext()})()}getStatus(){return{isPlaying:this.isPlaying,isProcessingQueue:this.isProcessingQueue,queueLength:this.audioQueue.length,audioContextState:this.audioContext?this.audioContext.state:"closed",outputFormat:this.outputFormat,scheduledBuffers:this.scheduledBuffers,preparedBufferLength:this.preparedBuffer.length,scheduledSourcesCount:this.scheduledSources.size}}destroy(){this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.removeAllListeners()}};function m(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function v(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){m(r,o,i,a,s,"next",e)}function s(e){m(r,o,i,a,s,"throw",e)}a(void 0)})}}class f extends c{constructor(e){super(),this.config=e,this.audioContext=null,this.audioWorkletNode=null,this.mediaStream=null,this.isRecording=!1}getAudioProcessorPath(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var e=document.getElementsByTagName("script");for(var t of e){var n=t.src;if(n&&(n.includes("agent-widget.js")||n.includes("ttp-agent-sdk")))try{var o=n.substring(0,n.lastIndexOf("/"));return"".concat(o,"/audio-processor.js")}catch(e){var i=n.substring(0,n.lastIndexOf("/"));return"".concat(i,"/audio-processor.js")}}return"https://cdn.talktopc.com/audio-processor.js"}start(){var e=this;return v(function*(){try{if("https:"!==location.protocol&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname){var t=new Error("Microphone access requires HTTPS. Please use https:// or test on localhost.");throw console.error("â AudioRecorder:",t.message),e.emit("error",t),t}if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){var n=new Error("getUserMedia is not supported in this browser. Please use a modern browser.");throw console.error("â AudioRecorder:",n.message),e.emit("error",n),n}console.log("đ¤ AudioRecorder: Requesting microphone access..."),e.mediaStream=yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:e.config.sampleRate,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),console.log("â
AudioRecorder: Microphone access granted"),e.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:e.config.sampleRate}),"suspended"===e.audioContext.state&&(yield e.audioContext.resume());var o=e.getAudioProcessorPath();yield e.audioContext.audioWorklet.addModule(o),e.audioWorkletNode=new AudioWorkletNode(e.audioContext,"audio-processor"),e.audioContext.createMediaStreamSource(e.mediaStream).connect(e.audioWorkletNode),e.audioWorkletNode.port.onmessage=t=>{var{type:n,data:o}=t.data;"pcm_audio_data"===n&&e.emit("audioData",o)},e.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),e.isRecording=!0,e.emit("recordingStarted")}catch(t){var i=t.message;"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?(i="Microphone permission denied. Please allow microphone access in your browser settings and try again.",console.error("â AudioRecorder: Permission denied. User needs to grant microphone access.")):"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?(i="No microphone found. Please connect a microphone and try again.",console.error("â AudioRecorder: No microphone device found.")):"NotReadableError"===t.name||"TrackStartError"===t.name?(i="Microphone is already in use by another application. Please close other apps using the microphone and try again.",console.error("â AudioRecorder: Microphone is busy or not readable.")):t.message&&t.message.includes("not allowed by the user agent")&&(i="Microphone access blocked. On mobile devices, please tap the recording button directly (not from an iframe or popup).",console.error("â AudioRecorder: User agent blocked microphone access. This often happens on mobile when not called from direct user interaction."));var r=new Error(i);throw r.name=t.name,r.originalError=t,console.error("â AudioRecorder: Failed to start recording:",r),e.emit("error",r),r}})()}stop(){var e=this;return v(function*(){if(e.isRecording)try{e.audioWorkletNode&&(e.audioWorkletNode.port.postMessage({type:"flush"}),yield new Promise(e=>setTimeout(e,100))),e.mediaStream&&(e.mediaStream.getTracks().forEach(e=>e.stop()),e.mediaStream=null),e.audioContext&&"closed"!==e.audioContext.state&&(yield e.audioContext.close(),e.audioContext=null),e.audioWorkletNode=null,e.isRecording=!1,e.emit("recordingStopped")}catch(t){throw e.emit("error",t),t}})()}getStatus(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}destroy(){this.stop()}}class y{static extractPcmFromWav(e){var t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<44)throw new Error("WAV data too short (< 44 bytes)");if("RIFF"!==String.fromCharCode(t[0],t[1],t[2],t[3]))throw new Error("Not a valid WAV file - missing RIFF header");if("WAVE"!==String.fromCharCode(t[8],t[9],t[10],t[11]))throw new Error("Not a valid WAV file - missing WAVE format");for(var n=t[22]|t[23]<<8,o=t[24]|t[25]<<8|t[26]<<16|t[27]<<24,i=t[34]|t[35]<<8,r=-1,a=12;a<t.length-8;a+=4){if("data"===String.fromCharCode(t[a],t[a+1],t[a+2],t[a+3])){r=a;break}a+=4+(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)}if(-1===r)throw new Error("No data chunk found in WAV");var s=t[r+4]|t[r+5]<<8|t[r+6]<<16|t[r+7]<<24,c=r+8,l=Math.min(s,t.length-c);return{pcmData:t.slice(c,c+l).buffer,format:{sampleRate:o,channels:n,bitDepth:i}}}static isWavFile(e){return e.length>=44&&82===e[0]&&73===e[1]&&70===e[2]&&70===e[3]}static createWavHeader(e,t,n,o){var i=new ArrayBuffer(44),r=new DataView(i);return r.setUint32(0,1380533830,!1),r.setUint32(4,36+e,!0),r.setUint32(8,1463899717,!1),r.setUint32(12,1718449184,!1),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,n,!0),r.setUint32(24,t,!0),r.setUint32(28,t*n*o/8,!0),r.setUint16(32,n*o/8,!0),r.setUint16(34,o,!0),r.setUint32(36,1684108385,!1),r.setUint32(40,e,!0),i}static wrapPcmInWav(e,t){var n=y.createWavHeader(e.byteLength,t.sampleRate,t.channels||1,t.bitDepth||16),o=new Uint8Array(n.byteLength+e.byteLength);return o.set(new Uint8Array(n),0),o.set(new Uint8Array(e),n.byteLength),o.buffer}}const x=y,b=class{constructor(){this.codecs={pcm:new l,pcmu:new d,pcma:new u}}decodeToPcm(e,t){var n=null==t?void 0:t.toLowerCase();if(!n||"pcm"===n)return e instanceof ArrayBuffer?e:e instanceof Uint8Array?e.buffer:e;var o=this.codecs[n];if(!o)throw new Error("Unsupported encoding: ".concat(t));var i=e instanceof Uint8Array?e:new Uint8Array(e);return o.decode(i)}encodeFromPcm(e,t){var n=null==t?void 0:t.toLowerCase();if(!n||"pcm"===n)return e;var o=this.codecs[n];if(!o)throw new Error("Unsupported target encoding: ".concat(t));var i=o.encode(e);return i instanceof Uint8Array?i.buffer:i}getCodec(e){var t=null==e?void 0:e.toLowerCase();return this.codecs[t]||null}};class w{static convert(e,t,n){if(t===n)return e;if(8===t)throw new Error("Source bit depth cannot be 8-bit (only 16-bit or 24-bit supported)");var o=t/8,i=n/8,r=e.byteLength/o;if(new ArrayBuffer(r*i),16===t&&16===n)return e;if(24===t&&16===n)return w.convert24To16(e);if(16===t&&24===n)return w.convert16To24(e);if(16===t&&8===n)return w.convert16To8(e);if(24===t&&8===n)return w.convert24To8(e);throw new Error("Unsupported bit depth conversion: ".concat(t,"-bit â ").concat(n,"-bit"))}static convert24To16(e){for(var t=new Uint8Array(e),n=Math.floor(t.length/3),o=new Int16Array(n),i=0;i<n;i++){var r=t[3*i],a=t[3*i+1],s=t[3*i+2],c=r|a<<8|(255&s)<<16;128&s&&(c|=4278190080),o[i]=Math.max(-32768,Math.min(32767,Math.round(c/256)))}return o.buffer}static convert16To24(e){for(var t=new Int16Array(e),n=new Uint8Array(3*t.length),o=0;o<t.length;o++){var i=256*t[o];n[3*o]=255&i,n[3*o+1]=i>>8&255,n[3*o+2]=i>>16&255}return n.buffer}static convert16To8(e){for(var t=new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++){var i=t[o];n[o]=Math.max(0,Math.min(255,Math.round(i/256+128)))}return n.buffer}static convert24To8(e){var t=w.convert24To16(e);return w.convert16To8(t)}}const S=w;function C(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}const k=class{static resample(e,t,n){return(o=function*(){if(t===n)return e;for(var o=new Int16Array(e),i=new Float32Array(o.length),r=1/32768,a=0;a<o.length;a++)i[a]=o[a]*r;var s=Math.ceil(i.length*n/t),c=new OfflineAudioContext(1,s,n),l=c.createBuffer(1,i.length,t);l.getChannelData(0).set(i);var d=c.createBufferSource();d.buffer=l,d.connect(c.destination),d.start();for(var u=(yield c.startRendering()).getChannelData(0),h=new Int16Array(u.length),p=0;p<u.length;p++){var g=Math.max(-1,Math.min(1,u[p]));h[p]=Math.round(32767*g)}return h.buffer},function(){var e=this,t=arguments;return new Promise(function(n,i){var r=o.apply(e,t);function a(e){C(r,n,i,a,s,"next",e)}function s(e){C(r,n,i,a,s,"throw",e)}a(void 0)})})();var o}};class P{static convert(e,t,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:16;if(t===n)return e;if(1===t&&1===n)return e;if(1===t&&2===n)return P.monoToStereo(e,o);if(2===t&&1===n)return P.stereoToMono(e,o);throw new Error("Unsupported channel conversion: ".concat(t," â ").concat(n))}static monoToStereo(e,t){for(var n=t/8,o=e.byteLength/n,i=new ArrayBuffer(o*n*2),r=new Uint8Array(e),a=new Uint8Array(i),s=0;s<o;s++)for(var c=s*n,l=s*n*2,d=0;d<n;d++)a[l+d]=r[c+d],a[l+n+d]=r[c+d];return i}static stereoToMono(e,t){var n=t/8,o=e.byteLength/(2*n),i=new ArrayBuffer(o*n),r=new Uint8Array(e),a=new Uint8Array(i);if(16===t)for(var s=0;s<o;s++){var c=s*n*2,l=c+n,d=(r[c]|r[c+1]<<8)<<16>>16,u=(r[l]|r[l+1]<<8)<<16>>16,h=Math.round((d+u)/2),p=s*n;a[p]=255&h,a[p+1]=h>>8&255}else for(var g=0;g<o;g++)for(var m=g*n*2,v=g*n,f=0;f<n;f++)a[v+f]=r[m+f];return i}}const T=P;function E(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function I(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?E(Object(n),!0).forEach(function(t){A(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):E(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function A(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function R(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}const D=class{constructor(e,t){this.requestedFormat=e,this.actualFormat=t,this.encodingConverter=new b,this.conversionSteps=[],this._analyzeConversions()}_analyzeConversions(){this.conversionSteps=[],this.actualFormat.container!==this.requestedFormat.container&&("wav"===this.actualFormat.container?this.conversionSteps.push("extract_wav"):"wav"===this.requestedFormat.container&&this.conversionSteps.push("wrap_wav")),this.actualFormat.encoding!==this.requestedFormat.encoding&&("pcm"!==this.actualFormat.encoding&&this.conversionSteps.push("decode_encoding"),"pcm"!==this.requestedFormat.encoding&&this.conversionSteps.push("encode_encoding")),this.actualFormat.sampleRate!==this.requestedFormat.sampleRate&&this.conversionSteps.push("resample"),this.actualFormat.bitDepth!==this.requestedFormat.bitDepth&&this.conversionSteps.push("convert_bitdepth"),this.actualFormat.channels!==this.requestedFormat.channels&&this.conversionSteps.push("convert_channels")}needsConversion(){return this.conversionSteps.length>0}getConversionSteps(){var e=[];return this.conversionSteps.includes("extract_wav")&&e.push("Extract PCM from WAV (".concat(this.actualFormat.container," â raw)")),this.conversionSteps.includes("decode_encoding")&&e.push("Decode ".concat(this.actualFormat.encoding.toUpperCase()," â PCM")),this.conversionSteps.includes("resample")&&e.push("Resample ".concat(this.actualFormat.sampleRate,"Hz â ").concat(this.requestedFormat.sampleRate,"Hz")),this.conversionSteps.includes("convert_bitdepth")&&e.push("Convert bit depth ".concat(this.actualFormat.bitDepth,"-bit â ").concat(this.requestedFormat.bitDepth,"-bit")),this.conversionSteps.includes("convert_channels")&&e.push("Convert channels ".concat(this.actualFormat.channels," â ").concat(this.requestedFormat.channels)),this.conversionSteps.includes("encode_encoding")&&e.push("Encode PCM â ".concat(this.requestedFormat.encoding.toUpperCase())),this.conversionSteps.includes("wrap_wav")&&e.push("Wrap in WAV container (raw â ".concat(this.requestedFormat.container,")")),e}convert(e){var t,n=this;return(t=function*(){if(!n.needsConversion())return e instanceof ArrayBuffer?e:e.buffer;var t=e instanceof ArrayBuffer?e:e.buffer,o=I({},n.actualFormat);if(n.conversionSteps.includes("extract_wav")){var i=x.extractPcmFromWav(t);t=i.pcmData,o=I(I({},o),{},{container:"raw",sampleRate:i.format.sampleRate,channels:i.format.channels,bitDepth:i.format.bitDepth}),console.log("đ AudioFormatConverter: Extracted PCM from WAV",i.format)}if(n.conversionSteps.includes("decode_encoding")&&(t=n.encodingConverter.decodeToPcm(t,o.encoding),o.encoding="pcm",o.bitDepth=16,console.log("đ AudioFormatConverter: Decoded ".concat(n.actualFormat.encoding.toUpperCase()," â PCM"))),24===o.bitDepth&&o.bitDepth!==n.requestedFormat.bitDepth&&(n.conversionSteps.includes("resample")||n.conversionSteps.includes("convert_channels")||24!==n.requestedFormat.bitDepth)&&(t=S.convert(t,24,16),o.bitDepth=16,console.log("đ AudioFormatConverter: Normalized 24-bit â 16-bit PCM")),n.conversionSteps.includes("resample")&&(t=yield k.resample(t,o.sampleRate,n.requestedFormat.sampleRate),o.sampleRate=n.requestedFormat.sampleRate,console.log("đ AudioFormatConverter: Resampled ".concat(n.actualFormat.sampleRate,"Hz â ").concat(n.requestedFormat.sampleRate,"Hz"))),n.conversionSteps.includes("convert_channels")&&(t=T.convert(t,o.channels,n.requestedFormat.channels,o.bitDepth),o.channels=n.requestedFormat.channels,console.log("đ AudioFormatConverter: Converted channels ".concat(n.actualFormat.channels," â ").concat(n.requestedFormat.channels))),n.conversionSteps.includes("convert_bitdepth")&&(t=S.convert(t,o.bitDepth,n.requestedFormat.bitDepth),o.bitDepth=n.requestedFormat.bitDepth,console.log("đ AudioFormatConverter: Converted bit depth ".concat(n.actualFormat.bitDepth,"-bit â ").concat(n.requestedFormat.bitDepth,"-bit"))),n.conversionSteps.includes("encode_encoding")){var r=n.encodingConverter.encodeFromPcm(t,n.requestedFormat.encoding);t=r instanceof ArrayBuffer?r:r.buffer,o.encoding=n.requestedFormat.encoding,console.log("đ AudioFormatConverter: Encoded PCM â ".concat(n.requestedFormat.encoding.toUpperCase()))}return n.conversionSteps.includes("wrap_wav")&&(t=x.wrapPcmInWav(t,o),o.container="wav",console.log("đ AudioFormatConverter: Wrapped in WAV container")),console.log("â
AudioFormatConverter: Conversion complete"),t},function(){var e=this,n=arguments;return new Promise(function(o,i){var r=t.apply(e,n);function a(e){R(r,o,i,a,s,"next",e)}function s(e){R(r,o,i,a,s,"throw",e)}a(void 0)})})()}};function F(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}const B=class{constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:()=>null;this.handlers=new Map,this.sendMessage=e,this.getConversationId=t}registerHandler(e,t){if("function"!=typeof t)throw new Error("Handler for tool '".concat(e,"' must be a function"));this.handlers.set(e,t),console.log("đ§ ClientTools: Registered handler for '".concat(e,"'"))}unregisterHandler(e){this.handlers.delete(e),console.log("đ§ ClientTools: Unregistered handler for '".concat(e,"'"))}hasHandler(e){return this.handlers.has(e)}getRegisteredTools(){return Array.from(this.handlers.keys())}handleToolCall(e){var t,n=this;return(t=function*(){var{toolCallId:t,toolName:o,parameters:i}=e,r=Date.now(),a=(new Date).toISOString();console.log("đ§ ClientTools: [".concat(a,"] Received tool call '").concat(o,"' (id: ").concat(t,")")),console.log(" đ Full message received:",JSON.stringify(e,null,2)),console.log(" âąī¸ Start time: ".concat(r,"ms (").concat(new Date(r).toISOString(),")"));var s=n.handlers.get(o);if(!s)return console.warn("đ§ ClientTools: No handler registered for '".concat(o,"'")),void n.sendError(t,o,"No handler registered for tool '".concat(o,"'"),"NO_HANDLER",r);try{var c=yield s(i),l=Date.now()-r;console.log("đ§ ClientTools: Tool '".concat(o,"' completed in ").concat(l,"ms")),n.sendResult(t,o,c,l)}catch(e){var d,u,h=Date.now()-r;console.error("đ§ ClientTools: Tool '".concat(o,"' failed:"),e);var p="EXECUTION_ERROR";"NotAllowedError"===e.name||null!==(d=e.message)&&void 0!==d&&d.includes("permission")?p="PERMISSION_DENIED":("NotSupportedError"===e.name||null!==(u=e.message)&&void 0!==u&&u.includes("not supported"))&&(p="API_UNAVAILABLE"),n.sendError(t,o,e.message||"Unknown error",p,h)}},function(){var e=this,n=arguments;return new Promise(function(o,i){var r=t.apply(e,n);function a(e){F(r,o,i,a,s,"next",e)}function s(e){F(r,o,i,a,s,"throw",e)}a(void 0)})})()}sendResult(e,t,n,o){var i=this.getConversationId(),r=(new Date).toISOString(),a={t:"client_tool_result",toolCallId:e,toolName:t,conversationId:i,result:n,executionTimeMs:o};console.log("đ§ ClientTools: [".concat(r,"] Sending result for tool '").concat(t,"'")),console.log(" đ toolCallId: ".concat(e)),console.log(" đ conversationId: ".concat(i||"null")),console.log(" đ toolName: ".concat(t)),console.log(" đ result:",n),console.log(" đ Full message:",JSON.stringify(a,null,2)),this.sendMessage(a),console.log("â
ClientTools: Result message sent at ".concat(r))}sendError(e,t,n,o,i){var r="number"==typeof i?Date.now()-i:i,a=(new Date).toISOString(),s=this.getConversationId(),c={t:"client_tool_error",toolCallId:e,toolName:t,conversationId:s,error:n,errorCode:o,executionTimeMs:r};console.log("đ§ ClientTools: [".concat(a,"] Sending error for tool '").concat(t,"'")),console.log(" đ toolCallId: ".concat(e)),console.log(" đ conversationId: ".concat(s||"null")),console.log(" đ toolName: ".concat(t)),console.log(" đ error: ".concat(n,", errorCode: ").concat(o)),console.log(" đ Full message:",JSON.stringify(c,null,2)),this.sendMessage(c),console.log("â
ClientTools: Error message sent at ".concat(a))}setSendMessage(e){this.sendMessage=e}};function _(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function O(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?_(Object(n),!0).forEach(function(t){N(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function M(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function U(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){M(r,o,i,a,s,"next",e)}function s(e){M(r,o,i,a,s,"throw",e)}a(void 0)})}}function N(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class z extends c{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.version="2.0.0",this.config={signedUrl:e.signedUrl||e.websocketUrl||"wss://speech.talktopc.com/ws/conv",websocketUrl:e.signedUrl||e.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:e.agentId,appId:e.appId,sampleRate:e.sampleRate||16e3,channels:e.channels||1,bitDepth:e.bitDepth||16,audioProcessorPath:e.audioProcessorPath,outputContainer:e.outputContainer||this.getDefaultContainer(e),outputEncoding:e.outputEncoding||e.outputCodec||"pcm",outputSampleRate:e.outputSampleRate||16e3,outputChannels:e.outputChannels||1,outputBitDepth:e.outputBitDepth||16,outputFrameDurationMs:e.outputFrameDurationMs||600,outputCodec:e.outputCodec,agentSettingsOverride:e.agentSettingsOverride||null,variables:e.variables||null,autoReconnect:!1!==e.autoReconnect,protocolVersion:e.protocolVersion||2},this.isConnected=!1,this.hasEverConnected=!1,this.isRecording=!1,this.isPlaying=!1,this.isDestroyed=!1,this.outputAudioFormat=null,this.requestedOutputFormat=null,this.formatConverter=null,this.websocket=null,this.conversationId=null,this.transcriptQueue=[],this.currentPlayingSentenceId=null,this.audioFrameCount=0,this.audioPlayer=new g(this.config),this.audioRecorder=new f(this.config),this.setupAudioPlayerEvents(),this.setupAudioRecorderEvents(),this.clientToolsRegistry=new B(e=>this.sendMessage(e),()=>this.conversationId),this.validateConfig(),this._setupPageUnloadHandler(),console.log("đĩ VoiceSDK v2 initialized:",{version:this.version,outputContainer:this.config.outputContainer,outputEncoding:this.config.outputEncoding,outputSampleRate:this.config.outputSampleRate})}getStoredConversationId(){try{if("undefined"==typeof sessionStorage)return console.warn("â ī¸ VoiceSDK v2: sessionStorage not available (private mode?)"),null;var e=sessionStorage.getItem(z.CONVERSATION_ID_KEY);return e?(console.log("đĻ VoiceSDK v2: Found stored conversationId:",e),e):null}catch(e){return console.warn("â ī¸ VoiceSDK v2: Error reading sessionStorage:",e),null}}storeConversationId(e){try{if("undefined"==typeof sessionStorage)return void console.warn("â ī¸ VoiceSDK v2: sessionStorage not available (private mode?)");e&&(sessionStorage.setItem(z.CONVERSATION_ID_KEY,e),console.log("đž VoiceSDK v2: Stored conversationId:",e))}catch(e){console.warn("â ī¸ VoiceSDK v2: Error writing to sessionStorage:",e)}}clearStoredConversationId(){try{if("undefined"==typeof sessionStorage)return;sessionStorage.removeItem(z.CONVERSATION_ID_KEY),console.log("đī¸ VoiceSDK v2: Cleared stored conversationId")}catch(e){console.warn("â ī¸ VoiceSDK v2: Error clearing sessionStorage:",e)}}_storeResumeState(){if(this.conversationId){var e={conversationId:this.conversationId,timestamp:Date.now(),fromPage:window.location.pathname+window.location.search};try{if("undefined"==typeof sessionStorage)return;sessionStorage.setItem(z.RESUME_STORAGE_KEY,JSON.stringify(e)),console.log("[VoiceSDK] Stored resume state:",e)}catch(e){console.warn("[VoiceSDK] Failed to store resume state:",e)}}}_getResumeState(){try{if("undefined"==typeof sessionStorage)return null;var e=sessionStorage.getItem(z.RESUME_STORAGE_KEY);if(!e)return null;var t=JSON.parse(e),n=Date.now()-t.timestamp;return n>z.RESUME_TTL_MS?(console.log("[VoiceSDK] Resume state expired:",n,"ms"),this._clearResumeState(),null):(console.log("[VoiceSDK] Found valid resume state:",t,"age:",n,"ms"),t)}catch(e){return console.warn("[VoiceSDK] Failed to get resume state:",e),null}}_clearResumeState(){try{if("undefined"==typeof sessionStorage)return;sessionStorage.removeItem(z.RESUME_STORAGE_KEY)}catch(e){}}_setupPageUnloadHandler(){window.addEventListener("beforeunload",()=>{this.conversationId&&this.websocket&&this.websocket.readyState===WebSocket.OPEN&&this._storeResumeState()}),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.conversationId&&this.websocket&&this.websocket.readyState===WebSocket.OPEN&&this._storeResumeState()})}checkAndResume(){var e=this._getResumeState();if(!e)return null;var t=window.location.pathname+window.location.search;return console.log("[VoiceSDK] Auto-resuming conversation:",e.conversationId),console.log("[VoiceSDK] Page change:",e.fromPage,"â",t),this._clearResumeState(),{conversationId:e.conversationId,fromPage:e.fromPage,toPage:t}}getDefaultContainer(e){return"wav"===e.outputCodec?"wav":"raw"}validateInputFormat(e){var t;if(!e)return"Input format is required";var n=null===(t=e.encoding)||void 0===t?void 0:t.toLowerCase();return n&&z.SUPPORTED_INPUT_ENCODINGS.includes(n)?e.sampleRate&&z.SUPPORTED_INPUT_SAMPLE_RATES.includes(e.sampleRate)?e.bitDepth&&z.SUPPORTED_INPUT_BIT_DEPTHS.includes(e.bitDepth)?e.channels&&z.SUPPORTED_INPUT_CHANNELS.includes(e.channels)?null:"Unsupported input channels: ".concat(e.channels,". Supported: ").concat(z.SUPPORTED_INPUT_CHANNELS.join(", ")):"Unsupported input bit depth: ".concat(e.bitDepth,". Supported: ").concat(z.SUPPORTED_INPUT_BIT_DEPTHS.join(", ")):"Unsupported input sample rate: ".concat(e.sampleRate,". Supported: ").concat(z.SUPPORTED_INPUT_SAMPLE_RATES.join(", ")):"Unsupported input encoding: ".concat(e.encoding,". Supported: ").concat(z.SUPPORTED_INPUT_ENCODINGS.join(", "))}validateOutputFormat(e){var t,n;if(!e)return"Output format is required";var o=null===(t=e.encoding)||void 0===t?void 0:t.toLowerCase();if(!o||!z.SUPPORTED_OUTPUT_ENCODINGS.includes(o))return"Unsupported output encoding: ".concat(e.encoding,". Supported: ").concat(z.SUPPORTED_OUTPUT_ENCODINGS.join(", "));if(!e.sampleRate||!z.SUPPORTED_OUTPUT_SAMPLE_RATES.includes(e.sampleRate))return"Unsupported output sample rate: ".concat(e.sampleRate,". Supported: ").concat(z.SUPPORTED_OUTPUT_SAMPLE_RATES.join(", "));if(!e.bitDepth||!z.SUPPORTED_OUTPUT_BIT_DEPTHS.includes(e.bitDepth))return"Unsupported output bit depth: ".concat(e.bitDepth,". Supported: ").concat(z.SUPPORTED_OUTPUT_BIT_DEPTHS.join(", "));if(!e.channels||!z.SUPPORTED_OUTPUT_CHANNELS.includes(e.channels))return"Unsupported output channels: ".concat(e.channels,". Supported: ").concat(z.SUPPORTED_OUTPUT_CHANNELS.join(", "));var i=null===(n=e.container)||void 0===n?void 0:n.toLowerCase();return i&&z.SUPPORTED_OUTPUT_CONTAINERS.includes(i)?null:"Unsupported output container: ".concat(e.container,". Supported: ").concat(z.SUPPORTED_OUTPUT_CONTAINERS.join(", "))}validateConfig(){var e={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},t=this.validateInputFormat(e);if(t)return console.error("â VoiceSDK v2: Invalid input format:",t),void this.emit("error",new Error(t));var n={encoding:this.config.outputEncoding,sampleRate:this.config.outputSampleRate,channels:this.config.outputChannels,bitDepth:this.config.outputBitDepth,container:this.config.outputContainer},o=this.validateOutputFormat(n);if(o)return console.error("â VoiceSDK v2: Invalid output format:",o),void this.emit("error",new Error(o));console.log("â
VoiceSDK v2: Format validation passed")}setupAudioPlayerEvents(){this.audioPlayer.on("playbackStarted",()=>{this.isPlaying=!0,this.emit("playbackStarted"),this.isConnected?(console.log("đ¤ VoiceSDK v2: Sending audio_started_playing message to server"),this.sendMessage({t:"audio_started_playing"})):console.warn("â ī¸ VoiceSDK v2: Cannot send audio_started_playing - not connected")}),this.audioPlayer.on("transcriptDisplay",e=>{var t=this.currentPlayingSentenceId?this.currentPlayingSentenceId+1:1;this.currentPlayingSentenceId=t;var n={text:e.text,role:"assistant",sentenceId:t,final:!0,timestamp:Date.now()};console.log("đ VoiceSDK v2: Emitting synced transcriptDisplay from AudioPlayer:",n),this.emit("transcriptDisplay",n),this.emit("transcript",n)}),this.audioPlayer.on("playbackStopped",()=>{this.isPlaying=!1,this.emit("playbackStopped"),this.isConnected?(console.log("đ¤ VoiceSDK v2: Sending audio_stopped_playing message to server"),this.sendMessage({t:"audio_stopped_playing"})):console.warn("â ī¸ VoiceSDK v2: Cannot send audio_stopped_playing - not connected")}),this.audioPlayer.on("playbackError",e=>{this.emit("playbackError",e),this.emit("error",e)})}setupAudioRecorderEvents(){this.audioRecorder.on("recordingStarted",()=>{this.isRecording=!0,this.emit("recordingStarted")}),this.audioRecorder.on("recordingStopped",()=>{this.isRecording&&(this.isRecording=!1,this.emit("recordingStopped"),console.log("đ VoiceSDK v2: Recording stopped (from audioRecorder event)"))}),this.audioRecorder.on("audioData",e=>{this.isConnected&&this.sendBinary(e)}),this.audioRecorder.on("error",e=>{console.error("â AudioRecorder error:",e),this.emit("error",e)})}buildWebSocketUrl(){var e=this.config.signedUrl||this.config.websocketUrl,t=new URLSearchParams;this.config.agentId&&t.append("agentId",this.config.agentId),this.config.appId&&t.append("appId",this.config.appId);var n=this.getStoredConversationId();n&&(t.append("conversationId",n),console.log("đ VoiceSDK v2: Attempting resume via query param:",n));var o=window.location.pathname+window.location.search;if(o&&t.append("currentPage",o),t.toString()){var i=e.includes("?")?"&":"?";return"".concat(e).concat(i).concat(t.toString())}return e}connect(){var e=this;return U(function*(){if(e.isDestroyed)return console.warn("VoiceSDK v2: Cannot connect - SDK is destroyed"),!1;if(e.isConnected)return console.warn("VoiceSDK v2: Already connected"),!0;try{var t=e.buildWebSocketUrl();return console.log("đ VoiceSDK v2: Connecting to",t),yield new Promise((n,o)=>{e.websocket=new WebSocket(t),e.websocket.onopen=()=>{console.log("â
VoiceSDK v2: WebSocket connected"),e.isConnected=!0,e.hasEverConnected=!0,e.clientToolsRegistry&&e.clientToolsRegistry.setSendMessage(t=>e.sendMessage(t)),e.sendHelloMessage(),e.emit("connected"),n(!0)},e.websocket.onerror=e=>{console.error("â VoiceSDK v2: WebSocket error:",e),o(e)},e.websocket.onclose=t=>{console.log("đ VoiceSDK v2: WebSocket closed:",t.code,t.reason),e.isConnected=!1,e.isRecording&&e.stopRecording().catch(e=>console.error("Error stopping recording:",e)),e.emit("disconnected",t),e.config.autoReconnect&&!e.isDestroyed&&e.hasEverConnected?(console.log("đ VoiceSDK v2: Auto-reconnecting in 3s..."),setTimeout(()=>{e.isDestroyed||e.isConnected||e.connect()},3e3)):e.config.autoReconnect&&!e.hasEverConnected&&console.log("â ī¸ VoiceSDK v2: Initial connection failed. Auto-reconnect disabled to prevent retry loop.")},e.websocket.onmessage=t=>{e.handleMessage(t)}})}catch(t){return console.error("đ VoiceSDK v2: Connection failed:",t),e.emit("error",t),!1}})()}sendHelloMessage(){if(this.isConnected){var e={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},t={encoding:this.config.outputEncoding,sampleRate:this.config.outputSampleRate,channels:this.config.outputChannels,bitDepth:this.config.outputBitDepth,container:this.config.outputContainer},n=this.validateInputFormat(e);if(n)return console.error("â VoiceSDK v2: Cannot send hello - invalid input format:",n),void this.emit("error",new Error("Invalid input format: ".concat(n)));var o=this.validateOutputFormat(t);if(o)return console.error("â VoiceSDK v2: Cannot send hello - invalid output format:",o),void this.emit("error",new Error("Invalid output format: ".concat(o)));var i={t:"hello",v:this.config.protocolVersion,inputFormat:e,requestedOutputFormat:t,outputFrameDurationMs:this.config.outputFrameDurationMs};this.config.agentSettingsOverride&&(i.agentSettingsOverride=this.config.agentSettingsOverride),console.log("đ VoiceSDK v2: Checking variables:",{hasVariables:!!this.config.variables,variables:this.config.variables,keys:this.config.variables?Object.keys(this.config.variables):[]}),this.config.variables&&Object.keys(this.config.variables).length>0?(i.variables=this.config.variables,console.log("đ VoiceSDK v2: Including variables in hello:",Object.keys(this.config.variables))):console.log("â ī¸ VoiceSDK v2: Variables NOT included - condition failed"),console.log("đ¤ VoiceSDK v2: Sending hello:",{version:i.v,requestedFormat:i.requestedOutputFormat,variables:i.variables?Object.keys(i.variables):void 0}),console.log("đ¤ VoiceSDK v2: Requested output format:",{container:i.requestedOutputFormat.container,encoding:i.requestedOutputFormat.encoding,sampleRate:i.requestedOutputFormat.sampleRate,bitDepth:i.requestedOutputFormat.bitDepth}),console.log("đ¤ VoiceSDK v2: Full hello message being sent:",JSON.stringify(i,null,2));try{this.sendMessage(i)}catch(e){console.error("VoiceSDK v2: Failed to send hello:",e),this.emit("error",e)}}else console.warn("VoiceSDK v2: Cannot send hello - not connected")}handleMessage(e){if(e.data instanceof ArrayBuffer||e.data instanceof Blob)this.handleBinaryMessage(e.data);else try{var t=JSON.parse(e.data);switch("audio"!==t.t&&console.log("đĨ VoiceSDK v2: Received message type:",t.t,"Full message:",JSON.stringify(t).substring(0,200)),!this.conversationId&&t.conversationId&&(this.conversationId=t.conversationId,console.log("đ VoiceSDK v2: Captured conversationId from message:",this.conversationId),this.emit("conversationIdChanged",this.conversationId)),"audio"!==t.t&&console.log("đ¨ VoiceSDK v2: Received message type:",t.t,t),t.t){case"hello_ack":this.handleHelloAck(t);break;case"transcript":console.log("đ VoiceSDK v2: Processing transcript message:",t),this.handleTranscript(t);break;case"user_transcript":console.log("đ VoiceSDK v2: Received user_transcript:",t),this.emit("message",t);break;case"agent_response":if(console.log("đ VoiceSDK v2: Received agent_response:",t),(t.text||t.transcript)&&(console.log("đ VoiceSDK v2: agent_response contains transcript data:",t.text||t.transcript),t.sentenceId&&(t.text||t.transcript))){var n={t:"transcript",sentenceId:t.sentenceId,text:t.text||t.transcript,role:t.role||"assistant",final:!1!==t.final,timestamp:t.timestamp||Date.now()};console.log("đ VoiceSDK v2: Converting agent_response to transcript:",n),this.handleTranscript(n)}this.emit("message",t);break;case"error":this.emit("message",t);break;case"barge_in":this.emit("bargeIn",t),this.stopAudioPlayback();break;case"stop_playing":this.emit("stopPlaying",t),this.stopAudioPlayback();break;case"audio_start":console.log("đ VoiceSDK v2: Received audio_start with text:",t.text),t.text&&this.audioPlayer&&this.audioPlayer.markNewSentence(t.text),this.emit("message",t);break;case"client_tool_call":this.clientToolsRegistry.handleToolCall(t);break;case"hangup_ack":console.log("đ VoiceSDK v2: Hangup acknowledged by server"),this.websocket&&this.websocket.readyState===WebSocket.OPEN&&(this.websocket.close(1e3,"User hangup"),this.websocket=null),this.isConnected=!1,this.emit("hangupAcknowledged");break;default:if(console.log("VoiceSDK v2: Unknown message type:",t.t,"Full message:",JSON.stringify(t).substring(0,300)),(t.text||t.transcript||t.transcription)&&(console.log("đ VoiceSDK v2: Unknown message contains transcript-like data:",{text:t.text,transcript:t.transcript,transcription:t.transcription,sentenceId:t.sentenceId,role:t.role}),t.sentenceId&&(t.text||t.transcript||t.transcription))){var o={t:"transcript",sentenceId:t.sentenceId,text:t.text||t.transcript||t.transcription,role:t.role||"assistant",final:!1!==t.final,timestamp:t.timestamp||Date.now()};console.log("đ VoiceSDK v2: Attempting to process unknown message as transcript:",o),this.handleTranscript(o)}this.emit("message",t)}}catch(e){console.error("VoiceSDK v2: Error parsing message:",e)}}handleHelloAck(e){if(console.log("đĨ VoiceSDK v2: Received hello_ack:",{hasOutputFormat:!!e.outputAudioFormat,outputFormat:e.outputAudioFormat,hasConversationId:!!e.conversationId,messageType:e.t}),e.conversationId&&(this.conversationId=e.conversationId,console.log("đ VoiceSDK v2: Received conversationId:",this.conversationId),this.emit("conversationIdChanged",this.conversationId),this.storeConversationId(this.conversationId),this.websocket&&this.websocket.readyState===WebSocket.OPEN&&this._storeResumeState()),!0===e.resumed?(console.log("â
VoiceSDK v2: Conversation resumed successfully"),this.emit("callResumed",{conversationId:this.conversationId,timestamp:Date.now()})):!1===e.resumed&&e.resumeRejectedReason&&(console.warn("â ī¸ VoiceSDK v2: Resume rejected:",e.resumeRejectedReason),this.clearStoredConversationId(),this.emit("resumeRejected",{reason:e.resumeRejectedReason,conversationId:e.conversationId||null,timestamp:Date.now()})),e.outputAudioFormat){this.outputAudioFormat=e.outputAudioFormat,this.audioPlayer.setOutputFormat(e.outputAudioFormat),console.log("â
VoiceSDK v2: Format negotiated by server:",this.outputAudioFormat),this.requestedOutputFormat={container:this.config.outputContainer||"wav",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,bitDepth:this.config.outputBitDepth||16,channels:this.config.outputChannels||1};var t={container:this.outputAudioFormat.container||"unknown",encoding:this.outputAudioFormat.encoding||"unknown",sampleRate:this.outputAudioFormat.sampleRate||0,bitDepth:this.outputAudioFormat.bitDepth||0,channels:this.outputAudioFormat.channels||0},n=[];if(this.requestedOutputFormat.container!==t.container&&n.push('container: "'.concat(this.requestedOutputFormat.container,'" â "').concat(t.container,'"')),this.requestedOutputFormat.encoding!==t.encoding&&n.push('encoding: "'.concat(this.requestedOutputFormat.encoding,'" â "').concat(t.encoding,'"')),this.requestedOutputFormat.sampleRate!==t.sampleRate&&n.push("sampleRate: ".concat(this.requestedOutputFormat.sampleRate,"Hz â ").concat(t.sampleRate,"Hz")),this.requestedOutputFormat.bitDepth!==t.bitDepth&&n.push("bitDepth: ".concat(this.requestedOutputFormat.bitDepth,"-bit â ").concat(t.bitDepth,"-bit")),this.requestedOutputFormat.channels!==t.channels&&n.push("channels: ".concat(this.requestedOutputFormat.channels," â ").concat(t.channels)),n.length>0){console.warn("â ī¸ VoiceSDK v2: Format negotiation mismatch!"),console.warn(" Requested:",this.requestedOutputFormat),console.warn(" Negotiated:",t),console.warn(" Differences:",n.join(", "));try{if(this.formatConverter=new D(this.requestedOutputFormat,t),this.formatConverter.needsConversion()){var o=this.formatConverter.getConversionSteps();console.log("đ VoiceSDK v2: Format conversion enabled"),console.log(" Conversion steps:",o.join(", ")),console.log(" Audio will be automatically converted to requested format")}}catch(e){console.error("â VoiceSDK v2: Failed to create format converter:",e),console.warn(" Will use backend format without conversion"),this.formatConverter=null}}else console.log("â
VoiceSDK v2: Format perfectly matched!",t),this.formatConverter=null;this.emit("formatNegotiated",this.outputAudioFormat)}else{this.config.protocolVersion>=2?(console.warn("â ī¸ VoiceSDK v2: hello_ack received but no outputAudioFormat in response."),console.warn(" This may happen if:"),console.warn(" 1. Backend is not sending outputAudioFormat (check backend logs)"),console.warn(" 2. Hello message missing v2 fields (v, inputFormat, requestedOutputFormat)"),console.warn(" 3. Backend validation failed (check backend error logs)"),console.warn(" Using default format from config...")):console.log("â
VoiceSDK v2: Connected (v1 legacy mode)");var i={container:this.config.outputContainer||"wav",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,channels:this.config.outputChannels||1,bitDepth:this.config.outputBitDepth||16};this.outputAudioFormat=i,this.requestedOutputFormat=i,this.audioPlayer.setOutputFormat(i),this.formatConverter=null}}handleTranscript(e){if(e.sentenceId&&e.text){var t=e.sentenceId,n={text:e.text,role:e.role||"assistant",sentenceId:t,final:!1!==e.final,timestamp:e.timestamp||Date.now()};this.transcriptQueue.push(n),console.log("đ VoiceSDK v2: Received transcript for sentence",t,":",n.text),console.log(" Transcript queue length:",this.transcriptQueue.length),console.log(" Current playing sentence:",this.currentPlayingSentenceId),console.log("đ VoiceSDK v2: Displaying transcript for completed sentence",t),this.emit("transcriptDisplay",n),this.currentPlayingSentenceId=t,this.emit("transcript",n)}else console.warn("â ī¸ VoiceSDK v2: Invalid transcript message:",e)}handleBinaryMessage(e){var t=this;return U(function*(){var n,o=n=e instanceof Blob?yield e.arrayBuffer():e;if(t.formatConverter&&t.formatConverter.needsConversion())try{o=yield t.formatConverter.convert(n),console.log("â
VoiceSDK v2: Audio converted to requested format")}catch(e){console.error("â VoiceSDK v2: Format conversion failed:",e),console.warn(" Using backend format without conversion"),o=n}var i=t.formatConverter&&t.formatConverter.needsConversion()?t.requestedOutputFormat:t.outputAudioFormat||{container:t.config.outputContainer||"raw",encoding:t.config.outputEncoding||"pcm",sampleRate:t.config.outputSampleRate||16e3,bitDepth:t.config.outputBitDepth||16,channels:t.config.outputChannels||1},r=i.container||"raw",a=(i.encoding||"pcm").toLowerCase();if("raw"===r){var s=o;if("pcm"!==a){var c=t.audioPlayer.getCodec(a);if(c){var l=c.decode(new Uint8Array(o));s=l.buffer,console.log("đ VoiceSDK v2: Decoded ".concat(a.toUpperCase()," to PCM (").concat(l.byteLength," bytes)"))}else console.warn("â ī¸ VoiceSDK v2: No codec for ".concat(a,", treating as PCM"))}t.audioPlayer.outputFormat||(console.warn("â ī¸ VoiceSDK v2: outputFormat not set on AudioPlayer, setting from playbackFormat"),t.audioPlayer.setOutputFormat(i)),t.audioFrameCount++,t.audioPlayer.playChunk(s)}else t.audioFrameCount++,t.audioPlayer.playAudio(o)})()}sendMessage(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send message - not connected"),!1;try{var t=(new Date).toISOString(),n=this.websocket?this.websocket.readyState:"NO_WEBSOCKET",o=this.websocket?{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[n]:"NO_WEBSOCKET";if("client_tool_result"!==e.t&&"client_tool_error"!==e.t||(console.log("đ¤ VoiceSDK v2: [".concat(t,"] Sending tool ").concat(e.t)),console.log(" đ WebSocket state: ".concat(o," (").concat(n,")")),console.log(" đ toolCallId: ".concat(e.toolCallId)),console.log(" đ conversationId: ".concat(e.conversationId||"null")),console.log(" đ toolName: ".concat(e.toolName)),"client_tool_result"===e.t?console.log(" đ result:",e.result):console.log(" đ error: ".concat(e.error,", errorCode: ").concat(e.errorCode)),console.log(" đ Full message:",JSON.stringify(e,null,2))),!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.error("â VoiceSDK v2: Cannot send message - WebSocket not open (state: ".concat(o,")")),!1;var i=JSON.stringify(e);return this.websocket.send(i),"client_tool_result"!==e.t&&"client_tool_error"!==e.t||console.log("â
VoiceSDK v2: [".concat(t,"] Tool ").concat(e.t," message sent successfully (").concat(i.length," bytes)")),!0}catch(e){return console.error("VoiceSDK v2: Error sending message:",e),this.emit("error",e),!1}}sendBinary(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send audio - not connected"),!1;try{return this.websocket.send(e),!0}catch(e){return console.error("VoiceSDK v2: Error sending audio:",e),this.emit("error",e),!1}}hangup(){if(this.websocket&&this.websocket.readyState===WebSocket.OPEN){console.log("đ VoiceSDK v2: Hanging up call..."),this.clearStoredConversationId(),this._clearResumeState(),this.stopRecording(),this.audioPlayer&&this.stopAudioPlayback();try{this.sendMessage({t:"hangup"}),setTimeout(()=>{this.websocket&&this.websocket.readyState===WebSocket.OPEN&&(this.websocket.close(1e3,"User hangup"),this.websocket=null),this.isConnected=!1},100)}catch(e){console.error("VoiceSDK v2: Error sending hangup message:",e),this.websocket&&(this.websocket.close(1e3,"User hangup"),this.websocket=null),this.isConnected=!1}}else console.warn("đ VoiceSDK v2: Cannot hangup - WebSocket not open")}startRecording(){var e=this;return U(function*(){if(!e.isConnected){var t=new Error("Not connected to voice server");throw e.emit("error",t),t}if(e.isRecording)return console.warn("VoiceSDK v2: Already recording"),!0;console.log("đ¤ VoiceSDK v2: Starting recording...");try{return console.log("đ¤ VoiceSDK v2: Requesting microphone permission (mobile-friendly)..."),yield e.audioRecorder.start(),yield e.audioPlayer.resumeAudioContext(),e.sendMessage({t:"start_continuous_mode",ttpId:e.generateTtpId()}),!0}catch(t){if(console.error("â VoiceSDK v2: Failed to start recording:",t),"NotAllowedError"===t.name||"PermissionDeniedError"===t.name){var n=new Error("Microphone permission denied. Please allow microphone access in your browser settings and try again.");n.name=t.name,n.originalError=t,e.emit("error",n)}else e.emit("error",t);return!1}})()}stopRecording(){var e=this;return U(function*(){if(!e.isRecording)return console.warn("VoiceSDK v2: Not recording"),!0;console.log("đ VoiceSDK v2: Stopping recording...");try{return e.sendMessage({t:"stop_continuous_mode",ttpId:e.generateTtpId()}),e.isRecording=!1,e.emit("recordingStopped"),console.log("đ VoiceSDK v2: Recording stopped (emitted before audioRecorder.stop())"),yield e.audioRecorder.stop(),e.stopAudioPlayback(),!0}catch(t){return console.error("VoiceSDK v2: Error stopping recording:",t),e.emit("error",t),!1}})()}toggleRecording(){var e=this;return U(function*(){return e.isRecording?yield e.stopRecording():yield e.startRecording()})()}clearTranscriptState(){this.currentPlayingSentenceId=null,console.log("đ VoiceSDK v2: Cleared transcript state")}stopAudioPlayback(){this.audioPlayer.stopImmediate(),this.clearTranscriptState()}handleBargeIn(){var e=this;return U(function*(){e.stopAudioPlayback(),e.isRecording||(yield e.startRecording())})()}getStatus(){return{version:this.version,isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying,outputFormat:this.outputAudioFormat,conversationId:this.conversationId,audioPlayer:this.audioPlayer.getStatus(),audioRecorder:this.audioRecorder.getStatus()}}updateConfig(e){this.config=O(O({},this.config),e)}generateTtpId(){return"sdk_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}registerToolHandler(e,t){return this.clientToolsRegistry.registerHandler(e,t)}unregisterToolHandler(e){return this.clientToolsRegistry.unregisterHandler(e)}hasToolHandler(e){return this.clientToolsRegistry.hasHandler(e)}getRegisteredTools(){return this.clientToolsRegistry.getRegisteredTools()}destroy(){this.isDestroyed||(console.log("đī¸ VoiceSDK v2: Destroying..."),this.isDestroyed=!0,this.isRecording&&this.stopRecording(),this.audioPlayer&&this.stopAudioPlayback(),this.websocket&&(this.websocket.close(),this.websocket=null),this.isConnected=!1,this.audioPlayer&&this.audioPlayer.destroy(),this.audioRecorder&&this.audioRecorder.destroy(),this.clientToolsRegistry&&this.clientToolsRegistry.getRegisteredTools().forEach(e=>this.clientToolsRegistry.unregisterHandler(e)),this.removeAllListeners())}}N(z,"CONVERSATION_ID_KEY","ttp_voice_conversation_id"),N(z,"RESUME_STORAGE_KEY","voice_resume_state"),N(z,"RESUME_TTL_MS",1e4),N(z,"SUPPORTED_INPUT_ENCODINGS",["pcm","pcmu","pcma"]),N(z,"SUPPORTED_INPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),N(z,"SUPPORTED_INPUT_BIT_DEPTHS",[8,16,24]),N(z,"SUPPORTED_INPUT_CHANNELS",[1]),N(z,"SUPPORTED_OUTPUT_ENCODINGS",["pcm","pcmu","pcma"]),N(z,"SUPPORTED_OUTPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),N(z,"SUPPORTED_OUTPUT_BIT_DEPTHS",[8,16,24]),N(z,"SUPPORTED_OUTPUT_CHANNELS",[1]),N(z,"SUPPORTED_OUTPUT_CONTAINERS",["raw","wav"]);const H=z;class L{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(e=>e!==t))}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];this.events[e]&&this.events[e].forEach(t=>{try{t(...n)}catch(t){console.error("Error in event listener for ".concat(e,":"),t)}})}removeAllListeners(e){e?delete this.events[e]:this.events={}}}function K(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function V(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function j(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?V(Object(n),!0).forEach(function(t){W(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):V(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function W(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class q extends L{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super();var t=this.readScriptTagConfig();this.config=j({baseWsUrl:"wss://backend.talktopc.com/chat/websocket",appId:e.appId||t.appId,agentId:e.agentId||t.agentId,conversationId:void 0!==e.conversationId?e.conversationId:this.getPersistedConversationId(),forceConversationId:e.forceConversationId,queue:[],inFlight:!1},e),this.fullResponseBuffer=""}readScriptTagConfig(){try{var e=Array.from(document.getElementsByTagName("script")).reverse().find(e=>e.dataset&&(e.dataset.appId||e.dataset.agentId)||e.src&&e.src.includes("agent-widget"));return e?{appId:e.dataset.appId,agentId:e.dataset.agentId}:{}}catch(e){return{}}}buildWebSocketUrl(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.config.baseWsUrl,t=new URLSearchParams;return this.config.appId&&t.append("appId",this.config.appId),this.config.agentId&&t.append("agentId",this.config.agentId),this.config.conversationId&&t.append("conversationId",this.config.conversationId),"".concat(e,"?").concat(t.toString())}sendMessage(e){var t,n=this;return(t=function*(){return new Promise((t,o)=>{if(e&&e.trim())if(n.config.appId&&n.config.agentId){var i={text:e,resolve:t,reject:o};n.config.inFlight?n.config.queue.push(i):n.executeTask(i)}else o(new Error("Missing appId or agentId"));else o(new Error("Message is empty"))})},function(){var e=this,n=arguments;return new Promise(function(o,i){var r=t.apply(e,n);function a(e){K(r,o,i,a,s,"next",e)}function s(e){K(r,o,i,a,s,"throw",e)}a(void 0)})})()}executeTask(e){if(this.config.inFlight=!0,this.fullResponseBuffer="",!this.config.conversationId){var t=this.getPersistedConversationId();t&&(this.config.conversationId=t,console.log("đ TextChatSDK hydrated conversationId from storage:",t))}var n=this.buildWebSocketUrl(this.config.baseWsUrl),o=this.config.baseWsUrl.endsWith("/websocket")?this.config.baseWsUrl.replace(/\/websocket$/,""):"".concat(this.config.baseWsUrl,"/websocket"),i=this.buildWebSocketUrl(o),r=!1,a=!1,s=null,c=t=>{if(!a)try{var n={message:e.text},o=this.config.forceConversationId||this.config.conversationId;o&&(n.conversationId=o,this.config.forceConversationId&&!this.config.conversationId&&(this.config.conversationId=o,this.persistConversationId(o))),console.log("đ TextChatSDK sending payload:",n,"conversationId in config:",this.config.conversationId),t.send(JSON.stringify(n)),a=!0}catch(n){e.reject(n),this.emit("error",n);try{t.close()}catch(e){}}},l=e=>()=>{this.config.conversationId?c(e):s=setTimeout(()=>c(e),200)},d=t=>n=>{try{try{console.log("đ [TextChatSDK] WS <= raw:",n.data)}catch(e){}var o=JSON.parse(n.data);try{console.log("đ [TextChatSDK] WS <= parsed:",o)}catch(e){}if("hello"===o.type&&o.conversationId){if(console.log("đ TextChatSDK received conversationId:",o.conversationId),this.config.conversationId=o.conversationId,this.persistConversationId(o.conversationId),this.emit&&this.emit("conversationIdChanged",o.conversationId),!a&&t&&1===t.readyState){if(s)try{clearTimeout(s)}catch(e){}c(t)}return}if(!this.config.conversationId&&o.conversationId&&(console.log("đ TextChatSDK captured conversationId from message:",o.conversationId),this.config.conversationId=o.conversationId,this.persistConversationId(o.conversationId)),"chunk"===o.type&&"string"==typeof o.content)this.fullResponseBuffer+=o.content,this.emit("chunk",o.content);else if("done"===o.type){try{var i=o.text||o.content||o.answer||o.message||"";i&&!this.fullResponseBuffer&&(this.fullResponseBuffer=i)}catch(e){}!this.config.conversationId&&o.conversationId&&(console.log("đ TextChatSDK captured conversationId from done:",o.conversationId),this.config.conversationId=o.conversationId),this.persistConversationId(this.config.conversationId),this.emit("done",{text:this.fullResponseBuffer}),e.resolve({conversationId:this.config.conversationId,fullText:this.fullResponseBuffer});try{t.close()}catch(e){}}else if("error"===o.type){var r=new Error(o.message||"Server error");this.emit("error",r),e.reject(r);try{t.close()}catch(e){}}}catch(e){}},u=t=>{if(1008===t.code&&t.reason&&(t.reason.includes("Domain not whitelisted")||t.reason.includes("domain")||t.reason.includes("whitelist"))){var n=new Error("DOMAIN_NOT_WHITELISTED");return n.reason=t.reason,n.code=t.code,this.emit("domainError",n),e.reject(n),this.config.inFlight=!1,void this.drainQueue()}this.config.inFlight=!1,this.drainQueue()},h=new WebSocket(n);h.onopen=l(h),h.onmessage=d(h),h.onerror=(t=>n=>{if(!r){r=!0;try{t.close()}catch(e){}var o=new WebSocket(i);return o.onopen=l(o),o.onmessage=d(o),o.onerror=t=>{this.emit("error",t),e.reject(t)},void(o.onclose=u)}this.emit("error",n),e.reject(n)})(h),h.onclose=u}drainQueue(){if(0!==this.config.queue.length&&!this.config.inFlight){var e=this.config.queue.shift();this.executeTask(e)}}persistConversationId(e){try{e&&localStorage.setItem("ttp_text_chat_conversation_id",e)}catch(e){}}getPersistedConversationId(){try{return localStorage.getItem("ttp_text_chat_conversation_id")||null}catch(e){return null}}updateConfig(e){this.config=j(j({},this.config),e)}destroy(){this.config.queue=[],this.config.inFlight=!1,this.removeAllListeners()}}function Q(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}const G=new class extends L{constructor(){super(),this.connections=new Map,this.connectionCounts=new Map,this.creatingConnections=new Set}getConnection(e){var t,n=this;return(t=function*(){if(n.connections.has(e)){var t=n.connections.get(e);return n.connectionCounts.set(e,(n.connectionCounts.get(e)||0)+1),t}if(n.creatingConnections&&n.creatingConnections.has(e))return new Promise(t=>{var o=()=>{if(n.connections.has(e)){var i=n.connections.get(e);n.connectionCounts.set(e,(n.connectionCounts.get(e)||0)+1),t(i)}else setTimeout(o,50)};o()});n.creatingConnections.add(e);var o=new WebSocket(e);return n.connections.set(e,o),n.connectionCounts.set(e,1),o.addEventListener("open",t=>{n.creatingConnections.delete(e),n.emit("open",t,e)}),o.addEventListener("close",t=>{n.creatingConnections.delete(e),n.connections.delete(e),n.connectionCounts.delete(e),n.emit("close",t,e)}),o.addEventListener("error",t=>{n.creatingConnections.delete(e),n.emit("error",t,e)}),o.addEventListener("message",t=>{n.emit("message",t,e)}),o},function(){var e=this,n=arguments;return new Promise(function(o,i){var r=t.apply(e,n);function a(e){Q(r,o,i,a,s,"next",e)}function s(e){Q(r,o,i,a,s,"throw",e)}a(void 0)})})()}releaseConnection(e){if(this.connections.has(e)){var t=this.connectionCounts.get(e)||0,n=Math.max(0,t-1);if(this.connectionCounts.set(e,n),0===n){var o=this.connections.get(e);o&&o.readyState===WebSocket.OPEN&&o.close(1e3,"No more subscribers"),this.connections.delete(e),this.connectionCounts.delete(e)}}}forceClose(e){if(this.connections.has(e)){var t=this.connections.get(e);t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Force close"),this.connections.delete(e),this.connectionCounts.delete(e)}}getConnectionStatus(e){return this.connections.has(e)?{exists:!0,readyState:this.connections.get(e).readyState,subscribers:this.connectionCounts.get(e)||0}:{exists:!1,readyState:null,subscribers:0}}getAllConnections(){var e={};for(var[t,n]of this.connections.entries())e[t]={readyState:n.readyState,subscribers:this.connectionCounts.get(t)||0};return e}clearAll(){for(var[e,t]of this.connections.entries())t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Clear all");this.connections.clear(),this.connectionCounts.clear(),this.creatingConnections.clear()}};function Y(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}class J extends L{constructor(e){super(),this.config=e,this.ws=null,this.isConnected=!1,this.connectionId=null}connect(){var e,t=this;return(e=function*(){return new Promise((e,n)=>{try{t.connectionId=Date.now()+"_"+Math.random().toString(36).substr(2,9),t.connectResolve=e,t.connectReject=n;var o=t.config.signedUrl||t.config.websocketUrl;G.getConnection(o,t.config).then(n=>{t.ws=n,t.setupEventListeners(),n.readyState===WebSocket.OPEN&&(t.isConnected=!0,t.emit("connected"),e(),t.connectResolve=null,t.connectReject=null)}).catch(e=>{console.error("đ WebSocketManager: Connection failed ".concat(t.connectionId),e),n(e),t.connectResolve=null,t.connectReject=null})}catch(e){console.error("đ WebSocketManager: Connection error ".concat(t.connectionId),e),n(e),t.connectResolve=null,t.connectReject=null}})},function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){Y(r,o,i,a,s,"next",e)}function s(e){Y(r,o,i,a,s,"throw",e)}a(void 0)})})()}setupEventListeners(){if(this.ws){var e=(e,t)=>{t===(this.config.signedUrl||this.config.websocketUrl)&&(this.isConnected=!0,this.emit("connected"),this.connectResolve&&(this.connectResolve(),this.connectResolve=null,this.connectReject=null))},t=(e,t)=>{t===(this.config.signedUrl||this.config.websocketUrl)&&(this.isConnected=!1,this.emit("disconnected",e))},n=(e,t)=>{t===(this.config.signedUrl||this.config.websocketUrl)&&(this.emit("error",e),this.connectReject&&(this.connectReject(e),this.connectResolve=null,this.connectReject=null))},o=(e,t)=>{t===(this.config.signedUrl||this.config.websocketUrl)&&this.handleMessage(e)};G.on("open",e),G.on("close",t),G.on("error",n),G.on("message",o),this.eventHandlers={open:e,close:t,error:n,message:o}}}disconnect(){this.eventHandlers&&(G.off("open",this.eventHandlers.open),G.off("close",this.eventHandlers.close),G.off("error",this.eventHandlers.error),G.off("message",this.eventHandlers.message));var e=this.config.signedUrl||this.config.websocketUrl;e&&G.releaseConnection(e),this.ws=null,this.isConnected=!1}sendMessage(e){if(this.isConnected&&this.ws)try{this.ws.send(JSON.stringify(e))}catch(e){console.warn("đ WebSocketManager: Failed to send message:",e.message)}}sendBinary(e){if(this.isConnected&&this.ws)try{this.ws.send(e)}catch(e){console.warn("đ WebSocketManager: Failed to send binary data:",e.message)}}handleMessage(e){if(e.data instanceof ArrayBuffer)this.emit("binaryAudio",e.data);else if(e.data instanceof Blob)e.data.arrayBuffer().then(e=>{this.emit("binaryAudio",e)}).catch(e=>{console.error("đ WebSocketManager: Error converting Blob to ArrayBuffer:",e)});else try{var t=JSON.parse(e.data);"barge_in_ack"!==t.t&&"stop_sending"!==t.t||this.emit("bargeIn",t),"stop_playing"===t.t&&this.emit("stopPlaying",t),this.emit("message",t)}catch(e){this.emit("error",e)}}getStatus(){return{isConnected:this.isConnected,readyState:this.ws?this.ws.readyState:null,connectionId:this.connectionId}}static getSingletonStatus(){return G.getAllConnections()}static clearAllConnections(){G.clearAll()}}function $(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function X(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){$(r,o,i,a,s,"next",e)}function s(e){$(r,o,i,a,s,"throw",e)}a(void 0)})}}class Z extends L{constructor(e){super(),this.config=e,this.audioContext=null,this.audioWorkletNode=null,this.mediaStream=null,this.isRecording=!1}getAudioProcessorPath(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var e=document.getElementsByTagName("script");for(var t of e){var n=t.src;if(n&&(n.includes("agent-widget.js")||n.includes("ttp-agent-sdk")))try{new URL(n);var o=n.substring(0,n.lastIndexOf("/"));return"".concat(o,"/audio-processor.js")}catch(e){var i=n.substring(0,n.lastIndexOf("/"));return"".concat(i,"/audio-processor.js")}}return"https://cdn.talktopc.com/audio-processor.js"}checkPermissionState(){return X(function*(){try{if(navigator.permissions&&navigator.permissions.query)return(yield navigator.permissions.query({name:"microphone"})).state}catch(e){console.log("â ī¸ AudioRecorder: Permissions API not available or not supported for microphone")}return null})()}requestPermission(){var e=this;return X(function*(){try{if("granted"===(yield e.checkPermissionState()))return console.log("â
AudioRecorder: Microphone permission already granted"),!0;console.log("đ¤ AudioRecorder: Requesting microphone permission...");var t=e.config.sampleRate||e.config.outputSampleRate||44100;return(yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:t,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})).getTracks().forEach(e=>e.stop()),console.log("â
AudioRecorder: Microphone permission granted"),!0}catch(e){return console.error("â AudioRecorder: Failed to get microphone permission:",e),!1}})()}start(){var e=this;return X(function*(){try{console.log("đ¤ AudioRecorder: Requesting microphone access...");var t=yield e.checkPermissionState();t&&(console.log("đ AudioRecorder: Current permission state: ".concat(t)),"denied"===t&&console.warn('â ī¸ AudioRecorder: Permission state is "denied" - browser may not show prompt. User may need to change in browser settings.'));var n=e.config.sampleRate||e.config.outputSampleRate||44100;e.mediaStream=yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:n,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),e.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:n}),"suspended"===e.audioContext.state&&(yield e.audioContext.resume());var o=e.getAudioProcessorPath();yield e.audioContext.audioWorklet.addModule(o),e.audioWorkletNode=new AudioWorkletNode(e.audioContext,"audio-processor",{processorOptions:{sampleRate:n,outputSampleRate:e.config.outputSampleRate}}),e.audioContext.createMediaStreamSource(e.mediaStream).connect(e.audioWorkletNode),e.audioWorkletNode.port.onmessage=t=>{var{type:n,data:o}=t.data;"pcm_audio_data"===n&&e.emit("audioData",o)},e.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),console.log("â
AudioRecorder: Microphone access granted"),e.isRecording=!0,e.emit("recordingStarted")}catch(t){var i=t.message;if("NotAllowedError"===t.name||"PermissionDeniedError"===t.name){var r=yield e.checkPermissionState();"denied"===r?(i='Microphone access was blocked. To enable it: 1) Click the lock icon (đ) in your browser\'s address bar, 2) Find "Microphone" and change it to "Allow", 3) Refresh this page and try again.',console.error("â AudioRecorder: Permission explicitly denied. User must change in browser settings.")):"prompt"===r?(i='Microphone permission was denied. Click the "Voice Call" button again to see the permission prompt.',console.error('â AudioRecorder: Permission denied but state is "prompt" - user can try again.')):(i="Microphone permission was denied. Click the button again to retry, or enable microphone access in your browser settings (lock icon đ in address bar).",console.error("â AudioRecorder: Permission denied. User can try again or change in browser settings."))}else"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?(i="No microphone found. Please connect a microphone and try again.",console.error("â AudioRecorder: No microphone device found.")):"NotReadableError"===t.name||"TrackStartError"===t.name?(i="Microphone is already in use by another application. Please close other apps using the microphone and try again.",console.error("â AudioRecorder: Microphone is busy or not readable.")):"SecurityError"!==t.name&&"PermissionDeniedError"!==t.name||(i="Microphone access blocked. On mobile devices, please tap the recording button directly (not from an iframe or popup).",console.error("â AudioRecorder: User agent blocked microphone access. This often happens on mobile when not called from direct user interaction."));var a=new Error(i);throw a.name=t.name,a.originalError=t,e.emit("error",a),a}})()}stop(){var e=this;return X(function*(){if(e.isRecording)try{e.audioWorkletNode&&(e.audioWorkletNode.port.postMessage({type:"flush"}),yield new Promise(e=>setTimeout(e,100))),e.mediaStream&&(e.mediaStream.getTracks().forEach(e=>e.stop()),e.mediaStream=null),e.audioContext&&"closed"!==e.audioContext.state&&(yield e.audioContext.close(),e.audioContext=null),e.audioWorkletNode=null,e.isRecording=!1,e.emit("recordingStopped")}catch(t){throw e.emit("error",t),t}})()}getStatus(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}destroy(){this.stop()}}function ee(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function te(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){ee(r,o,i,a,s,"next",e)}function s(e){ee(r,o,i,a,s,"throw",e)}a(void 0)})}}class ne extends L{constructor(e){super(),this.config=e,this.audioContext=null,this.audioQueue=[],this.isPlaying=!1,this.isProcessingQueue=!1,this.currentSource=null,this.audioContextReady=!1,this.initializeAudioContext().catch(()=>{})}initializeAudioContext(){var e=this;return te(function*(){if(!e.audioContext||"closed"===e.audioContext.state)try{var t={sampleRate:e.config.sampleRate||e.config.outputSampleRate||44100};if(e.audioContext=new(window.AudioContext||window.webkitAudioContext)(t),"suspended"===e.audioContext.state&&(yield e.audioContext.resume()),"running"===e.audioContext.state)try{var n=e.audioContext.sampleRate,o=e.audioContext.createBuffer(1,.01*n,n),i=e.audioContext.createBufferSource();i.buffer=o,i.connect(e.audioContext.destination),i.start(0),i.stop(e.audioContext.currentTime+.01)}catch(e){console.debug("AudioPlayer: AudioContext warmup skipped:",e)}e.audioContextReady=!0}catch(t){console.warn("AudioPlayer: Failed to pre-initialize AudioContext:",t),e.audioContextReady=!1}})()}playAudio(e){try{var t=this.createAudioBlob(e);if(this.audioQueue.push(t),!this.isPlaying&&!this.isProcessingQueue&&!this.currentSource){var n=this.audioContextReady?0:50;setTimeout(()=>this.processQueue(),n)}}catch(e){this.emit("playbackError",e)}}createAudioBlob(e){var t=new Uint8Array(e);if(t.length>=4){if(82===t[0]&&73===t[1]&&70===t[2]&&70===t[3])return new Blob([e],{type:"audio/wav"});if(255===t[0]&&!(224&~t[1]))return new Blob([e],{type:"audio/mpeg"});if(79===t[0]&&103===t[1]&&103===t[2]&&83===t[3])return new Blob([e],{type:"audio/ogg"})}return new Blob([e],{type:"audio/wav"})}processQueue(){var e=this;return te(function*(){if(!e.isProcessingQueue&&0!==e.audioQueue.length){e.isProcessingQueue=!0;var t=e.audioQueue.shift();if(t)try{var n=!e.isPlaying&&null===e.currentSource;e.audioContext&&"closed"!==e.audioContext.state||(yield e.initializeAudioContext());var o=e.audioContext;"suspended"===o.state&&(yield o.resume(),n&&(yield new Promise(e=>setTimeout(e,10)))),"running"!==o.state&&(console.warn("AudioPlayer: AudioContext not in running state:",o.state),"suspended"===o.state&&(yield o.resume(),yield new Promise(e=>setTimeout(e,10))));var i=yield t.arrayBuffer(),r=yield o.decodeAudioData(i),a=n&&!e.isPlaying&&null===e.currentSource,s=o.createBufferSource();s.buffer=r,s.connect(o.destination),e.currentSource=s,e.isPlaying=!0,a&&e.emit("playbackStarted"),s.onended=()=>{e.currentSource=null,e.isProcessingQueue=!1,e.audioQueue.length>0?setTimeout(()=>e.processQueue(),0):setTimeout(()=>{0!==e.audioQueue.length||e.currentSource||(e.isPlaying=!1,e.emit("playbackStopped"))},100)},s.start()}catch(t){e.currentSource=null,e.emit("playbackError",t),e.audioQueue.length>0?(e.isProcessingQueue=!1,setTimeout(()=>e.processQueue(),100)):(e.isPlaying=!1,e.isProcessingQueue=!1,e.emit("playbackStopped"))}else e.isProcessingQueue=!1}})()}stop(){this.stopImmediate()}stopImmediate(){var e=this.isPlaying||null!==this.currentSource;if(this.currentSource){try{this.currentSource.stop()}catch(e){}this.currentSource=null}this.isPlaying=!1,this.isProcessingQueue=!1,this.audioQueue=[],e&&this.emit("playbackStopped")}resumeAudioContext(){var e=this;return te(function*(){if(e.audioContext&&"closed"!==e.audioContext.state){if("suspended"===e.audioContext.state)try{yield e.audioContext.resume(),console.log("â
AudioPlayer: AudioContext resumed after mic permission")}catch(e){console.warn("â ī¸ AudioPlayer: Failed to resume AudioContext:",e)}}else yield e.initializeAudioContext()})()}getStatus(){return{isPlaying:this.isPlaying,isProcessingQueue:this.isProcessingQueue,queueLength:this.audioQueue.length,audioContextState:this.audioContext?this.audioContext.state:"closed"}}destroy(){this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.audioContextReady=!1}}var oe=r(848);function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function re(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ie(Object(n),!0).forEach(function(t){ae(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ie(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ae(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function se(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}const ce=o=>{var{signedUrl:i,websocketUrl:r,agentId:a,appId:s,voice:c="default",language:l="en",autoReconnect:d=!0,agentSettingsOverride:u=null,onConnected:h,onDisconnected:p,onRecordingStarted:g,onRecordingStopped:m,onPlaybackStarted:v,onPlaybackStopped:f,onError:y,onMessage:x,onBargeIn:b,onStopPlaying:w,onStartConversation:S,onEndConversation:C,className:k="",style:P={},children:T}=o,[E,I]=n(!1),[A,R]=n(!1),[D,F]=n(!1),[B,_]=n("Disconnected"),O=t(null);e(()=>{console.log("đī¸ VoiceButton: Creating VoiceSDK_v2 instance for ".concat(r||i)),O.current&&(console.log("đī¸ VoiceButton: Destroying existing VoiceSDK_v2 instance"),O.current.destroy(),O.current=null);var e=new H({signedUrl:r||i,websocketUrl:r||i,agentId:a,appId:s,voice:c,language:l,autoReconnect:d,agentSettingsOverride:u,onStartConversation:S,onEndConversation:C});return e.on("connected",()=>{I(!0),_("Connected"),null==h||h()}),e.on("disconnected",()=>{I(!1),_("Disconnected"),null==p||p()}),e.on("recordingStarted",()=>{R(!0),null==g||g()}),e.on("recordingStopped",()=>{R(!1),null==m||m()}),e.on("playbackStarted",()=>{F(!0),null==v||v()}),e.on("playbackStopped",()=>{F(!1),null==f||f()}),e.on("error",e=>{null==y||y(e)}),e.on("message",e=>{null==x||x(e)}),e.on("bargeIn",e=>{null==b||b(e)}),e.on("stopPlaying",e=>{null==w||w(e)}),O.current=e,e.connect(),()=>{var e=i||r;console.log("đī¸ VoiceButton: Cleaning up VoiceSDK instance for ".concat(e)),O.current&&(O.current.destroy(),O.current=null)}},[i,r,a,s,c,l,u]);var M=function(){var e,t=(e=function*(){if(O.current)try{yield O.current.toggleRecording()}catch(e){console.error("Error toggling recording:",e)}},function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){se(r,o,i,a,s,"next",e)}function s(e){se(r,o,i,a,s,"throw",e)}a(void 0)})});return function(){return t.apply(this,arguments)}}(),U=(0,oe.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,oe.jsx)("div",{style:{fontSize:"20px"},children:A?"đ´":"đ¤"}),(0,oe.jsx)("div",{children:A?"Stop Listening":"Start Listening"})]});return(0,oe.jsx)("button",{className:"voice-button ".concat(A?"recording":""," ").concat(k),style:re({padding:"12px 24px",border:"none",borderRadius:"8px",backgroundColor:A?"#dc3545":"#007bff",color:"white",cursor:"pointer",fontSize:"16px",fontWeight:"500",transition:"all 0.2s ease"},P),onClick:M,disabled:!E,children:T||U})};function le(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function de(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){le(r,o,i,a,s,"next",e)}function s(e){le(r,o,i,a,s,"throw",e)}a(void 0)})}}function ue(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function he(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class pe{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.options=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ue(Object(n),!0).forEach(function(t){he(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ue(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({websocketUrl:e.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:e.agentId,voice:e.voice||"default",language:e.language||"en",container:e.container||document.body,buttonText:e.buttonText||"Start Listening",buttonClass:e.buttonClass||"voice-button"},e),this.isConnected=!1,this.isRecording=!1,this.isPlaying=!1,this.voiceSDK=new H({signedUrl:this.options.websocketUrl||this.options.signedUrl,websocketUrl:this.options.websocketUrl||this.options.signedUrl,agentId:this.options.agentId,appId:this.options.appId,voice:this.options.voice,language:this.options.language}),this.setupEventListeners(),this.createButton(),this.connect()}setupEventListeners(){this.voiceSDK.on("connected",()=>{var e,t;this.isConnected=!0,this.updateButton(),null===(e=(t=this.options).onConnected)||void 0===e||e.call(t)}),this.voiceSDK.on("disconnected",()=>{var e,t;this.isConnected=!1,this.updateButton(),null===(e=(t=this.options).onDisconnected)||void 0===e||e.call(t)}),this.voiceSDK.on("recordingStarted",()=>{var e,t;this.isRecording=!0,this.updateButton(),null===(e=(t=this.options).onRecordingStarted)||void 0===e||e.call(t)}),this.voiceSDK.on("recordingStopped",()=>{var e,t;this.isRecording=!1,this.updateButton(),null===(e=(t=this.options).onRecordingStopped)||void 0===e||e.call(t)}),this.voiceSDK.on("playbackStarted",()=>{var e,t;this.isPlaying=!0,null===(e=(t=this.options).onPlaybackStarted)||void 0===e||e.call(t)}),this.voiceSDK.on("playbackStopped",()=>{var e,t;this.isPlaying=!1,null===(e=(t=this.options).onPlaybackStopped)||void 0===e||e.call(t)}),this.voiceSDK.on("error",e=>{var t,n;null===(t=(n=this.options).onError)||void 0===t||t.call(n,e)}),this.voiceSDK.on("message",e=>{var t,n;null===(t=(n=this.options).onMessage)||void 0===t||t.call(n,e)}),this.voiceSDK.on("bargeIn",e=>{var t,n;null===(t=(n=this.options).onBargeIn)||void 0===t||t.call(n,e)}),this.voiceSDK.on("stopPlaying",e=>{var t,n;null===(t=(n=this.options).onStopPlaying)||void 0===t||t.call(n,e)})}createButton(){this.button=document.createElement("button"),this.button.className=this.options.buttonClass,this.button.style.cssText="\n padding: 12px 24px;\n border: none;\n border-radius: 8px;\n background-color: #6c757d;\n color: white;\n cursor: pointer;\n font-size: 16px;\n font-weight: 500;\n transition: all 0.2s ease;\n display: flex;\n align-items: center;\n gap: 8px;\n ",this.button.addEventListener("click",()=>this.toggleRecording()),this.options.container.appendChild(this.button),this.updateButton()}updateButton(){if(this.button){var e=this.isRecording?"đ´":"đ¤",t=this.isRecording?"Stop Listening":"Start Listening";this.button.innerHTML='\n <span style="font-size: 20px;">'.concat(e,"</span>\n <span>").concat(t,"</span>\n "),this.button.disabled=!this.isConnected,this.button.style.backgroundColor=this.isRecording?"#dc3545":this.isConnected?"#007bff":"#6c757d"}}connect(){var e=this;return de(function*(){try{yield e.voiceSDK.connect()}catch(e){console.error("Failed to connect:",e)}})()}toggleRecording(){var e=this;return de(function*(){if(e.voiceSDK)try{yield e.voiceSDK.toggleRecording()}catch(e){console.error("Error toggling recording:",e)}})()}getStatus(){return{isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying}}updateConfig(e){this.voiceSDK.updateConfig(e)}destroy(){this.button&&this.button.parentNode&&this.button.parentNode.removeChild(this.button),this.voiceSDK&&this.voiceSDK.destroy()}}function ge(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function me(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){ge(r,o,i,a,s,"next",e)}function s(e){ge(r,o,i,a,s,"throw",e)}a(void 0)})}}class ve{constructor(e){console.log("đ AgentSDK v2.1.8 initialized with config:",e),this.config=e,this.voiceSDK=null,this.isConnected=!1,this.isListening=!1,this.wasListening=!1,this._resumeInfo=null,this.onConnected=()=>{},this.onDisconnected=()=>{},this.onError=e=>console.error("SDK Error:",e),this.onTranscript=e=>{},this.onAgentSpeaking=e=>{},this.onConversationStart=e.onConversationStart||(()=>{}),this.onConversationEnd=e.onConversationEnd||(()=>{}),this.onBargeIn=e.onBargeIn||(()=>{}),this.onAudioStartPlaying=e.onAudioStartPlaying||(()=>{}),this.onAudioStoppedPlaying=e.onAudioStoppedPlaying||(()=>{}),this.onSubtitleDisplay=e.onSubtitleDisplay||(()=>{})}checkResumeBeforeConnect(){try{var e=new H({signedUrl:"wss://placeholder",autoReconnect:!1,agentId:this.config.agentId,appId:this.config.appId,language:this.config.language||"en",protocolVersion:2}).checkAndResume();return e?(console.log("đ [AGENT SDK] Found resume state before connect:",e),this._resumeInfo=e,e):null}catch(e){return console.warn("â ī¸ [AGENT SDK] Error checking resume:",e),null}}connect(e){var t=this;return me(function*(){try{if(!e)throw new Error("signedUrl is required");if(t.voiceSDK&&(console.log("đ AgentSDK: Cleaning up existing connection"),t.voiceSDK.destroy(),t.voiceSDK=null),t.voiceSDK=new H({signedUrl:e,autoReconnect:!1,agentId:t.config.agentId,appId:t.config.appId,language:t.config.language||"en",agentSettingsOverride:t.config.agentSettingsOverride,protocolVersion:2,outputContainer:t.config.outputContainer||"raw",outputEncoding:t.config.outputEncoding||"pcm",outputSampleRate:t.config.outputSampleRate||44100,outputChannels:t.config.outputChannels||1,outputBitDepth:t.config.outputBitDepth||16}),t._resumeInfo&&(console.log("đ [AGENT SDK] Using stored resume info:",t._resumeInfo),console.log(" From:",t._resumeInfo.fromPage,"â To:",t._resumeInfo.toPage)),t.voiceSDK.on("connected",()=>{t.isConnected=!0,t.onConnected()}),setTimeout(()=>{t.voiceSDK&&t.voiceSDK.isConnected&&!t.isConnected&&(t.isConnected=!0,t.onConnected())},10),t.voiceSDK.on("disconnected",e=>{if(t.isConnected=!1,e&&1008===e.code&&e.reason&&(e.reason.includes("Domain not whitelisted")||e.reason.includes("domain")||e.reason.includes("whitelist"))){var n=new Error("DOMAIN_NOT_WHITELISTED");n.reason=e.reason,n.code=e.code,t.onError(n)}if((t.isListening||t.wasListening)&&(console.log("đ¤ [AGENT SDK] disconnected event - calling onConversationEnd hook (isListening:",t.isListening,", wasListening:",t.wasListening,")"),t.onConversationEnd&&"function"==typeof t.onConversationEnd))try{t.onConversationEnd(),console.log("đ¤ [AGENT SDK] â
onConversationEnd hook called from disconnected event"),t.wasListening=!1}catch(e){console.error("đ¤ [AGENT SDK] â Error calling onConversationEnd from disconnected:",e)}t.onDisconnected()}),t.voiceSDK.on("domainError",e=>{t.onError(e)}),t.voiceSDK.on("error",e=>{t.onError(e)}),t.voiceSDK.on("message",e=>{t.handleWebSocketMessage(e)}),t.voiceSDK.on("recordingStarted",()=>{if(t.isListening=!0,t.wasListening=!0,t.onConversationStart&&"function"==typeof t.onConversationStart)try{t.onConversationStart()}catch(e){console.error("đ¤ [AGENT SDK] â Error calling onConversationStart:",e)}}),t.voiceSDK.on("recordingStopped",()=>{console.log("đ¤ [AGENT SDK] recordingStopped event received");var e=t.isListening;if(t.isListening=!1,e&&t.onConversationEnd&&"function"==typeof t.onConversationEnd)try{console.log("đ¤ [AGENT SDK] â
Calling onConversationEnd hook from recordingStopped"),t.onConversationEnd(),console.log("đ¤ [AGENT SDK] â
onConversationEnd hook called successfully"),t.wasListening=!1}catch(e){console.error("đ¤ [AGENT SDK] â Error calling onConversationEnd:",e)}}),t.voiceSDK.on("playbackStarted",()=>{t.onAgentSpeaking(!0),t.onAudioStartPlaying()}),t.voiceSDK.on("playbackStopped",()=>{t.onAgentSpeaking(!1),t.onAudioStoppedPlaying()}),t.voiceSDK.on("bargeIn",e=>{t.onBargeIn(e)}),t.voiceSDK.on("transcriptDisplay",e=>{console.log("đ [AGENT SDK] transcriptDisplay event received:",e),e&&e.text&&(console.log("đ [AGENT SDK] Calling onTranscript with text:",e.text),t.onTranscript&&"function"==typeof t.onTranscript?t.onTranscript(e.text):console.warn("đ [AGENT SDK] â ī¸ onTranscript is not a function!",typeof t.onTranscript)),t.onSubtitleDisplay(e)}),t._pendingToolHandlers&&t._pendingToolHandlers.size>0)for(var[n,o]of(console.log("đ§ AgentSDK: Registering ".concat(t._pendingToolHandlers.size," pending tool handlers")),t._pendingToolHandlers))t.voiceSDK.registerToolHandler(n,o);yield t.voiceSDK.connect()}catch(e){throw t.onError(e),e}})()}handleWebSocketMessage(e){switch(e.t||e.type){case"connected":case"hello_ack":console.log("Session started successfully");break;case"user_transcript":this.onTranscript(e.user_transcription||e.text||e.transcript);break;case"agent_response":case"barge_in":case"stop_playing":default:break;case"error":this.onError(new Error(e.message||e.error||"Unknown error"))}}startListening(){var e=this;return me(function*(){if(console.log("đ¤ AgentSDK: startListening() called"),!e.voiceSDK)throw console.error("â AgentSDK: No voiceSDK instance available"),new Error("No voiceSDK instance available");try{console.log("đ¤ AgentSDK: Starting recording..."),yield e.voiceSDK.startRecording(),console.log("â
AgentSDK: Recording started successfully")}catch(e){throw console.error("â AgentSDK: Failed to start recording:",e),e}})()}stopListening(){this.voiceSDK&&this.voiceSDK.stopRecording()}hangup(){this.voiceSDK&&this.voiceSDK.hangup()}updateVariables(e){this.voiceSDK&&this.isConnected&&this.voiceSDK.sendMessage({t:"update_variables",variables:e})}disconnect(){this.voiceSDK&&(this.voiceSDK.destroy(),this.voiceSDK=null),this.isConnected=!1,this.isListening=!1}registerToolHandler(e,t){if(this.voiceSDK)return this.voiceSDK.registerToolHandler(e,t);this._pendingToolHandlers||(this._pendingToolHandlers=new Map),this._pendingToolHandlers.set(e,t),console.log("đ§ AgentSDK: Queued tool handler '".concat(e,"' for registration after connect"))}unregisterToolHandler(e){if(this.voiceSDK)return this.voiceSDK.unregisterToolHandler(e);this._pendingToolHandlers&&this._pendingToolHandlers.delete(e)}hasToolHandler(e){var t;return this.voiceSDK?this.voiceSDK.hasToolHandler(e):(null===(t=this._pendingToolHandlers)||void 0===t?void 0:t.has(e))||!1}getRegisteredTools(){return this.voiceSDK?this.voiceSDK.getRegisteredTools():this._pendingToolHandlers?Array.from(this._pendingToolHandlers.keys()):[]}}function fe(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function ye(){var e=navigator.userAgent,t=/iPad|iPhone|iPod/.test(e)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,n=/Android/.test(e),o=/Mac/.test(e)&&!t,i=/Win/.test(e),r=/Chrome/.test(e)&&!/Edg|OPR/.test(e),a=/Safari/.test(e)&&!/Chrome/.test(e),s=/Firefox/.test(e),c=/Edg/.test(e),l=/SamsungBrowser/.test(e),d="unknown";t?d="safari":l?d="samsung":r?d="chrome":a?d="safari":s?d="firefox":c&&(d="edge");var u="unknown";return t?u="ios":n?u="android":o?u="mac":i&&(u="windows"),{platform:u,browser:d,isIOS:t,isAndroid:n,isMac:o,isWindows:i,isMobile:t||n,isDesktop:!t&&!n}}function xe(){return be.apply(this,arguments)}function be(){var e;return e=function*(){try{if(navigator.permissions&&navigator.permissions.query)return(yield navigator.permissions.query({name:"microphone"})).state}catch(e){console.log("â ī¸ MicPermissionUtils: Permissions API not available or not supported for microphone")}return"unknown"},be=function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){fe(r,o,i,a,s,"next",e)}function s(e){fe(r,o,i,a,s,"throw",e)}a(void 0)})},be.apply(this,arguments)}function we(e){var{platform:t,browser:n}=e,o={ios:{title:"Enable Microphone on iPhone/iPad",icon:"đą",steps:["Tap the <strong>lock icon đ</strong>, <strong>information icon âšī¸</strong>, or <strong>AA icon</strong> in the address bar","Tap <strong>Website Settings</strong> or <strong>Permissions</strong>","Find <strong>Microphone</strong> and set it to <strong>Allow</strong>","Return to this page and refresh"],altTitle:"Alternative Method",altSteps:["Open the <strong>Settings</strong> app on your device","Scroll down and tap <strong>Safari</strong> (or your browser app)",'Tap <strong>Microphone</strong> under "Settings for Websites"',"Set it to <strong>Allow</strong> or <strong>Ask</strong>","Return to this page and refresh"],note:"On iOS, you can also change permissions in the browser address bar or in device Settings.",canOpenSettings:!0,settingsButtonText:"Open Settings App"},android_chrome:{title:"Enable Microphone in Chrome",icon:"đ¤",steps:["Tap the <strong>lock icon đ</strong>, <strong>information icon âšī¸</strong>, or <strong>settings icon âŽ</strong> in the address bar","Tap <strong>Permissions</strong>","Tap <strong>Microphone</strong>","Select <strong>Allow</strong>","The page will refresh automatically"],altTitle:"Alternative Method",altSteps:["Tap the <strong>⎠menu</strong> (three dots)","Tap <strong>Settings â Site settings â Microphone</strong>","Find this website and set to <strong>Allow</strong>"],canOpenSettings:!0,settingsButtonText:"Open App Settings"},android_firefox:{title:"Enable Microphone in Firefox",icon:"đĻ",steps:["Tap the <strong>lock icon đ</strong> or <strong>information icon âšī¸</strong> in the address bar","Tap <strong>Edit Site Permissions</strong>","Toggle <strong>Microphone</strong> to enabled","Refresh the page"],canOpenSettings:!1},android_samsung:{title:"Enable Microphone in Samsung Browser",icon:"đą",steps:["Tap the <strong>menu icon</strong> (three lines)","Tap <strong>Settings â Sites and downloads</strong>","Tap <strong>Site permissions â Microphone</strong>","Find this website and set to <strong>Allow</strong>","Return and refresh the page"],canOpenSettings:!1},desktop_chrome:{title:"Enable Microphone in Chrome",icon:"đ",steps:["Click the <strong>lock icon đ</strong> or <strong>information icon âšī¸</strong> in the address bar (left side)","Find <strong>Microphone</strong> in the dropdown menu",'Change it from "Block" to <strong>Allow</strong>',"Click the <strong>Refresh</strong> button or press F5"],showAddressBarHint:!0,canOpenSettings:!1},desktop_safari:{title:"Enable Microphone in Safari",icon:"đ§",steps:["Click <strong>Safari</strong> in the menu bar (top of screen)","Click <strong>Settings for This Website...</strong>","Find <strong>Microphone</strong> in the popup","Change it to <strong>Allow</strong>","Close settings and refresh the page"],canOpenSettings:!1},desktop_firefox:{title:"Enable Microphone in Firefox",icon:"đĻ",steps:["Click the <strong>lock icon đ</strong> in the address bar",'Click the <strong>X</strong> next to "Blocked" for Microphone',"Refresh the page (press F5)","Click <strong>Allow</strong> when prompted again"],note:"Firefox requires you to clear the block and then re-allow on the next prompt.",showAddressBarHint:!0,canOpenSettings:!1},desktop_edge:{title:"Enable Microphone in Edge",icon:"đ",steps:["Click the <strong>lock icon đ</strong> in the address bar","Find <strong>Microphone</strong> in the permissions list","Change it to <strong>Allow</strong>","Refresh the page"],showAddressBarHint:!0,canOpenSettings:!1},unknown:{title:"Enable Microphone Access",icon:"đ¤",steps:["Look for a <strong>lock icon đ</strong>, <strong>information icon âšī¸</strong>, or <strong>settings icon</strong> in your browser's address bar","Find the <strong>Microphone</strong> permission setting","Change it to <strong>Allow</strong>","Refresh this page"],canOpenSettings:!1}};return"ios"===t?o.ios:"android"===t?o["android_".concat(n)]||o.android_chrome:o["desktop_".concat(n)]||o.desktop_chrome}function Se(e){var{isIOS:t,isAndroid:n,browser:o}=e;if(t)try{return window.location.href="app-settings:",!0}catch(e){return console.warn("Could not open iOS settings:",e),!1}if(n&&"chrome"===o)try{return window.location.href="intent:#Intent;action=android.settings.APPLICATION_DETAILS_SETTINGS;data=package:com.android.chrome;end",!0}catch(e){return console.warn("Could not open Android settings:",e),!1}return!1}class Ce{constructor(){this.overlay=null,this.modal=null}createOverlay(){var e=document.createElement("div");return e.className="mic-permission-overlay",e.style.cssText="\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.6);\n backdrop-filter: blur(4px);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10000;\n padding: 20px;\n animation: mic-fadeIn 0.2s ease-out;\n ",document.getElementById("mic-permission-styles")||this.injectStyles(),e}injectStyles(){if(!document.getElementById("mic-permission-styles")){var e=document.createElement("style");e.id="mic-permission-styles",e.textContent="\n @keyframes mic-fadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes mic-slideUp {\n from {\n opacity: 0;\n transform: translateY(20px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n \n @keyframes mic-bounce {\n 0%, 100% { transform: translateY(0); }\n 50% { transform: translateY(-5px); }\n }\n \n .mic-permission-overlay {\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.6);\n backdrop-filter: blur(4px);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10000;\n padding: 20px;\n animation: mic-fadeIn 0.2s ease-out;\n }\n \n .mic-permission-modal {\n background: #ffffff;\n border-radius: 16px;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);\n max-width: 480px;\n width: 100%;\n padding: 32px;\n position: relative;\n animation: mic-slideUp 0.3s ease-out;\n max-height: 90vh;\n overflow-y: auto;\n }\n \n .mic-permission-modal__close {\n position: absolute;\n top: 16px;\n right: 16px;\n background: none;\n border: none;\n font-size: 20px;\n cursor: pointer;\n color: #6b7280;\n width: 32px;\n height: 32px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.2s;\n }\n \n .mic-permission-modal__close:hover {\n background: #e5e7eb;\n }\n \n .mic-permission-modal__icon {\n font-size: 48px;\n text-align: center;\n margin-bottom: 16px;\n }\n \n .mic-permission-modal__title {\n font-size: 24px;\n font-weight: 700;\n color: #111827;\n margin: 0 0 12px;\n line-height: 1.3;\n text-align: center;\n }\n \n .mic-permission-modal__description {\n color: #6b7280;\n font-size: 16px;\n line-height: 1.6;\n margin: 0 0 20px;\n text-align: center;\n }\n \n .mic-permission-modal__highlight {\n display: flex;\n align-items: center;\n gap: 12px;\n background: linear-gradient(135deg, #dbeafe, #ede9fe);\n padding: 16px 20px;\n border-radius: 8px;\n margin-bottom: 20px;\n border: 1px solid #bfdbfe;\n }\n \n .mic-permission-modal__highlight-icon {\n font-size: 24px;\n animation: mic-bounce 1s infinite;\n }\n \n .mic-permission-modal__status {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n background: #fef2f2;\n color: #ef4444;\n padding: 12px 16px;\n border-radius: 8px;\n margin-bottom: 20px;\n font-weight: 500;\n }\n \n .mic-permission-modal__note {\n display: flex;\n align-items: flex-start;\n gap: 10px;\n background: #fffbeb;\n color: #92400e;\n padding: 12px 16px;\n border-radius: 8px;\n margin-bottom: 20px;\n font-size: 14px;\n line-height: 1.5;\n border: 1px solid #fde68a;\n }\n \n .mic-permission-modal__steps {\n margin-bottom: 20px;\n }\n \n .mic-permission-modal__steps h3 {\n font-size: 14px;\n font-weight: 600;\n color: #6b7280;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin: 0 0 12px;\n }\n \n .mic-permission-modal__steps ol {\n margin: 0;\n padding-left: 24px;\n counter-reset: step-counter;\n list-style: none;\n }\n \n .mic-permission-modal__steps li {\n position: relative;\n padding: 12px 0 12px 16px;\n border-left: 2px solid #e5e7eb;\n color: #111827;\n font-size: 15px;\n line-height: 1.5;\n counter-increment: step-counter;\n }\n \n .mic-permission-modal__steps li::before {\n content: counter(step-counter);\n position: absolute;\n left: -14px;\n top: 10px;\n width: 24px;\n height: 24px;\n background: #4f46e5;\n color: white;\n border-radius: 50%;\n font-size: 12px;\n font-weight: 600;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n \n .mic-permission-modal__steps li:last-child {\n border-left-color: transparent;\n }\n \n .mic-permission-modal__actions {\n display: flex;\n flex-direction: column;\n gap: 10px;\n margin-top: 24px;\n }\n \n .mic-permission-modal__btn {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n padding: 14px 24px;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition: all 0.2s;\n border: none;\n width: 100%;\n }\n \n .mic-permission-modal__btn--primary {\n background: #4f46e5;\n color: white;\n }\n \n .mic-permission-modal__btn--primary:hover {\n background: #4338ca;\n transform: translateY(-1px);\n }\n \n .mic-permission-modal__btn--secondary {\n background: #e5e7eb;\n color: #111827;\n }\n \n .mic-permission-modal__btn--secondary:hover {\n background: #d1d5db;\n }\n \n .mic-permission-modal__footer {\n text-align: center;\n font-size: 13px;\n color: #6b7280;\n margin-top: 20px;\n margin-bottom: 0;\n }\n \n .mic-permission-modal__visual-guide {\n width: 100%;\n max-width: 380px;\n height: auto;\n margin: 20px auto;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);\n display: block;\n }\n \n .mic-permission-modal__visual-guide-container {\n text-align: center;\n margin: 20px 0;\n }\n \n @media (max-width: 480px) {\n .mic-permission-modal {\n padding: 24px 20px;\n margin: 10px;\n max-height: 85vh;\n }\n \n .mic-permission-modal__title {\n font-size: 20px;\n }\n \n .mic-permission-modal__icon {\n font-size: 40px;\n }\n \n .mic-permission-modal__visual-guide {\n max-width: 100%;\n }\n }\n ",document.head.appendChild(e)}}close(){this.overlay&&this.overlay.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.modal=null}show(){this.overlay&&this.modal&&document.body.appendChild(this.overlay)}}function ke(e,t){var n=new Ce,o=n.createOverlay(),i=ye(),r=document.createElement("div");return r.className="mic-permission-modal",r.innerHTML='\n <div class="mic-permission-modal__icon">đ¤</div>\n <h2 class="mic-permission-modal__title">Enable Your Microphone</h2>\n <p class="mic-permission-modal__description">\n To start a voice call with our agent, we need access to your microphone.\n </p>\n <div class="mic-permission-modal__highlight">\n <span class="mic-permission-modal__highlight-icon">đ</span>\n <span>Please click <strong>"Allow"</strong> on the next popup</span>\n </div>\n '.concat(i.isIOS?'\n <div class="mic-permission-modal__note">\n <span>âšī¸</span>\n <span>On iPhone/iPad, you may need to allow microphone access in your device Settings.</span>\n </div>\n ':"",'\n <div class="mic-permission-modal__actions">\n <button class="mic-permission-modal__btn mic-permission-modal__btn--primary" data-action="accept">\n Continue\n </button>\n <button class="mic-permission-modal__btn mic-permission-modal__btn--secondary" data-action="cancel">\n Not Now\n </button>\n </div>\n '),o.appendChild(r),n.overlay=o,n.modal=r,r.querySelector('[data-action="accept"]').addEventListener("click",()=>{n.close(),e()}),r.querySelector('[data-action="cancel"]').addEventListener("click",()=>{n.close(),t()}),o.addEventListener("click",e=>{e.target===o&&(n.close(),t())}),n.show(),n}function Pe(e,t){var n,o,i,r=new Ce,a=r.createOverlay(),s=ye(),c=we(s),l=document.createElement("div");l.className="mic-permission-modal";var d="";c.altSteps&&c.altSteps.length>0&&(d='\n <div style="margin-top: 20px; border-top: 1px solid #e5e7eb; padding-top: 16px;">\n <button class="mic-permission-modal__alt-toggle" style="background: none; border: none; color: #4f46e5; font-size: 14px; font-weight: 500; cursor: pointer; padding: 0; margin-bottom: 12px;">\n âŧ '.concat(c.altTitle||"Alternative method",'\n </button>\n <ol style="margin: 0; padding-left: 20px; display: none;">\n ').concat(c.altSteps.map(e=>'<li style="padding: 8px 0; font-size: 14px; color: #6b7280;">'.concat(e,"</li>")).join(""),"\n </ol>\n </div>\n "));var u=function(e){var{platform:t,browser:n}=e,o=document.getElementsByTagName("script"),i="";for(var r of o){var a=r.src;if(a&&(a.includes("agent-widget.js")||a.includes("ttp-agent-sdk")||a.includes("ttp-sdk-front")))try{new URL(a),i=a.substring(0,a.lastIndexOf("/"));break}catch(e){var s=a.match(/^(.*\/)[^\/]+$/);if(s){i=s[1];break}}}var c;if(c="ios"===t?"ios-settings.svg":"android"===t?"android-chrome.svg":"chrome"===n?"desktop-chrome.svg":"safari"===n?"desktop-safari.svg":"firefox"===n?"desktop-firefox.svg":"edge"===n?"desktop-edge.svg":"desktop-chrome.svg",!i||""===i||i.startsWith("/")){for(var l of o){var d=l.src;if(d&&(d.includes("cdn.talktopc.com")||d.includes("talktopc.com"))){if(d.includes("/ttp-agent-sdk/")||d.includes("/ttp-sdk-front/")){var u=d.match(/(https?:\/\/[^\/]+(?:\/[^\/]+)*)/);if(u){i=u[1].replace(/\/[^\/]+\.js$/,"");break}}if(!i&&(d.includes("cdn.talktopc.com")||d.includes("talktopc.com"))){i="https://cdn.talktopc.com/ttp-agent-sdk";break}}}if(!i||""===i)if(window.location.hostname.includes("cdn.talktopc.com")||window.location.hostname.includes("talktopc.com"))i="https://cdn.talktopc.com/ttp-agent-sdk";else{var h=window.location.pathname.split("/");h.pop(),(i=window.location.origin+h.join("/"))&&i!==window.location.origin||(i=window.location.origin)}}i=i.replace(/\/$/,"");var p="".concat(i,"/shared/mic-permission-assets/").concat(c);return"undefined"!=typeof console&&console.log&&console.log("[MicPermission] Visual guide path:",p,"Base path:",i,"Platform:",t,"Browser:",n),p}(s);l.innerHTML='\n <button class="mic-permission-modal__close" data-action="close">â</button>\n <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">\n <span style="font-size: 32px;">'.concat(c.icon,'</span>\n <h2 class="mic-permission-modal__title" style="text-align: left; margin: 0;">').concat(c.title,'</h2>\n </div>\n <div class="mic-permission-modal__status">\n <span>đĢ</span>\n <span>Microphone access is currently blocked</span>\n </div>\n ').concat(c.note?'\n <div class="mic-permission-modal__note">\n <span>âšī¸</span>\n <span>'.concat(c.note,"</span>\n </div>\n "):"",'\n <div class="mic-permission-modal__visual-guide-container">\n <img src="').concat(u,'" alt="Visual guide for enabling microphone" class="mic-permission-modal__visual-guide" \n onerror="console.error(\'[MicPermission] Failed to load image:\', this.src); this.style.display=\'none\';" \n onload="console.log(\'[MicPermission] Image loaded successfully:\', this.src);" />\n </div>\n <div class="mic-permission-modal__steps">\n <h3>Follow these steps:</h3>\n <ol>\n ').concat(c.steps.map(e=>"<li>".concat(e,"</li>")).join(""),"\n </ol>\n </div>\n ").concat(d,'\n <div class="mic-permission-modal__actions">\n ').concat(c.canOpenSettings?'\n <button class="mic-permission-modal__btn mic-permission-modal__btn--primary" data-action="open-settings">\n '.concat(c.settingsButtonText||"Open Settings","\n </button>\n "):"","\n ").concat(c.showAddressBarHint?'\n <button class="mic-permission-modal__btn mic-permission-modal__btn--primary" data-action="show-hint">\n Show Me Where\n </button>\n ':"",'\n <button class="mic-permission-modal__btn mic-permission-modal__btn--secondary" data-action="refresh">\n đ Refresh Page\n </button>\n </div>\n <p class="mic-permission-modal__footer">\n After enabling microphone access, return here and click "Refresh Page"\n </p>\n '),a.appendChild(l),r.overlay=a,r.modal=l,null===(n=l.querySelector('[data-action="close"]'))||void 0===n||n.addEventListener("click",()=>{r.close(),e()}),null===(o=l.querySelector('[data-action="open-settings"]'))||void 0===o||o.addEventListener("click",()=>{Se(s)}),null===(i=l.querySelector('[data-action="refresh"]'))||void 0===i||i.addEventListener("click",()=>{window.location.reload()});var h=l.querySelector('[data-action="show-hint"]');h&&h.addEventListener("click",()=>{r.close(),e(),function(){var e=document.getElementById("mic-address-bar-hint");e&&e.remove(),ye();var t=document.getElementsByTagName("script"),n="";for(var o of t){var i=o.src;if(i&&(i.includes("agent-widget.js")||i.includes("ttp-agent-sdk")||i.includes("ttp-sdk-front")))try{new URL(i),n=i.substring(0,i.lastIndexOf("/"));break}catch(e){var r=i.match(/^(.*\/)[^\/]+$/);if(r){n=r[1];break}}}if(!n||""===n||n.startsWith("/")){for(var a of t){var s=a.src;if(s&&(s.includes("cdn.talktopc.com")||s.includes("talktopc.com"))){if(s.includes("/ttp-agent-sdk/")||s.includes("/ttp-sdk-front/")){var c=s.match(/(https?:\/\/[^\/]+(?:\/[^\/]+)*)/);if(c){n=c[1].replace(/\/[^\/]+\.js$/,"");break}}if(!n&&(s.includes("cdn.talktopc.com")||s.includes("talktopc.com"))){n="https://cdn.talktopc.com/ttp-agent-sdk";break}}}if(!n||""===n)if(window.location.hostname.includes("cdn.talktopc.com")||window.location.hostname.includes("talktopc.com"))n="https://cdn.talktopc.com/ttp-agent-sdk";else{var l=window.location.pathname.split("/");l.pop(),(n=window.location.origin+l.join("/"))&&n!==window.location.origin||(n=window.location.origin)}}n=n.replace(/\/$/,"");var d="".concat(n,"/shared/mic-permission-assets/address-bar-hint.svg"),u=document.createElement("div");u.id="mic-address-bar-hint",u.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n z-index: 10001;\n padding: 10px 20px;\n pointer-events: none;\n animation: mic-fadeIn 0.3s ease-out;\n display: flex;\n justify-content: center;\n ";var h=document.createElement("div");h.style.cssText="\n display: flex;\n align-items: center;\n gap: 12px;\n background: #f59e0b;\n color: white;\n padding: 12px 20px;\n border-radius: 0 0 8px 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n pointer-events: all;\n animation: mic-slideDown 0.3s ease-out;\n max-width: 540px;\n ";var p=document.createElement("div");p.style.cssText="\n flex-shrink: 0;\n ";var g=document.createElement("img");g.src=d,g.alt="Address bar hint",g.style.cssText="\n width: auto;\n height: 80px;\n display: block;\n ",g.onerror=()=>{p.style.display="none"},p.appendChild(g);var m=document.createElement("div");m.style.cssText="\n display: flex;\n flex-direction: column;\n gap: 4px;\n flex: 1;\n ";var v=document.createElement("div");v.style.cssText="\n font-size: 15px;\n font-weight: 500;\n ",v.innerHTML="Click the <strong>lock icon đ</strong>, <strong>information icon âšī¸</strong>, or <strong>settings icon âŽ</strong> in the address bar to enable microphone";var f=document.createElement("button");if(f.style.cssText="\n background: rgba(255, 255, 255, 0.2);\n border: none;\n color: white;\n width: 28px;\n height: 28px;\n border-radius: 50%;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 14px;\n transition: background 0.2s;\n flex-shrink: 0;\n ",f.textContent="â",f.addEventListener("click",()=>{u.remove()}),f.addEventListener("mouseenter",()=>{f.style.background="rgba(255, 255, 255, 0.3)"}),f.addEventListener("mouseleave",()=>{f.style.background="rgba(255, 255, 255, 0.2)"}),!document.getElementById("mic-address-bar-hint-styles")){var y=document.createElement("style");y.id="mic-address-bar-hint-styles",y.textContent="\n @keyframes mic-slideDown {\n from {\n opacity: 0;\n transform: translateY(-100%);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n \n @keyframes mic-pointUp {\n 0%, 100% {\n transform: translate(0, 0);\n }\n 50% {\n transform: translate(-5px, -5px);\n }\n }\n ",document.head.appendChild(y)}m.appendChild(v),h.appendChild(p),h.appendChild(m),h.appendChild(f),u.appendChild(h),document.body.appendChild(u),setTimeout(()=>{u.parentNode&&(u.style.opacity="0",u.style.transition="opacity 0.3s ease-out",setTimeout(()=>{u.parentNode&&u.remove()},300))},1e4)}()});var p=l.querySelector(".mic-permission-modal__alt-toggle");if(p&&c.altSteps){var g=p.nextElementSibling;g&&(g.style.display="none",p.addEventListener("click",()=>{"none"===g.style.display?(g.style.display="block",p.innerHTML="âŧ ".concat(c.altTitle||"Alternative method")):(g.style.display="none",p.innerHTML="âļ ".concat(c.altTitle||"Alternative method"))}))}return a.addEventListener("click",t=>{t.target===a&&(r.close(),e())}),r.show(),r}function Te(e){var t=new Ce,n=t.createOverlay(),o=document.createElement("div");return o.className="mic-permission-modal",o.innerHTML='\n <div class="mic-permission-modal__icon">đ¤â</div>\n <h2 class="mic-permission-modal__title">No Microphone Found</h2>\n <p class="mic-permission-modal__description">\n We couldn\'t detect a microphone on your device. Please make sure:\n </p>\n <ul style="list-style: none; padding: 0; margin: 0 0 24px;">\n <li style="padding: 10px 0 10px 32px; position: relative; color: #111827; border-bottom: 1px solid #e5e7eb;">\n <span style="position: absolute; left: 0; font-size: 18px;">â</span>\n Your microphone is properly connected\n </li>\n <li style="padding: 10px 0 10px 32px; position: relative; color: #111827; border-bottom: 1px solid #e5e7eb;">\n <span style="position: absolute; left: 0; font-size: 18px;">â</span>\n Your microphone is not muted at the hardware level\n </li>\n <li style="padding: 10px 0 10px 32px; position: relative; color: #111827;">\n <span style="position: absolute; left: 0; font-size: 18px;">â</span>\n No other app is exclusively using the microphone\n </li>\n </ul>\n <div class="mic-permission-modal__actions">\n <button class="mic-permission-modal__btn mic-permission-modal__btn--primary" data-action="retry">\n Retry\n </button>\n <button class="mic-permission-modal__btn mic-permission-modal__btn--secondary" data-action="close">\n Close\n </button>\n </div>\n ',n.appendChild(o),t.overlay=n,t.modal=o,o.querySelector('[data-action="retry"]').addEventListener("click",()=>{window.location.reload()}),o.querySelector('[data-action="close"]').addEventListener("click",()=>{t.close(),e()}),n.addEventListener("click",o=>{o.target===n&&(t.close(),e())}),t.show(),t}function Ee(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function Ie(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){Ee(r,o,i,a,s,"next",e)}function s(e){Ee(r,o,i,a,s,"throw",e)}a(void 0)})}}class Ae{constructor(e){this.config=e,this.audioStream=null,this.callStartTime=null,this.callTimerInterval=null,this.sdk=null,this.isActive=!1,this.shadowRoot=e.shadowRoot||document,this.sdk=new ve({agentId:e.agentId,appId:e.appId,signedUrl:e.signedUrl,agentSettingsOverride:e.agentSettingsOverride,variables:e.variables||{},language:e.language||"en",outputContainer:e.outputContainer,outputEncoding:e.outputEncoding,outputSampleRate:e.outputSampleRate,outputChannels:e.outputChannels,outputBitDepth:e.outputBitDepth,onConversationStart:e.onConversationStart,onConversationEnd:e.onConversationEnd,onBargeIn:e.onBargeIn,onAudioStartPlaying:e.onAudioStartPlaying,onAudioStoppedPlaying:e.onAudioStoppedPlaying,onSubtitleDisplay:e.onSubtitleDisplay}),this.setupSDKEventHandlers(),this.checkAndHandleResume()}checkAndHandleResume(){var e=this.sdk.checkResumeBeforeConnect();return e?(console.log("đ [WIDGET] Auto-resuming call:",e),console.log(" From:",e.fromPage,"â To:",e.toPage),this._resumeInfo=e,this.config.onResume&&this.config.onResume(e),e):null}setupSDKEventHandlers(){this.sdk.onTranscript=e=>{console.log("đ [VOICE INTERFACE] onTranscript called with text:",e),this.updateTranscript(e)},this.sdk.onAgentSpeaking=e=>{var t=this.shadowRoot.getElementById("voiceAvatarActive");t&&(e?t.classList.add("speaking"):t.classList.remove("speaking"))},this.sdk.onDisconnected=()=>{console.log("đ WebSocket disconnected, hanging up call..."),this.isActive&&(this.isActive=!1,this.endVoiceCall())},this.sdk.onError=e=>{console.error("â Voice SDK Error:",e),e&&("DOMAIN_NOT_WHITELISTED"===e.message||e.message&&e.message.includes("Domain not whitelisted"))?this.showDomainError():this.showError(e.message||e)}}t(e){var t,n,o=this.config.language||"en";return((null===(t=this.config.translations)||void 0===t?void 0:t[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[e]||e}getText(e,t){return void 0!==this.config[e]&&null!==this.config[e]?this.config[e]:this.t(t)}getTooltip(e){var t,n=null===(t=this.config.tooltips)||void 0===t?void 0:t[e];return null!=n?n:{mute:this.t("mute"),speaker:this.t("speaker"),endCall:this.t("endCall")}[e]||""}generateHTML(){return'<div class="voice-interface" id="voiceInterface">\n \x3c!-- Before Call State --\x3e\n <div id="voiceIdleState">\n <div class="voice-avatar" id="voiceAvatar">đ¤</div>\n <div class="voice-status">\n <div class="voice-status-title">'.concat(this.getText("startCallTitle","clickToStartCall"),'</div>\n <div class="voice-status-subtitle">').concat(this.getText("startCallSubtitle","realTimeVoice"),'</div>\n </div>\n <button class="start-call-btn" id="startCallBtn">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="currentColor">\n <path d="M20.01 15.38c-1.23 0-2.42-.2-3.53-.56-.35-.12-.74-.03-1.01.24l-1.57 1.97c-2.83-1.35-5.48-3.9-6.89-6.83l1.95-1.66c.27-.28.35-.67.24-1.02-.37-1.11-.56-2.3-.56-3.53 0-.54-.45-.99-.99-.99H4.19C3.65 3 3 3.24 3 3.99 3 13.28 10.73 21 20.01 21c.71 0 .99-.63.99-1.18v-3.45c0-.54-.45-.99-.99-.99z"/>\n </svg>\n <span>').concat(this.getText("startCallButtonText","startCall"),'</span>\n </button>\n </div>\n \x3c!-- During Call State --\x3e\n <div id="voiceActiveState" style="display: none;">\n <div class="voice-avatar-active" id="voiceAvatarActive">\n <div class="voice-rings">\n <div class="voice-ring"></div>\n <div class="voice-ring"></div>\n <div class="voice-ring"></div>\n </div>\n đ¤\n </div>\n <div class="voice-status">\n <div class="voice-status-title" id="voiceStatusTitleActive">').concat(this.t("listening"),'</div>\n <div class="voice-status-subtitle" id="voiceStatusSubtitleActive">').concat(this.t("speakFreely"),'</div>\n </div>\n <div class="voice-transcript">\n <div class="transcript-label">').concat(this.t("liveTranscript"),'</div>\n <div class="transcript-text empty" id="transcriptText">\n ').concat(this.t("transcriptWillAppear"),'\n </div>\n </div>\n <div class="voice-controls">\n <button class="voice-control-btn secondary" id="muteBtn" title="').concat(this.getTooltip("mute"),'">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="mute-icon">\n <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>\n <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>\n <line x1="12" y1="19" x2="12" y2="23"/>\n <line x1="8" y1="23" x2="16" y2="23"/>\n <line x1="2" y1="2" x2="22" y2="22" class="mute-cross" style="display: none; stroke: #ef4444; stroke-width: 3.5;"/>\n </svg>\n </button>\n <button class="voice-control-btn primary active" id="endCallBtn" title="').concat(this.getTooltip("endCall"),'">\n <svg width="56" height="56" viewBox="0 0 24 24" fill="#ef4444">\n <rect x="6" y="6" width="12" height="12" rx="2"/>\n </svg>\n <div class="voice-timer" id="voiceTimer">00:00</div>\n </button>\n <button class="voice-control-btn secondary" id="speakerBtn" title="').concat(this.getTooltip("speaker"),'">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">\n <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>\n <path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>\n <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>\n </svg>\n </button>\n </div>\n </div>\n </div>')}generateCSS(){var e=this.config.avatarBackgroundColor||"#667eea",t=this.config.avatarActiveBackgroundColor||this.config.avatarBackgroundColor||"#667eea",n=this.config.statusTitleColor||"#1e293b",o=this.config.statusSubtitleColor||"#64748b",i=this.config.startCallButtonColor||"#667eea",r=this.config.startCallButtonTextColor||"#FFFFFF",a=this.config.transcriptBackgroundColor||"#FFFFFF",s=this.config.transcriptTextColor||"#1e293b",c=this.config.transcriptLabelColor||"#94a3b8",l=this.config.controlButtonColor||"#FFFFFF",d=this.config.controlButtonSecondaryColor||"#64748b",u=(this.config.endCallButtonColor,!1===this.config.useShadowDOM?" !important":"");return"\n /* Voice Interface Styles - Ultra-compact for Wix iframes */\n .voice-interface { \n display: none".concat(u,"; \n flex: 1; \n flex-direction: column;\n align-items: center; \n justify-content: center; \n padding: 6px 10px 6px 10px; \n background: linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%);\n overflow: hidden;\n min-height: 0;\n height: 100%;\n width: 100%;\n box-sizing: border-box;\n }\n .voice-interface.active { display: flex").concat(u,'; }\n \n /* Voice States - Better scaling gaps */\n #voiceIdleState,\n #voiceActiveState {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n height: 100%;\n min-height: 0;\n justify-content: center;\n overflow: hidden;\n flex: 1;\n box-sizing: border-box;\n gap: clamp(6px, 1.5vh, 12px);\n }\n \n #voiceActiveState[style*="display: none"] {\n display: none !important;\n }\n \n /* Voice Avatar - Scales better from small to large */\n .voice-avatar,\n .voice-avatar-active {\n width: clamp(80px, 18vh, 160px);\n height: clamp(80px, 18vh, 160px);\n aspect-ratio: 1;\n border-radius: 50%;\n background: linear-gradient(135deg, ').concat(e," 0%, ").concat(t," 100%);\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: clamp(40px, 9vh, 80px);\n margin: 0;\n box-shadow: 0 8px 30px rgba(102, 126, 234, 0.3);\n transition: all 0.3s ease;\n flex-shrink: 1;\n position: relative;\n }\n \n .voice-avatar-active {\n animation: avatarPulse 2s ease-in-out infinite;\n }\n \n @keyframes avatarPulse {\n 0%, 100% { \n transform: scale(1);\n }\n 50% { \n transform: scale(1.05);\n }\n }\n \n .voice-avatar-active.speaking {\n animation: avatarSpeak 0.5s ease-in-out infinite;\n }\n \n @keyframes avatarSpeak {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.08); }\n }\n \n /* Voice Rings Animation */\n .voice-rings {\n position: absolute;\n width: 100%;\n height: 100%;\n border-radius: 50%;\n }\n \n .voice-ring {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n border: 2px solid rgba(102, 126, 234, 0.3);\n border-radius: 50%;\n opacity: 0;\n animation: ringExpand 2s ease-out infinite;\n }\n \n .voice-ring:nth-child(2) { animation-delay: 0.5s; }\n .voice-ring:nth-child(3) { animation-delay: 1s; }\n \n @keyframes ringExpand {\n 0% {\n width: 100%;\n height: 100%;\n opacity: 0.6;\n }\n 100% {\n width: 160%;\n height: 160%;\n opacity: 0;\n }\n }\n \n /* Voice Status - Scales with container */\n .voice-status {\n text-align: center;\n margin: 0;\n flex-shrink: 1;\n min-height: 0;\n }\n \n .voice-status-title {\n font-size: clamp(12px, 3vh, 20px);\n font-weight: 600;\n color: ").concat(n,";\n margin-bottom: clamp(2px, 0.5vh, 4px);\n line-height: 1.2;\n }\n \n .voice-status-subtitle {\n font-size: clamp(10px, 2vh, 14px);\n color: ").concat(o,";\n line-height: 1.2;\n }\n \n /* Start Call Button - Scales with container */\n .start-call-btn {\n margin: 0;\n width: min(280px, 70vw);\n height: clamp(48px, 8vh, 64px);\n border-radius: clamp(24px, 4vh, 32px);\n border: none;\n background: ").concat(i,";\n color: ").concat(r,";\n font-size: clamp(14px, 2.5vh, 18px);\n font-weight: 600;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: clamp(8px, 1.5vh, 12px);\n box-shadow: 0 12px 30px rgba(102, 126, 234, 0.4);\n transition: all 0.3s ease;\n flex-shrink: 0;\n }\n \n .start-call-btn svg {\n width: clamp(22px, 4vh, 32px);\n height: clamp(22px, 4vh, 32px);\n }\n \n .start-call-btn:hover {\n transform: translateY(-2px);\n box-shadow: 0 12px 28px rgba(102, 126, 234, 0.5);\n }\n \n .start-call-btn:active {\n transform: translateY(-1px);\n }\n \n /* Voice Transcript - Scales with container */\n .voice-transcript {\n background: ").concat(a,";\n padding: clamp(6px, 1.5vh, 12px);\n border-radius: 10px;\n width: min(360px, calc(100% - 40px));\n margin: 0;\n min-height: clamp(100px, 18vh, 140px);\n max-height: clamp(120px, 22vh, 160px);\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n flex-shrink: 1;\n overflow-y: auto;\n overflow-x: hidden;\n display: flex;\n flex-direction: column;\n box-sizing: border-box;\n }\n \n .transcript-label {\n font-size: clamp(8px, 1.4vh, 11px);\n color: ").concat(c,";\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.3px;\n margin-bottom: clamp(3px, 0.6vh, 6px);\n flex-shrink: 0;\n word-wrap: break-word;\n }\n \n .transcript-text {\n font-size: clamp(11px, 2vh, 15px);\n color: ").concat(s,";\n line-height: 1.4;\n flex: 1;\n overflow-y: auto;\n overflow-x: hidden;\n word-wrap: break-word;\n overflow-wrap: break-word;\n }\n \n .transcript-text.empty {\n color: #cbd5e1;\n font-style: italic;\n }\n \n /* Voice Controls - Scales with container */\n .voice-controls {\n display: flex;\n gap: clamp(8px, 1.8vh, 14px);\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n margin: 0;\n padding-top: clamp(5px, 1.2vh, 10px);\n }\n \n .voice-control-btn {\n width: clamp(48px, 9vh, 72px);\n height: clamp(48px, 9vh, 72px);\n aspect-ratio: 1;\n border-radius: 50%;\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n position: relative;\n flex-shrink: 0;\n }\n \n .voice-control-btn svg {\n width: 48%;\n height: 48%;\n }\n \n .voice-control-btn.primary {\n width: clamp(54px, 10vh, 80px);\n height: clamp(54px, 10vh, 80px);\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n box-shadow: 0 6px 18px rgba(102, 126, 234, 0.4);\n }\n \n .voice-control-btn.primary:hover {\n transform: scale(1.05);\n }\n \n .voice-control-btn.primary.active {\n background: white;\n animation: recordingPulse 1.5s ease-in-out infinite;\n }\n \n @keyframes recordingPulse {\n 0%, 100% { \n box-shadow: 0 6px 16px rgba(239, 68, 68, 0.4);\n }\n 50% { \n box-shadow: 0 6px 24px rgba(239, 68, 68, 0.7);\n }\n }\n \n .voice-control-btn.secondary {\n background: ").concat(l,";\n color: ").concat(d,";\n box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);\n }\n \n .voice-control-btn.secondary:hover {\n background: #f8fafc;\n transform: scale(1.05);\n }\n \n .voice-control-btn.secondary.muted {\n background: #f3f4f6;\n }\n \n .voice-control-btn.secondary.muted .mute-icon {\n stroke: #9ca3af !important;\n }\n \n .voice-timer {\n position: absolute;\n bottom: clamp(-18px, -3vh, -24px);\n font-size: clamp(9px, 1.6vh, 12px);\n color: #64748b;\n font-weight: 500;\n white-space: nowrap;\n }\n \n /* Mobile optimization */\n @media (max-width: 768px) {\n .voice-interface {\n padding: 6px 10px;\n }\n }\n \n @media (max-width: 480px) {\n .voice-interface {\n padding: 5px 8px;\n }\n }\n ")}setupEventHandlers(e){var t=this,n=this.shadowRoot.getElementById("startCallBtn"),o=this.shadowRoot.getElementById("endCallBtn"),i=this.shadowRoot.getElementById("muteBtn"),r=this.shadowRoot.getElementById("speakerBtn");n&&(n.onclick=()=>this.startVoiceCall()),o&&(o.onclick=()=>this.endVoiceCall()),i&&(i.onclick=()=>this.toggleMute()),r&&(r.onclick=()=>this.toggleSpeaker());var a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=t.shadowRoot.getElementById("voiceInterface");n&&n.classList.contains("active")&&n.clientHeight>100?(console.log("â
Interface is active and has proper dimensions, adjusting sizes (attempt",e+1,")"),t.adjustSizesForContainer(),0===e&&setTimeout(()=>t.adjustSizesForContainer(),500)):e<15?(console.log("âŗ Interface not ready yet (height:",null==n?void 0:n.clientHeight,"), retrying... (attempt",e+1,")"),setTimeout(()=>a(e+1),250)):(console.warn("â ī¸ Interface never became fully ready, adjusting sizes anyway"),t.adjustSizesForContainer())};setTimeout(()=>a(),200),window.addEventListener("resize",()=>{console.log("đ Window resized, re-adjusting sizes"),this.adjustSizesForContainer()})}getSignedUrl(){var e=this;return Ie(function*(){if(e.config.signedUrl)return e.config.signedUrl;if(!e.config.agentId)throw new Error("agentId is required when signedUrl is not provided");var t=e.config.websocketUrl||"wss://speech.talktopc.com/ws/conv",n=new URLSearchParams;return n.append("agentId",e.config.agentId),e.config.appId&&n.append("appId",e.config.appId),!1!==e.config.demo&&n.append("demo","true"),"".concat(t,"?").concat(n.toString())})()}adjustSizesForContainer(){var e=this.shadowRoot.getElementById("voiceInterface");if(e){var t=e.clientHeight,n=e.clientWidth;console.log("đ Container size:",t,"x",n);var o,i,r,a,s,c,l,d,u,h=this.shadowRoot.getElementById("voiceIdleState"),p=this.shadowRoot.getElementById("voiceActiveState"),g=h&&"none"!==h.style.display,m=p&&"none"!==p.style.display;console.log("đī¸ Visible state - Idle:",g,"Active:",m),t<=350?(u=5,o=70,i=35,r=11,a=9,s=32,c=100,l=42,d=48):t<=450?(u=7,o=110,i=55,r=15,a=11,s=38,c=110,l=52,d=58):t<=550?(u=8,o=140,i=70,r=16,a=12,s=42,c=120,l=56,d=64):t<=700?(u=10,o=130,i=65,r=18,a=13,s=46,c=130,l=60,d=70):(u=12,o=150,i=75,r=20,a=14,s=50,c=140,l=66,d=76),this.shadowRoot.querySelectorAll("#voiceIdleState, #voiceActiveState").forEach(e=>{e.style.gap="".concat(u,"px")});var v=this.shadowRoot.querySelectorAll(".voice-avatar, .voice-avatar-active");console.log("đ¤ Found",v.length,"avatars, setting size to",o,"px"),v.forEach(e=>{e.style.width="".concat(o,"px"),e.style.height="".concat(o,"px"),e.style.fontSize="".concat(i,"px")}),this.shadowRoot.querySelectorAll(".voice-status-title").forEach(e=>e.style.fontSize="".concat(r,"px")),this.shadowRoot.querySelectorAll(".voice-status-subtitle").forEach(e=>e.style.fontSize="".concat(a,"px"));var f=this.shadowRoot.querySelector(".voice-transcript");f&&(f.style.minHeight="".concat(c,"px"),f.style.maxHeight="".concat(c,"px"),f.style.height="".concat(c,"px"),f.style.width="min(360px, ".concat(n-40,"px)"),f.style.boxSizing="border-box");var y=this.shadowRoot.querySelector(".transcript-label");y&&(y.style.fontSize="".concat(Math.max(8,r-4),"px"));var x=this.shadowRoot.querySelector(".transcript-text");x&&(x.style.fontSize="".concat(Math.max(10,r-2),"px")),this.shadowRoot.querySelectorAll(".voice-control-btn.secondary").forEach(e=>{e.style.width="".concat(l,"px"),e.style.height="".concat(l,"px");var t=e.querySelector("svg");if(t){var n=.65*l;t.style.setProperty("width","".concat(n,"px"),"important"),t.style.setProperty("height","".concat(n,"px"),"important"),t.style.setProperty("min-width","".concat(n,"px"),"important"),t.style.setProperty("min-height","".concat(n,"px"),"important")}});var b=this.shadowRoot.querySelector(".voice-control-btn.primary");if(b){b.style.width="".concat(d,"px"),b.style.height="".concat(d,"px");var w=b.querySelector("svg");if(w){var S=.7*d;w.style.setProperty("width","".concat(S,"px"),"important"),w.style.setProperty("height","".concat(S,"px"),"important"),w.style.setProperty("min-width","".concat(S,"px"),"important"),w.style.setProperty("min-height","".concat(S,"px"),"important")}}var C=this.shadowRoot.querySelector(".start-call-btn");if(C){var k,P;t<=350?(k=48,P=14):t<=450?(k=52,P=15):t<=550?(k=58,P=17):t<=700?(k=62,P=18):(k=64,P=18),C.style.height="".concat(k,"px"),C.style.fontSize="".concat(P,"px");var T=C.querySelector("svg");if(T){var E=Math.max(22,.5*k);T.style.width="".concat(E,"px"),T.style.height="".concat(E,"px")}}console.log("â
Sizes adjusted - Avatar:",o,"Status:",s,"Transcript:",c,"Buttons:",l)}else console.warn("â ī¸ voiceInterface not found, skipping size adjustment")}startVoiceCall(){var e=this;return Ie(function*(){if(e.isActive)console.log("â ī¸ Voice call already active");else{console.log("đ¤ Starting voice call...");var t=yield xe();if(console.log("đ Current permission state: ".concat(t)),"denied"!==t){if("prompt"===t||"unknown"===t)return console.log("đ Permission is in prompt state, showing pre-prompt modal..."),new Promise(t=>{ke(Ie(function*(){console.log("â
Pre-prompt accepted, proceeding with voice call..."),yield e.proceedWithVoiceCall(),t()}),()=>{console.log("â Pre-prompt cancelled"),t()})});yield e.proceedWithVoiceCall()}else console.log("đĢ Permission is denied, showing blocked modal..."),ye(),Pe(()=>{console.log("Blocked modal closed")})}})()}proceedWithVoiceCall(){var e=this;return Ie(function*(){try{var t=e.shadowRoot.getElementById("voiceIdleState"),n=e.shadowRoot.getElementById("voiceActiveState"),o=e.shadowRoot.getElementById("voiceInterface");t&&(t.style.display="none"),n&&(n.style.display="flex"),setTimeout(()=>e.adjustSizesForContainer(),50),o&&(o.scrollTop=0);var i=ye(),r=yield xe();if(i.isMobile&&"granted"!==r){console.log("đą Mobile device detected - requesting mic permission before connecting..."),console.log("đ Current permission state: ".concat(r));try{var a=e.config.outputSampleRate||44100;(yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:a,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})).getTracks().forEach(e=>e.stop()),console.log("â
Microphone permission granted on mobile - proceeding with connection")}catch(t){return console.log("đĢ Permission denied on mobile, showing blocked modal..."),void Pe(()=>{e.resetUIState()})}}var s=yield e.getSignedUrl();if(console.log("đ Got signed URL:",s),e.sdk&&e.sdk.isConnected){console.log("đ SDK already connected, disconnecting for clean retry...");try{e.sdk.disconnect(),yield new Promise(e=>setTimeout(e,100))}catch(e){console.warn("Warning: Error disconnecting existing connection:",e)}}var c=yield e.sdk.connect(s);console.log("â
Connected to WebSocket, connected:",c);for(var l=0;l<50&&!(e.sdk.isConnected&&e.sdk.voiceSDK&&e.sdk.voiceSDK.isConnected&&e.sdk.voiceSDK.websocket&&e.sdk.voiceSDK.websocket.readyState===WebSocket.OPEN);)yield new Promise(e=>setTimeout(e,100)),l++;e.sdk.isConnected&&e.sdk.voiceSDK&&e.sdk.voiceSDK.websocket&&e.sdk.voiceSDK.websocket.readyState===WebSocket.OPEN?(console.log("â
WebSocket ready, starting listening..."),yield e.sdk.startListening(),console.log("đ¤ Started listening"),e.isActive=!0,e.callStartTime=Date.now(),e.callTimerInterval=setInterval(()=>{var t=Date.now()-e.callStartTime,n=Math.floor(t/6e4),o=Math.floor(t%6e4/1e3),i=e.shadowRoot.getElementById("voiceTimer");i&&(i.textContent="".concat(n.toString().padStart(2,"0"),":").concat(o.toString().padStart(2,"0")))},1e3)):(console.warn("â ī¸ Connection not fully ready, but trying to start listening anyway..."),yield e.sdk.startListening(),console.log("đ¤ Started listening"),e.isActive=!0,e.callStartTime=Date.now(),e.callTimerInterval=setInterval(()=>{var t=Date.now()-e.callStartTime,n=Math.floor(t/6e4),o=Math.floor(t%6e4/1e3),i=e.shadowRoot.getElementById("voiceTimer");i&&(i.textContent="".concat(n.toString().padStart(2,"0"),":").concat(o.toString().padStart(2,"0")))},1e3)),console.log("â
Voice call started successfully")}catch(t){if(console.error("â Error starting voice call:",t),e.isActive=!1,e.callTimerInterval&&(clearInterval(e.callTimerInterval),e.callTimerInterval=null),e.sdk&&e.sdk.isConnected)try{e.sdk.disconnect()}catch(e){console.warn("Error disconnecting SDK on error:",e)}"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?(ye(),Pe(()=>{e.resetUIState()})):"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?Te(()=>{e.resetUIState()}):(e.showError(t.message||t),e.resetUIState())}})()}resetUIState(){var e=this.shadowRoot.getElementById("voiceIdleState"),t=this.shadowRoot.getElementById("voiceActiveState");e&&(e.style.display="flex"),t&&(t.style.display="none")}endVoiceCall(){console.log("đ´ Ending voice call..."),this.sdk&&this.isActive&&(this.sdk.stopListening(),this.sdk.hangup(),this.isActive=!1),this.audioStream&&(this.audioStream.getTracks().forEach(e=>e.stop()),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null);var e=this.shadowRoot.getElementById("voiceIdleState"),t=this.shadowRoot.getElementById("voiceActiveState");e&&(e.style.display="flex"),t&&(t.style.display="none"),setTimeout(()=>this.adjustSizesForContainer(),50);var n=this.shadowRoot.getElementById("transcriptText");n&&(n.textContent=this.t("transcriptWillAppear"),n.classList.add("empty"));var o=this.shadowRoot.getElementById("voiceAvatarActive");o&&o.classList.remove("speaking"),console.log("â
Voice call ended")}updateTranscript(e){console.log("đ [VOICE INTERFACE] updateTranscript called with text:",e);var t=this.shadowRoot.getElementById("transcriptText");t?(console.log("đ [VOICE INTERFACE] Found transcript element, updating text"),t.textContent=e,t.classList.remove("empty")):console.warn("đ [VOICE INTERFACE] â ī¸ transcriptText element not found!")}showError(e){var t=this.shadowRoot.getElementById("transcriptText");t&&(t.textContent="".concat(this.t("error"),": ").concat(e),t.classList.remove("empty"))}showDomainError(){var e=this.shadowRoot.getElementById("transcriptText");if(e){var t=this.t("domainNotValidated"),n=this.t("domainErrorMessage");e.innerHTML='<div style="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;">'.concat(t,'</div><div style="font-size: 14px; color: #991B1B; line-height: 1.5;">').concat(n,"</div>"),e.classList.remove("empty")}}toggleMute(){if(this.sdk&&this.isActive){var e=null;if(this.sdk.voiceSDK&&this.sdk.voiceSDK.audioRecorder&&this.sdk.voiceSDK.audioRecorder.mediaStream&&(e=this.sdk.voiceSDK.audioRecorder.mediaStream.getAudioTracks()[0]),!e&&this.audioStream&&(e=this.audioStream.getAudioTracks()[0]),e){e.enabled=!e.enabled;var t=this.shadowRoot.getElementById("muteBtn"),n=null==t?void 0:t.querySelector(".mute-icon"),o=null==t?void 0:t.querySelector(".mute-cross");t&&n&&o&&(e.enabled?(n.style.stroke="",o.style.display="none",t.classList.remove("muted")):(n.style.stroke="#9ca3af",o.style.display="block",t.classList.add("muted"))),console.log(e.enabled?"đ Unmuted":"đ Muted")}else console.warn("â ī¸ No audio track available for mute toggle")}}toggleSpeaker(){console.log("đ Speaker toggle")}destroy(){this.isActive&&this.endVoiceCall(),this.audioStream&&(this.audioStream.getTracks().forEach(e=>e.stop()),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null),this.sdk&&(this.sdk.disconnect(),this.sdk=null)}}function Re(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function De(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){Re(r,o,i,a,s,"next",e)}function s(e){Re(r,o,i,a,s,"throw",e)}a(void 0)})}}class Fe{constructor(e,t){this.config=e,this.sdk=t,this.streamingEl=null,this.hasStartedStreaming=!1,this.isActive=!1,this.shadowRoot=e.shadowRoot||document,this.eventHandlers={autoResize:null,keydown:null},this.eventHandlersSetup=!1}t(e){var t,n,o=this.config.language||"en";return((null===(t=this.config.translations)||void 0===t?void 0:t[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[e]||e}generateHTML(){var e,t,n,o,i,r,a,s,c,l=this.config.inputPlaceholder||(null===(e=this.config.panel)||void 0===e?void 0:e.inputPlaceholder)||this.t("typeMessage")||"Type your message...";return'<div class="text-interface" id="textInterface">\n <div class="messages-container" id="messagesContainer">\n <div class="empty-state">\n <div class="empty-state-icon">đŦ</div>\n <div class="empty-state-title">'.concat(this.t("hello"),'</div>\n <div class="empty-state-text">').concat(this.t("sendMessage"),'</div>\n </div>\n </div>\n <div class="input-container">\n <div class="input-wrapper" style="flex:1;">\n <textarea class="message-input" id="messageInput" placeholder="').concat(l,'" rows="1" dir="').concat(this.config.direction||"ltr",'"></textarea>\n </div>\n <button class="send-button" id="sendButton" aria-label="').concat(this.t("sendMessageAria"),'">').concat(this.config.sendButtonText||"â¤","</button>\n ").concat(null!==(t=this.config.sendButtonHint)&&void 0!==t&&t.text||null!==(n=this.config.panel)&&void 0!==n&&null!==(n=n.sendButtonHint)&&void 0!==n&&n.text?'\n <div class="send-button-hint" style="color: '.concat((null===(o=this.config.sendButtonHint)||void 0===o?void 0:o.color)||(null===(i=this.config.panel)||void 0===i||null===(i=i.sendButtonHint)||void 0===i?void 0:i.color)||"#6B7280","; font-size: ").concat((null===(r=this.config.sendButtonHint)||void 0===r?void 0:r.fontSize)||(null===(a=this.config.panel)||void 0===a||null===(a=a.sendButtonHint)||void 0===a?void 0:a.fontSize)||"12px",'; text-align: center; margin-top: 4px;">\n ').concat((null===(s=this.config.sendButtonHint)||void 0===s?void 0:s.text)||(null===(c=this.config.panel)||void 0===c||null===(c=c.sendButtonHint)||void 0===c?void 0:c.text),"\n </div>\n "):"","\n </div>\n </div>")}generateCSS(){var e,t,n,o,i,r,a,s,c,l,d,u,h,p=this.config.messages,g=(this.config.panel,this.config.animation,this.config.sendButtonColor||(null===(e=this.config.panel)||void 0===e?void 0:e.sendButtonColor)||"#7C3AED"),m=this.config.sendButtonHoverColor||(null===(t=this.config.panel)||void 0===t?void 0:t.sendButtonHoverColor)||"#6D28D9",v=this.config.sendButtonTextColor||(null===(n=this.config.panel)||void 0===n?void 0:n.sendButtonTextColor)||"#FFFFFF",f=(this.config.inputPlaceholder||null===(o=this.config.panel)||void 0===o||o.inputPlaceholder,this.config.inputBorderColor||(null===(i=this.config.panel)||void 0===i?void 0:i.inputBorderColor)||"#E5E7EB"),y=this.config.inputFocusColor||(null===(r=this.config.panel)||void 0===r?void 0:r.inputFocusColor)||"#7C3AED",x=this.config.inputBackgroundColor||(null===(a=this.config.panel)||void 0===a?void 0:a.inputBackgroundColor)||"#FFFFFF",b=this.config.inputTextColor||(null===(s=this.config.panel)||void 0===s?void 0:s.inputTextColor)||"#1F2937",w=this.config.inputFontSize||(null===(c=this.config.panel)||void 0===c?void 0:c.inputFontSize)||"14px",S=this.config.inputBorderRadius||(null===(l=this.config.panel)||void 0===l?void 0:l.inputBorderRadius)||20,C=this.config.inputPadding||(null===(d=this.config.panel)||void 0===d?void 0:d.inputPadding)||"6px 14px",k=!1===this.config.useShadowDOM?" !important":"";return"\n /* Messages container using new classes */\n #messagesContainer { \n flex: 1; \n overflow-y: auto; \n overflow-x: hidden; \n padding: 20px; \n background: #f8fafc; \n display: flex; \n flex-direction: column; \n gap: 16px; \n min-height: 0; \n }\n .empty-state { \n flex: 1; \n display: flex; \n flex-direction: column; \n align-items: center; \n justify-content: center; \n gap: 12px; \n color: #64748b; \n text-align: center; \n padding: 20px; \n }\n .empty-state-icon { font-size: 48px; opacity: 0.3; }\n .empty-state-title { font-size: 20px; font-weight: 700; color: #334155; }\n .empty-state-text { font-size: 13px; max-width: 280px; }\n\n .text-interface { \n display: none".concat(k,"; \n flex: 1; \n flex-direction: column; \n min-height: 0; \n overflow: hidden; \n }\n .text-interface.active { display: flex").concat(k,"; }\n \n .message { \n display: flex; \n gap: 8px; \n padding: 4px 0; \n max-width: 100%; \n align-items: center; \n }\n .message.edge-left { flex-direction: row; }\n .message.edge-right { flex-direction: row-reverse; }\n .message-bubble { \n padding: 12px; \n border-radius: ").concat(p.borderRadius,"px; \n max-width: 80%; \n font-size: ").concat(p.fontSize,"; \n color: ").concat(p.textColor,"; \n word-wrap: break-word; \n text-align: ").concat("rtl"===this.config.direction?"right":"left","; \n direction: ").concat(this.config.direction||"ltr",";\n }\n .message.user { \n background: ").concat(p.userBackgroundColor,"; \n align-self: ").concat("rtl"===this.config.direction?"flex-start":"flex-end","; \n }\n .message.agent { \n background: ").concat(p.agentBackgroundColor,"; \n align-self: ").concat("rtl"===this.config.direction?"flex-end":"flex-start","; \n }\n .message .message-bubble { \n text-align: ").concat("rtl"===this.config.direction?"right":"left"," !important; \n }\n ").concat("rtl"===this.config.direction?"\n .message-bubble {\n text-align: right !important;\n }\n ":"","\n .message-avatar { \n width: 20px; \n height: 20px; \n display: flex; \n align-items: center; \n justify-content: center; \n flex-shrink: 0; \n color: inherit; \n font-size: 18px; \n line-height: 1; \n background: transparent; \n border: none; \n }\n .message-avatar.user { background: transparent; }\n .message-avatar.agent { background: transparent; }\n \n .message.system {\n background: ").concat(p.systemBackgroundColor,";\n align-self: flex-start;\n }\n .message.error {\n background: ").concat(p.errorBackgroundColor,";\n align-self: flex-start;\n }\n \n .input-container {\n display: flex;\n gap: 8px;\n padding: 12px 16px;\n background: #FFFFFF;\n border-top: 1px solid #E5E7EB;\n align-items: center;\n flex-shrink: 0;\n flex-direction: ").concat("rtl"===this.config.direction?"row-reverse":"row",";\n }\n \n .input-wrapper {\n position: relative;\n display: flex;\n align-items: center;\n }\n \n .message-input {\n width: 100%;\n min-height: 32px;\n max-height: 120px;\n padding: ").concat(C,";\n border: 1px solid ").concat(f,";\n border-radius: ").concat(S,"px;\n font-size: ").concat(w,";\n font-family: inherit;\n line-height: 1.3;\n resize: none;\n overflow-y: auto;\n background: ").concat(x,";\n color: ").concat(b,";\n vertical-align: top;\n margin: 0;\n display: block;\n white-space: pre-wrap;\n word-wrap: break-word;\n text-align: ").concat("rtl"===this.config.direction?"right":"left",";\n direction: ").concat(this.config.direction||"ltr",";\n -webkit-appearance: none;\n appearance: none;\n box-sizing: border-box;\n }\n \n .message-input:focus {\n outline: none;\n border-color: ").concat(y,";\n background: ").concat("#FFFFFF"===x?"#FFFFFF":x,";\n box-shadow: 0 0 0 3px ").concat(y,"33;\n }\n \n .message-input::placeholder {\n color: #9CA3AF;\n text-align: ").concat("rtl"===this.config.direction?"right":"left",";\n }\n \n .send-button {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n border: none;\n background: ").concat(g,";\n color: ").concat(v,";\n font-size: ").concat(this.config.sendButtonFontSize||(null===(u=this.config.panel)||void 0===u?void 0:u.sendButtonFontSize)||"18px",";\n font-weight: ").concat(this.config.sendButtonFontWeight||(null===(h=this.config.panel)||void 0===h?void 0:h.sendButtonFontWeight)||"500",";\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n transition: all 0.2s ease;\n box-shadow: 0 4px 12px rgba(124, 60, 237, 0.3);\n }\n \n .send-button:hover:not(:disabled) {\n background: ").concat(m,";\n transform: scale(1.05);\n box-shadow: 0 6px 16px rgba(124, 60, 237, 0.4);\n }\n \n .send-button-hint {\n width: 100%;\n text-align: center;\n margin-top: 4px;\n }\n \n .send-button:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n \n .typing-indicator {\n display: inline-flex;\n gap: 4px;\n align-items: center;\n }\n \n .typing-dot {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: #64748b;\n animation: typingDot 1.4s ease-in-out infinite;\n }\n \n .typing-dot:nth-child(2) { animation-delay: 0.2s; }\n .typing-dot:nth-child(3) { animation-delay: 0.4s; }\n \n @keyframes typingDot {\n 0%, 60%, 100% { transform: translateY(0); opacity: 0.7; }\n 30% { transform: translateY(-8px); opacity: 1; }\n }\n \n .error-message {\n padding: 12px;\n background: ").concat(p.errorBackgroundColor,";\n border-radius: ").concat(p.borderRadius,"px;\n color: #991B1B;\n font-size: ").concat(p.fontSize,";\n margin: 8px 0;\n }\n \n @media (max-width: 768px) {\n #messagesContainer {\n padding: 12px;\n gap: 12px;\n }\n \n .message-bubble {\n max-width: 85%;\n font-size: 14px;\n padding: 10px;\n }\n \n .text-input-container {\n padding: 10px;\n gap: 8px;\n }\n \n #text-chat-input {\n font-size: 16px !important; /* Prevents iOS zoom on focus */\n padding: 10px 14px;\n min-height: 44px;\n }\n \n #text-chat-send {\n min-width: 56px;\n min-height: 44px;\n width: 56px;\n height: 44px;\n }\n \n .empty-state-icon {\n font-size: 40px;\n }\n \n .empty-state-title {\n font-size: 18px;\n }\n \n .empty-state-text {\n font-size: 12px;\n }\n }\n \n @media (max-width: 480px) {\n #messagesContainer {\n padding: 10px;\n gap: 10px;\n }\n \n .message-bubble {\n max-width: 90%;\n font-size: 13px;\n padding: 8px;\n }\n \n .text-input-container {\n padding: 8px;\n }\n \n #text-chat-input {\n font-size: 16px !important;\n padding: 8px 12px;\n }\n }\n ")}setupEventHandlers(){var e=this.shadowRoot.getElementById("sendButton"),t=this.shadowRoot.getElementById("messageInput"),n=this.shadowRoot.getElementById("newChatBtn");if(e&&(e.onclick=()=>this.sendMessage()),n&&(n.onclick=()=>this.startNewChat()),this.updateInputAttributes(),t){t.style.height="32px",t.style.overflow="hidden";var o=()=>{t.style.height="auto";var e=Math.min(t.scrollHeight,120);t.style.height=e+"px",t.style.overflowY=e>=120?"auto":"hidden",e>=120&&setTimeout(()=>{t.scrollTop=t.scrollHeight},0)};t.addEventListener("input",o),t.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey?"Enter"===e.key&&e.shiftKey&&setTimeout(o,0):(e.preventDefault(),this.sendMessage())})}}startNewChat(){try{localStorage.removeItem("ttp_text_chat_conversation_id")}catch(e){}this.sdk&&(this.sdk.config.conversationId=null);var e=this.shadowRoot.getElementById("messagesContainer");e&&(e.innerHTML='\n <div class="empty-state">\n <div class="empty-state-icon">đŦ</div>\n <div class="empty-state-title">'.concat(this.t("hello"),'</div>\n <div class="empty-state-text">').concat(this.t("sendMessage"),"</div>\n </div>"));var t=this.shadowRoot.getElementById("messageInput");t&&t.focus()}updateInputAttributes(){var e=this.shadowRoot.getElementById("messageInput");if(e){var t,n=this.config.inputPlaceholder||(null===(t=this.config.panel)||void 0===t?void 0:t.inputPlaceholder)||this.t("typeMessage")||"Type your message...";e.placeholder=n,e.dir=this.config.direction||"ltr",e.style.textAlign="rtl"===this.config.direction?"right":"left"}}show(){var e=this.shadowRoot.getElementById("textInterface");e&&e.classList.add("active"),setTimeout(()=>{var e=this.shadowRoot.getElementById("messageInput");e&&e.focus()},50)}hide(){var e=this.shadowRoot.getElementById("textInterface");e&&e.classList.remove("active")}startChat(){var e=this;return De(function*(){e.isActive=!0,e.updateSendButtonState()})()}sendMessage(){var e=this;return De(function*(){var t=e.shadowRoot.getElementById("messageInput"),n=t.value.trim();if(n){e.isActive||(yield e.startChat()),e.addMessage("user",n),t.value="",t.style.height="32px",t.style.overflow="hidden";try{e.beginStreaming(),yield e.sdk.sendMessage(n)}catch(t){console.error("â Failed to send message:",t),t&&("DOMAIN_NOT_WHITELISTED"===t.message||t.message&&t.message.includes("Domain not whitelisted"))||e.showError(t),e.stopStreamingState()}}})()}updateSendButtonState(){var e=this.shadowRoot.getElementById("sendButton");e&&(e.disabled=!this.isActive)}addMessage(e,t){var n=this.shadowRoot.getElementById("messagesContainer");if(n){var o=n.querySelector(".empty-state");o&&o.remove();var i=document.createElement("div"),r="rtl"===this.config.direction?"user"===e?"edge-left":"edge-right":"user"===e?"edge-right":"edge-left";i.className="message ".concat(e," ").concat(r);var a=document.createElement("div");a.className="message-avatar ".concat(e),a.textContent="user"===e?"đ¤":"đ¤";var s=document.createElement("div");s.className="message-bubble",s.textContent=t,i.appendChild(a),i.appendChild(s),n.appendChild(i),n.scrollTop=n.scrollHeight}}beginStreaming(){var e=this.shadowRoot.getElementById("messagesContainer");if(e){this.stopStreamingState();var t=document.createElement("div"),n="rtl"===this.config.direction?"edge-right":"edge-left";t.className="message agent ".concat(n),t.id="agent-streaming";var o=document.createElement("div");o.className="message-avatar agent",o.textContent="đ¤";var i=document.createElement("div");i.className="message-bubble",i.innerHTML='<span class="typing-indicator"><span class="typing-dot"></span><span class="typing-dot"></span><span class="typing-dot"></span></span>',t.appendChild(o),t.appendChild(i),e.appendChild(t),this.streamingEl=i,this.hasStartedStreaming=!1,e.scrollTop=e.scrollHeight}}appendStreamingChunk(e){if(this.streamingEl){this.hasStartedStreaming||(this.streamingEl.textContent="",this.hasStartedStreaming=!0),this.streamingEl.textContent+=e;var t=this.shadowRoot.getElementById("messagesContainer");t&&(t.scrollTop=t.scrollHeight)}}finalizeStreaming(e){if(this.streamingEl){this.streamingEl.textContent=e||this.streamingEl.textContent;var t=this.shadowRoot.getElementById("agent-streaming");t&&(t.id=""),this.streamingEl=null}this.updateSendButtonState()}stopStreamingState(){var e=this.shadowRoot.getElementById("agent-streaming");e&&e.remove(),this.streamingEl=null,this.hasStartedStreaming=!1}showError(e){var t=this.shadowRoot.getElementById("messagesContainer");if(t){if(e&&("DOMAIN_NOT_WHITELISTED"===e.message||"string"==typeof e&&e.includes("DOMAIN_NOT_WHITELISTED")||e.message&&e.message.includes("Domain not whitelisted")||"string"==typeof e&&e.includes("Domain not whitelisted"))){var n,o=document.createElement("div");o.className="error-message",o.style.cssText="padding: 16px; margin: 12px; border-radius: 8px; background: "+((null===(n=this.config.messages)||void 0===n?void 0:n.errorBackgroundColor)||"#FEE2E2")+";";var i=document.createElement("div");i.style.cssText="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;",i.textContent=this.t("domainNotValidated");var r=document.createElement("div");r.style.cssText="font-size: 14px; color: #991B1B; line-height: 1.5;",r.textContent=this.t("domainErrorMessage"),o.appendChild(i),o.appendChild(r),t.appendChild(o)}else{var a=document.createElement("div");a.className="error-message",a.textContent="string"==typeof e?e:(null==e?void 0:e.message)||e,t.appendChild(a)}t.scrollTop=t.scrollHeight}}setActive(e){this.isActive=e,this.updateSendButtonState()}}const Be={en:{landingTitle:"How would you like to communicate?",voiceCall:"Voice Call",textChat:"Text Chat",clickToStartCall:"Click to Start Call",realTimeVoice:"Real-time voice conversation",startCall:"Start Call",listening:"Listening...",speakFreely:"Speak freely",liveTranscript:"Live Transcript",transcriptWillAppear:"Transcript will appear here during the call...",mute:"Mute",speaker:"Speaker",endCall:"End Call",hello:"Hello! How can I help?",sendMessage:"Send a message to get started",online:"Online",newChat:"New Chat",back:"Back",close:"Close",error:"Error",typeMessage:"Type your message...",sendMessageAria:"Send message",domainNotValidated:"Domain not validated",domainErrorMessage:"This domain is not whitelisted. Please contact the administrator to whitelist your website URL."},he:{landingTitle:"××× ×Ēר×Ļ× ××Ēק׊ר?",voiceCall:"׊××× ×§××××Ē",textChat:"×Ļ'×× ×קץ×",clickToStartCall:"×××Ĩ ×××Ē×××Ē ×Š×××",realTimeVoice:"׊××× ×§××××Ē ×××× ×××Ē",startCall:"××Ē×× ×Š×××",listening:"×ק׊××...",speakFreely:"××ר ×××פ׊×××Ē",liveTranscript:"×Ē×××× ×××× ×××Ē",transcriptWillAppear:"××Ē×××× ××פ××ĸ ××× ××××× ×׊×××...",mute:"×׊×Ē×§",speaker:"ר××§××",endCall:"ץ××× ×Š×××",hello:"׊×××! ××× ×פ׊ר ××ĸ××ר?",sendMessage:"׊×× ××××ĸ× ×× ×ĸ××ר ×××Ļ× ×§××× ×׊××× ×××× ×××Ē",online:"××§×××",newChat:"×Ļ'×× ××׊",back:"×××ר",close:"ץ××ר",error:"׊××××",typeMessage:"××§×× ××××ĸ×...",sendMessageAria:"׊×× ××××ĸ×",domainNotValidated:"×××××× ×× ×××××Ē",domainErrorMessage:"×××××× ×× ×× ×ר׊×××Ē ×××ר׊××. ×× × ×¤× × ××× ×× ×××ĸר××Ē ××× ×××ץ××Ŗ ××Ē ××Ē×××Ē ×××Ēר ׊×× ×ר׊×××."},ar:{landingTitle:"ŲŲŲ ØĒØąŲØ¯ Ø§ŲØĒŲØ§ØĩŲØ",voiceCall:"Ų
ŲØ§ŲŲ
ØŠ ØĩŲØĒŲØŠ",textChat:"Ø¯ØąØ¯Ø´ØŠ ŲØĩŲØŠ",clickToStartCall:"اŲŲØą ŲØ¨Ø¯ØĄ اŲŲ
ŲØ§ŲŲ
ØŠ",realTimeVoice:"Ų
ØØ§Ø¯ØĢØŠ ØĩŲØĒŲØŠ ŲŲ Ø§ŲŲŲØĒ Ø§ŲŲØšŲŲ",startCall:"Ø§Ø¨Ø¯ØŖ اŲŲ
ŲØ§ŲŲ
ØŠ",listening:"Ø§ŲØ§ØŗØĒŲ
اؚ...",speakFreely:"ØĒŲŲŲ
Ø¨ØØąŲØŠ",liveTranscript:"ŲØĩ Ų
Ø¨Ø§Ø´Øą",transcriptWillAppear:"ØŗŲØ¸ŲØą اŲŲØĩ ŲŲØ§ ØŖØĢŲØ§ØĄ اŲŲ
ŲØ§ŲŲ
ØŠ...",mute:"ŲØĒŲ
Ø§ŲØĩŲØĒ",speaker:"Ų
ŲØ¨Øą Ø§ŲØĩŲØĒ",endCall:"ØĨŲŲØ§ØĄ اŲŲ
ŲØ§ŲŲ
ØŠ",hello:"Ų
ØąØØ¨Ø§! ŲŲŲ ŲŲ
ŲŲŲŲ Ø§ŲŲ
ØŗØ§ØšØ¯ØŠØ",sendMessage:"ØŖØąØŗŲ ØąØŗØ§ŲØŠ ŲŲØ¨Ø¯ØĄ",online:"Ų
ØĒØĩŲ",newChat:"Ų
ØØ§Ø¯ØĢØŠ ØŦØ¯ŲØ¯ØŠ",back:"ØąØŦŲØš",close:"ØĨØēŲØ§Ų",error:"ØŽØˇØŖ",typeMessage:"Ø§ŲØĒØ¨ ØąØŗØ§ŲØŠ...",sendMessageAria:"ØĨØąØŗØ§Ų ØąØŗØ§ŲØŠ",domainNotValidated:"اŲŲØˇØ§Ų ØēŲØą Ų
ØšØĒŲ
د",domainErrorMessage:"ŲØ°Ø§ اŲŲØˇØ§Ų ØēŲØą Ų
ØŗŲ
ŲØ بŲ. ŲØąØŦŲ Ø§ŲØ§ØĒØĩØ§Ų Ø¨Ø§ŲŲ
ØŗØ¤ŲŲ ŲØĨØļØ§ŲØŠ ØšŲŲØ§Ų Ų
Ųب𠨧ŲŲŲØ¨ Ø§ŲØŽØ§Øĩ Ø¨Ų ØĨŲŲ Ø§ŲŲØ§ØĻŲ
ØŠ."},ru:{landingTitle:"ĐаĐē Đ˛Ņ Ņ
ĐžŅиŅĐĩ ОйŅаŅŅŅŅ?",voiceCall:"ĐĐžĐģĐžŅОвОК СвОĐŊĐžĐē",textChat:"ĐĸĐĩĐēŅŅОвŅĐš ŅаŅ",clickToStartCall:"ĐаĐļĐŧиŅĐĩ, ŅŅĐžĐąŅ ĐŊаŅаŅŅ ĐˇĐ˛ĐžĐŊĐžĐē",realTimeVoice:"ĐĐžĐģĐžŅОвОК ŅĐ°ĐˇĐŗĐžĐ˛ĐžŅ Đ˛ ŅĐĩаĐģŅĐŊĐžĐŧ вŅĐĩĐŧĐĩĐŊи",startCall:"ĐаŅаŅŅ ĐˇĐ˛ĐžĐŊĐžĐē",listening:"ĐĄĐģŅŅаŅ...",speakFreely:"ĐОвОŅиŅĐĩ ŅвОйОдĐŊĐž",liveTranscript:"ĐĐ¸Đ˛Đ°Ņ ŅŅаĐŊŅĐēŅиĐŋŅиŅ",transcriptWillAppear:"ĐĸŅаĐŊŅĐēŅиĐŋŅĐ¸Ņ ĐŋĐžŅвиŅŅŅ ĐˇĐ´ĐĩŅŅ Đ˛Đž вŅĐĩĐŧŅ ĐˇĐ˛ĐžĐŊĐēа...",mute:"ĐŅĐēĐģŅŅиŅŅ ĐˇĐ˛ŅĐē",speaker:"ĐиĐŊаĐŧиĐē",endCall:"ĐавĐĩŅŅиŅŅ ĐˇĐ˛ĐžĐŊĐžĐē",hello:"ĐŅивĐĩŅ! ĐаĐē Ņ ĐŧĐžĐŗŅ ĐŋĐžĐŧĐžŅŅ?",sendMessage:"ĐŅĐŋŅавŅŅĐĩ ŅООйŅĐĩĐŊиĐĩ Đ´ĐģŅ ĐŊаŅаĐģа",online:"Đ ŅĐĩŅи",newChat:"ĐОвŅĐš ŅаŅ",back:"ĐаСад",close:"ĐаĐēŅŅŅŅ",error:"ĐŅийĐēа",typeMessage:"ĐвĐĩдиŅĐĩ ŅООйŅĐĩĐŊиĐĩ...",sendMessageAria:"ĐŅĐŋŅавиŅŅ ŅООйŅĐĩĐŊиĐĩ",domainNotValidated:"ĐĐžĐŧĐĩĐŊ ĐŊĐĩ ĐŋŅОвĐĩŅĐĩĐŊ",domainErrorMessage:"ĐŅĐžŅ Đ´ĐžĐŧĐĩĐŊ ĐŊĐĩ в ĐąĐĩĐģĐžĐŧ ŅĐŋиŅĐēĐĩ. ĐĐžĐļаĐģŅĐšŅŅа, ŅвŅĐļиŅĐĩŅŅ Ņ Đ°Đ´ĐŧиĐŊиŅŅŅаŅĐžŅĐžĐŧ, ŅŅĐžĐąŅ Đ´ĐžĐąĐ°Đ˛Đ¸ŅŅ URL ваŅĐĩĐŗĐž вĐĩĐą-ŅаКŅа в ŅĐŋиŅĐžĐē."},es:{landingTitle:"ÂŋCÃŗmo te gustarÃa comunicarte?",voiceCall:"Llamada de voz",textChat:"Chat de texto",clickToStartCall:"Haz clic para iniciar la llamada",realTimeVoice:"ConversaciÃŗn de voz en tiempo real",startCall:"Iniciar llamada",listening:"Escuchando...",speakFreely:"Habla libremente",liveTranscript:"TranscripciÃŗn en vivo",transcriptWillAppear:"La transcripciÃŗn aparecerÃĄ aquà durante la llamada...",mute:"Silenciar",speaker:"Altavoz",endCall:"Terminar llamada",hello:"ÂĄHola! ÂŋCÃŗmo puedo ayudarte?",sendMessage:"EnvÃa un mensaje para comenzar",online:"En lÃnea",newChat:"Nuevo chat",back:"AtrÃĄs",close:"Cerrar",error:"Error",typeMessage:"Escribe un mensaje...",sendMessageAria:"Enviar mensaje",domainNotValidated:"Dominio no validado",domainErrorMessage:"Este dominio no estÃĄ en la lista blanca. Por favor, contacte al administrador para agregar la URL de su sitio web a la lista."},fr:{landingTitle:"Comment souhaitez-vous communiquer?",voiceCall:"Appel vocal",textChat:"Chat texte",clickToStartCall:"Cliquez pour dÊmarrer l'appel",realTimeVoice:"Conversation vocale en temps rÊel",startCall:"DÊmarrer l'appel",listening:"Ãcoute...",speakFreely:"Parlez librement",liveTranscript:"TranscripciÃŗn en direct",transcriptWillAppear:"La transcription apparaÃŽtra ici pendant l'appel...",mute:"Muet",speaker:"Haut-parleur",endCall:"Terminer l'appel",hello:"Bonjour! Comment puis-je vous aider?",sendMessage:"Envoyez un message pour commencer",online:"En ligne",newChat:"Nouveau chat",back:"Retour",close:"Fermer",error:"Erreur",typeMessage:"Tapez votre message...",sendMessageAria:"Envoyer un message",domainNotValidated:"Domaine non validÊ",domainErrorMessage:"Ce domaine n'est pas sur la liste blanche. Veuillez contacter l'administrateur pour ajouter l'URL de votre site Web à la liste."},de:{landingTitle:"Wie mÃļchten Sie kommunizieren?",voiceCall:"Sprachanruf",textChat:"Text-Chat",clickToStartCall:"Klicken Sie, um den Anruf zu starten",realTimeVoice:"Sprachanruf in Echtzeit",startCall:"Anruf starten",listening:"HÃļren...",speakFreely:"Sprechen Sie frei",liveTranscript:"Live-Transkription",transcriptWillAppear:"Die Transkription erscheint hier während des Anrufs...",mute:"Stumm",speaker:"Lautsprecher",endCall:"Anruf beenden",hello:"Hallo! Wie kann ich helfen?",sendMessage:"Senden Sie eine Nachricht zum Starten",online:"Online",newChat:"Neuer Chat",back:"ZurÃŧck",close:"SchlieÃen",error:"Fehler",typeMessage:"Geben Sie eine Nachricht ein...",sendMessageAria:"Nachricht senden",domainNotValidated:"Domain nicht validiert",domainErrorMessage:"Diese Domain steht nicht auf der Whitelist. Bitte kontaktieren Sie den Administrator, um die URL Ihrer Website zur Liste hinzuzufÃŧgen."}};function _e(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function Oe(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){_e(r,o,i,a,s,"next",e)}function s(e){_e(r,o,i,a,s,"throw",e)}a(void 0)})}}function Me(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function Ue(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Me(Object(n),!0).forEach(function(t){Ne(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Me(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Ne(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class ze{constructor(){var e,t,n,o,i,r,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.config=this.mergeWithDefaults(a),this.sdk=new q(this.config),this.isOpen=!1,this.isActive=!1,this.translations=Be,this.currentView="landing",this.shadowRoot=null,this.container=null,this._pendingClientTools=null,this.config.useShadowDOM?(this.createShadowHost(),this.container=this.shadowRoot):(this.createRegularContainer(),this.container=this.regularContainer,this.shadowRoot=document);var s=Ue(Ue(Ue({},this.config),this.config.voice),{},{language:(null===(e=this.config.voice)||void 0===e?void 0:e.language)||this.config.language||"en",signedUrl:this.config.signedUrl,agentSettingsOverride:this.config.agentSettingsOverride,translations:this.translations,shadowRoot:this.shadowRoot,outputContainer:(null===(t=this.config.voice)||void 0===t?void 0:t.outputContainer)||"raw",outputEncoding:(null===(n=this.config.voice)||void 0===n?void 0:n.outputEncoding)||"pcm",outputSampleRate:(null===(o=this.config.voice)||void 0===o?void 0:o.outputSampleRate)||44100,outputChannels:(null===(i=this.config.voice)||void 0===i?void 0:i.outputChannels)||1,outputBitDepth:(null===(r=this.config.voice)||void 0===r?void 0:r.outputBitDepth)||16,onConversationStart:this.config.onConversationStart,onConversationEnd:this.config.onConversationEnd,onBargeIn:this.config.onBargeIn,onAudioStartPlaying:this.config.onAudioStartPlaying,onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,onSubtitleDisplay:this.config.onSubtitleDisplay});this.voiceInterface=new Ae(s);var c=Ue(Ue(Ue({},this.config),this.config.text),{},{translations:this.translations,shadowRoot:this.shadowRoot});if(this.textInterface=new Fe(c,this.sdk),this.createWidget(),this.setupEventHandlers(),this.config.behavior.startOpen||this.config.behavior.autoOpen){var l,d=null===(l=this.shadowRoot)||void 0===l?void 0:l.getElementById("text-chat-panel");d&&(this.isOpen=!0,d.classList.add("open"))}this.checkAndHandleResume()}checkAndHandleResume(){var e=this.voiceInterface.checkAndHandleResume();e&&(console.log("đ [WIDGET] Auto-resuming call from page navigation"),console.log(" From:",e.fromPage,"â To:",e.toPage),this.open(),setTimeout(()=>{this.startVoiceCall().then(()=>{console.log("â
[WIDGET] Auto-resumed call successfully")}).catch(e=>{console.error("â [WIDGET] Failed to auto-resume call:",e)})},100))}open(){var e;if(!this.isOpen){var t=null===(e=this.shadowRoot)||void 0===e?void 0:e.getElementById("text-chat-panel");t&&(this.isOpen=!0,t.classList.add("open"))}}mergeWithDefaults(e){var t,n,o,i,r,a,s,c,l,d,u,h,p,g,m,v,f,y,x,b,w,S,C,k,P,T,E,I,A,R,D,F,B,_,O,M,U,N,z,H,L,K,V,j,W,q,Q,G,Y,J,$,X,Z,ee,te,ne,oe,ie,re,ae,se,ce,le,de,ue,he,pe,ge,me,ve,fe,ye,xe,be,we,Se,Ce,ke,Pe,Te,Ee,Ie,Ae,Re,De,Fe,Be,_e,Oe,Me,Ne,ze,He,Le,Ke,Ve,je,We,qe,Qe,Ge,Ye,Je,$e,Xe,Ze,et,tt,nt,ot,it,rt,at,st,ct,lt,dt,ut,ht,pt,gt,mt,vt,ft,yt,xt,bt,wt,St,Ct,kt,Pt,Tt,Et,It,At,Rt,Dt,Ft,Bt,_t=e.position||"bottom-right";if("string"==typeof _t){var Ot=_t.split("-");_t={vertical:Ot[0]||"bottom",horizontal:Ot[1]||"right",offset:e.positionOffset||{x:20,y:20}}}var Mt=e.primaryColor||(null===(t=e.button)||void 0===t?void 0:t.primaryColor)||(null===(n=e.button)||void 0===n?void 0:n.backgroundColor)||"#FFFFFF",Ut=(null===(o=e.header)||void 0===o?void 0:o.backgroundColor)||"#7C3AED";return Ue({agentId:e.agentId,appId:e.appId,signedUrl:e.signedUrl,agentSettingsOverride:e.agentSettingsOverride,demo:!1!==e.demo,direction:e.direction||"ltr",language:e.language||"en",icon:Ue({type:(null===(i=e.icon)||void 0===i?void 0:i.type)||"custom",customImage:(null===(r=e.icon)||void 0===r?void 0:r.customImage)||"https://talktopc.com/logo192.png",emoji:(null===(a=e.icon)||void 0===a?void 0:a.emoji)||"đ¤",text:(null===(s=e.icon)||void 0===s?void 0:s.text)||"AI",size:(null===(c=e.icon)||void 0===c?void 0:c.size)||"medium",backgroundColor:(null===(l=e.icon)||void 0===l?void 0:l.backgroundColor)||"#FFFFFF"},e.icon),position:Ue({vertical:_t.vertical||"bottom",horizontal:_t.horizontal||"right",offset:_t.offset||{x:20,y:20}},"object"==typeof e.position?e.position:{}),button:Ue({size:(null===(d=e.button)||void 0===d?void 0:d.size)||"medium",shape:(null===(u=e.button)||void 0===u?void 0:u.shape)||"circle",backgroundColor:(null===(h=e.button)||void 0===h?void 0:h.backgroundColor)||(null===(p=e.icon)||void 0===p?void 0:p.backgroundColor)||"#FFFFFF",hoverColor:(null===(g=e.button)||void 0===g?void 0:g.hoverColor)||"#D3D3D3",shadow:!1!==(null===(m=e.button)||void 0===m?void 0:m.shadow),shadowColor:(null===(v=e.button)||void 0===v?void 0:v.shadowColor)||"rgba(0,0,0,0.15)",primaryColor:(null===(f=e.button)||void 0===f?void 0:f.backgroundColor)||(null===(y=e.icon)||void 0===y?void 0:y.backgroundColor)||"#FFFFFF"},e.button),panel:Ue({width:(null===(x=e.panel)||void 0===x?void 0:x.width)||350,height:(null===(b=e.panel)||void 0===b?void 0:b.height)||500,borderRadius:(null===(w=e.panel)||void 0===w?void 0:w.borderRadius)||12,backgroundColor:(null===(S=e.panel)||void 0===S?void 0:S.backgroundColor)||"#FFFFFF",backdropFilter:(null===(C=e.panel)||void 0===C?void 0:C.backdropFilter)||null,border:(null===(k=e.panel)||void 0===k?void 0:k.border)||"1px solid #E5E7EB"},e.panel),voice:Ue({micButtonColor:(null===(P=e.voice)||void 0===P?void 0:P.micButtonColor)||(null===(T=e.panel)||void 0===T?void 0:T.micButtonColor)||Mt,micButtonActiveColor:(null===(E=e.voice)||void 0===E?void 0:E.micButtonActiveColor)||(null===(I=e.panel)||void 0===I?void 0:I.micButtonActiveColor)||"#EF4444",micButtonHint:Ue(Ue({text:(null===(A=e.voice)||void 0===A||null===(A=A.micButtonHint)||void 0===A?void 0:A.text)||(null===(R=e.panel)||void 0===R||null===(R=R.micButtonHint)||void 0===R?void 0:R.text)||"Click the button to start voice conversation",color:(null===(D=e.voice)||void 0===D||null===(D=D.micButtonHint)||void 0===D?void 0:D.color)||(null===(F=e.panel)||void 0===F||null===(F=F.micButtonHint)||void 0===F?void 0:F.color)||"#6B7280",fontSize:(null===(B=e.voice)||void 0===B||null===(B=B.micButtonHint)||void 0===B?void 0:B.fontSize)||(null===(_=e.panel)||void 0===_||null===(_=_.micButtonHint)||void 0===_?void 0:_.fontSize)||"12px"},null===(O=e.voice)||void 0===O?void 0:O.micButtonHint),null===(M=e.panel)||void 0===M?void 0:M.micButtonHint),avatarBackgroundColor:(null===(U=e.voice)||void 0===U?void 0:U.avatarBackgroundColor)||"#667eea",avatarActiveBackgroundColor:(null===(N=e.voice)||void 0===N?void 0:N.avatarActiveBackgroundColor)||"#667eea",statusTitleColor:(null===(z=e.voice)||void 0===z?void 0:z.statusTitleColor)||"#1e293b",statusSubtitleColor:(null===(H=e.voice)||void 0===H?void 0:H.statusSubtitleColor)||"#64748b",startCallButtonColor:(null===(L=e.voice)||void 0===L?void 0:L.startCallButtonColor)||"#667eea",startCallButtonTextColor:(null===(K=e.voice)||void 0===K?void 0:K.startCallButtonTextColor)||"#FFFFFF",startCallTitle:(null===(V=e.voice)||void 0===V?void 0:V.startCallTitle)||null,startCallSubtitle:(null===(j=e.voice)||void 0===j?void 0:j.startCallSubtitle)||null,startCallButtonText:(null===(W=e.voice)||void 0===W?void 0:W.startCallButtonText)||null,transcriptBackgroundColor:(null===(q=e.voice)||void 0===q?void 0:q.transcriptBackgroundColor)||"#FFFFFF",transcriptTextColor:(null===(Q=e.voice)||void 0===Q?void 0:Q.transcriptTextColor)||"#1e293b",transcriptLabelColor:(null===(G=e.voice)||void 0===G?void 0:G.transcriptLabelColor)||"#94a3b8",controlButtonColor:(null===(Y=e.voice)||void 0===Y?void 0:Y.controlButtonColor)||"#FFFFFF",controlButtonSecondaryColor:(null===(J=e.voice)||void 0===J?void 0:J.controlButtonSecondaryColor)||"#64748b",endCallButtonColor:(null===($=e.voice)||void 0===$?void 0:$.endCallButtonColor)||"#ef4444",language:(null===(X=e.voice)||void 0===X?void 0:X.language)||e.language||"en"},e.voice),text:Ue({sendButtonColor:(null===(Z=e.text)||void 0===Z?void 0:Z.sendButtonColor)||(null===(ee=e.panel)||void 0===ee?void 0:ee.sendButtonColor)||"#7C3AED",sendButtonHoverColor:(null===(te=e.text)||void 0===te?void 0:te.sendButtonHoverColor)||(null===(ne=e.panel)||void 0===ne?void 0:ne.sendButtonHoverColor)||"#6D28D9",sendButtonActiveColor:(null===(oe=e.text)||void 0===oe?void 0:oe.sendButtonActiveColor)||(null===(ie=e.panel)||void 0===ie?void 0:ie.sendButtonActiveColor)||"#6D28D9",sendButtonText:(null===(re=e.text)||void 0===re?void 0:re.sendButtonText)||(null===(ae=e.panel)||void 0===ae?void 0:ae.sendButtonText)||"â¤",sendButtonTextColor:(null===(se=e.text)||void 0===se?void 0:se.sendButtonTextColor)||(null===(ce=e.panel)||void 0===ce?void 0:ce.sendButtonTextColor)||"#FFFFFF",sendButtonFontSize:(null===(le=e.text)||void 0===le?void 0:le.sendButtonFontSize)||(null===(de=e.panel)||void 0===de?void 0:de.sendButtonFontSize)||"18px",sendButtonFontWeight:(null===(ue=e.text)||void 0===ue?void 0:ue.sendButtonFontWeight)||(null===(he=e.panel)||void 0===he?void 0:he.sendButtonFontWeight)||"500",sendButtonHint:Ue(Ue({text:(null===(pe=e.text)||void 0===pe||null===(pe=pe.sendButtonHint)||void 0===pe?void 0:pe.text)||(null===(ge=e.panel)||void 0===ge||null===(ge=ge.sendButtonHint)||void 0===ge?void 0:ge.text)||"",color:(null===(me=e.text)||void 0===me||null===(me=me.sendButtonHint)||void 0===me?void 0:me.color)||(null===(ve=e.panel)||void 0===ve||null===(ve=ve.sendButtonHint)||void 0===ve?void 0:ve.color)||"#6B7280",fontSize:(null===(fe=e.text)||void 0===fe||null===(fe=fe.sendButtonHint)||void 0===fe?void 0:fe.fontSize)||(null===(ye=e.panel)||void 0===ye||null===(ye=ye.sendButtonHint)||void 0===ye?void 0:ye.fontSize)||"12px"},null===(xe=e.text)||void 0===xe?void 0:xe.sendButtonHint),null===(be=e.panel)||void 0===be?void 0:be.sendButtonHint),inputPlaceholder:(null===(we=e.text)||void 0===we?void 0:we.inputPlaceholder)||(null===(Se=e.panel)||void 0===Se?void 0:Se.inputPlaceholder)||"Type your message...",inputBorderColor:(null===(Ce=e.text)||void 0===Ce?void 0:Ce.inputBorderColor)||(null===(ke=e.panel)||void 0===ke?void 0:ke.inputBorderColor)||"#E5E7EB",inputFocusColor:(null===(Pe=e.text)||void 0===Pe?void 0:Pe.inputFocusColor)||(null===(Te=e.panel)||void 0===Te?void 0:Te.inputFocusColor)||"#7C3AED",inputBackgroundColor:(null===(Ee=e.text)||void 0===Ee?void 0:Ee.inputBackgroundColor)||(null===(Ie=e.panel)||void 0===Ie?void 0:Ie.inputBackgroundColor)||"#FFFFFF",inputTextColor:(null===(Ae=e.text)||void 0===Ae?void 0:Ae.inputTextColor)||(null===(Re=e.panel)||void 0===Re?void 0:Re.inputTextColor)||"#1F2937",inputFontSize:(null===(De=e.text)||void 0===De?void 0:De.inputFontSize)||(null===(Fe=e.panel)||void 0===Fe?void 0:Fe.inputFontSize)||"14px",inputBorderRadius:(null===(Be=e.text)||void 0===Be?void 0:Be.inputBorderRadius)||(null===(_e=e.panel)||void 0===_e?void 0:_e.inputBorderRadius)||20,inputPadding:(null===(Oe=e.text)||void 0===Oe?void 0:Oe.inputPadding)||(null===(Me=e.panel)||void 0===Me?void 0:Me.inputPadding)||"6px 14px"},e.text),landing:Ue({backgroundColor:(null===(Ne=e.landing)||void 0===Ne?void 0:Ne.backgroundColor)||"linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%)",logo:(null===(ze=e.landing)||void 0===ze?void 0:ze.logo)||"đ¤",title:(null===(He=e.landing)||void 0===He?void 0:He.title)||null,titleColor:(null===(Le=e.landing)||void 0===Le?void 0:Le.titleColor)||"#1e293b",modeCardBackgroundColor:(null===(Ke=e.landing)||void 0===Ke?void 0:Ke.modeCardBackgroundColor)||"#FFFFFF",modeCardBorderColor:(null===(Ve=e.landing)||void 0===Ve?void 0:Ve.modeCardBorderColor)||"#E2E8F0",modeCardHoverBorderColor:(null===(je=e.landing)||void 0===je?void 0:je.modeCardHoverBorderColor)||Ut,modeCardIconBackgroundColor:(null===(We=e.landing)||void 0===We?void 0:We.modeCardIconBackgroundColor)||Ut,modeCardTitleColor:(null===(qe=e.landing)||void 0===qe?void 0:qe.modeCardTitleColor)||"#111827",voiceCardIcon:(null===(Qe=e.landing)||void 0===Qe?void 0:Qe.voiceCardIcon)||"đ¤",textCardIcon:(null===(Ge=e.landing)||void 0===Ge?void 0:Ge.textCardIcon)||"đŦ",voiceCardTitle:(null===(Ye=e.landing)||void 0===Ye?void 0:Ye.voiceCardTitle)||null,textCardTitle:(null===(Je=e.landing)||void 0===Je?void 0:Je.textCardTitle)||null},e.landing),header:Ue({title:(null===($e=e.header)||void 0===$e?void 0:$e.title)||"Chat Assistant",showTitle:!1!==(null===(Xe=e.header)||void 0===Xe?void 0:Xe.showTitle),backgroundColor:(null===(Ze=e.header)||void 0===Ze?void 0:Ze.backgroundColor)||"#7C3AED",textColor:(null===(et=e.header)||void 0===et?void 0:et.textColor)||"#FFFFFF",showCloseButton:!1!==(null===(tt=e.header)||void 0===tt?void 0:tt.showCloseButton)},e.header),footer:Ue({show:!1!==(null===(nt=e.footer)||void 0===nt?void 0:nt.show),backgroundColor:(null===(ot=e.footer)||void 0===ot?void 0:ot.backgroundColor)||"#f9fafb",textColor:(null===(it=e.footer)||void 0===it?void 0:it.textColor)||"#9ca3af",hoverColor:(null===(rt=e.footer)||void 0===rt?void 0:rt.hoverColor)||"#7C3AED"},e.footer),tooltips:Ue({newChat:(null===(at=e.tooltips)||void 0===at?void 0:at.newChat)||null,back:(null===(st=e.tooltips)||void 0===st?void 0:st.back)||null,close:(null===(ct=e.tooltips)||void 0===ct?void 0:ct.close)||null,mute:(null===(lt=e.tooltips)||void 0===lt?void 0:lt.mute)||null,speaker:(null===(dt=e.tooltips)||void 0===dt?void 0:dt.speaker)||null,endCall:(null===(ut=e.tooltips)||void 0===ut?void 0:ut.endCall)||null},e.tooltips),messages:Ue({userBackgroundColor:(null===(ht=e.messages)||void 0===ht?void 0:ht.userBackgroundColor)||"#E5E7EB",agentBackgroundColor:(null===(pt=e.messages)||void 0===pt?void 0:pt.agentBackgroundColor)||"#F3F4F6",systemBackgroundColor:(null===(gt=e.messages)||void 0===gt?void 0:gt.systemBackgroundColor)||"#DCFCE7",errorBackgroundColor:(null===(mt=e.messages)||void 0===mt?void 0:mt.errorBackgroundColor)||"#FEE2E2",textColor:(null===(vt=e.messages)||void 0===vt?void 0:vt.textColor)||"#1F2937",fontSize:(null===(ft=e.messages)||void 0===ft?void 0:ft.fontSize)||"14px",borderRadius:(null===(yt=e.messages)||void 0===yt?void 0:yt.borderRadius)||8},e.messages),animation:Ue({enableHover:!1!==(null===(xt=e.animation)||void 0===xt?void 0:xt.enableHover),enablePulse:!1!==(null===(bt=e.animation)||void 0===bt?void 0:bt.enablePulse),enableSlide:!1!==(null===(wt=e.animation)||void 0===wt?void 0:wt.enableSlide),duration:(null===(St=e.animation)||void 0===St?void 0:St.duration)||.3},e.animation),behavior:Ue({autoOpen:(null===(Ct=e.behavior)||void 0===Ct?void 0:Ct.autoOpen)||!1,startOpen:(null===(kt=e.behavior)||void 0===kt?void 0:kt.startOpen)||!1,hidden:(null===(Pt=e.behavior)||void 0===Pt?void 0:Pt.hidden)||!1,autoConnect:(null===(Tt=e.behavior)||void 0===Tt?void 0:Tt.autoConnect)||!1,showWelcomeMessage:!1!==(null===(Et=e.behavior)||void 0===Et?void 0:Et.showWelcomeMessage),welcomeMessage:(null===(It=e.behavior)||void 0===It?void 0:It.welcomeMessage)||"Hello! How can I help you today?",enableVoiceMode:void 0===(null===(At=e.behavior)||void 0===At?void 0:At.enableVoiceMode)||e.behavior.enableVoiceMode,mode:(null===(Rt=e.behavior)||void 0===Rt?void 0:Rt.mode)||"unified"},e.behavior),accessibility:Ue({ariaLabel:(null===(Dt=e.accessibility)||void 0===Dt?void 0:Dt.ariaLabel)||"Chat Assistant",ariaDescription:(null===(Ft=e.accessibility)||void 0===Ft?void 0:Ft.ariaDescription)||"Click to open chat assistant",keyboardNavigation:!1!==(null===(Bt=e.accessibility)||void 0===Bt?void 0:Bt.keyboardNavigation)},e.accessibility),customStyles:e.customStyles||"",useShadowDOM:!1!==e.useShadowDOM,variables:e.variables||{},forceConversationId:e.forceConversationId,onConversationStart:e.onConversationStart,onConversationEnd:e.onConversationEnd,onBargeIn:e.onBargeIn,onAudioStartPlaying:e.onAudioStartPlaying,onAudioStoppedPlaying:e.onAudioStoppedPlaying,onSubtitleDisplay:e.onSubtitleDisplay,primaryColor:Mt},"string"==typeof e.position?{positionString:e.position}:{})}setupEventHandlers(){this.sdk.on("domainError",e=>{this.textInterface.showError(e),this.textInterface.stopStreamingState()}),this.sdk.on("error",e=>{e&&("DOMAIN_NOT_WHITELISTED"===e.message||e.message&&e.message.includes("Domain not whitelisted"))||(this.textInterface.showError(e.message||e),this.textInterface.stopStreamingState())}),this.sdk.on("chunk",e=>{this.textInterface.appendStreamingChunk(e)}),this.sdk.on("done",e=>{var{text:t}=e;this.textInterface.finalizeStreaming(t)})}createShadowHost(){var e=document.getElementById("ttp-widget-shadow-host");e&&e.remove();var t=document.createElement("div");t.id="ttp-widget-shadow-host",t.style.cssText="position: fixed; z-index: 10000; pointer-events: none; top: 0; left: 0; width: 100%; height: 100%; overflow: visible;",this.shadowRoot=t.attachShadow({mode:"open"}),document.body.appendChild(t)}createRegularContainer(){var e=document.getElementById("ttp-widget-container");e&&e.remove();var t=document.createElement("div");t.id="ttp-widget-container",t.style.cssText="position: fixed; z-index: 10000; pointer-events: none; top: 0; left: 0; width: 100%; height: 100%; overflow: visible;",document.body.appendChild(t),this.regularContainer=t}createWidget(){this.container||(this.config.useShadowDOM?(this.createShadowHost(),this.container=this.shadowRoot):(this.createRegularContainer(),this.container=this.regularContainer,this.shadowRoot=document));var e;e=this.config.useShadowDOM?"\n :host {\n all: initial;\n display: block;\n pointer-events: none;\n }\n img {\n max-width: none !important;\n }\n #text-chat-button img {\n width: 28px !important;\n height: 28px !important;\n }\n #text-chat-button {\n pointer-events: auto;\n }\n #text-chat-panel {\n pointer-events: auto;\n }\n ":'\n /* Reset only problematic inherited styles, not all styles */\n #text-chat-button,\n #text-chat-panel,\n #text-chat-panel * {\n box-sizing: border-box;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n }\n \n /* Prevent theme CSS from affecting images */\n #text-chat-button img,\n #text-chat-panel img {\n max-width: none !important;\n width: auto;\n height: auto;\n }\n \n #text-chat-button img {\n width: 28px !important;\n height: 28px !important;\n }\n \n /* Ensure button and panel can receive clicks */\n #text-chat-button,\n #text-chat-panel {\n pointer-events: auto;\n }\n \n /* Reset any inherited text styles that might break layout */\n #text-chat-panel {\n text-align: left;\n line-height: normal;\n letter-spacing: normal;\n word-spacing: normal;\n text-transform: none;\n text-indent: 0;\n text-shadow: none;\n white-space: normal;\n }\n \n /* Ensure flexbox works properly */\n #text-chat-panel .widget-shell,\n #text-chat-panel .panel-inner,\n #text-chat-panel .widget-container,\n #text-chat-panel .landing-screen,\n #text-chat-panel .voice-interface,\n #text-chat-panel .text-interface,\n #text-chat-panel .widget-header,\n #text-chat-panel .mode-selection {\n display: flex;\n }\n \n #text-chat-panel .widget-shell,\n #text-chat-panel .panel-inner,\n #text-chat-panel .widget-container,\n #text-chat-panel .landing-screen,\n #text-chat-panel .voice-interface,\n #text-chat-panel .text-interface {\n flex-direction: column;\n }\n \n #text-chat-panel .mode-selection {\n flex-direction: row;\n }\n \n /* Ensure proper stacking */\n #text-chat-button {\n z-index: 10001 !important;\n }\n \n #text-chat-panel {\n z-index: 10000 !important;\n }\n ';var t=this.generateWidgetHTML();if(this.config.useShadowDOM){var n="\n <style>".concat(e,"</style>\n ").concat(t,"\n ");this.shadowRoot.innerHTML=n}else this.injectStylesIntoHead(e),this.container.innerHTML=t;this.setupWidgetEvents();var o=this.shadowRoot.getElementById("text-chat-panel");o&&(this.config.behavior.startOpen||this.config.behavior.autoOpen)&&(this.isOpen=!0,o.classList.add("open"))}injectStylesIntoHead(e){var t,n,o=document.getElementById("ttp-widget-styles");o&&o.remove();var i={small:50,medium:60,large:70,xl:80}[null===(t=this.config.button)||void 0===t?void 0:t.size]||60,r={small:20,medium:28,large:36,xl:44}[null===(n=this.config.icon)||void 0===n?void 0:n.size]||28,a=this.generatePositionStyles(),s=this.generateCSS(a,i,r),c=document.createElement("style");c.id="ttp-widget-styles",c.textContent=e+"\n"+s,this.config.customStyles&&(c.textContent+="\n"+this.config.customStyles),document.head.appendChild(c)}generateWidgetHTML(){this.config.position;var e,t,n,o,i=this.config.button,r=this.config.icon,a=(this.config.panel,this.config.header),s=(this.config.animation,{small:50,medium:60,large:70,xl:80}[i.size]||60),c={small:20,medium:28,large:36,xl:44}[r.size]||28,l=this.generatePositionStyles(),d=this.generateIconHTML(c),u=this.config.behavior.mode||"unified",h="unified"===u,p="unified"===u||"voice-only"===u,g="unified"===u||"text-only"===u,m=e=>{var t=this.config.language||"en";return(this.translations[t]||this.translations.en)[e]||e},v=e=>{var t,n=null===(t=this.config.tooltips)||void 0===t?void 0:t[e];return null!=n?n:{newChat:m("newChat"),back:m("back"),close:m("close"),mute:m("mute"),speaker:m("speaker"),endCall:m("endCall")}[e]||""},f=this.config.useShadowDOM?"\n <style>\n ".concat(this.generateCSS(l,s,c),"\n ").concat(this.config.customStyles,"\n </style>\n "):"";return"\n ".concat(f,"\n \n ").concat(this.config.behavior.hidden?"":'\n <button id="text-chat-button" \n aria-label="'.concat(this.config.accessibility.ariaLabel,'"\n aria-description="').concat(this.config.accessibility.ariaDescription,'">\n ').concat(d,"\n </button>\n "),'\n \n <div id="text-chat-panel">\n <div class="widget-shell">\n <div class="panel-inner widget-container" style="direction: ').concat(this.config.direction,';">\n <div class="widget-header" style="background: ').concat(a.backgroundColor,"; color: ").concat(a.textColor,';">\n <div>\n ').concat(a.showTitle?'<div class="header-title">'.concat(a.title,"</div>"):"",'\n <div class="header-status">\n <span class="status-dot"></span>\n <span>').concat(m("online"),'</span>\n </div>\n </div>\n \n <div style="display: flex; gap: 12px; align-items: center;">\n \x3c!-- New Chat Button (hide on landing screen, show otherwise) --\x3e\n <button class="header-icon new-chat-btn" id="newChatBtn" title="').concat(v("newChat"),'" style="').concat(h?"display: none;":"",'">\n <span style="font-size: 18px; font-weight: bold;">+</span>\n </button>\n \n \x3c!-- Back Button (only show in unified mode) --\x3e\n ').concat("unified"===u?'<button class="header-icon back-btn" id="backBtn" title="'.concat(v("back"),'" style="display: none;">\n <span style="font-size: 16px;">âš</span>\n </button>'):"","\n \n \x3c!-- Close Button --\x3e\n ").concat(a.showCloseButton?'<button class="header-icon close-btn" id="closeBtn" title="'+v("close")+'"><span style="font-size: 18px; font-weight: bold;">Ã</span></button>':"","\n </div>\n </div>\n\n ").concat(h?'\n <div class="landing-screen" id="landingScreen">\n <div class="landing-logo">'.concat((null===(e=this.config.landing)||void 0===e?void 0:e.logo)||"đ¤",'</div>\n <div class="landing-title">').concat((null===(t=this.config.landing)||void 0===t?void 0:t.title)||m("landingTitle"),'</div>\n <div class="mode-selection">\n ').concat(p?'<div class="mode-card voice" id="mode-card-voice">\n <div class="mode-card-icon">đ¤</div>\n <div class="mode-card-title">'.concat((null===(n=this.config.landing)||void 0===n?void 0:n.voiceCardTitle)||m("voiceCall"),"</div>\n </div>"):"","\n ").concat(g?'<div class="mode-card text" id="mode-card-text">\n <div class="mode-card-icon">đŦ</div>\n <div class="mode-card-title">'.concat((null===(o=this.config.landing)||void 0===o?void 0:o.textCardTitle)||m("textChat"),"</div>\n </div>"):"","\n </div>\n </div>"):"","\n\n ").concat(p?this.voiceInterface.generateHTML():"","\n ").concat(g?this.textInterface.generateHTML():"","\n ").concat(this.generateFooterHTML(),"\n </div>\n </div>\n </div>\n ")}generateFooterHTML(){var e=this.config.footer;if(!e.show)return"";var t=encodeURIComponent(window.location.hostname||"widget"),n="https://talktopc.com?ref=widget&source=".concat(t);return'\n <div class="widget-footer" style="\n height: 36px;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background-color: '.concat(e.backgroundColor,';\n border-top: 1px solid #e5e7eb;\n flex-shrink: 0;\n ">\n <a \n href="').concat(n,'" \n target="_blank" \n rel="noopener noreferrer"\n aria-label="Visit TalkToPC website"\n class="footer-brand-link"\n style="\n display: flex;\n flex-direction: column;\n align-items: center;\n text-decoration: none;\n color: ').concat(e.textColor,';\n transition: color 0.2s ease;\n "\n onmouseover="this.style.color=\'').concat(e.hoverColor,"'\"\n onmouseout=\"this.style.color='").concat(e.textColor,'\'"\n >\n <span style="font-size: 11px; line-height: 1.3;">\n ⥠Powered by <strong>TalkToPC</strong>\n </span>\n <span style="font-size: 9px; opacity: 0.7; line-height: 1.2;">\n https://talktopc.com\n </span>\n </a>\n </div>\n ')}generatePositionStyles(){var e=this.config.position,t=e.offset||{x:20,y:20},n="";return"top"===e.vertical?n+="top: ".concat(t.y,"px;"):"bottom"===e.vertical?n+="bottom: ".concat(t.y,"px;"):"center"===e.vertical&&(n+="top: 50%; transform: translateY(-50%);"),"left"===e.horizontal?n+="left: ".concat(t.x,"px;"):"right"===e.horizontal?n+="right: ".concat(t.x,"px;"):"center"===e.horizontal&&(n+="left: 50%; transform: translateX(-50%);"),n}generateIconHTML(e){var t=this.config.icon;switch(t.type){case"custom":return'<img src="'.concat(t.customImage,'" alt="Chat Assistant" style="width: ').concat(e,"px; height: ").concat(e,'px; object-fit: contain;" />');case"emoji":return'<span style="font-size: '.concat(e,'px; line-height: 1;">').concat(t.emoji,"</span>");case"text":return'<span style="font-size: '.concat(Math.floor(.6*e),'px; font-weight: bold; color: white;">').concat(t.text,"</span>");case"microphone":default:return'<svg viewBox="0 0 24 24" style="width: '.concat(e,"px; height: ").concat(e,'px; fill: white;">\n <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/>\n <path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/>\n </svg>');case"chat":return'<svg viewBox="0 0 24 24" style="width: '.concat(e,"px; height: ").concat(e,'px; fill: white;">\n <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>\n </svg>')}}generateCSS(e,t,n){var o,i,r,a,s,c,l,d,u,h,p,g=this.config.button,m=this.config.icon,v=this.config.panel,f=this.config.header,y=(this.config.messages,this.config.animation),x=this.config.behavior.mode||"unified",b="unified"===x||"voice-only"===x,w="unified"===x||"text-only"===x,S=!1===this.config.useShadowDOM?" !important":"",C=f.backgroundColor;return'\n /* MOBILE FIRST - Default styles for all devices */\n #text-chat-widget {\n position: fixed !important;\n z-index: 10000;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n /* Mobile defaults */\n right: 10px;\n bottom: 10px;\n left: auto;\n top: auto;\n }\n \n /* Desktop positioning (only on larger screens) */\n @media (min-width: 769px) {\n #text-chat-widget {\n '.concat(e,"\n right: ").concat("right"===this.config.position.horizontal?"20px":"auto",";\n left: ").concat("left"===this.config.position.horizontal?"20px":"auto",";\n bottom: ").concat("bottom"===this.config.position.vertical?"20px":"auto",";\n top: ").concat("top"===this.config.position.vertical?"20px":"auto",";\n }\n }\n \n /* Mobile override (force mobile positioning) */\n @media (max-width: 768px) {\n #text-chat-widget {\n right: 10px !important;\n bottom: 10px !important;\n left: auto !important;\n top: auto !important;\n transform: none !important;\n }\n }\n \n @media (max-width: 480px) {\n #text-chat-widget {\n right: 8px !important;\n bottom: 8px !important;\n left: auto !important;\n top: auto !important;\n }\n }\n \n #text-chat-button {\n position: fixed;\n ").concat("bottom"===this.config.position.vertical?"bottom: ".concat((null===(o=this.config.position.offset)||void 0===o?void 0:o.y)||20,"px;"):"top: ".concat((null===(i=this.config.position.offset)||void 0===i?void 0:i.y)||20,"px;"),"\n ").concat("right"===this.config.position.horizontal?"right: ".concat((null===(r=this.config.position.offset)||void 0===r?void 0:r.x)||20,"px;"):"left: ".concat((null===(a=this.config.position.offset)||void 0===a?void 0:a.x)||20,"px;"),"\n width: ").concat(t,"px;\n height: ").concat(t,"px;\n border-radius: ").concat("circle"===g.shape?"50%":"square"===g.shape?"0":"12px",";\n background: ").concat(g.backgroundColor||m.backgroundColor||"#7C3AED",";\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all ").concat(y.duration,"s ease;\n box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);\n touch-action: manipulation;\n -webkit-tap-highlight-color: transparent;\n -webkit-touch-callout: none;\n user-select: none;\n min-width: 44px;\n min-height: 44px;\n z-index: 10001;\n }\n \n @media (max-width: 768px) {\n #text-chat-widget {\n right: 10px !important;\n bottom: 10px !important;\n left: auto !important;\n top: auto !important;\n transform: none !important;\n }\n \n #text-chat-button {\n right: 10px !important;\n bottom: 10px !important;\n left: auto !important;\n top: auto !important;\n width: 56px !important;\n height: 56px !important;\n min-width: 56px !important;\n min-height: 56px !important;\n max-width: 56px !important;\n max-height: 56px !important;\n }\n \n #text-chat-panel {\n position: fixed !important;\n left: 10px !important;\n right: 10px !important;\n bottom: 92px !important; /* 56px button + 20px gap + 16px footer */\n top: 60px !important; /* Add top spacing */\n width: auto !important;\n max-width: none !important;\n height: auto !important; /* Change from max-height to auto */\n max-height: none !important; /* Remove max-height */\n transform: none !important;\n margin: 0 !important;\n }\n \n #text-chat-panel .widget-header {\n padding: 10px 14px;\n min-height: 56px;\n }\n \n #text-chat-panel .header-title {\n font-size: 15px;\n }\n \n #text-chat-panel .header-icon {\n width: 40px;\n height: 40px;\n min-width: 40px;\n min-height: 40px;\n }\n \n #text-chat-input {\n font-size: 16px !important; /* Prevents iOS zoom on focus */\n padding: 12px 16px !important;\n min-height: 48px !important;\n }\n \n #text-chat-send {\n min-width: 48px !important;\n min-height: 48px !important;\n width: 48px !important;\n height: 48px !important;\n }\n \n .landing-screen {\n padding: 16px;\n }\n \n .landing-logo {\n font-size: 40px;\n }\n \n .landing-title {\n font-size: 18px;\n margin-bottom: 16px;\n }\n \n .mode-selection {\n flex-direction: column;\n gap: 12px;\n align-items: center;\n }\n \n .mode-card {\n max-width: 100%;\n width: 100%;\n padding: 16px;\n }\n \n .mode-card-icon {\n width: 50px;\n height: 50px;\n font-size: 28px;\n }\n \n .mode-card-title {\n font-size: 14px;\n }\n }\n \n @media (max-width: 480px) {\n #text-chat-widget {\n right: 8px !important;\n bottom: 8px !important;\n left: auto !important;\n top: auto !important;\n }\n \n #text-chat-button {\n right: 8px !important;\n bottom: 8px !important;\n left: auto !important;\n top: auto !important;\n width: 54px !important;\n height: 54px !important;\n min-width: 54px !important;\n min-height: 54px !important;\n }\n \n #text-chat-panel {\n left: 8px !important;\n right: 8px !important;\n bottom: 86px !important; /* 54px button + 20px gap + 12px footer */\n top: 50px !important; /* Add top spacing for very small screens */\n height: auto !important;\n max-height: none !important;\n }\n \n #text-chat-panel .widget-header {\n padding: 8px 12px;\n min-height: 52px;\n }\n \n #text-chat-panel .header-title {\n font-size: 14px;\n }\n \n .landing-logo {\n font-size: 36px;\n }\n \n .landing-title {\n font-size: 16px;\n }\n }\n \n ").concat(y.enableHover?"\n #text-chat-button:hover {\n ".concat(g.hoverColor?"background: ".concat(g.hoverColor,";"):"","\n transform: scale(1.05);\n box-shadow: 0 8px 20px rgba(102, 126, 234, 0.5);\n }\n "):"","\n \n #text-chat-panel {\n display: none").concat(S,";\n position: fixed;\n bottom: calc(").concat(t,"px + 20px + 20px); /* Button + gap + reduced footer offset */\n ").concat("right"===this.config.position.horizontal?"right: 20px;":"left: 20px;","\n width: ").concat(v.width,"px;\n max-width: calc(100vw - 40px);\n height: ").concat(v.height,"px;\n max-height: calc(100vh - ").concat(t,"px - 40px - 20px); /* Account for footer height */\n background: transparent;\n border-radius: ").concat(v.borderRadius,"px;\n border: none;\n flex-direction: column;\n overflow: hidden;\n ").concat(v.backdropFilter?"backdrop-filter: ".concat(v.backdropFilter,";"):"","\n ").concat(y.enableSlide?"transition: all ".concat(y.duration,"s ease;"):"","\n box-sizing: border-box;\n }\n \n #text-chat-panel.open {\n display: flex").concat(S,";\n ").concat(y.enableSlide?"transform: translateY(0); opacity: 1;":"","\n }\n\n /* Shell for gradient border/background */\n .widget-shell { width: 100%; height: 100%; padding: 0; border-radius: ").concat(v.borderRadius,"px; background: transparent; box-shadow: 0 20px 60px rgba(0,0,0,0.15); overflow: hidden; display: flex; flex-direction: column; box-sizing: border-box; }\n .panel-inner { width: 100%; height: 100%; background: #ffffff; border-radius: ").concat(v.borderRadius,"px; border: ").concat(v.border,"; overflow: hidden; display:flex; flex-direction: column; padding: 0; box-sizing: border-box; max-width: 100%; }\n\n /* New structure styles matching provided design */\n #text-chat-panel .widget-container {\n width: 100%; height: 100%; min-height: 0; background: #FFFFFF; overflow: hidden; display: flex; flex-direction: column; border-radius: ").concat(v.borderRadius,"px;\n container-type: size;\n }\n \n /* Ensure content areas can scroll when height is constrained */\n #text-chat-panel .widget-container > .landing-screen,\n #text-chat-panel .widget-container > .voice-interface,\n #text-chat-panel .widget-container > .text-interface {\n flex: 1;\n min-height: 0;\n overflow-y: auto;\n overflow-x: hidden;\n }\n \n /* Header should not scroll */\n #text-chat-panel .widget-header {\n padding: 12px 16px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n border-top-left-radius: ").concat(v.borderRadius,"px;\n border-top-right-radius: ").concat(v.borderRadius,"px;\n flex-shrink: 0;\n min-height: 60px;\n box-sizing: border-box;\n }\n #text-chat-panel .header-title { font-size: 16px; font-weight: 600; }\n #text-chat-panel .header-status { display: flex; align-items: center; gap: 8px; font-size: 12px; opacity: 0.9; }\n #text-chat-panel .status-dot { width: 8px; height: 8px; background: #4ade80; border-radius: 50%; animation: pulse 2s ease-in-out infinite; }\n @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }\n /* Header icon buttons */\n .header-icon {\n background: rgba(255, 255, 255, 0.2);\n border: none;\n color: white;\n width: 36px;\n height: 36px;\n min-width: 36px;\n min-height: 36px;\n border-radius: 50%;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.2s;\n flex-shrink: 0;\n font-size: 16px;\n padding: 0;\n box-sizing: border-box;\n }\n \n .header-icon:hover {\n background: rgba(255, 255, 255, 0.3);\n }\n \n .header-icon svg {\n pointer-events: none;\n stroke: white;\n fill: none;\n }\n \n .back-btn.visible {\n display: flex !important;\n }\n\n /* Landing and mode selection (shown only if voice enabled) */\n .landing-screen { \n display: none").concat(S,"; \n flex: 1; \n padding: 20px; \n background: ").concat((null===(s=this.config.landing)||void 0===s?void 0:s.backgroundColor)||"linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%)","; \n align-items: center; \n justify-content: flex-start; \n flex-direction: column; \n gap: 16px; \n overflow-y: auto; \n min-height: 0; \n }\n .landing-screen.active { display: flex").concat(S,"; }\n .landing-logo { font-size: 48px; }\n .landing-title { \n font-size: 20px; \n color: ").concat((null===(c=this.config.landing)||void 0===c?void 0:c.titleColor)||"#1e293b","; \n font-weight: 700; \n margin-bottom: 20px; \n text-align: center;\n width: 100%;\n }\n .mode-selection { display: flex; gap: 16px; width: 100%; justify-content: center; }\n .mode-card { \n flex: 1; \n max-width: 180px; \n background: ").concat((null===(l=this.config.landing)||void 0===l?void 0:l.modeCardBackgroundColor)||"#FFFFFF","; \n border: 2px solid ").concat((null===(d=this.config.landing)||void 0===d?void 0:d.modeCardBorderColor)||"#E2E8F0","; \n border-radius: 20px; \n padding: 20px 12px; \n cursor: pointer; \n display: flex; \n flex-direction: column; \n align-items: center; \n gap: 8px; \n transition: transform ").concat(y.duration,"s ease, box-shadow ").concat(y.duration,"s ease, border-color ").concat(y.duration,"s ease; \n box-shadow: 0 4px 12px rgba(0,0,0,0.05); \n }\n .mode-card:hover { \n transform: translateY(-6px); \n box-shadow: 0 12px 24px rgba(102, 126, 234, 0.2); \n border-color: ").concat((null===(u=this.config.landing)||void 0===u?void 0:u.modeCardHoverBorderColor)||C,"; \n }\n .mode-card-icon { \n width: 60px; \n height: 60px; \n display: flex; \n align-items: center; \n justify-content: center; \n border-radius: 50%; \n background: ").concat((null===(h=this.config.landing)||void 0===h?void 0:h.modeCardIconBackgroundColor)||C,"; \n color: #fff; \n font-size: 32px; \n }\n .mode-card-title { \n color: ").concat((null===(p=this.config.landing)||void 0===p?void 0:p.modeCardTitleColor)||"#111827","; \n font-weight: 600; \n text-align: center;\n width: 100%;\n }\n\n ").concat(b?this.voiceInterface.generateCSS():"","\n ").concat(w?this.textInterface.generateCSS():"","\n \n /* Footer Branding */\n .widget-footer {\n box-sizing: border-box;\n }\n \n .footer-brand-link {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n }\n \n .footer-brand-link:hover {\n opacity: 0.9;\n }\n \n @media (max-width: 768px) {\n .widget-footer {\n height: 32px;\n }\n .widget-footer span {\n font-size: 10px;\n }\n .widget-footer span:last-child {\n font-size: 8px;\n }\n }\n \n #text-chat-send-hint {\n text-align: center;\n line-height: 1.4;\n }\n \n .agent-thinking {\n font-style: italic;\n color: #6B7280;\n }\n ")}setupWidgetEvents(){if(this.shadowRoot){var e=this.shadowRoot.getElementById("text-chat-button");e&&(e.onclick=()=>this.togglePanel());var t=this.shadowRoot.getElementById("closeBtn");t&&(t.onclick=()=>this.togglePanel());var n=this.config.behavior.mode||"unified",o="unified"===n,i="unified"===n||"voice-only"===n,r="unified"===n||"text-only"===n,a=this.shadowRoot.getElementById("backBtn"),s=this.shadowRoot.getElementById("landingScreen"),c=this.shadowRoot.getElementById("mode-card-voice"),l=this.shadowRoot.getElementById("mode-card-text"),d=this.shadowRoot.getElementById("textInterface"),u=this.shadowRoot.getElementById("voiceInterface");a&&(a.onclick=()=>this.showLanding()),o?(c&&(c.onclick=()=>this.showVoice()),l&&(l.onclick=()=>this.showText()),"text"===this.currentView?(s&&s.classList.remove("active"),d&&d.classList.add("active"),u&&u.classList.remove("active"),a&&"unified"===n&&a.classList.add("visible"),h&&(h.style.display="")):"voice"===this.currentView?(s&&s.classList.remove("active"),d&&d.classList.remove("active"),u&&u.classList.add("active"),a&&"unified"===n&&a.classList.add("visible"),h&&(h.style.display="none")):(this.currentView="landing",s&&s.classList.add("active"),d&&d.classList.remove("active"),u&&u.classList.remove("active"),a&&"unified"===n&&a.classList.remove("visible"))):"voice-only"===n?(u&&u.classList.add("active"),d&&d.classList.remove("active"),s&&s.classList.remove("active")):"text-only"===n&&(d&&d.classList.add("active"),u&&u.classList.remove("active"),s&&s.classList.remove("active")),i&&(console.log("âī¸ Setting up voice interface event handlers"),this.voiceInterface.setupEventHandlers()),r&&(console.log("âī¸ Setting up text interface event handlers"),this.textInterface.setupEventHandlers());var h=this.shadowRoot.getElementById("newChatBtn");h&&(h.onclick=()=>this.textInterface.startNewChat(),o&&(h.style.display="none")),this.config.accessibility.keyboardNavigation&&this.setupKeyboardNavigation()}}startNewChat(){this.textInterface.startNewChat()}showLanding(){if(this.shadowRoot&&"unified"===(this.config.behavior.mode||"unified")){this.currentView="landing";var e=this.shadowRoot.getElementById("landingScreen"),t=this.shadowRoot.getElementById("textInterface"),n=this.shadowRoot.getElementById("voiceInterface"),o=this.shadowRoot.getElementById("backBtn"),i=this.shadowRoot.getElementById("newChatBtn");e&&e.classList.add("active"),t&&t.classList.remove("active"),n&&n.classList.remove("active"),o&&o.classList.remove("visible"),i&&(i.style.display="none")}}showText(){if(this.shadowRoot){this.currentView="text";var e=this.shadowRoot.getElementById("landingScreen"),t=this.shadowRoot.getElementById("voiceInterface"),n=this.shadowRoot.getElementById("backBtn"),o=this.shadowRoot.getElementById("newChatBtn");e&&e.classList.remove("active"),t&&t.classList.remove("active"),this.textInterface.show();var i=this.config.behavior.mode||"unified";n&&"unified"===i&&n.classList.add("visible"),o&&(o.style.display="")}}showVoice(){if(this.shadowRoot){this.currentView="voice";var e=this.shadowRoot.getElementById("landingScreen"),t=this.shadowRoot.getElementById("textInterface"),n=this.shadowRoot.getElementById("voiceInterface"),o=this.shadowRoot.getElementById("backBtn"),i=this.shadowRoot.getElementById("newChatBtn");e&&e.classList.remove("active"),t&&t.classList.remove("active"),n&&n.classList.add("active");var r=this.config.behavior.mode||"unified";o&&"unified"===r&&o.classList.add("visible"),i&&(i.style.display="none")}}setupKeyboardNavigation(){document.addEventListener("keydown",e=>{"Escape"===e.key&&this.isOpen&&this.togglePanel()})}togglePanel(){if(this.shadowRoot){this.isOpen=!this.isOpen;var e=this.shadowRoot.getElementById("text-chat-panel");e&&e.classList.toggle("open"),this.isOpen&&setTimeout(()=>{var e=this.shadowRoot.getElementById("messageInput");e&&e.focus()},100),this.isOpen&&!this.isActive&&this.config.behavior.autoConnect&&this.startChat()}}startChat(){var e=this;return Oe(function*(){e.isActive=!0,e.textInterface.setActive(!0)})()}sendMessage(){var e=this;return Oe(function*(){yield e.textInterface.sendMessage()})()}updateSendButtonState(){this.textInterface.updateSendButtonState()}getSignedUrl(){var e=this;return Oe(function*(){if(e.config.signedUrl)return e.config.signedUrl;if(!e.config.agentId)throw new Error("agentId is required when signedUrl is not provided");var t=e.config.websocketUrl||"wss://backend.talktopc.com/ws/conv",n=new URLSearchParams;return n.append("agentId",e.config.agentId),e.config.appId&&n.append("appId",e.config.appId),!1!==e.config.demo&&n.append("demo","true"),"".concat(t,"?").concat(n.toString())})()}addMessage(e,t){this.textInterface.addMessage(e,t)}beginStreaming(){this.textInterface.beginStreaming()}appendStreamingChunk(e){this.textInterface.appendStreamingChunk(e)}finalizeStreaming(e){this.textInterface.finalizeStreaming(e)}stopStreamingState(){this.textInterface.stopStreamingState()}showError(e){this.textInterface.showError(e)}updateStatus(e){}updateConfig(e){var t,n,o,i,r,a,s,c,l,d=Ue({},this.config);e.panel&&(d.panel=Ue(Ue({},this.config.panel),e.panel)),e.voice&&(d.voice=Ue(Ue({},this.config.voice),e.voice),e.voice.micButtonHint&&(d.voice.micButtonHint=Ue(Ue({},null===(c=this.config.voice)||void 0===c?void 0:c.micButtonHint),e.voice.micButtonHint))),e.text&&(d.text=Ue(Ue({},this.config.text),e.text),e.text.sendButtonHint&&(d.text.sendButtonHint=Ue(Ue({},null===(l=this.config.text)||void 0===l?void 0:l.sendButtonHint),e.text.sendButtonHint))),void 0!==e.language&&(d.language=e.language),void 0!==e.language&&(["he","ar"].includes(e.language)?d.direction="rtl":void 0===e.direction&&(d.direction="ltr")),e.translations&&(d.translations=e.translations,this.translations=e.translations),e.button&&(d.button=Ue(Ue({},this.config.button),e.button)),e.header&&(d.header=Ue(Ue({},this.config.header),e.header)),e.icon&&(d.icon=Ue(Ue({},this.config.icon),e.icon)),e.messages&&(d.messages=Ue(Ue({},this.config.messages),e.messages)),e.animation&&(d.animation=Ue(Ue({},this.config.animation),e.animation)),e.behavior&&(d.behavior=Ue(Ue({},this.config.behavior),e.behavior)),e.accessibility&&(d.accessibility=Ue(Ue({},this.config.accessibility),e.accessibility)),e.tooltips&&(d.tooltips=Ue(Ue({},this.config.tooltips),e.tooltips)),e.landing&&(d.landing=Ue(Ue({},this.config.landing),e.landing)),e.footer&&(d.footer=Ue(Ue({},this.config.footer),e.footer)),void 0!==e.direction&&void 0===d.direction&&(d.direction=e.direction),void 0!==e.primaryColor&&(d.primaryColor=e.primaryColor),d.onConversationStart=void 0!==e.onConversationStart?e.onConversationStart:this.config.onConversationStart,d.onConversationEnd=void 0!==e.onConversationEnd?e.onConversationEnd:this.config.onConversationEnd,d.onBargeIn=void 0!==e.onBargeIn?e.onBargeIn:this.config.onBargeIn,d.onAudioStartPlaying=void 0!==e.onAudioStartPlaying?e.onAudioStartPlaying:this.config.onAudioStartPlaying,d.onAudioStoppedPlaying=void 0!==e.onAudioStoppedPlaying?e.onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,d.onSubtitleDisplay=void 0!==e.onSubtitleDisplay?e.onSubtitleDisplay:this.config.onSubtitleDisplay,void 0!==e.useShadowDOM&&(d.useShadowDOM=e.useShadowDOM),Object.keys(e).forEach(t=>{["panel","button","header","footer","icon","messages","direction","voice","text","animation","behavior","accessibility","language","tooltips","landing","primaryColor","useShadowDOM","onConversationStart","onConversationEnd","onBargeIn","onAudioStartPlaying","onAudioStoppedPlaying","onSubtitleDisplay"].includes(t)||(d[t]=e[t])}),null===(t=this.config)||void 0===t||t.language;var u=!1!==(null===(n=this.config)||void 0===n?void 0:n.useShadowDOM);if(this.config=this.mergeWithDefaults(d),!1!==this.config.useShadowDOM===u&&this.container){var h=document.getElementById("ttp-widget-shadow-host");h&&!this.config.useShadowDOM&&h.remove();var p=document.getElementById("ttp-widget-container");if(p&&this.config.useShadowDOM&&p.remove(),this.config.useShadowDOM)if(this.shadowRoot)this.container=this.shadowRoot;else{var g=document.getElementById("ttp-widget-shadow-host");g?(this.shadowRoot=g.shadowRoot,this.container=this.shadowRoot):(this.createShadowHost(),this.container=this.shadowRoot)}else{if(this.regularContainer)this.container=this.regularContainer;else{var m=document.getElementById("ttp-widget-container");m?(this.regularContainer=m,this.container=m):(this.createRegularContainer(),this.container=this.regularContainer)}this.shadowRoot=document}}else{var v=document.getElementById("ttp-widget-shadow-host");v&&v.remove();var f=document.getElementById("ttp-widget-container");if(f&&f.remove(),!1===u){var y=document.getElementById("ttp-widget-styles");y&&y.remove()}this.config.useShadowDOM?(this.createShadowHost(),this.container=this.shadowRoot):(this.createRegularContainer(),this.container=this.regularContainer,this.shadowRoot=document)}var x=this.config.language||"en",b=Ue(Ue(Ue({},this.config),this.config.voice),{},{language:x,translations:this.translations,shadowRoot:this.shadowRoot,outputContainer:(null===(o=this.config.voice)||void 0===o?void 0:o.outputContainer)||"raw",outputEncoding:(null===(i=this.config.voice)||void 0===i?void 0:i.outputEncoding)||"pcm",outputSampleRate:(null===(r=this.config.voice)||void 0===r?void 0:r.outputSampleRate)||44100,outputChannels:(null===(a=this.config.voice)||void 0===a?void 0:a.outputChannels)||1,outputBitDepth:(null===(s=this.config.voice)||void 0===s?void 0:s.outputBitDepth)||16,onConversationStart:this.config.onConversationStart,onConversationEnd:this.config.onConversationEnd,onBargeIn:this.config.onBargeIn,onAudioStartPlaying:this.config.onAudioStartPlaying,onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,onSubtitleDisplay:this.config.onSubtitleDisplay});this.voiceInterface=new Ae(b);var w=Ue(Ue(Ue({},this.config),this.config.text),{},{language:x,translations:this.translations,shadowRoot:this.shadowRoot});this.textInterface=new Fe(w,this.sdk),this.createWidget(),this.textInterface&&this.textInterface.updateInputAttributes&&this.textInterface.updateInputAttributes()}destroy(){var e=document.getElementById("ttp-widget-shadow-host");e&&e.remove();var t=document.getElementById("ttp-widget-container");t&&t.remove();var n=document.getElementById("ttp-widget-styles");n&&n.remove(),this.sdk&&this.sdk.destroy(),this.voiceInterface&&this.voiceInterface.destroy()}startVoiceCall(){var e=this;return Oe(function*(){yield e.voiceInterface.startVoiceCall(),e._flushPendingClientTools()})()}endVoiceCall(){this.voiceInterface.endVoiceCall()}toggleMute(){this.voiceInterface.toggleMute()}toggleSpeaker(){this.voiceInterface.toggleSpeaker()}registerToolHandler(e,t){var n;return null!==(n=this.voiceInterface)&&void 0!==n&&n.sdk?this.voiceInterface.sdk.registerToolHandler(e,t):(this._pendingClientTools=this._pendingClientTools||[],this._pendingClientTools.push({name:e,handler:t}),console.warn("TTPChatWidget: Tool handler queued - voice interface SDK not ready yet"),this._flushPendingClientTools(),this)}unregisterToolHandler(e){var t;return null!==(t=this.voiceInterface)&&void 0!==t&&t.sdk?this.voiceInterface.sdk.unregisterToolHandler(e):(this._pendingClientTools&&(this._pendingClientTools=this._pendingClientTools.filter(t=>t.name!==e)),this)}hasToolHandler(e){var t;return!(null===(t=this.voiceInterface)||void 0===t||!t.sdk)&&this.voiceInterface.sdk.hasToolHandler(e)}getRegisteredTools(){var e;return null!==(e=this.voiceInterface)&&void 0!==e&&e.sdk?this.voiceInterface.sdk.getRegisteredTools():this._pendingClientTools?this._pendingClientTools.map(e=>e.name):[]}_flushPendingClientTools(){var e;this._pendingClientTools&&null!==(e=this.voiceInterface)&&void 0!==e&&e.sdk&&(this._pendingClientTools.forEach(e=>{var{name:t,handler:n}=e;this.voiceInterface.sdk.registerToolHandler(t,n)}),this._pendingClientTools=null,console.log("TTPChatWidget: Flushed pending client tools"))}registerClientTool(e,t){return this.registerToolHandler(e,t)}unregisterClientTool(e){return this.unregisterToolHandler(e)}hasClientTool(e){return this.hasToolHandler(e)}getRegisteredClientTools(){return this.getRegisteredTools()}}var He="2.18.0";const Le={VoiceSDK_v2:H,TextChatSDK:q,WebSocketManager:J,AudioRecorder:Z,AudioPlayer:ne,EventEmitter:L,VoiceButton:ce,VanillaVoiceButton:pe,AgentSDK:ve,TTPChatWidget:ze,VERSION:He};export{ve as AgentSDK,ne as AudioPlayer,Z as AudioRecorder,L as EventEmitter,s as MicPermissionModals,a as MicPermissionUtils,ze as TTPChatWidget,q as TextChatSDK,He as VERSION,pe as VanillaVoiceButton,ce as VoiceButton,H as VoiceSDK_v2,J as WebSocketManager,Le as default};
|
|
2
|
+
import{useEffect as e,useRef as t,useState as n}from"react";var o={698:(e,t)=>{var n=Symbol.for("react.transitional.element");function o(e,t,o){var i=null;if(void 0!==o&&(i=""+o),void 0!==t.key&&(i=""+t.key),"key"in t)for(var r in o={},t)"key"!==r&&(o[r]=t[r]);else o=t;return t=o.ref,{$$typeof:n,type:e,key:i,ref:void 0!==t?t:null,props:o}}Symbol.for("react.fragment"),t.jsx=o,t.jsxs=o},848:(e,t,n)=>{e.exports=n(698)}},i={};function r(e){var t=i[e];if(void 0!==t)return t.exports;var n=i[e]={exports:{}};return o[e](n,n.exports,r),n.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var a={};r.r(a),r.d(a,{checkPermissionState:()=>xe,getDeviceInfo:()=>ye,getPermissionInstructions:()=>we,openSettings:()=>Se});var s={};r.r(s),r.d(s,{showBlockedModal:()=>Pe,showNoMicrophoneModal:()=>Ee,showPrePromptModal:()=>ke});const c=class{constructor(){this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this}off(e,t){return this.events[e]?(this.events[e]=this.events[e].filter(e=>e!==t),this):this}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return!!this.events[e]&&(this.events[e].forEach(e=>{e(...n)}),!0)}once(e,t){var n=this,o=function(){t(...arguments),n.off(e,o)};return this.on(e,o)}removeAllListeners(e){return e?delete this.events[e]:this.events={},this}},l=class{constructor(){this.name="PCM"}decode(e){if(e instanceof ArrayBuffer)return e;if(e instanceof Uint8Array)return e.buffer;throw new Error("Invalid PCM data type")}encode(e){return e}},d=class{constructor(){this.name="PCMU"}decode(e){for(var t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Int16Array(t.length),o=0;o<t.length;o++)n[o]=this.mulawToLinear(t[o]);return n.buffer}encode(e){for(var t=e instanceof Int16Array?e:new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=this.linearToMulaw(t[o]);return n}mulawToLinear(e){var t=1<<3+(e>>4&7);return(128&e?-1:1)*(132+(15&e)*t+(t>>1)-4)}linearToMulaw(e){var t=e>>8&128;t&&(e=-e),e>32635&&(e=32635),e+=132;for(var n=7,o=16384;0===(e&o)&&n>0;n--,o>>=1);return 255&~(t|n<<4|e>>n+3&15)}},u=class{constructor(){this.name="PCMA"}decode(e){for(var t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Int16Array(t.length),o=0;o<t.length;o++)n[o]=this.alawToLinear(t[o]);return n.buffer}encode(e){for(var t=e instanceof Int16Array?e:new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=this.linearToAlaw(t[o]);return n}alawToLinear(e){var t=(e^=85)>>4&7,n=15&e;return(128&e?-1:1)*(0===t?8+(n<<4):264+(n<<4)<<t-1)}linearToAlaw(e){var t,n,o=e>>8&128;if(o&&(e=-e),e>32635&&(e=32635),e<256)t=0,n=e>>4;else{t=7;for(var i=16384;0===(e&i)&&t>0;t--,i>>=1);n=e>>t+3&15}return 85^(o|t<<4|n)}};function h(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function p(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){h(r,o,i,a,s,"next",e)}function s(e){h(r,o,i,a,s,"throw",e)}a(void 0)})}}const g=class extends c{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.config=e,this.audioContext=null,this.audioQueue=[],this.isPlaying=!1,this.isProcessingQueue=!1,this.currentSource=null,this.outputFormat=null,this.nextStartTime=0,this.scheduledBuffers=0,this.scheduledSources=new Set,this.pcmChunkQueue=[],this.preparedBuffer=[],this.isProcessingPcmQueue=!1,this.isSchedulingFrames=!1,this.MAX_LOOKAHEAD_SECONDS=.02,this.pendingSentenceText=null,this.sentenceTimings=[],this.isCheckingTranscripts=!1,this.codecs={pcm:new l,pcmu:new d,pcma:new u},this.SUPPORTED_CONTAINERS=["wav","raw"],this.SUPPORTED_ENCODINGS=["pcm","pcmu","pcma"],this.SUPPORTED_SAMPLE_RATES=[8e3,16e3,22050,24e3,44100,48e3],this.SUPPORTED_BIT_DEPTHS=[8,16,24],this.SUPPORTED_CHANNELS=[1],console.log("đĩ AudioPlayer v2 initialized")}setOutputFormat(e){var t;this.validateFormat(e)||(console.warn("â ī¸ AudioPlayer: Invalid format, using defaults:",e),e=this.getDefaultFormat());var n=null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate,o=e.sampleRate;this.outputFormat=e,console.log("â
AudioPlayer v2: Format set:",e),this.audioContext&&n&&n!==o&&(console.warn("â ī¸ AudioPlayer: Sample rate changed, recreating AudioContext"),console.warn(" Old: ".concat(n,"Hz â New: ").concat(o,"Hz")),this.stopImmediate(),"closed"!==this.audioContext.state&&this.audioContext.close(),this.audioContext=null,console.log("âšī¸ AudioContext will be recreated on next audio chunk with correct sample rate")),this.audioContext||(this.initializeAudioContext(),this.audioContext&&"suspended"===this.audioContext.state&&this.audioContext.resume().then(()=>{console.log("â
AudioPlayer v2: AudioContext resumed and ready")}).catch(e=>{console.warn("â ī¸ AudioPlayer v2: Could not resume AudioContext:",e)}))}validateFormat(e){var t,n;if(!e)return!1;var o=null===(t=e.container)||void 0===t?void 0:t.toLowerCase(),i=null===(n=e.encoding)||void 0===n?void 0:n.toLowerCase();return o&&i&&this.SUPPORTED_CONTAINERS.includes(o)&&this.SUPPORTED_ENCODINGS.includes(i)&&this.SUPPORTED_SAMPLE_RATES.includes(e.sampleRate)&&this.SUPPORTED_BIT_DEPTHS.includes(e.bitDepth)&&(!e.channels||this.SUPPORTED_CHANNELS.includes(e.channels))}getDefaultFormat(){return{container:"raw",encoding:"pcm",sampleRate:16e3,channels:1,bitDepth:16}}playAudio(e){try{var t=this.createAudioBlob(e);this.audioQueue.push(t),this.isPlaying||this.isProcessingQueue||this.currentSource||setTimeout(()=>this.processQueue(),50)}catch(e){console.error("â AudioPlayer v2: Playback error:",e),this.emit("playbackError",e)}}playChunk(e){var t=this;return p(function*(){var n,o=t.prepareChunk(e);o?(t.preparedBuffer.push(o),t.isSchedulingFrames?setTimeout(()=>{t.preparedBuffer.length>0&&!t.isSchedulingFrames&&t.schedulePreparedFrames()},5):t.schedulePreparedFrames(),t.pcmChunkQueue.length>0&&!t.isProcessingPcmQueue&&t.processPcmQueue()):(console.error("â AudioPlayer: playChunk failed - prepareChunk returned null"),console.error(" pcmData length:",(null==e?void 0:e.byteLength)||"undefined"),console.error(" outputFormat:",t.outputFormat),console.error(" audioContext:",t.audioContext?"initialized":"not initialized"),console.error(" audioContext state:",(null===(n=t.audioContext)||void 0===n?void 0:n.state)||"N/A"),t.emit("playbackError",new Error("Failed to prepare PCM chunk for playback")))})()}prepareChunk(e){try{var t;if(!this.outputFormat)return console.error("â AudioPlayer: Cannot prepare chunk - outputFormat not set"),console.error(" Call setOutputFormat() before playing audio chunks"),null;if(this.audioContext||this.initializeAudioContext(),!this.audioContext)return console.error("â AudioPlayer: Cannot prepare chunk - AudioContext not available"),null;var n=e;if(e.byteLength%2!=0){console.warn("â ī¸ Odd PCM chunk size, padding:",e.byteLength);var o=new Uint8Array(e.byteLength+1);o.set(new Uint8Array(e),0),o[e.byteLength]=0,n=o.buffer}for(var i=new Int16Array(n),r=new Float32Array(i.length),a=1/32768,s=i.length,c=0;c<s;c++)r[c]=i[c]*a;var l=(null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate)||this.audioContext.sampleRate,d=this.audioContext.sampleRate,u=this.audioContext.createBuffer(1,r.length,l);u.getChannelData(0).set(r);var h=u.duration,p=r.length,g=h;return d!==l&&(g=p/d),{buffer:u,duration:g,sampleRate:l,contextSampleRate:d}}catch(e){return console.error("â AudioPlayer: Error preparing chunk:",e),null}}applyFadeOut(e){return e}schedulePreparedFrames(){var e=this;return p(function*(){if(!e.isSchedulingFrames){e.isSchedulingFrames=!0;var t=e.preparedBuffer.length,n=Math.min(t,5);0===n&&t>0&&(n=1);try{e.audioContext||e.initializeAudioContext();var o=0===e.scheduledBuffers&&!e.isPlaying;"suspended"===e.audioContext.state&&(yield e.audioContext.resume(),o&&(yield new Promise(e=>setTimeout(e,50)))),"running"!==e.audioContext.state&&(console.warn("AudioPlayer v2: AudioContext not in running state:",e.audioContext.state),"suspended"===e.audioContext.state&&(yield e.audioContext.resume(),o?yield new Promise(e=>setTimeout(e,50)):yield new Promise(e=>setTimeout(e,10))));for(var i=0,r=function*(){var t=e.preparedBuffer.shift();if(!t)return 1;var n=e.audioContext.createBufferSource();n.buffer=t.buffer,n.connect(e.audioContext.destination),e.scheduledSources.add(n);var o=e.audioContext.currentTime;if(0===e.scheduledBuffers)e.nextStartTime<o&&(e.nextStartTime=o+e.MAX_LOOKAHEAD_SECONDS),console.log("đĩ Starting playback with minimal delay:",e.nextStartTime);else{var r=o+e.MAX_LOOKAHEAD_SECONDS;e.nextStartTime<r&&(e.nextStartTime=r,console.warn("â ī¸ AudioPlayer: Fell behind schedule, adjusting nextStartTime to ".concat(e.nextStartTime.toFixed(4),"s")))}e.pendingSentenceText&&(e.sentenceTimings.push({startTime:e.nextStartTime,text:e.pendingSentenceText,displayed:!1}),console.log("đ AudioPlayer: Sentence scheduled at ".concat(e.nextStartTime.toFixed(3),'s: "').concat(e.pendingSentenceText.substring(0,40),'..."')),e.pendingSentenceText=null,e.isCheckingTranscripts||e.startTranscriptChecker()),n.start(e.nextStartTime),e.nextStartTime+=t.duration,e.nextStartTime=Math.round(1e6*e.nextStartTime)/1e6;var a=e.nextStartTime-t.duration;e.scheduledBuffers<5&&(console.log("đĩ AudioPlayer: Scheduled frame ".concat(e.scheduledBuffers+1," at ").concat(a.toFixed(4),"s, next at ").concat(e.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(t.duration.toFixed(4),"s (").concat((1e3*t.duration).toFixed(2),"ms), Queued: ").concat(e.preparedBuffer.length,", Scheduled: ").concat(e.scheduledBuffers))),e.scheduledBuffers++,i++,n.onended=()=>{if(e.scheduledSources.delete(n),e.scheduledBuffers--,0===e.scheduledBuffers&&0===e.preparedBuffer.length&&0===e.pcmChunkQueue.length)e.isPlaying=!1,e.isSchedulingFrames=!1,console.log("đ AudioPlayer: Emitting playbackStopped event (all buffers finished)"),e.emit("playbackStopped");else if(e.preparedBuffer.length>0)setTimeout(()=>{e.preparedBuffer.length>0&&!e.isSchedulingFrames&&e.schedulePreparedFrames()},0);else if(e.scheduledBuffers>0){var t=()=>{e.preparedBuffer.length>0&&!e.isSchedulingFrames&&e.scheduledBuffers>0?e.schedulePreparedFrames():e.scheduledBuffers>0&&setTimeout(t,10)};setTimeout(t,10)}},e.isPlaying||(e.isPlaying=!0,console.log("đĩ AudioPlayer: Emitting playbackStarted event"),e.emit("playbackStarted"))};e.preparedBuffer.length>0&&i<n&&!(yield*r()););e.isSchedulingFrames=!1,e.preparedBuffer.length>0&&requestAnimationFrame(()=>{e.preparedBuffer.length>0&&!e.isSchedulingFrames&&e.schedulePreparedFrames()}),e.scheduledBuffers>0&&setTimeout(()=>{e.preparedBuffer.length>0&&!e.isSchedulingFrames&&e.scheduledBuffers>0?e.schedulePreparedFrames():e.scheduledBuffers>0&&setTimeout(()=>{e.preparedBuffer.length>0&&!e.isSchedulingFrames&&e.scheduledBuffers>0&&e.schedulePreparedFrames()},10)},10)}catch(t){console.error("â AudioPlayer v2: Error scheduling frames:",t),e.emit("playbackError",t),e.isSchedulingFrames=!1}}})()}processPcmQueue(){var e=this;return p(function*(){if(!e.isProcessingPcmQueue){e.isProcessingPcmQueue=!0;try{e.audioContext||e.initializeAudioContext();var t=0===e.scheduledBuffers&&!e.isPlaying;for("suspended"===e.audioContext.state&&(yield e.audioContext.resume(),t&&(yield new Promise(e=>setTimeout(e,50)))),"running"!==e.audioContext.state&&(console.warn("AudioPlayer v2: AudioContext not in running state:",e.audioContext.state),"suspended"===e.audioContext.state&&(yield e.audioContext.resume(),t?yield new Promise(e=>setTimeout(e,50)):yield new Promise(e=>setTimeout(e,10))));e.pcmChunkQueue.length>0;){var n,o,i=e.pcmChunkQueue.shift();if(i){var r=i;if(i.byteLength%2!=0){console.warn("â ī¸ Odd PCM chunk size, padding:",i.byteLength);var a=new Uint8Array(i.byteLength+1);a.set(new Uint8Array(i),0),a[i.byteLength]=0,r=a.buffer}for(var s=new Int16Array(r),c=new Float32Array(s.length),l=1/32768,d=s.length,u=0;u<d;u++)c[u]=s[u]*l;var h=(null===(n=e.outputFormat)||void 0===n?void 0:n.sampleRate)||e.audioContext.sampleRate,p=e.audioContext.sampleRate;null!==(o=e.outputFormat)&&void 0!==o&&o.sampleRate?e.scheduledBuffers<3&&console.log("đĩ AudioPlayer: Creating buffer at ".concat(h,"Hz (AudioContext: ").concat(p,"Hz)")):console.warn("â ī¸ AudioPlayer: outputFormat.sampleRate not set! Using AudioContext sample rate:",p);var g=e.audioContext.createBuffer(1,c.length,h);g.getChannelData(0).set(c);var m=e.audioContext.createBufferSource();m.buffer=g,m.connect(e.audioContext.destination);var v=e.audioContext.currentTime;e.nextStartTime<v&&(e.nextStartTime=v,0===e.scheduledBuffers&&console.log("đĩ Starting playback at current time:",v));var f=g.duration,y=c.length,x=f;if(p!==h&&(x=y/p,e.scheduledBuffers<3&&(console.log("đ Resampling detected: ".concat(h,"Hz â ").concat(p,"Hz")),console.log(" Buffer duration: ".concat(f.toFixed(4),"s, Calculated: ").concat(x.toFixed(4),"s")))),m.start(e.nextStartTime),e.nextStartTime+=x,e.nextStartTime=Math.round(1e6*e.nextStartTime)/1e6,e.scheduledBuffers<3){var b=e.nextStartTime-x;console.log("đĩ AudioPlayer: Scheduled chunk ".concat(e.scheduledBuffers+1," at ").concat(b.toFixed(4),"s, next at ").concat(e.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(x.toFixed(4),"s (").concat((1e3*x).toFixed(2),"ms)"))}e.scheduledBuffers++,m.onended=()=>{e.scheduledBuffers--,0===e.scheduledBuffers&&0===e.pcmChunkQueue.length&&(e.isPlaying=!1,e.isProcessingPcmQueue=!1,e.emit("playbackStopped"))},e.isPlaying||(e.isPlaying=!0,e.emit("playbackStarted"))}}e.isProcessingPcmQueue=!1}catch(t){console.error("â AudioPlayer v2: Error playing chunk:",t),e.emit("playbackError",t),e.isProcessingPcmQueue=!1}}})()}createAudioBlob(e){var t=new Uint8Array(e);console.log("đĩ AudioPlayer: Processing ".concat(t.length," bytes")),console.log("đĩ AudioPlayer: Negotiated format:",this.outputFormat);var n=this.outputFormat&&this.outputFormat.container&&"wav"===this.outputFormat.container.toLowerCase(),o=this.outputFormat&&this.outputFormat.container&&"raw"===this.outputFormat.container.toLowerCase(),i=this.isWavFile(t);if(i&&console.log("đĩ AudioPlayer: Data has WAV header (RIFF)"),o&&i)return console.error("â AudioPlayer: CRITICAL MISMATCH!"),console.error(" Negotiated format: RAW"),console.error(" Actual data: WAV (RIFF header detected)"),console.error(" Backend is ignoring format request and sending WAV anyway."),console.warn("â ī¸ AudioPlayer: Processing as WAV to avoid playback failure, but UI configuration was bypassed."),this.handleWavFile(t);if(o&&!i)console.log("đĩ AudioPlayer: Processing as RAW data (as negotiated)");else{if(n&&i)return console.log("â
AudioPlayer: Processing as WAV file (matches negotiation)"),this.handleWavFile(t);if(n&&!i)return console.warn("â ī¸ AudioPlayer: Negotiated WAV but data lacks WAV header. Attempting WAV processing anyway."),this.handleWavFile(t);if(!this.outputFormat&&i)return console.log("đĩ AudioPlayer: No format negotiated, auto-detecting WAV"),this.handleWavFile(t);this.outputFormat||i||(console.warn("â ī¸ AudioPlayer: No format negotiated and data not WAV, using defaults"),this.outputFormat=this.getDefaultFormat())}return this.outputFormat||(console.warn("â ī¸ AudioPlayer: No format set, using defaults"),this.outputFormat=this.getDefaultFormat()),console.log("đĩ AudioPlayer: Processing as RAW data with encoding:",this.outputFormat.encoding),this.handleRawData(t)}isWavFile(e){return e.length>=44&&82===e[0]&&73===e[1]&&70===e[2]&&70===e[3]}handleWavFile(e){var t=this.parseWavHeader(e);if(console.log("đĩ WAV file detected:",{format:t.audioFormat,encoding:this.getEncodingName(t.audioFormat),sampleRate:t.sampleRate,channels:t.channels,bitDepth:t.bitsPerSample}),1===t.audioFormat)return console.log("â
PCM WAV - using directly"),new Blob([e],{type:"audio/wav"});var n=this.getCodecForWavFormat(t.audioFormat);if(!n)throw new Error("Unsupported WAV format code: ".concat(t.audioFormat));console.log("đ Non-PCM WAV - converting to PCM WAV");var o=e.slice(44),i=n.decode(o),r=this.createWavHeader(i.byteLength,t.sampleRate,t.channels,16);return new Blob([r,i],{type:"audio/wav"})}handleRawData(e){var t,n,o=this.outputFormat.encoding.toLowerCase(),i=this.getCodec(o);if(!i)throw new Error("No codec found for encoding: ".concat(o));if(console.log("đĩ AudioPlayer: Decoding ".concat(o.toUpperCase()," to PCM")),console.log("đĩ AudioPlayer: Input format - bitDepth: ".concat(this.outputFormat.bitDepth,", sampleRate: ").concat(this.outputFormat.sampleRate)),"pcm"===o){var r=this.outputFormat.bitDepth||16;e.length,24===r?(console.warn("â ī¸ AudioPlayer: Format says 24-bit PCM, but browser support is limited."),console.warn(" Treating as 16-bit PCM. If audio sounds wrong, backend should send 16-bit instead."),t=this.convert24BitTo16Bit(e),n=16):8===r?(console.log("đ AudioPlayer: Converting 8-bit PCM to 16-bit PCM"),t=this.convert8BitTo16Bit(e),n=16):(t=e.buffer,n=r,console.log("â
AudioPlayer: Using native ".concat(r,"-bit PCM (no conversion needed)")))}else t=i.decode(e),n=16,console.log("đ AudioPlayer: Decoded ".concat(o.toUpperCase()," to 16-bit PCM"));var a=this.createWavHeader(t.byteLength,this.outputFormat.sampleRate,this.outputFormat.channels,n);return new Blob([a,t],{type:"audio/wav"})}convert24BitTo16Bit(e){for(var t=Math.floor(e.length/3),n=new Int16Array(t),o=0;o<t;o++){var i=e[3*o],r=e[3*o+1],a=e[3*o+2],s=i|r<<8|(255&a)<<16;128&a&&(s|=4278190080),n[o]=Math.max(-32768,Math.min(32767,Math.round(s/256)))}return n.buffer}convert8BitTo16Bit(e){for(var t=e.length,n=new Int16Array(t),o=0;o<t;o++){var i=e[o];n[o]=256*(i-128)}return n.buffer}getCodec(e){var t={pcm:"pcm",linear:"pcm",l16:"pcm",pcmu:"pcmu",ulaw:"pcmu",mulaw:"pcmu",g711u:"pcmu",pcma:"pcma",alaw:"pcma",g711a:"pcma"}[e.toLowerCase()];return this.codecs[t]}getCodecForWavFormat(e){switch(e){case 1:return this.codecs.pcm;case 6:return this.codecs.pcma;case 7:return this.codecs.pcmu;default:return null}}getEncodingName(e){switch(e){case 1:return"PCM";case 6:return"A-law";case 7:return"Îŧ-law";default:return"Unknown (".concat(e,")")}}parseWavHeader(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);return{audioFormat:t.getUint16(20,!0),channels:t.getUint16(22,!0),sampleRate:t.getUint32(24,!0),byteRate:t.getUint32(28,!0),blockAlign:t.getUint16(32,!0),bitsPerSample:t.getUint16(34,!0)}}createWavHeader(e,t,n,o){var i=new ArrayBuffer(44),r=new DataView(i);return r.setUint32(0,1380533830,!1),r.setUint32(4,36+e,!0),r.setUint32(8,1463899717,!1),r.setUint32(12,1718449184,!1),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,n,!0),r.setUint32(24,t,!0),r.setUint32(28,t*n*o/8,!0),r.setUint16(32,n*o/8,!0),r.setUint16(34,o,!0),r.setUint32(36,1684108385,!1),r.setUint32(40,e,!0),i}initializeAudioContext(){var e,t,n=(null===(e=this.outputFormat)||void 0===e?void 0:e.sampleRate)||44100;if(48e3!==n&&44100!==n&&(console.log("âšī¸ AudioPlayer: Backend requested ".concat(n,"Hz, but browser may resample")),console.log(" Consider requesting 44100Hz or 48000Hz from backend to avoid resampling and improve quality")),this.audioContext){var o=this.audioContext.sampleRate;if(!(Math.abs(o-n)>100))return;console.warn("â ī¸ AudioPlayer: AudioContext sample rate (".concat(o,"Hz) doesn't match format (").concat(n,"Hz), recreating...")),this.stopImmediate(),"closed"!==this.audioContext.state&&this.audioContext.close(),this.audioContext=null}console.log("đĩ AudioPlayer: Creating AudioContext at ".concat(n,"Hz (from outputFormat: ").concat((null===(t=this.outputFormat)||void 0===t?void 0:t.sampleRate)||"not set",")"));try{this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:n,latencyHint:"playback"}),console.log("â
AudioContext created at ".concat(this.audioContext.sampleRate,"Hz (requested: ").concat(n,"Hz)")),Math.abs(this.audioContext.sampleRate-n)>100?(console.error("â CRITICAL: Browser sample rate mismatch!"),console.error(" Requested: ".concat(n,"Hz")),console.error(" Got: ".concat(this.audioContext.sampleRate,"Hz")),console.error(" This WILL cause audio distortion/noise!"),console.error(" Solution: Backend should send ".concat(this.audioContext.sampleRate,"Hz audio instead"))):this.audioContext.sampleRate!==n&&(console.warn("â ī¸ Browser adjusted sample rate: ".concat(n,"Hz â ").concat(this.audioContext.sampleRate,"Hz")),console.warn(" Browser will automatically resample audio."))}catch(e){console.error("â Failed to create AudioContext:",e),this.audioContext=new(window.AudioContext||window.webkitAudioContext),console.log("âšī¸ Using browser default: ".concat(this.audioContext.sampleRate,"Hz"))}}processQueue(){var e=this;return p(function*(){if(!e.isProcessingQueue&&0!==e.audioQueue.length){e.isProcessingQueue=!0;var t=e.audioQueue.shift();if(t)try{var n=!e.isPlaying&&null===e.currentSource;e.audioContext||e.initializeAudioContext();var o=e.audioContext;"suspended"===o.state&&(yield o.resume(),n&&(yield new Promise(e=>setTimeout(e,50)))),"running"!==o.state&&(console.warn("AudioPlayer v2: AudioContext not in running state:",o.state),"suspended"===o.state&&(yield o.resume(),n?yield new Promise(e=>setTimeout(e,50)):yield new Promise(e=>setTimeout(e,10))));var i=yield t.arrayBuffer(),r=yield o.decodeAudioData(i),a=n&&!e.isPlaying&&null===e.currentSource,s=o.createBufferSource();s.buffer=r,s.connect(o.destination),e.currentSource=s,e.isPlaying=!0,a&&e.emit("playbackStarted"),s.onended=()=>{e.currentSource=null,e.isProcessingQueue=!1,e.audioQueue.length>0?setTimeout(()=>e.processQueue(),50):setTimeout(()=>{0!==e.audioQueue.length||e.currentSource||(e.isPlaying=!1,e.emit("playbackStopped"))},100)},s.start()}catch(t){console.error("â AudioPlayer v2: Error processing queue:",t),e.currentSource=null,e.emit("playbackError",t),e.audioQueue.length>0?(e.isProcessingQueue=!1,setTimeout(()=>e.processQueue(),100)):(e.isPlaying=!1,e.isProcessingQueue=!1,e.emit("playbackStopped"))}else e.isProcessingQueue=!1}})()}stop(){this.stopImmediate()}reset(){this.stop(),this.audioQueue=[],this.pcmChunkQueue=[]}stopImmediate(){var e=this.isPlaying||null!==this.currentSource||this.scheduledSources.size>0;if(console.log("đ AudioPlayer.stopImmediate() called"),console.log(" isPlaying:",this.isPlaying),console.log(" currentSource:",null!==this.currentSource),console.log(" scheduledSources.size:",this.scheduledSources.size),console.log(" scheduledBuffers:",this.scheduledBuffers),this.currentSource){try{console.log(" Stopping currentSource..."),this.currentSource.stop()}catch(e){console.log(" currentSource already stopped or error:",e.message)}this.currentSource=null}if(this.scheduledSources.size>0){console.log(" Stopping ".concat(this.scheduledSources.size," scheduled sources..."));var t=0;for(var n of this.scheduledSources)try{n.stop(),t++}catch(e){console.log(" Source already stopped or not started:",e.message)}console.log(" Stopped ".concat(t," sources")),this.scheduledSources.clear()}this.isPlaying=!1,this.isProcessingQueue=!1,this.audioQueue=[],this.pcmChunkQueue=[],this.preparedBuffer=[],this.isProcessingPcmQueue=!1,this.isSchedulingFrames=!1,this.nextStartTime=0,this.scheduledBuffers=0,this.clearTranscriptState(),e&&(console.log("đ AudioPlayer: Emitting playbackStopped event (stopImmediate called)"),this.emit("playbackStopped"))}markNewSentence(e){this.pendingSentenceText=e,console.log('đ AudioPlayer: New sentence marked: "'.concat(e.substring(0,40),'..."'))}startTranscriptChecker(){if(!this.isCheckingTranscripts){this.isCheckingTranscripts=!0,console.log("đ AudioPlayer: Transcript checker started");var e=()=>{if(this.isCheckingTranscripts&&this.audioContext){var t=this.audioContext.currentTime;for(var n of this.sentenceTimings)!n.displayed&&t>=n.startTime&&(n.displayed=!0,console.log("đ AudioPlayer: Display transcript at ".concat(t.toFixed(3),'s: "').concat(n.text.substring(0,40),'..."')),this.emit("transcriptDisplay",{text:n.text}));this.isPlaying||this.scheduledBuffers>0?requestAnimationFrame(e):(this.isCheckingTranscripts=!1,console.log("đ AudioPlayer: Transcript checker stopped"))}};requestAnimationFrame(e)}}clearTranscriptState(){this.pendingSentenceText=null,this.sentenceTimings=[],this.isCheckingTranscripts=!1,console.log("đ AudioPlayer: Transcript state cleared")}resumeAudioContext(){var e=this;return p(function*(){if(e.audioContext&&"closed"!==e.audioContext.state){if("suspended"===e.audioContext.state)try{yield e.audioContext.resume(),console.log("â
AudioPlayer v2: AudioContext resumed after mic permission")}catch(e){console.warn("â ī¸ AudioPlayer v2: Failed to resume AudioContext:",e)}}else yield e.initializeAudioContext()})()}getStatus(){return{isPlaying:this.isPlaying,isProcessingQueue:this.isProcessingQueue,queueLength:this.audioQueue.length,audioContextState:this.audioContext?this.audioContext.state:"closed",outputFormat:this.outputFormat,scheduledBuffers:this.scheduledBuffers,preparedBufferLength:this.preparedBuffer.length,scheduledSourcesCount:this.scheduledSources.size}}destroy(){this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.removeAllListeners()}};function m(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function v(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){m(r,o,i,a,s,"next",e)}function s(e){m(r,o,i,a,s,"throw",e)}a(void 0)})}}class f extends c{constructor(e){super(),this.config=e,this.audioContext=null,this.audioWorkletNode=null,this.mediaStream=null,this.isRecording=!1}getAudioProcessorPath(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var e=document.getElementsByTagName("script");for(var t of e){var n=t.src;if(n&&(n.includes("agent-widget.js")||n.includes("ttp-agent-sdk")))try{var o=n.substring(0,n.lastIndexOf("/"));return"".concat(o,"/audio-processor.js")}catch(e){var i=n.substring(0,n.lastIndexOf("/"));return"".concat(i,"/audio-processor.js")}}return"https://cdn.talktopc.com/audio-processor.js"}start(){var e=this;return v(function*(){try{if("https:"!==location.protocol&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname){var t=new Error("Microphone access requires HTTPS. Please use https:// or test on localhost.");throw console.error("â AudioRecorder:",t.message),e.emit("error",t),t}if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){var n=new Error("getUserMedia is not supported in this browser. Please use a modern browser.");throw console.error("â AudioRecorder:",n.message),e.emit("error",n),n}console.log("đ¤ AudioRecorder: Requesting microphone access..."),e.mediaStream=yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:e.config.sampleRate,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),console.log("â
AudioRecorder: Microphone access granted"),e.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:e.config.sampleRate}),"suspended"===e.audioContext.state&&(yield e.audioContext.resume());var o=e.getAudioProcessorPath();yield e.audioContext.audioWorklet.addModule(o),e.audioWorkletNode=new AudioWorkletNode(e.audioContext,"audio-processor"),e.audioContext.createMediaStreamSource(e.mediaStream).connect(e.audioWorkletNode),e.audioWorkletNode.port.onmessage=t=>{var{type:n,data:o}=t.data;"pcm_audio_data"===n&&e.emit("audioData",o)},e.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),e.isRecording=!0,e.emit("recordingStarted")}catch(t){var i=t.message;"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?(i="Microphone permission denied. Please allow microphone access in your browser settings and try again.",console.error("â AudioRecorder: Permission denied. User needs to grant microphone access.")):"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?(i="No microphone found. Please connect a microphone and try again.",console.error("â AudioRecorder: No microphone device found.")):"NotReadableError"===t.name||"TrackStartError"===t.name?(i="Microphone is already in use by another application. Please close other apps using the microphone and try again.",console.error("â AudioRecorder: Microphone is busy or not readable.")):t.message&&t.message.includes("not allowed by the user agent")&&(i="Microphone access blocked. On mobile devices, please tap the recording button directly (not from an iframe or popup).",console.error("â AudioRecorder: User agent blocked microphone access. This often happens on mobile when not called from direct user interaction."));var r=new Error(i);throw r.name=t.name,r.originalError=t,console.error("â AudioRecorder: Failed to start recording:",r),e.emit("error",r),r}})()}stop(){var e=this;return v(function*(){if(e.isRecording)try{e.audioWorkletNode&&(e.audioWorkletNode.port.postMessage({type:"flush"}),yield new Promise(e=>setTimeout(e,100))),e.mediaStream&&(e.mediaStream.getTracks().forEach(e=>e.stop()),e.mediaStream=null),e.audioContext&&"closed"!==e.audioContext.state&&(yield e.audioContext.close(),e.audioContext=null),e.audioWorkletNode=null,e.isRecording=!1,e.emit("recordingStopped")}catch(t){throw e.emit("error",t),t}})()}getStatus(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}destroy(){this.stop()}}class y{static extractPcmFromWav(e){var t=e instanceof Uint8Array?e:new Uint8Array(e);if(t.length<44)throw new Error("WAV data too short (< 44 bytes)");if("RIFF"!==String.fromCharCode(t[0],t[1],t[2],t[3]))throw new Error("Not a valid WAV file - missing RIFF header");if("WAVE"!==String.fromCharCode(t[8],t[9],t[10],t[11]))throw new Error("Not a valid WAV file - missing WAVE format");for(var n=t[22]|t[23]<<8,o=t[24]|t[25]<<8|t[26]<<16|t[27]<<24,i=t[34]|t[35]<<8,r=-1,a=12;a<t.length-8;a+=4){if("data"===String.fromCharCode(t[a],t[a+1],t[a+2],t[a+3])){r=a;break}a+=4+(t[a+4]|t[a+5]<<8|t[a+6]<<16|t[a+7]<<24)}if(-1===r)throw new Error("No data chunk found in WAV");var s=t[r+4]|t[r+5]<<8|t[r+6]<<16|t[r+7]<<24,c=r+8,l=Math.min(s,t.length-c);return{pcmData:t.slice(c,c+l).buffer,format:{sampleRate:o,channels:n,bitDepth:i}}}static isWavFile(e){return e.length>=44&&82===e[0]&&73===e[1]&&70===e[2]&&70===e[3]}static createWavHeader(e,t,n,o){var i=new ArrayBuffer(44),r=new DataView(i);return r.setUint32(0,1380533830,!1),r.setUint32(4,36+e,!0),r.setUint32(8,1463899717,!1),r.setUint32(12,1718449184,!1),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,n,!0),r.setUint32(24,t,!0),r.setUint32(28,t*n*o/8,!0),r.setUint16(32,n*o/8,!0),r.setUint16(34,o,!0),r.setUint32(36,1684108385,!1),r.setUint32(40,e,!0),i}static wrapPcmInWav(e,t){var n=y.createWavHeader(e.byteLength,t.sampleRate,t.channels||1,t.bitDepth||16),o=new Uint8Array(n.byteLength+e.byteLength);return o.set(new Uint8Array(n),0),o.set(new Uint8Array(e),n.byteLength),o.buffer}}const x=y,b=class{constructor(){this.codecs={pcm:new l,pcmu:new d,pcma:new u}}decodeToPcm(e,t){var n=null==t?void 0:t.toLowerCase();if(!n||"pcm"===n)return e instanceof ArrayBuffer?e:e instanceof Uint8Array?e.buffer:e;var o=this.codecs[n];if(!o)throw new Error("Unsupported encoding: ".concat(t));var i=e instanceof Uint8Array?e:new Uint8Array(e);return o.decode(i)}encodeFromPcm(e,t){var n=null==t?void 0:t.toLowerCase();if(!n||"pcm"===n)return e;var o=this.codecs[n];if(!o)throw new Error("Unsupported target encoding: ".concat(t));var i=o.encode(e);return i instanceof Uint8Array?i.buffer:i}getCodec(e){var t=null==e?void 0:e.toLowerCase();return this.codecs[t]||null}};class w{static convert(e,t,n){if(t===n)return e;if(8===t)throw new Error("Source bit depth cannot be 8-bit (only 16-bit or 24-bit supported)");var o=t/8,i=n/8,r=e.byteLength/o;if(new ArrayBuffer(r*i),16===t&&16===n)return e;if(24===t&&16===n)return w.convert24To16(e);if(16===t&&24===n)return w.convert16To24(e);if(16===t&&8===n)return w.convert16To8(e);if(24===t&&8===n)return w.convert24To8(e);throw new Error("Unsupported bit depth conversion: ".concat(t,"-bit â ").concat(n,"-bit"))}static convert24To16(e){for(var t=new Uint8Array(e),n=Math.floor(t.length/3),o=new Int16Array(n),i=0;i<n;i++){var r=t[3*i],a=t[3*i+1],s=t[3*i+2],c=r|a<<8|(255&s)<<16;128&s&&(c|=4278190080),o[i]=Math.max(-32768,Math.min(32767,Math.round(c/256)))}return o.buffer}static convert16To24(e){for(var t=new Int16Array(e),n=new Uint8Array(3*t.length),o=0;o<t.length;o++){var i=256*t[o];n[3*o]=255&i,n[3*o+1]=i>>8&255,n[3*o+2]=i>>16&255}return n.buffer}static convert16To8(e){for(var t=new Int16Array(e),n=new Uint8Array(t.length),o=0;o<t.length;o++){var i=t[o];n[o]=Math.max(0,Math.min(255,Math.round(i/256+128)))}return n.buffer}static convert24To8(e){var t=w.convert24To16(e);return w.convert16To8(t)}}const S=w;function C(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}const k=class{static resample(e,t,n){return(o=function*(){if(t===n)return e;for(var o=new Int16Array(e),i=new Float32Array(o.length),r=1/32768,a=0;a<o.length;a++)i[a]=o[a]*r;var s=Math.ceil(i.length*n/t),c=new OfflineAudioContext(1,s,n),l=c.createBuffer(1,i.length,t);l.getChannelData(0).set(i);var d=c.createBufferSource();d.buffer=l,d.connect(c.destination),d.start();for(var u=(yield c.startRendering()).getChannelData(0),h=new Int16Array(u.length),p=0;p<u.length;p++){var g=Math.max(-1,Math.min(1,u[p]));h[p]=Math.round(32767*g)}return h.buffer},function(){var e=this,t=arguments;return new Promise(function(n,i){var r=o.apply(e,t);function a(e){C(r,n,i,a,s,"next",e)}function s(e){C(r,n,i,a,s,"throw",e)}a(void 0)})})();var o}};class P{static convert(e,t,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:16;if(t===n)return e;if(1===t&&1===n)return e;if(1===t&&2===n)return P.monoToStereo(e,o);if(2===t&&1===n)return P.stereoToMono(e,o);throw new Error("Unsupported channel conversion: ".concat(t," â ").concat(n))}static monoToStereo(e,t){for(var n=t/8,o=e.byteLength/n,i=new ArrayBuffer(o*n*2),r=new Uint8Array(e),a=new Uint8Array(i),s=0;s<o;s++)for(var c=s*n,l=s*n*2,d=0;d<n;d++)a[l+d]=r[c+d],a[l+n+d]=r[c+d];return i}static stereoToMono(e,t){var n=t/8,o=e.byteLength/(2*n),i=new ArrayBuffer(o*n),r=new Uint8Array(e),a=new Uint8Array(i);if(16===t)for(var s=0;s<o;s++){var c=s*n*2,l=c+n,d=(r[c]|r[c+1]<<8)<<16>>16,u=(r[l]|r[l+1]<<8)<<16>>16,h=Math.round((d+u)/2),p=s*n;a[p]=255&h,a[p+1]=h>>8&255}else for(var g=0;g<o;g++)for(var m=g*n*2,v=g*n,f=0;f<n;f++)a[v+f]=r[m+f];return i}}const E=P;function T(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function I(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?T(Object(n),!0).forEach(function(t){A(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):T(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function A(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function R(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}const D=class{constructor(e,t){this.requestedFormat=e,this.actualFormat=t,this.encodingConverter=new b,this.conversionSteps=[],this._analyzeConversions()}_analyzeConversions(){this.conversionSteps=[],this.actualFormat.container!==this.requestedFormat.container&&("wav"===this.actualFormat.container?this.conversionSteps.push("extract_wav"):"wav"===this.requestedFormat.container&&this.conversionSteps.push("wrap_wav")),this.actualFormat.encoding!==this.requestedFormat.encoding&&("pcm"!==this.actualFormat.encoding&&this.conversionSteps.push("decode_encoding"),"pcm"!==this.requestedFormat.encoding&&this.conversionSteps.push("encode_encoding")),this.actualFormat.sampleRate!==this.requestedFormat.sampleRate&&this.conversionSteps.push("resample"),this.actualFormat.bitDepth!==this.requestedFormat.bitDepth&&this.conversionSteps.push("convert_bitdepth"),this.actualFormat.channels!==this.requestedFormat.channels&&this.conversionSteps.push("convert_channels")}needsConversion(){return this.conversionSteps.length>0}getConversionSteps(){var e=[];return this.conversionSteps.includes("extract_wav")&&e.push("Extract PCM from WAV (".concat(this.actualFormat.container," â raw)")),this.conversionSteps.includes("decode_encoding")&&e.push("Decode ".concat(this.actualFormat.encoding.toUpperCase()," â PCM")),this.conversionSteps.includes("resample")&&e.push("Resample ".concat(this.actualFormat.sampleRate,"Hz â ").concat(this.requestedFormat.sampleRate,"Hz")),this.conversionSteps.includes("convert_bitdepth")&&e.push("Convert bit depth ".concat(this.actualFormat.bitDepth,"-bit â ").concat(this.requestedFormat.bitDepth,"-bit")),this.conversionSteps.includes("convert_channels")&&e.push("Convert channels ".concat(this.actualFormat.channels," â ").concat(this.requestedFormat.channels)),this.conversionSteps.includes("encode_encoding")&&e.push("Encode PCM â ".concat(this.requestedFormat.encoding.toUpperCase())),this.conversionSteps.includes("wrap_wav")&&e.push("Wrap in WAV container (raw â ".concat(this.requestedFormat.container,")")),e}convert(e){var t,n=this;return(t=function*(){if(!n.needsConversion())return e instanceof ArrayBuffer?e:e.buffer;var t=e instanceof ArrayBuffer?e:e.buffer,o=I({},n.actualFormat);if(n.conversionSteps.includes("extract_wav")){var i=x.extractPcmFromWav(t);t=i.pcmData,o=I(I({},o),{},{container:"raw",sampleRate:i.format.sampleRate,channels:i.format.channels,bitDepth:i.format.bitDepth}),console.log("đ AudioFormatConverter: Extracted PCM from WAV",i.format)}if(n.conversionSteps.includes("decode_encoding")&&(t=n.encodingConverter.decodeToPcm(t,o.encoding),o.encoding="pcm",o.bitDepth=16,console.log("đ AudioFormatConverter: Decoded ".concat(n.actualFormat.encoding.toUpperCase()," â PCM"))),24===o.bitDepth&&o.bitDepth!==n.requestedFormat.bitDepth&&(n.conversionSteps.includes("resample")||n.conversionSteps.includes("convert_channels")||24!==n.requestedFormat.bitDepth)&&(t=S.convert(t,24,16),o.bitDepth=16,console.log("đ AudioFormatConverter: Normalized 24-bit â 16-bit PCM")),n.conversionSteps.includes("resample")&&(t=yield k.resample(t,o.sampleRate,n.requestedFormat.sampleRate),o.sampleRate=n.requestedFormat.sampleRate,console.log("đ AudioFormatConverter: Resampled ".concat(n.actualFormat.sampleRate,"Hz â ").concat(n.requestedFormat.sampleRate,"Hz"))),n.conversionSteps.includes("convert_channels")&&(t=E.convert(t,o.channels,n.requestedFormat.channels,o.bitDepth),o.channels=n.requestedFormat.channels,console.log("đ AudioFormatConverter: Converted channels ".concat(n.actualFormat.channels," â ").concat(n.requestedFormat.channels))),n.conversionSteps.includes("convert_bitdepth")&&(t=S.convert(t,o.bitDepth,n.requestedFormat.bitDepth),o.bitDepth=n.requestedFormat.bitDepth,console.log("đ AudioFormatConverter: Converted bit depth ".concat(n.actualFormat.bitDepth,"-bit â ").concat(n.requestedFormat.bitDepth,"-bit"))),n.conversionSteps.includes("encode_encoding")){var r=n.encodingConverter.encodeFromPcm(t,n.requestedFormat.encoding);t=r instanceof ArrayBuffer?r:r.buffer,o.encoding=n.requestedFormat.encoding,console.log("đ AudioFormatConverter: Encoded PCM â ".concat(n.requestedFormat.encoding.toUpperCase()))}return n.conversionSteps.includes("wrap_wav")&&(t=x.wrapPcmInWav(t,o),o.container="wav",console.log("đ AudioFormatConverter: Wrapped in WAV container")),console.log("â
AudioFormatConverter: Conversion complete"),t},function(){var e=this,n=arguments;return new Promise(function(o,i){var r=t.apply(e,n);function a(e){R(r,o,i,a,s,"next",e)}function s(e){R(r,o,i,a,s,"throw",e)}a(void 0)})})()}};function F(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}const B=class{constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:()=>null;this.handlers=new Map,this.sendMessage=e,this.getConversationId=t}registerHandler(e,t){if("function"!=typeof t)throw new Error("Handler for tool '".concat(e,"' must be a function"));this.handlers.set(e,t),console.log("đ§ ClientTools: Registered handler for '".concat(e,"'"))}unregisterHandler(e){this.handlers.delete(e),console.log("đ§ ClientTools: Unregistered handler for '".concat(e,"'"))}hasHandler(e){return this.handlers.has(e)}getRegisteredTools(){return Array.from(this.handlers.keys())}handleToolCall(e){var t,n=this;return(t=function*(){var{toolCallId:t,toolName:o,parameters:i}=e,r=Date.now(),a=(new Date).toISOString();console.log("đ§ ClientTools: [".concat(a,"] Received tool call '").concat(o,"' (id: ").concat(t,")")),console.log(" đ Full message received:",JSON.stringify(e,null,2)),console.log(" âąī¸ Start time: ".concat(r,"ms (").concat(new Date(r).toISOString(),")"));var s=n.handlers.get(o);if(!s)return console.warn("đ§ ClientTools: No handler registered for '".concat(o,"'")),void n.sendError(t,o,"No handler registered for tool '".concat(o,"'"),"NO_HANDLER",r);try{var c=yield s(i),l=Date.now()-r;console.log("đ§ ClientTools: Tool '".concat(o,"' completed in ").concat(l,"ms")),n.sendResult(t,o,c,l)}catch(e){var d,u,h=Date.now()-r;console.error("đ§ ClientTools: Tool '".concat(o,"' failed:"),e);var p="EXECUTION_ERROR";"NotAllowedError"===e.name||null!==(d=e.message)&&void 0!==d&&d.includes("permission")?p="PERMISSION_DENIED":("NotSupportedError"===e.name||null!==(u=e.message)&&void 0!==u&&u.includes("not supported"))&&(p="API_UNAVAILABLE"),n.sendError(t,o,e.message||"Unknown error",p,h)}},function(){var e=this,n=arguments;return new Promise(function(o,i){var r=t.apply(e,n);function a(e){F(r,o,i,a,s,"next",e)}function s(e){F(r,o,i,a,s,"throw",e)}a(void 0)})})()}sendResult(e,t,n,o){var i=this.getConversationId(),r=(new Date).toISOString(),a={t:"client_tool_result",toolCallId:e,toolName:t,conversationId:i,result:n,executionTimeMs:o};console.log("đ§ ClientTools: [".concat(r,"] Sending result for tool '").concat(t,"'")),console.log(" đ toolCallId: ".concat(e)),console.log(" đ conversationId: ".concat(i||"null")),console.log(" đ toolName: ".concat(t)),console.log(" đ result:",n),console.log(" đ Full message:",JSON.stringify(a,null,2)),this.sendMessage(a),console.log("â
ClientTools: Result message sent at ".concat(r))}sendError(e,t,n,o,i){var r="number"==typeof i?Date.now()-i:i,a=(new Date).toISOString(),s=this.getConversationId(),c={t:"client_tool_error",toolCallId:e,toolName:t,conversationId:s,error:n,errorCode:o,executionTimeMs:r};console.log("đ§ ClientTools: [".concat(a,"] Sending error for tool '").concat(t,"'")),console.log(" đ toolCallId: ".concat(e)),console.log(" đ conversationId: ".concat(s||"null")),console.log(" đ toolName: ".concat(t)),console.log(" đ error: ".concat(n,", errorCode: ").concat(o)),console.log(" đ Full message:",JSON.stringify(c,null,2)),this.sendMessage(c),console.log("â
ClientTools: Error message sent at ".concat(a))}setSendMessage(e){this.sendMessage=e}};function _(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function O(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?_(Object(n),!0).forEach(function(t){N(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function M(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function U(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){M(r,o,i,a,s,"next",e)}function s(e){M(r,o,i,a,s,"throw",e)}a(void 0)})}}function N(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class z extends c{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.version="2.0.0",this.config={signedUrl:e.signedUrl||e.websocketUrl||"wss://speech.talktopc.com/ws/conv",websocketUrl:e.signedUrl||e.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:e.agentId,appId:e.appId,sampleRate:e.sampleRate||16e3,channels:e.channels||1,bitDepth:e.bitDepth||16,audioProcessorPath:e.audioProcessorPath,outputContainer:e.outputContainer||this.getDefaultContainer(e),outputEncoding:e.outputEncoding||e.outputCodec||"pcm",outputSampleRate:e.outputSampleRate||16e3,outputChannels:e.outputChannels||1,outputBitDepth:e.outputBitDepth||16,outputFrameDurationMs:e.outputFrameDurationMs||600,outputCodec:e.outputCodec,agentSettingsOverride:e.agentSettingsOverride||null,variables:e.variables||null,autoReconnect:!1!==e.autoReconnect,protocolVersion:e.protocolVersion||2},this.isConnected=!1,this.hasEverConnected=!1,this.isRecording=!1,this.isPlaying=!1,this.isDestroyed=!1,this.outputAudioFormat=null,this.requestedOutputFormat=null,this.formatConverter=null,this.websocket=null,this.conversationId=null,this.transcriptQueue=[],this.currentPlayingSentenceId=null,this.audioFrameCount=0,this.audioPlayer=new g(this.config),this.audioRecorder=new f(this.config),this.setupAudioPlayerEvents(),this.setupAudioRecorderEvents(),this.clientToolsRegistry=new B(e=>this.sendMessage(e),()=>this.conversationId),this.validateConfig(),this._setupPageUnloadHandler(),console.log("đĩ VoiceSDK v2 initialized:",{version:this.version,outputContainer:this.config.outputContainer,outputEncoding:this.config.outputEncoding,outputSampleRate:this.config.outputSampleRate})}getStoredConversationId(){try{if("undefined"==typeof sessionStorage)return console.warn("â ī¸ VoiceSDK v2: sessionStorage not available (private mode?)"),null;var e=sessionStorage.getItem(z.RESUME_STORAGE_KEY);if(e){var t=JSON.parse(e);if(t&&t.conversationId)return console.log("đĻ VoiceSDK v2: Found stored conversationId:",t.conversationId),t.conversationId}return null}catch(e){return console.warn("â ī¸ VoiceSDK v2: Error reading sessionStorage:",e),null}}storeConversationId(e){if(e)try{if("undefined"==typeof sessionStorage)return void console.warn("â ī¸ VoiceSDK v2: sessionStorage not available (private mode?)");var t={},n=sessionStorage.getItem(z.RESUME_STORAGE_KEY);if(n)try{t=JSON.parse(n)}catch(e){}t.conversationId=e,t.timestamp=Date.now(),t.fromPage=t.fromPage||window.location.pathname+window.location.search,sessionStorage.setItem(z.RESUME_STORAGE_KEY,JSON.stringify(t)),console.log("đž VoiceSDK v2: Stored conversationId:",e)}catch(e){console.warn("â ī¸ VoiceSDK v2: Error writing to sessionStorage:",e)}}clearStoredConversationId(){try{if("undefined"==typeof sessionStorage)return;sessionStorage.removeItem(z.RESUME_STORAGE_KEY),console.log("đī¸ VoiceSDK v2: Cleared stored conversationId")}catch(e){console.warn("â ī¸ VoiceSDK v2: Error clearing sessionStorage:",e)}}_getResumeState(){try{if("undefined"==typeof sessionStorage)return null;var e=sessionStorage.getItem(z.RESUME_STORAGE_KEY);if(!e)return null;var t=JSON.parse(e),n=Date.now()-t.timestamp;return n>z.RESUME_TTL_MS?(console.log("[VoiceSDK] Resume state expired:",n,"ms"),this._clearResumeState(),null):(console.log("[VoiceSDK] Found valid resume state:",t,"age:",n,"ms"),t)}catch(e){return console.warn("[VoiceSDK] Failed to get resume state:",e),null}}_clearResumeState(){try{if("undefined"==typeof sessionStorage)return;sessionStorage.removeItem(z.RESUME_STORAGE_KEY)}catch(e){}}_setupPageUnloadHandler(){window.addEventListener("beforeunload",()=>{this.conversationId&&this.websocket&&this.websocket.readyState===WebSocket.OPEN&&this.storeConversationId(this.conversationId)}),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&this.conversationId&&this.websocket&&this.websocket.readyState===WebSocket.OPEN&&this.storeConversationId(this.conversationId)})}checkAndResume(){var e=this._getResumeState();if(!e)return null;var t=window.location.pathname+window.location.search;return console.log("[VoiceSDK] Auto-resuming conversation:",e.conversationId),console.log("[VoiceSDK] Page change:",e.fromPage,"â",t),this._clearResumeState(),{conversationId:e.conversationId,fromPage:e.fromPage,toPage:t}}getDefaultContainer(e){return"wav"===e.outputCodec?"wav":"raw"}validateInputFormat(e){var t;if(!e)return"Input format is required";var n=null===(t=e.encoding)||void 0===t?void 0:t.toLowerCase();return n&&z.SUPPORTED_INPUT_ENCODINGS.includes(n)?e.sampleRate&&z.SUPPORTED_INPUT_SAMPLE_RATES.includes(e.sampleRate)?e.bitDepth&&z.SUPPORTED_INPUT_BIT_DEPTHS.includes(e.bitDepth)?e.channels&&z.SUPPORTED_INPUT_CHANNELS.includes(e.channels)?null:"Unsupported input channels: ".concat(e.channels,". Supported: ").concat(z.SUPPORTED_INPUT_CHANNELS.join(", ")):"Unsupported input bit depth: ".concat(e.bitDepth,". Supported: ").concat(z.SUPPORTED_INPUT_BIT_DEPTHS.join(", ")):"Unsupported input sample rate: ".concat(e.sampleRate,". Supported: ").concat(z.SUPPORTED_INPUT_SAMPLE_RATES.join(", ")):"Unsupported input encoding: ".concat(e.encoding,". Supported: ").concat(z.SUPPORTED_INPUT_ENCODINGS.join(", "))}validateOutputFormat(e){var t,n;if(!e)return"Output format is required";var o=null===(t=e.encoding)||void 0===t?void 0:t.toLowerCase();if(!o||!z.SUPPORTED_OUTPUT_ENCODINGS.includes(o))return"Unsupported output encoding: ".concat(e.encoding,". Supported: ").concat(z.SUPPORTED_OUTPUT_ENCODINGS.join(", "));if(!e.sampleRate||!z.SUPPORTED_OUTPUT_SAMPLE_RATES.includes(e.sampleRate))return"Unsupported output sample rate: ".concat(e.sampleRate,". Supported: ").concat(z.SUPPORTED_OUTPUT_SAMPLE_RATES.join(", "));if(!e.bitDepth||!z.SUPPORTED_OUTPUT_BIT_DEPTHS.includes(e.bitDepth))return"Unsupported output bit depth: ".concat(e.bitDepth,". Supported: ").concat(z.SUPPORTED_OUTPUT_BIT_DEPTHS.join(", "));if(!e.channels||!z.SUPPORTED_OUTPUT_CHANNELS.includes(e.channels))return"Unsupported output channels: ".concat(e.channels,". Supported: ").concat(z.SUPPORTED_OUTPUT_CHANNELS.join(", "));var i=null===(n=e.container)||void 0===n?void 0:n.toLowerCase();return i&&z.SUPPORTED_OUTPUT_CONTAINERS.includes(i)?null:"Unsupported output container: ".concat(e.container,". Supported: ").concat(z.SUPPORTED_OUTPUT_CONTAINERS.join(", "))}validateConfig(){var e={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},t=this.validateInputFormat(e);if(t)return console.error("â VoiceSDK v2: Invalid input format:",t),void this.emit("error",new Error(t));var n={encoding:this.config.outputEncoding,sampleRate:this.config.outputSampleRate,channels:this.config.outputChannels,bitDepth:this.config.outputBitDepth,container:this.config.outputContainer},o=this.validateOutputFormat(n);if(o)return console.error("â VoiceSDK v2: Invalid output format:",o),void this.emit("error",new Error(o));console.log("â
VoiceSDK v2: Format validation passed")}setupAudioPlayerEvents(){this.audioPlayer.on("playbackStarted",()=>{this.isPlaying=!0,this.emit("playbackStarted"),this.isConnected?(console.log("đ¤ VoiceSDK v2: Sending audio_started_playing message to server"),this.sendMessage({t:"audio_started_playing"})):console.warn("â ī¸ VoiceSDK v2: Cannot send audio_started_playing - not connected")}),this.audioPlayer.on("transcriptDisplay",e=>{var t=this.currentPlayingSentenceId?this.currentPlayingSentenceId+1:1;this.currentPlayingSentenceId=t;var n={text:e.text,role:"assistant",sentenceId:t,final:!0,timestamp:Date.now()};console.log("đ VoiceSDK v2: Emitting synced transcriptDisplay from AudioPlayer:",n),this.emit("transcriptDisplay",n),this.emit("transcript",n)}),this.audioPlayer.on("playbackStopped",()=>{this.isPlaying=!1,this.emit("playbackStopped"),this.isConnected?(console.log("đ¤ VoiceSDK v2: Sending audio_stopped_playing message to server"),this.sendMessage({t:"audio_stopped_playing"})):console.warn("â ī¸ VoiceSDK v2: Cannot send audio_stopped_playing - not connected")}),this.audioPlayer.on("playbackError",e=>{this.emit("playbackError",e),this.emit("error",e)})}setupAudioRecorderEvents(){this.audioRecorder.on("recordingStarted",()=>{this.isRecording=!0,this.emit("recordingStarted")}),this.audioRecorder.on("recordingStopped",()=>{this.isRecording&&(this.isRecording=!1,this.emit("recordingStopped"),console.log("đ VoiceSDK v2: Recording stopped (from audioRecorder event)"))}),this.audioRecorder.on("audioData",e=>{this.isConnected&&this.sendBinary(e)}),this.audioRecorder.on("error",e=>{console.error("â AudioRecorder error:",e),this.emit("error",e)})}buildWebSocketUrl(){var e=this.config.signedUrl||this.config.websocketUrl,t=new URLSearchParams;this.config.agentId&&t.append("agentId",this.config.agentId),this.config.appId&&t.append("appId",this.config.appId);var n=this.getStoredConversationId();n&&(t.append("conversationId",n),console.log("đ VoiceSDK v2: Attempting resume via query param:",n));var o=window.location.pathname+window.location.search;if(o&&t.append("currentPage",o),t.toString()){var i=e.includes("?")?"&":"?";return"".concat(e).concat(i).concat(t.toString())}return e}connect(){var e=this;return U(function*(){if(e.isDestroyed)return console.warn("VoiceSDK v2: Cannot connect - SDK is destroyed"),!1;if(e.isConnected)return console.warn("VoiceSDK v2: Already connected"),!0;try{var t=e.buildWebSocketUrl();return console.log("đ VoiceSDK v2: Connecting to",t),yield new Promise((n,o)=>{e.websocket=new WebSocket(t),e.websocket.onopen=()=>{console.log("â
VoiceSDK v2: WebSocket connected"),e.isConnected=!0,e.hasEverConnected=!0,e.clientToolsRegistry&&e.clientToolsRegistry.setSendMessage(t=>e.sendMessage(t)),e.sendHelloMessage(),e.emit("connected"),n(!0)},e.websocket.onerror=e=>{console.error("â VoiceSDK v2: WebSocket error:",e),o(e)},e.websocket.onclose=t=>{console.log("đ VoiceSDK v2: WebSocket closed:",t.code,t.reason),e.isConnected=!1,e.isRecording&&e.stopRecording().catch(e=>console.error("Error stopping recording:",e)),e.emit("disconnected",t),e.config.autoReconnect&&!e.isDestroyed&&e.hasEverConnected?(console.log("đ VoiceSDK v2: Auto-reconnecting in 3s..."),setTimeout(()=>{e.isDestroyed||e.isConnected||e.connect()},3e3)):e.config.autoReconnect&&!e.hasEverConnected&&console.log("â ī¸ VoiceSDK v2: Initial connection failed. Auto-reconnect disabled to prevent retry loop.")},e.websocket.onmessage=t=>{e.handleMessage(t)}})}catch(t){return console.error("đ VoiceSDK v2: Connection failed:",t),e.emit("error",t),!1}})()}sendHelloMessage(){if(this.isConnected){var e={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},t={encoding:this.config.outputEncoding,sampleRate:this.config.outputSampleRate,channels:this.config.outputChannels,bitDepth:this.config.outputBitDepth,container:this.config.outputContainer},n=this.validateInputFormat(e);if(n)return console.error("â VoiceSDK v2: Cannot send hello - invalid input format:",n),void this.emit("error",new Error("Invalid input format: ".concat(n)));var o=this.validateOutputFormat(t);if(o)return console.error("â VoiceSDK v2: Cannot send hello - invalid output format:",o),void this.emit("error",new Error("Invalid output format: ".concat(o)));var i={t:"hello",v:this.config.protocolVersion,inputFormat:e,requestedOutputFormat:t,outputFrameDurationMs:this.config.outputFrameDurationMs};this.config.agentSettingsOverride&&(i.agentSettingsOverride=this.config.agentSettingsOverride),console.log("đ VoiceSDK v2: Checking variables:",{hasVariables:!!this.config.variables,variables:this.config.variables,keys:this.config.variables?Object.keys(this.config.variables):[]}),this.config.variables&&Object.keys(this.config.variables).length>0?(i.variables=this.config.variables,console.log("đ VoiceSDK v2: Including variables in hello:",Object.keys(this.config.variables))):console.log("â ī¸ VoiceSDK v2: Variables NOT included - condition failed"),console.log("đ¤ VoiceSDK v2: Sending hello:",{version:i.v,requestedFormat:i.requestedOutputFormat,variables:i.variables?Object.keys(i.variables):void 0}),console.log("đ¤ VoiceSDK v2: Requested output format:",{container:i.requestedOutputFormat.container,encoding:i.requestedOutputFormat.encoding,sampleRate:i.requestedOutputFormat.sampleRate,bitDepth:i.requestedOutputFormat.bitDepth}),console.log("đ¤ VoiceSDK v2: Full hello message being sent:",JSON.stringify(i,null,2));try{this.sendMessage(i)}catch(e){console.error("VoiceSDK v2: Failed to send hello:",e),this.emit("error",e)}}else console.warn("VoiceSDK v2: Cannot send hello - not connected")}handleMessage(e){if(e.data instanceof ArrayBuffer||e.data instanceof Blob)this.handleBinaryMessage(e.data);else try{var t=JSON.parse(e.data);switch("audio"!==t.t&&console.log("đĨ VoiceSDK v2: Received message type:",t.t,"Full message:",JSON.stringify(t).substring(0,200)),!this.conversationId&&t.conversationId&&(this.conversationId=t.conversationId,console.log("đ VoiceSDK v2: Captured conversationId from message:",this.conversationId),this.emit("conversationIdChanged",this.conversationId)),"audio"!==t.t&&console.log("đ¨ VoiceSDK v2: Received message type:",t.t,t),t.t){case"hello_ack":this.handleHelloAck(t);break;case"transcript":console.log("đ VoiceSDK v2: Processing transcript message:",t),this.handleTranscript(t);break;case"user_transcript":console.log("đ VoiceSDK v2: Received user_transcript:",t),this.emit("message",t);break;case"agent_response":if(console.log("đ VoiceSDK v2: Received agent_response:",t),(t.text||t.transcript)&&(console.log("đ VoiceSDK v2: agent_response contains transcript data:",t.text||t.transcript),t.sentenceId&&(t.text||t.transcript))){var n={t:"transcript",sentenceId:t.sentenceId,text:t.text||t.transcript,role:t.role||"assistant",final:!1!==t.final,timestamp:t.timestamp||Date.now()};console.log("đ VoiceSDK v2: Converting agent_response to transcript:",n),this.handleTranscript(n)}this.emit("message",t);break;case"error":this.emit("message",t);break;case"barge_in":this.emit("bargeIn",t),this.stopAudioPlayback();break;case"stop_playing":this.emit("stopPlaying",t),this.stopAudioPlayback();break;case"audio_start":console.log("đ VoiceSDK v2: Received audio_start with text:",t.text),t.text&&this.audioPlayer&&this.audioPlayer.markNewSentence(t.text),this.emit("message",t);break;case"client_tool_call":this.clientToolsRegistry.handleToolCall(t);break;case"hangup_ack":console.log("đ VoiceSDK v2: Hangup acknowledged by server"),this.websocket&&this.websocket.readyState===WebSocket.OPEN&&(this.websocket.close(1e3,"User hangup"),this.websocket=null),this.isConnected=!1,this.emit("hangupAcknowledged");break;default:if(console.log("VoiceSDK v2: Unknown message type:",t.t,"Full message:",JSON.stringify(t).substring(0,300)),(t.text||t.transcript||t.transcription)&&(console.log("đ VoiceSDK v2: Unknown message contains transcript-like data:",{text:t.text,transcript:t.transcript,transcription:t.transcription,sentenceId:t.sentenceId,role:t.role}),t.sentenceId&&(t.text||t.transcript||t.transcription))){var o={t:"transcript",sentenceId:t.sentenceId,text:t.text||t.transcript||t.transcription,role:t.role||"assistant",final:!1!==t.final,timestamp:t.timestamp||Date.now()};console.log("đ VoiceSDK v2: Attempting to process unknown message as transcript:",o),this.handleTranscript(o)}this.emit("message",t)}}catch(e){console.error("VoiceSDK v2: Error parsing message:",e)}}handleHelloAck(e){if(console.log("đĨ VoiceSDK v2: Received hello_ack:",{hasOutputFormat:!!e.outputAudioFormat,outputFormat:e.outputAudioFormat,hasConversationId:!!e.conversationId,messageType:e.t}),e.conversationId&&(this.conversationId=e.conversationId,console.log("đ VoiceSDK v2: Received conversationId:",this.conversationId),this.emit("conversationIdChanged",this.conversationId),this.storeConversationId(this.conversationId)),!0===e.resumed?(console.log("â
VoiceSDK v2: Conversation resumed successfully"),this.emit("callResumed",{conversationId:this.conversationId,timestamp:Date.now()})):!1===e.resumed&&e.resumeRejectedReason&&(console.warn("â ī¸ VoiceSDK v2: Resume rejected:",e.resumeRejectedReason),this.clearStoredConversationId(),this.emit("resumeRejected",{reason:e.resumeRejectedReason,conversationId:e.conversationId||null,timestamp:Date.now()})),e.outputAudioFormat){this.outputAudioFormat=e.outputAudioFormat,this.audioPlayer.setOutputFormat(e.outputAudioFormat),console.log("â
VoiceSDK v2: Format negotiated by server:",this.outputAudioFormat),this.requestedOutputFormat={container:this.config.outputContainer||"wav",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,bitDepth:this.config.outputBitDepth||16,channels:this.config.outputChannels||1};var t={container:this.outputAudioFormat.container||"unknown",encoding:this.outputAudioFormat.encoding||"unknown",sampleRate:this.outputAudioFormat.sampleRate||0,bitDepth:this.outputAudioFormat.bitDepth||0,channels:this.outputAudioFormat.channels||0},n=[];if(this.requestedOutputFormat.container!==t.container&&n.push('container: "'.concat(this.requestedOutputFormat.container,'" â "').concat(t.container,'"')),this.requestedOutputFormat.encoding!==t.encoding&&n.push('encoding: "'.concat(this.requestedOutputFormat.encoding,'" â "').concat(t.encoding,'"')),this.requestedOutputFormat.sampleRate!==t.sampleRate&&n.push("sampleRate: ".concat(this.requestedOutputFormat.sampleRate,"Hz â ").concat(t.sampleRate,"Hz")),this.requestedOutputFormat.bitDepth!==t.bitDepth&&n.push("bitDepth: ".concat(this.requestedOutputFormat.bitDepth,"-bit â ").concat(t.bitDepth,"-bit")),this.requestedOutputFormat.channels!==t.channels&&n.push("channels: ".concat(this.requestedOutputFormat.channels," â ").concat(t.channels)),n.length>0){console.warn("â ī¸ VoiceSDK v2: Format negotiation mismatch!"),console.warn(" Requested:",this.requestedOutputFormat),console.warn(" Negotiated:",t),console.warn(" Differences:",n.join(", "));try{if(this.formatConverter=new D(this.requestedOutputFormat,t),this.formatConverter.needsConversion()){var o=this.formatConverter.getConversionSteps();console.log("đ VoiceSDK v2: Format conversion enabled"),console.log(" Conversion steps:",o.join(", ")),console.log(" Audio will be automatically converted to requested format")}}catch(e){console.error("â VoiceSDK v2: Failed to create format converter:",e),console.warn(" Will use backend format without conversion"),this.formatConverter=null}}else console.log("â
VoiceSDK v2: Format perfectly matched!",t),this.formatConverter=null;this.emit("formatNegotiated",this.outputAudioFormat)}else{this.config.protocolVersion>=2?(console.warn("â ī¸ VoiceSDK v2: hello_ack received but no outputAudioFormat in response."),console.warn(" This may happen if:"),console.warn(" 1. Backend is not sending outputAudioFormat (check backend logs)"),console.warn(" 2. Hello message missing v2 fields (v, inputFormat, requestedOutputFormat)"),console.warn(" 3. Backend validation failed (check backend error logs)"),console.warn(" Using default format from config...")):console.log("â
VoiceSDK v2: Connected (v1 legacy mode)");var i={container:this.config.outputContainer||"wav",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,channels:this.config.outputChannels||1,bitDepth:this.config.outputBitDepth||16};this.outputAudioFormat=i,this.requestedOutputFormat=i,this.audioPlayer.setOutputFormat(i),this.formatConverter=null}}handleTranscript(e){if(e.sentenceId&&e.text){var t=e.sentenceId,n={text:e.text,role:e.role||"assistant",sentenceId:t,final:!1!==e.final,timestamp:e.timestamp||Date.now()};this.transcriptQueue.push(n),console.log("đ VoiceSDK v2: Received transcript for sentence",t,":",n.text),console.log(" Transcript queue length:",this.transcriptQueue.length),console.log(" Current playing sentence:",this.currentPlayingSentenceId),console.log("đ VoiceSDK v2: Displaying transcript for completed sentence",t),this.emit("transcriptDisplay",n),this.currentPlayingSentenceId=t,this.emit("transcript",n)}else console.warn("â ī¸ VoiceSDK v2: Invalid transcript message:",e)}handleBinaryMessage(e){var t=this;return U(function*(){var n,o=n=e instanceof Blob?yield e.arrayBuffer():e;if(t.formatConverter&&t.formatConverter.needsConversion())try{o=yield t.formatConverter.convert(n),console.log("â
VoiceSDK v2: Audio converted to requested format")}catch(e){console.error("â VoiceSDK v2: Format conversion failed:",e),console.warn(" Using backend format without conversion"),o=n}var i=t.formatConverter&&t.formatConverter.needsConversion()?t.requestedOutputFormat:t.outputAudioFormat||{container:t.config.outputContainer||"raw",encoding:t.config.outputEncoding||"pcm",sampleRate:t.config.outputSampleRate||16e3,bitDepth:t.config.outputBitDepth||16,channels:t.config.outputChannels||1},r=i.container||"raw",a=(i.encoding||"pcm").toLowerCase();if("raw"===r){var s=o;if("pcm"!==a){var c=t.audioPlayer.getCodec(a);if(c){var l=c.decode(new Uint8Array(o));s=l.buffer,console.log("đ VoiceSDK v2: Decoded ".concat(a.toUpperCase()," to PCM (").concat(l.byteLength," bytes)"))}else console.warn("â ī¸ VoiceSDK v2: No codec for ".concat(a,", treating as PCM"))}t.audioPlayer.outputFormat||(console.warn("â ī¸ VoiceSDK v2: outputFormat not set on AudioPlayer, setting from playbackFormat"),t.audioPlayer.setOutputFormat(i)),t.audioFrameCount++,t.audioPlayer.playChunk(s)}else t.audioFrameCount++,t.audioPlayer.playAudio(o)})()}sendMessage(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send message - not connected"),!1;try{var t=(new Date).toISOString(),n=this.websocket?this.websocket.readyState:"NO_WEBSOCKET",o=this.websocket?{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[n]:"NO_WEBSOCKET";if("client_tool_result"!==e.t&&"client_tool_error"!==e.t||(console.log("đ¤ VoiceSDK v2: [".concat(t,"] Sending tool ").concat(e.t)),console.log(" đ WebSocket state: ".concat(o," (").concat(n,")")),console.log(" đ toolCallId: ".concat(e.toolCallId)),console.log(" đ conversationId: ".concat(e.conversationId||"null")),console.log(" đ toolName: ".concat(e.toolName)),"client_tool_result"===e.t?console.log(" đ result:",e.result):console.log(" đ error: ".concat(e.error,", errorCode: ").concat(e.errorCode)),console.log(" đ Full message:",JSON.stringify(e,null,2))),!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.error("â VoiceSDK v2: Cannot send message - WebSocket not open (state: ".concat(o,")")),!1;var i=JSON.stringify(e);return this.websocket.send(i),"client_tool_result"!==e.t&&"client_tool_error"!==e.t||console.log("â
VoiceSDK v2: [".concat(t,"] Tool ").concat(e.t," message sent successfully (").concat(i.length," bytes)")),!0}catch(e){return console.error("VoiceSDK v2: Error sending message:",e),this.emit("error",e),!1}}sendBinary(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send audio - not connected"),!1;try{return this.websocket.send(e),!0}catch(e){return console.error("VoiceSDK v2: Error sending audio:",e),this.emit("error",e),!1}}hangup(){if(this.websocket&&this.websocket.readyState===WebSocket.OPEN){console.log("đ VoiceSDK v2: Hanging up call..."),this.clearStoredConversationId(),this.stopRecording(),this.audioPlayer&&this.stopAudioPlayback();try{this.sendMessage({t:"hangup"}),setTimeout(()=>{this.websocket&&this.websocket.readyState===WebSocket.OPEN&&(this.websocket.close(1e3,"User hangup"),this.websocket=null),this.isConnected=!1},100)}catch(e){console.error("VoiceSDK v2: Error sending hangup message:",e),this.websocket&&(this.websocket.close(1e3,"User hangup"),this.websocket=null),this.isConnected=!1}}else console.warn("đ VoiceSDK v2: Cannot hangup - WebSocket not open")}startRecording(){var e=this;return U(function*(){if(!e.isConnected){var t=new Error("Not connected to voice server");throw e.emit("error",t),t}if(e.isRecording)return console.warn("VoiceSDK v2: Already recording"),!0;console.log("đ¤ VoiceSDK v2: Starting recording...");try{return console.log("đ¤ VoiceSDK v2: Requesting microphone permission (mobile-friendly)..."),yield e.audioRecorder.start(),yield e.audioPlayer.resumeAudioContext(),e.sendMessage({t:"start_continuous_mode",ttpId:e.generateTtpId()}),!0}catch(t){if(console.error("â VoiceSDK v2: Failed to start recording:",t),"NotAllowedError"===t.name||"PermissionDeniedError"===t.name){var n=new Error("Microphone permission denied. Please allow microphone access in your browser settings and try again.");n.name=t.name,n.originalError=t,e.emit("error",n)}else e.emit("error",t);return!1}})()}stopRecording(){var e=this;return U(function*(){if(!e.isRecording)return console.warn("VoiceSDK v2: Not recording"),!0;console.log("đ VoiceSDK v2: Stopping recording...");try{return e.sendMessage({t:"stop_continuous_mode",ttpId:e.generateTtpId()}),e.isRecording=!1,e.emit("recordingStopped"),console.log("đ VoiceSDK v2: Recording stopped (emitted before audioRecorder.stop())"),yield e.audioRecorder.stop(),e.stopAudioPlayback(),!0}catch(t){return console.error("VoiceSDK v2: Error stopping recording:",t),e.emit("error",t),!1}})()}toggleRecording(){var e=this;return U(function*(){return e.isRecording?yield e.stopRecording():yield e.startRecording()})()}clearTranscriptState(){this.currentPlayingSentenceId=null,console.log("đ VoiceSDK v2: Cleared transcript state")}stopAudioPlayback(){this.audioPlayer.stopImmediate(),this.clearTranscriptState()}handleBargeIn(){var e=this;return U(function*(){e.stopAudioPlayback(),e.isRecording||(yield e.startRecording())})()}getStatus(){return{version:this.version,isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying,outputFormat:this.outputAudioFormat,conversationId:this.conversationId,audioPlayer:this.audioPlayer.getStatus(),audioRecorder:this.audioRecorder.getStatus()}}updateConfig(e){this.config=O(O({},this.config),e)}generateTtpId(){return"sdk_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}registerToolHandler(e,t){return this.clientToolsRegistry.registerHandler(e,t)}unregisterToolHandler(e){return this.clientToolsRegistry.unregisterHandler(e)}hasToolHandler(e){return this.clientToolsRegistry.hasHandler(e)}getRegisteredTools(){return this.clientToolsRegistry.getRegisteredTools()}destroy(){this.isDestroyed||(console.log("đī¸ VoiceSDK v2: Destroying..."),this.isDestroyed=!0,this.isRecording&&this.stopRecording(),this.audioPlayer&&this.stopAudioPlayback(),this.websocket&&(this.websocket.close(),this.websocket=null),this.isConnected=!1,this.audioPlayer&&this.audioPlayer.destroy(),this.audioRecorder&&this.audioRecorder.destroy(),this.clientToolsRegistry&&this.clientToolsRegistry.getRegisteredTools().forEach(e=>this.clientToolsRegistry.unregisterHandler(e)),this.removeAllListeners())}}N(z,"RESUME_STORAGE_KEY","voice_resume_state"),N(z,"RESUME_TTL_MS",1e4),N(z,"SUPPORTED_INPUT_ENCODINGS",["pcm","pcmu","pcma"]),N(z,"SUPPORTED_INPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),N(z,"SUPPORTED_INPUT_BIT_DEPTHS",[8,16,24]),N(z,"SUPPORTED_INPUT_CHANNELS",[1]),N(z,"SUPPORTED_OUTPUT_ENCODINGS",["pcm","pcmu","pcma"]),N(z,"SUPPORTED_OUTPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),N(z,"SUPPORTED_OUTPUT_BIT_DEPTHS",[8,16,24]),N(z,"SUPPORTED_OUTPUT_CHANNELS",[1]),N(z,"SUPPORTED_OUTPUT_CONTAINERS",["raw","wav"]);const H=z;class L{constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(e=>e!==t))}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];this.events[e]&&this.events[e].forEach(t=>{try{t(...n)}catch(t){console.error("Error in event listener for ".concat(e,":"),t)}})}removeAllListeners(e){e?delete this.events[e]:this.events={}}}function K(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function V(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function j(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?V(Object(n),!0).forEach(function(t){W(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):V(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function W(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class q extends L{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super();var t=this.readScriptTagConfig();this.config=j({baseWsUrl:"wss://backend.talktopc.com/chat/websocket",appId:e.appId||t.appId,agentId:e.agentId||t.agentId,conversationId:void 0!==e.conversationId?e.conversationId:this.getPersistedConversationId(),forceConversationId:e.forceConversationId,queue:[],inFlight:!1},e),this.fullResponseBuffer=""}readScriptTagConfig(){try{var e=Array.from(document.getElementsByTagName("script")).reverse().find(e=>e.dataset&&(e.dataset.appId||e.dataset.agentId)||e.src&&e.src.includes("agent-widget"));return e?{appId:e.dataset.appId,agentId:e.dataset.agentId}:{}}catch(e){return{}}}buildWebSocketUrl(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.config.baseWsUrl,t=new URLSearchParams;return this.config.appId&&t.append("appId",this.config.appId),this.config.agentId&&t.append("agentId",this.config.agentId),this.config.conversationId&&t.append("conversationId",this.config.conversationId),"".concat(e,"?").concat(t.toString())}sendMessage(e){var t,n=this;return(t=function*(){return new Promise((t,o)=>{if(e&&e.trim())if(n.config.appId&&n.config.agentId){var i={text:e,resolve:t,reject:o};n.config.inFlight?n.config.queue.push(i):n.executeTask(i)}else o(new Error("Missing appId or agentId"));else o(new Error("Message is empty"))})},function(){var e=this,n=arguments;return new Promise(function(o,i){var r=t.apply(e,n);function a(e){K(r,o,i,a,s,"next",e)}function s(e){K(r,o,i,a,s,"throw",e)}a(void 0)})})()}executeTask(e){if(this.config.inFlight=!0,this.fullResponseBuffer="",!this.config.conversationId){var t=this.getPersistedConversationId();t&&(this.config.conversationId=t,console.log("đ TextChatSDK hydrated conversationId from storage:",t))}var n=this.buildWebSocketUrl(this.config.baseWsUrl),o=this.config.baseWsUrl.endsWith("/websocket")?this.config.baseWsUrl.replace(/\/websocket$/,""):"".concat(this.config.baseWsUrl,"/websocket"),i=this.buildWebSocketUrl(o),r=!1,a=!1,s=null,c=t=>{if(!a)try{var n={message:e.text},o=this.config.forceConversationId||this.config.conversationId;o&&(n.conversationId=o,this.config.forceConversationId&&!this.config.conversationId&&(this.config.conversationId=o,this.persistConversationId(o))),console.log("đ TextChatSDK sending payload:",n,"conversationId in config:",this.config.conversationId),t.send(JSON.stringify(n)),a=!0}catch(n){e.reject(n),this.emit("error",n);try{t.close()}catch(e){}}},l=e=>()=>{this.config.conversationId?c(e):s=setTimeout(()=>c(e),200)},d=t=>n=>{try{try{console.log("đ [TextChatSDK] WS <= raw:",n.data)}catch(e){}var o=JSON.parse(n.data);try{console.log("đ [TextChatSDK] WS <= parsed:",o)}catch(e){}if("hello"===o.type&&o.conversationId){if(console.log("đ TextChatSDK received conversationId:",o.conversationId),this.config.conversationId=o.conversationId,this.persistConversationId(o.conversationId),this.emit&&this.emit("conversationIdChanged",o.conversationId),!a&&t&&1===t.readyState){if(s)try{clearTimeout(s)}catch(e){}c(t)}return}if(!this.config.conversationId&&o.conversationId&&(console.log("đ TextChatSDK captured conversationId from message:",o.conversationId),this.config.conversationId=o.conversationId,this.persistConversationId(o.conversationId)),"chunk"===o.type&&"string"==typeof o.content)this.fullResponseBuffer+=o.content,this.emit("chunk",o.content);else if("done"===o.type){try{var i=o.text||o.content||o.answer||o.message||"";i&&!this.fullResponseBuffer&&(this.fullResponseBuffer=i)}catch(e){}!this.config.conversationId&&o.conversationId&&(console.log("đ TextChatSDK captured conversationId from done:",o.conversationId),this.config.conversationId=o.conversationId),this.persistConversationId(this.config.conversationId),this.emit("done",{text:this.fullResponseBuffer}),e.resolve({conversationId:this.config.conversationId,fullText:this.fullResponseBuffer});try{t.close()}catch(e){}}else if("error"===o.type){var r=new Error(o.message||"Server error");this.emit("error",r),e.reject(r);try{t.close()}catch(e){}}}catch(e){}},u=t=>{if(1008===t.code&&t.reason&&(t.reason.includes("Domain not whitelisted")||t.reason.includes("domain")||t.reason.includes("whitelist"))){var n=new Error("DOMAIN_NOT_WHITELISTED");return n.reason=t.reason,n.code=t.code,this.emit("domainError",n),e.reject(n),this.config.inFlight=!1,void this.drainQueue()}this.config.inFlight=!1,this.drainQueue()},h=new WebSocket(n);h.onopen=l(h),h.onmessage=d(h),h.onerror=(t=>n=>{if(!r){r=!0;try{t.close()}catch(e){}var o=new WebSocket(i);return o.onopen=l(o),o.onmessage=d(o),o.onerror=t=>{this.emit("error",t),e.reject(t)},void(o.onclose=u)}this.emit("error",n),e.reject(n)})(h),h.onclose=u}drainQueue(){if(0!==this.config.queue.length&&!this.config.inFlight){var e=this.config.queue.shift();this.executeTask(e)}}persistConversationId(e){try{e&&localStorage.setItem("ttp_text_chat_conversation_id",e)}catch(e){}}getPersistedConversationId(){try{return localStorage.getItem("ttp_text_chat_conversation_id")||null}catch(e){return null}}updateConfig(e){this.config=j(j({},this.config),e)}destroy(){this.config.queue=[],this.config.inFlight=!1,this.removeAllListeners()}}function Q(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}const G=new class extends L{constructor(){super(),this.connections=new Map,this.connectionCounts=new Map,this.creatingConnections=new Set}getConnection(e){var t,n=this;return(t=function*(){if(n.connections.has(e)){var t=n.connections.get(e);return n.connectionCounts.set(e,(n.connectionCounts.get(e)||0)+1),t}if(n.creatingConnections&&n.creatingConnections.has(e))return new Promise(t=>{var o=()=>{if(n.connections.has(e)){var i=n.connections.get(e);n.connectionCounts.set(e,(n.connectionCounts.get(e)||0)+1),t(i)}else setTimeout(o,50)};o()});n.creatingConnections.add(e);var o=new WebSocket(e);return n.connections.set(e,o),n.connectionCounts.set(e,1),o.addEventListener("open",t=>{n.creatingConnections.delete(e),n.emit("open",t,e)}),o.addEventListener("close",t=>{n.creatingConnections.delete(e),n.connections.delete(e),n.connectionCounts.delete(e),n.emit("close",t,e)}),o.addEventListener("error",t=>{n.creatingConnections.delete(e),n.emit("error",t,e)}),o.addEventListener("message",t=>{n.emit("message",t,e)}),o},function(){var e=this,n=arguments;return new Promise(function(o,i){var r=t.apply(e,n);function a(e){Q(r,o,i,a,s,"next",e)}function s(e){Q(r,o,i,a,s,"throw",e)}a(void 0)})})()}releaseConnection(e){if(this.connections.has(e)){var t=this.connectionCounts.get(e)||0,n=Math.max(0,t-1);if(this.connectionCounts.set(e,n),0===n){var o=this.connections.get(e);o&&o.readyState===WebSocket.OPEN&&o.close(1e3,"No more subscribers"),this.connections.delete(e),this.connectionCounts.delete(e)}}}forceClose(e){if(this.connections.has(e)){var t=this.connections.get(e);t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Force close"),this.connections.delete(e),this.connectionCounts.delete(e)}}getConnectionStatus(e){return this.connections.has(e)?{exists:!0,readyState:this.connections.get(e).readyState,subscribers:this.connectionCounts.get(e)||0}:{exists:!1,readyState:null,subscribers:0}}getAllConnections(){var e={};for(var[t,n]of this.connections.entries())e[t]={readyState:n.readyState,subscribers:this.connectionCounts.get(t)||0};return e}clearAll(){for(var[e,t]of this.connections.entries())t&&t.readyState===WebSocket.OPEN&&t.close(1e3,"Clear all");this.connections.clear(),this.connectionCounts.clear(),this.creatingConnections.clear()}};function Y(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}class J extends L{constructor(e){super(),this.config=e,this.ws=null,this.isConnected=!1,this.connectionId=null}connect(){var e,t=this;return(e=function*(){return new Promise((e,n)=>{try{t.connectionId=Date.now()+"_"+Math.random().toString(36).substr(2,9),t.connectResolve=e,t.connectReject=n;var o=t.config.signedUrl||t.config.websocketUrl;G.getConnection(o,t.config).then(n=>{t.ws=n,t.setupEventListeners(),n.readyState===WebSocket.OPEN&&(t.isConnected=!0,t.emit("connected"),e(),t.connectResolve=null,t.connectReject=null)}).catch(e=>{console.error("đ WebSocketManager: Connection failed ".concat(t.connectionId),e),n(e),t.connectResolve=null,t.connectReject=null})}catch(e){console.error("đ WebSocketManager: Connection error ".concat(t.connectionId),e),n(e),t.connectResolve=null,t.connectReject=null}})},function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){Y(r,o,i,a,s,"next",e)}function s(e){Y(r,o,i,a,s,"throw",e)}a(void 0)})})()}setupEventListeners(){if(this.ws){var e=(e,t)=>{t===(this.config.signedUrl||this.config.websocketUrl)&&(this.isConnected=!0,this.emit("connected"),this.connectResolve&&(this.connectResolve(),this.connectResolve=null,this.connectReject=null))},t=(e,t)=>{t===(this.config.signedUrl||this.config.websocketUrl)&&(this.isConnected=!1,this.emit("disconnected",e))},n=(e,t)=>{t===(this.config.signedUrl||this.config.websocketUrl)&&(this.emit("error",e),this.connectReject&&(this.connectReject(e),this.connectResolve=null,this.connectReject=null))},o=(e,t)=>{t===(this.config.signedUrl||this.config.websocketUrl)&&this.handleMessage(e)};G.on("open",e),G.on("close",t),G.on("error",n),G.on("message",o),this.eventHandlers={open:e,close:t,error:n,message:o}}}disconnect(){this.eventHandlers&&(G.off("open",this.eventHandlers.open),G.off("close",this.eventHandlers.close),G.off("error",this.eventHandlers.error),G.off("message",this.eventHandlers.message));var e=this.config.signedUrl||this.config.websocketUrl;e&&G.releaseConnection(e),this.ws=null,this.isConnected=!1}sendMessage(e){if(this.isConnected&&this.ws)try{this.ws.send(JSON.stringify(e))}catch(e){console.warn("đ WebSocketManager: Failed to send message:",e.message)}}sendBinary(e){if(this.isConnected&&this.ws)try{this.ws.send(e)}catch(e){console.warn("đ WebSocketManager: Failed to send binary data:",e.message)}}handleMessage(e){if(e.data instanceof ArrayBuffer)this.emit("binaryAudio",e.data);else if(e.data instanceof Blob)e.data.arrayBuffer().then(e=>{this.emit("binaryAudio",e)}).catch(e=>{console.error("đ WebSocketManager: Error converting Blob to ArrayBuffer:",e)});else try{var t=JSON.parse(e.data);"barge_in_ack"!==t.t&&"stop_sending"!==t.t||this.emit("bargeIn",t),"stop_playing"===t.t&&this.emit("stopPlaying",t),this.emit("message",t)}catch(e){this.emit("error",e)}}getStatus(){return{isConnected:this.isConnected,readyState:this.ws?this.ws.readyState:null,connectionId:this.connectionId}}static getSingletonStatus(){return G.getAllConnections()}static clearAllConnections(){G.clearAll()}}function $(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function X(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){$(r,o,i,a,s,"next",e)}function s(e){$(r,o,i,a,s,"throw",e)}a(void 0)})}}class Z extends L{constructor(e){super(),this.config=e,this.audioContext=null,this.audioWorkletNode=null,this.mediaStream=null,this.isRecording=!1}getAudioProcessorPath(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var e=document.getElementsByTagName("script");for(var t of e){var n=t.src;if(n&&(n.includes("agent-widget.js")||n.includes("ttp-agent-sdk")))try{new URL(n);var o=n.substring(0,n.lastIndexOf("/"));return"".concat(o,"/audio-processor.js")}catch(e){var i=n.substring(0,n.lastIndexOf("/"));return"".concat(i,"/audio-processor.js")}}return"https://cdn.talktopc.com/audio-processor.js"}checkPermissionState(){return X(function*(){try{if(navigator.permissions&&navigator.permissions.query)return(yield navigator.permissions.query({name:"microphone"})).state}catch(e){console.log("â ī¸ AudioRecorder: Permissions API not available or not supported for microphone")}return null})()}requestPermission(){var e=this;return X(function*(){try{if("granted"===(yield e.checkPermissionState()))return console.log("â
AudioRecorder: Microphone permission already granted"),!0;console.log("đ¤ AudioRecorder: Requesting microphone permission...");var t=e.config.sampleRate||e.config.outputSampleRate||44100;return(yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:t,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})).getTracks().forEach(e=>e.stop()),console.log("â
AudioRecorder: Microphone permission granted"),!0}catch(e){return console.error("â AudioRecorder: Failed to get microphone permission:",e),!1}})()}start(){var e=this;return X(function*(){try{console.log("đ¤ AudioRecorder: Requesting microphone access...");var t=yield e.checkPermissionState();t&&(console.log("đ AudioRecorder: Current permission state: ".concat(t)),"denied"===t&&console.warn('â ī¸ AudioRecorder: Permission state is "denied" - browser may not show prompt. User may need to change in browser settings.'));var n=e.config.sampleRate||e.config.outputSampleRate||44100;e.mediaStream=yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:n,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),e.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:n}),"suspended"===e.audioContext.state&&(yield e.audioContext.resume());var o=e.getAudioProcessorPath();yield e.audioContext.audioWorklet.addModule(o),e.audioWorkletNode=new AudioWorkletNode(e.audioContext,"audio-processor",{processorOptions:{sampleRate:n,outputSampleRate:e.config.outputSampleRate}}),e.audioContext.createMediaStreamSource(e.mediaStream).connect(e.audioWorkletNode),e.audioWorkletNode.port.onmessage=t=>{var{type:n,data:o}=t.data;"pcm_audio_data"===n&&e.emit("audioData",o)},e.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),console.log("â
AudioRecorder: Microphone access granted"),e.isRecording=!0,e.emit("recordingStarted")}catch(t){var i=t.message;if("NotAllowedError"===t.name||"PermissionDeniedError"===t.name){var r=yield e.checkPermissionState();"denied"===r?(i='Microphone access was blocked. To enable it: 1) Click the lock icon (đ) in your browser\'s address bar, 2) Find "Microphone" and change it to "Allow", 3) Refresh this page and try again.',console.error("â AudioRecorder: Permission explicitly denied. User must change in browser settings.")):"prompt"===r?(i='Microphone permission was denied. Click the "Voice Call" button again to see the permission prompt.',console.error('â AudioRecorder: Permission denied but state is "prompt" - user can try again.')):(i="Microphone permission was denied. Click the button again to retry, or enable microphone access in your browser settings (lock icon đ in address bar).",console.error("â AudioRecorder: Permission denied. User can try again or change in browser settings."))}else"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?(i="No microphone found. Please connect a microphone and try again.",console.error("â AudioRecorder: No microphone device found.")):"NotReadableError"===t.name||"TrackStartError"===t.name?(i="Microphone is already in use by another application. Please close other apps using the microphone and try again.",console.error("â AudioRecorder: Microphone is busy or not readable.")):"SecurityError"!==t.name&&"PermissionDeniedError"!==t.name||(i="Microphone access blocked. On mobile devices, please tap the recording button directly (not from an iframe or popup).",console.error("â AudioRecorder: User agent blocked microphone access. This often happens on mobile when not called from direct user interaction."));var a=new Error(i);throw a.name=t.name,a.originalError=t,e.emit("error",a),a}})()}stop(){var e=this;return X(function*(){if(e.isRecording)try{e.audioWorkletNode&&(e.audioWorkletNode.port.postMessage({type:"flush"}),yield new Promise(e=>setTimeout(e,100))),e.mediaStream&&(e.mediaStream.getTracks().forEach(e=>e.stop()),e.mediaStream=null),e.audioContext&&"closed"!==e.audioContext.state&&(yield e.audioContext.close(),e.audioContext=null),e.audioWorkletNode=null,e.isRecording=!1,e.emit("recordingStopped")}catch(t){throw e.emit("error",t),t}})()}getStatus(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}destroy(){this.stop()}}function ee(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function te(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){ee(r,o,i,a,s,"next",e)}function s(e){ee(r,o,i,a,s,"throw",e)}a(void 0)})}}class ne extends L{constructor(e){super(),this.config=e,this.audioContext=null,this.audioQueue=[],this.isPlaying=!1,this.isProcessingQueue=!1,this.currentSource=null,this.audioContextReady=!1,this.initializeAudioContext().catch(()=>{})}initializeAudioContext(){var e=this;return te(function*(){if(!e.audioContext||"closed"===e.audioContext.state)try{var t={sampleRate:e.config.sampleRate||e.config.outputSampleRate||44100};if(e.audioContext=new(window.AudioContext||window.webkitAudioContext)(t),"suspended"===e.audioContext.state&&(yield e.audioContext.resume()),"running"===e.audioContext.state)try{var n=e.audioContext.sampleRate,o=e.audioContext.createBuffer(1,.01*n,n),i=e.audioContext.createBufferSource();i.buffer=o,i.connect(e.audioContext.destination),i.start(0),i.stop(e.audioContext.currentTime+.01)}catch(e){console.debug("AudioPlayer: AudioContext warmup skipped:",e)}e.audioContextReady=!0}catch(t){console.warn("AudioPlayer: Failed to pre-initialize AudioContext:",t),e.audioContextReady=!1}})()}playAudio(e){try{var t=this.createAudioBlob(e);if(this.audioQueue.push(t),!this.isPlaying&&!this.isProcessingQueue&&!this.currentSource){var n=this.audioContextReady?0:50;setTimeout(()=>this.processQueue(),n)}}catch(e){this.emit("playbackError",e)}}createAudioBlob(e){var t=new Uint8Array(e);if(t.length>=4){if(82===t[0]&&73===t[1]&&70===t[2]&&70===t[3])return new Blob([e],{type:"audio/wav"});if(255===t[0]&&!(224&~t[1]))return new Blob([e],{type:"audio/mpeg"});if(79===t[0]&&103===t[1]&&103===t[2]&&83===t[3])return new Blob([e],{type:"audio/ogg"})}return new Blob([e],{type:"audio/wav"})}processQueue(){var e=this;return te(function*(){if(!e.isProcessingQueue&&0!==e.audioQueue.length){e.isProcessingQueue=!0;var t=e.audioQueue.shift();if(t)try{var n=!e.isPlaying&&null===e.currentSource;e.audioContext&&"closed"!==e.audioContext.state||(yield e.initializeAudioContext());var o=e.audioContext;"suspended"===o.state&&(yield o.resume(),n&&(yield new Promise(e=>setTimeout(e,10)))),"running"!==o.state&&(console.warn("AudioPlayer: AudioContext not in running state:",o.state),"suspended"===o.state&&(yield o.resume(),yield new Promise(e=>setTimeout(e,10))));var i=yield t.arrayBuffer(),r=yield o.decodeAudioData(i),a=n&&!e.isPlaying&&null===e.currentSource,s=o.createBufferSource();s.buffer=r,s.connect(o.destination),e.currentSource=s,e.isPlaying=!0,a&&e.emit("playbackStarted"),s.onended=()=>{e.currentSource=null,e.isProcessingQueue=!1,e.audioQueue.length>0?setTimeout(()=>e.processQueue(),0):setTimeout(()=>{0!==e.audioQueue.length||e.currentSource||(e.isPlaying=!1,e.emit("playbackStopped"))},100)},s.start()}catch(t){e.currentSource=null,e.emit("playbackError",t),e.audioQueue.length>0?(e.isProcessingQueue=!1,setTimeout(()=>e.processQueue(),100)):(e.isPlaying=!1,e.isProcessingQueue=!1,e.emit("playbackStopped"))}else e.isProcessingQueue=!1}})()}stop(){this.stopImmediate()}stopImmediate(){var e=this.isPlaying||null!==this.currentSource;if(this.currentSource){try{this.currentSource.stop()}catch(e){}this.currentSource=null}this.isPlaying=!1,this.isProcessingQueue=!1,this.audioQueue=[],e&&this.emit("playbackStopped")}resumeAudioContext(){var e=this;return te(function*(){if(e.audioContext&&"closed"!==e.audioContext.state){if("suspended"===e.audioContext.state)try{yield e.audioContext.resume(),console.log("â
AudioPlayer: AudioContext resumed after mic permission")}catch(e){console.warn("â ī¸ AudioPlayer: Failed to resume AudioContext:",e)}}else yield e.initializeAudioContext()})()}getStatus(){return{isPlaying:this.isPlaying,isProcessingQueue:this.isProcessingQueue,queueLength:this.audioQueue.length,audioContextState:this.audioContext?this.audioContext.state:"closed"}}destroy(){this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.audioContextReady=!1}}var oe=r(848);function ie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function re(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ie(Object(n),!0).forEach(function(t){ae(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ie(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ae(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function se(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}const ce=o=>{var{signedUrl:i,websocketUrl:r,agentId:a,appId:s,voice:c="default",language:l="en",autoReconnect:d=!0,agentSettingsOverride:u=null,onConnected:h,onDisconnected:p,onRecordingStarted:g,onRecordingStopped:m,onPlaybackStarted:v,onPlaybackStopped:f,onError:y,onMessage:x,onBargeIn:b,onStopPlaying:w,onStartConversation:S,onEndConversation:C,className:k="",style:P={},children:E}=o,[T,I]=n(!1),[A,R]=n(!1),[D,F]=n(!1),[B,_]=n("Disconnected"),O=t(null);e(()=>{console.log("đī¸ VoiceButton: Creating VoiceSDK_v2 instance for ".concat(r||i)),O.current&&(console.log("đī¸ VoiceButton: Destroying existing VoiceSDK_v2 instance"),O.current.destroy(),O.current=null);var e=new H({signedUrl:r||i,websocketUrl:r||i,agentId:a,appId:s,voice:c,language:l,autoReconnect:d,agentSettingsOverride:u,onStartConversation:S,onEndConversation:C});return e.on("connected",()=>{I(!0),_("Connected"),null==h||h()}),e.on("disconnected",()=>{I(!1),_("Disconnected"),null==p||p()}),e.on("recordingStarted",()=>{R(!0),null==g||g()}),e.on("recordingStopped",()=>{R(!1),null==m||m()}),e.on("playbackStarted",()=>{F(!0),null==v||v()}),e.on("playbackStopped",()=>{F(!1),null==f||f()}),e.on("error",e=>{null==y||y(e)}),e.on("message",e=>{null==x||x(e)}),e.on("bargeIn",e=>{null==b||b(e)}),e.on("stopPlaying",e=>{null==w||w(e)}),O.current=e,e.connect(),()=>{var e=i||r;console.log("đī¸ VoiceButton: Cleaning up VoiceSDK instance for ".concat(e)),O.current&&(O.current.destroy(),O.current=null)}},[i,r,a,s,c,l,u]);var M=function(){var e,t=(e=function*(){if(O.current)try{yield O.current.toggleRecording()}catch(e){console.error("Error toggling recording:",e)}},function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){se(r,o,i,a,s,"next",e)}function s(e){se(r,o,i,a,s,"throw",e)}a(void 0)})});return function(){return t.apply(this,arguments)}}(),U=(0,oe.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,oe.jsx)("div",{style:{fontSize:"20px"},children:A?"đ´":"đ¤"}),(0,oe.jsx)("div",{children:A?"Stop Listening":"Start Listening"})]});return(0,oe.jsx)("button",{className:"voice-button ".concat(A?"recording":""," ").concat(k),style:re({padding:"12px 24px",border:"none",borderRadius:"8px",backgroundColor:A?"#dc3545":"#007bff",color:"white",cursor:"pointer",fontSize:"16px",fontWeight:"500",transition:"all 0.2s ease"},P),onClick:M,disabled:!T,children:E||U})};function le(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function de(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){le(r,o,i,a,s,"next",e)}function s(e){le(r,o,i,a,s,"throw",e)}a(void 0)})}}function ue(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function he(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class pe{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.options=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ue(Object(n),!0).forEach(function(t){he(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ue(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({websocketUrl:e.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:e.agentId,voice:e.voice||"default",language:e.language||"en",container:e.container||document.body,buttonText:e.buttonText||"Start Listening",buttonClass:e.buttonClass||"voice-button"},e),this.isConnected=!1,this.isRecording=!1,this.isPlaying=!1,this.voiceSDK=new H({signedUrl:this.options.websocketUrl||this.options.signedUrl,websocketUrl:this.options.websocketUrl||this.options.signedUrl,agentId:this.options.agentId,appId:this.options.appId,voice:this.options.voice,language:this.options.language}),this.setupEventListeners(),this.createButton(),this.connect()}setupEventListeners(){this.voiceSDK.on("connected",()=>{var e,t;this.isConnected=!0,this.updateButton(),null===(e=(t=this.options).onConnected)||void 0===e||e.call(t)}),this.voiceSDK.on("disconnected",()=>{var e,t;this.isConnected=!1,this.updateButton(),null===(e=(t=this.options).onDisconnected)||void 0===e||e.call(t)}),this.voiceSDK.on("recordingStarted",()=>{var e,t;this.isRecording=!0,this.updateButton(),null===(e=(t=this.options).onRecordingStarted)||void 0===e||e.call(t)}),this.voiceSDK.on("recordingStopped",()=>{var e,t;this.isRecording=!1,this.updateButton(),null===(e=(t=this.options).onRecordingStopped)||void 0===e||e.call(t)}),this.voiceSDK.on("playbackStarted",()=>{var e,t;this.isPlaying=!0,null===(e=(t=this.options).onPlaybackStarted)||void 0===e||e.call(t)}),this.voiceSDK.on("playbackStopped",()=>{var e,t;this.isPlaying=!1,null===(e=(t=this.options).onPlaybackStopped)||void 0===e||e.call(t)}),this.voiceSDK.on("error",e=>{var t,n;null===(t=(n=this.options).onError)||void 0===t||t.call(n,e)}),this.voiceSDK.on("message",e=>{var t,n;null===(t=(n=this.options).onMessage)||void 0===t||t.call(n,e)}),this.voiceSDK.on("bargeIn",e=>{var t,n;null===(t=(n=this.options).onBargeIn)||void 0===t||t.call(n,e)}),this.voiceSDK.on("stopPlaying",e=>{var t,n;null===(t=(n=this.options).onStopPlaying)||void 0===t||t.call(n,e)})}createButton(){this.button=document.createElement("button"),this.button.className=this.options.buttonClass,this.button.style.cssText="\n padding: 12px 24px;\n border: none;\n border-radius: 8px;\n background-color: #6c757d;\n color: white;\n cursor: pointer;\n font-size: 16px;\n font-weight: 500;\n transition: all 0.2s ease;\n display: flex;\n align-items: center;\n gap: 8px;\n ",this.button.addEventListener("click",()=>this.toggleRecording()),this.options.container.appendChild(this.button),this.updateButton()}updateButton(){if(this.button){var e=this.isRecording?"đ´":"đ¤",t=this.isRecording?"Stop Listening":"Start Listening";this.button.innerHTML='\n <span style="font-size: 20px;">'.concat(e,"</span>\n <span>").concat(t,"</span>\n "),this.button.disabled=!this.isConnected,this.button.style.backgroundColor=this.isRecording?"#dc3545":this.isConnected?"#007bff":"#6c757d"}}connect(){var e=this;return de(function*(){try{yield e.voiceSDK.connect()}catch(e){console.error("Failed to connect:",e)}})()}toggleRecording(){var e=this;return de(function*(){if(e.voiceSDK)try{yield e.voiceSDK.toggleRecording()}catch(e){console.error("Error toggling recording:",e)}})()}getStatus(){return{isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying}}updateConfig(e){this.voiceSDK.updateConfig(e)}destroy(){this.button&&this.button.parentNode&&this.button.parentNode.removeChild(this.button),this.voiceSDK&&this.voiceSDK.destroy()}}function ge(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function me(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){ge(r,o,i,a,s,"next",e)}function s(e){ge(r,o,i,a,s,"throw",e)}a(void 0)})}}class ve{constructor(e){console.log("đ AgentSDK v2.1.8 initialized with config:",e),this.config=e,this.voiceSDK=null,this.isConnected=!1,this.isListening=!1,this.wasListening=!1,this._resumeInfo=null,this.onConnected=()=>{},this.onDisconnected=()=>{},this.onError=e=>console.error("SDK Error:",e),this.onTranscript=e=>{},this.onAgentSpeaking=e=>{},this.onConversationStart=e.onConversationStart||(()=>{}),this.onConversationEnd=e.onConversationEnd||(()=>{}),this.onBargeIn=e.onBargeIn||(()=>{}),this.onAudioStartPlaying=e.onAudioStartPlaying||(()=>{}),this.onAudioStoppedPlaying=e.onAudioStoppedPlaying||(()=>{}),this.onSubtitleDisplay=e.onSubtitleDisplay||(()=>{})}checkResumeBeforeConnect(){try{var e=new H({signedUrl:"wss://placeholder",autoReconnect:!1,agentId:this.config.agentId,appId:this.config.appId,language:this.config.language||"en",protocolVersion:2}).checkAndResume();return e?(console.log("đ [AGENT SDK] Found resume state before connect:",e),this._resumeInfo=e,e):null}catch(e){return console.warn("â ī¸ [AGENT SDK] Error checking resume:",e),null}}connect(e){var t=this;return me(function*(){try{if(!e)throw new Error("signedUrl is required");if(t.voiceSDK&&(console.log("đ AgentSDK: Cleaning up existing connection"),t.voiceSDK.destroy(),t.voiceSDK=null),t.voiceSDK=new H({signedUrl:e,autoReconnect:!1,agentId:t.config.agentId,appId:t.config.appId,language:t.config.language||"en",agentSettingsOverride:t.config.agentSettingsOverride,protocolVersion:2,outputContainer:t.config.outputContainer||"raw",outputEncoding:t.config.outputEncoding||"pcm",outputSampleRate:t.config.outputSampleRate||44100,outputChannels:t.config.outputChannels||1,outputBitDepth:t.config.outputBitDepth||16}),t._resumeInfo&&(console.log("đ [AGENT SDK] Using stored resume info:",t._resumeInfo),console.log(" From:",t._resumeInfo.fromPage,"â To:",t._resumeInfo.toPage)),t.voiceSDK.on("connected",()=>{t.isConnected=!0,t.onConnected()}),setTimeout(()=>{t.voiceSDK&&t.voiceSDK.isConnected&&!t.isConnected&&(t.isConnected=!0,t.onConnected())},10),t.voiceSDK.on("disconnected",e=>{if(t.isConnected=!1,e&&1008===e.code&&e.reason&&(e.reason.includes("Domain not whitelisted")||e.reason.includes("domain")||e.reason.includes("whitelist"))){var n=new Error("DOMAIN_NOT_WHITELISTED");n.reason=e.reason,n.code=e.code,t.onError(n)}if((t.isListening||t.wasListening)&&(console.log("đ¤ [AGENT SDK] disconnected event - calling onConversationEnd hook (isListening:",t.isListening,", wasListening:",t.wasListening,")"),t.onConversationEnd&&"function"==typeof t.onConversationEnd))try{t.onConversationEnd(),console.log("đ¤ [AGENT SDK] â
onConversationEnd hook called from disconnected event"),t.wasListening=!1}catch(e){console.error("đ¤ [AGENT SDK] â Error calling onConversationEnd from disconnected:",e)}t.onDisconnected()}),t.voiceSDK.on("domainError",e=>{t.onError(e)}),t.voiceSDK.on("error",e=>{t.onError(e)}),t.voiceSDK.on("message",e=>{t.handleWebSocketMessage(e)}),t.voiceSDK.on("recordingStarted",()=>{if(t.isListening=!0,t.wasListening=!0,t.onConversationStart&&"function"==typeof t.onConversationStart)try{t.onConversationStart()}catch(e){console.error("đ¤ [AGENT SDK] â Error calling onConversationStart:",e)}}),t.voiceSDK.on("recordingStopped",()=>{console.log("đ¤ [AGENT SDK] recordingStopped event received");var e=t.isListening;if(t.isListening=!1,e&&t.onConversationEnd&&"function"==typeof t.onConversationEnd)try{console.log("đ¤ [AGENT SDK] â
Calling onConversationEnd hook from recordingStopped"),t.onConversationEnd(),console.log("đ¤ [AGENT SDK] â
onConversationEnd hook called successfully"),t.wasListening=!1}catch(e){console.error("đ¤ [AGENT SDK] â Error calling onConversationEnd:",e)}}),t.voiceSDK.on("playbackStarted",()=>{t.onAgentSpeaking(!0),t.onAudioStartPlaying()}),t.voiceSDK.on("playbackStopped",()=>{t.onAgentSpeaking(!1),t.onAudioStoppedPlaying()}),t.voiceSDK.on("bargeIn",e=>{t.onBargeIn(e)}),t.voiceSDK.on("transcriptDisplay",e=>{console.log("đ [AGENT SDK] transcriptDisplay event received:",e),e&&e.text&&(console.log("đ [AGENT SDK] Calling onTranscript with text:",e.text),t.onTranscript&&"function"==typeof t.onTranscript?t.onTranscript(e.text):console.warn("đ [AGENT SDK] â ī¸ onTranscript is not a function!",typeof t.onTranscript)),t.onSubtitleDisplay(e)}),t._pendingToolHandlers&&t._pendingToolHandlers.size>0)for(var[n,o]of(console.log("đ§ AgentSDK: Registering ".concat(t._pendingToolHandlers.size," pending tool handlers")),t._pendingToolHandlers))t.voiceSDK.registerToolHandler(n,o);yield t.voiceSDK.connect()}catch(e){throw t.onError(e),e}})()}handleWebSocketMessage(e){switch(e.t||e.type){case"connected":case"hello_ack":console.log("Session started successfully");break;case"user_transcript":this.onTranscript(e.user_transcription||e.text||e.transcript);break;case"agent_response":case"barge_in":case"stop_playing":default:break;case"error":this.onError(new Error(e.message||e.error||"Unknown error"))}}startListening(){var e=this;return me(function*(){if(console.log("đ¤ AgentSDK: startListening() called"),!e.voiceSDK)throw console.error("â AgentSDK: No voiceSDK instance available"),new Error("No voiceSDK instance available");try{console.log("đ¤ AgentSDK: Starting recording..."),yield e.voiceSDK.startRecording(),console.log("â
AgentSDK: Recording started successfully")}catch(e){throw console.error("â AgentSDK: Failed to start recording:",e),e}})()}stopListening(){this.voiceSDK&&this.voiceSDK.stopRecording()}hangup(){this.voiceSDK&&this.voiceSDK.hangup()}updateVariables(e){this.voiceSDK&&this.isConnected&&this.voiceSDK.sendMessage({t:"update_variables",variables:e})}disconnect(){this.voiceSDK&&(this.voiceSDK.destroy(),this.voiceSDK=null),this.isConnected=!1,this.isListening=!1}registerToolHandler(e,t){if(this.voiceSDK)return this.voiceSDK.registerToolHandler(e,t);this._pendingToolHandlers||(this._pendingToolHandlers=new Map),this._pendingToolHandlers.set(e,t),console.log("đ§ AgentSDK: Queued tool handler '".concat(e,"' for registration after connect"))}unregisterToolHandler(e){if(this.voiceSDK)return this.voiceSDK.unregisterToolHandler(e);this._pendingToolHandlers&&this._pendingToolHandlers.delete(e)}hasToolHandler(e){var t;return this.voiceSDK?this.voiceSDK.hasToolHandler(e):(null===(t=this._pendingToolHandlers)||void 0===t?void 0:t.has(e))||!1}getRegisteredTools(){return this.voiceSDK?this.voiceSDK.getRegisteredTools():this._pendingToolHandlers?Array.from(this._pendingToolHandlers.keys()):[]}}function fe(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function ye(){var e=navigator.userAgent,t=/iPad|iPhone|iPod/.test(e)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,n=/Android/.test(e),o=/Mac/.test(e)&&!t,i=/Win/.test(e),r=/Chrome/.test(e)&&!/Edg|OPR/.test(e),a=/Safari/.test(e)&&!/Chrome/.test(e),s=/Firefox/.test(e),c=/Edg/.test(e),l=/SamsungBrowser/.test(e),d="unknown";t?d="safari":l?d="samsung":r?d="chrome":a?d="safari":s?d="firefox":c&&(d="edge");var u="unknown";return t?u="ios":n?u="android":o?u="mac":i&&(u="windows"),{platform:u,browser:d,isIOS:t,isAndroid:n,isMac:o,isWindows:i,isMobile:t||n,isDesktop:!t&&!n}}function xe(){return be.apply(this,arguments)}function be(){var e;return e=function*(){try{if(navigator.permissions&&navigator.permissions.query)return(yield navigator.permissions.query({name:"microphone"})).state}catch(e){console.log("â ī¸ MicPermissionUtils: Permissions API not available or not supported for microphone")}return"unknown"},be=function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){fe(r,o,i,a,s,"next",e)}function s(e){fe(r,o,i,a,s,"throw",e)}a(void 0)})},be.apply(this,arguments)}function we(e){var{platform:t,browser:n}=e,o={ios:{title:"Enable Microphone on iPhone/iPad",icon:"đą",steps:["Tap the <strong>lock icon đ</strong>, <strong>information icon âšī¸</strong>, or <strong>AA icon</strong> in the address bar","Tap <strong>Website Settings</strong> or <strong>Permissions</strong>","Find <strong>Microphone</strong> and set it to <strong>Allow</strong>","Return to this page and refresh"],altTitle:"Alternative Method",altSteps:["Open the <strong>Settings</strong> app on your device","Scroll down and tap <strong>Safari</strong> (or your browser app)",'Tap <strong>Microphone</strong> under "Settings for Websites"',"Set it to <strong>Allow</strong> or <strong>Ask</strong>","Return to this page and refresh"],note:"On iOS, you can also change permissions in the browser address bar or in device Settings.",canOpenSettings:!0,settingsButtonText:"Open Settings App"},android_chrome:{title:"Enable Microphone in Chrome",icon:"đ¤",steps:["Tap the <strong>lock icon đ</strong>, <strong>information icon âšī¸</strong>, or <strong>settings icon âŽ</strong> in the address bar","Tap <strong>Permissions</strong>","Tap <strong>Microphone</strong>","Select <strong>Allow</strong>","The page will refresh automatically"],altTitle:"Alternative Method",altSteps:["Tap the <strong>⎠menu</strong> (three dots)","Tap <strong>Settings â Site settings â Microphone</strong>","Find this website and set to <strong>Allow</strong>"],canOpenSettings:!0,settingsButtonText:"Open App Settings"},android_firefox:{title:"Enable Microphone in Firefox",icon:"đĻ",steps:["Tap the <strong>lock icon đ</strong> or <strong>information icon âšī¸</strong> in the address bar","Tap <strong>Edit Site Permissions</strong>","Toggle <strong>Microphone</strong> to enabled","Refresh the page"],canOpenSettings:!1},android_samsung:{title:"Enable Microphone in Samsung Browser",icon:"đą",steps:["Tap the <strong>menu icon</strong> (three lines)","Tap <strong>Settings â Sites and downloads</strong>","Tap <strong>Site permissions â Microphone</strong>","Find this website and set to <strong>Allow</strong>","Return and refresh the page"],canOpenSettings:!1},desktop_chrome:{title:"Enable Microphone in Chrome",icon:"đ",steps:["Click the <strong>lock icon đ</strong> or <strong>information icon âšī¸</strong> in the address bar (left side)","Find <strong>Microphone</strong> in the dropdown menu",'Change it from "Block" to <strong>Allow</strong>',"Click the <strong>Refresh</strong> button or press F5"],showAddressBarHint:!0,canOpenSettings:!1},desktop_safari:{title:"Enable Microphone in Safari",icon:"đ§",steps:["Click <strong>Safari</strong> in the menu bar (top of screen)","Click <strong>Settings for This Website...</strong>","Find <strong>Microphone</strong> in the popup","Change it to <strong>Allow</strong>","Close settings and refresh the page"],canOpenSettings:!1},desktop_firefox:{title:"Enable Microphone in Firefox",icon:"đĻ",steps:["Click the <strong>lock icon đ</strong> in the address bar",'Click the <strong>X</strong> next to "Blocked" for Microphone',"Refresh the page (press F5)","Click <strong>Allow</strong> when prompted again"],note:"Firefox requires you to clear the block and then re-allow on the next prompt.",showAddressBarHint:!0,canOpenSettings:!1},desktop_edge:{title:"Enable Microphone in Edge",icon:"đ",steps:["Click the <strong>lock icon đ</strong> in the address bar","Find <strong>Microphone</strong> in the permissions list","Change it to <strong>Allow</strong>","Refresh the page"],showAddressBarHint:!0,canOpenSettings:!1},unknown:{title:"Enable Microphone Access",icon:"đ¤",steps:["Look for a <strong>lock icon đ</strong>, <strong>information icon âšī¸</strong>, or <strong>settings icon</strong> in your browser's address bar","Find the <strong>Microphone</strong> permission setting","Change it to <strong>Allow</strong>","Refresh this page"],canOpenSettings:!1}};return"ios"===t?o.ios:"android"===t?o["android_".concat(n)]||o.android_chrome:o["desktop_".concat(n)]||o.desktop_chrome}function Se(e){var{isIOS:t,isAndroid:n,browser:o}=e;if(t)try{return window.location.href="app-settings:",!0}catch(e){return console.warn("Could not open iOS settings:",e),!1}if(n&&"chrome"===o)try{return window.location.href="intent:#Intent;action=android.settings.APPLICATION_DETAILS_SETTINGS;data=package:com.android.chrome;end",!0}catch(e){return console.warn("Could not open Android settings:",e),!1}return!1}class Ce{constructor(){this.overlay=null,this.modal=null}createOverlay(){var e=document.createElement("div");return e.className="mic-permission-overlay",e.style.cssText="\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.6);\n backdrop-filter: blur(4px);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10000;\n padding: 20px;\n animation: mic-fadeIn 0.2s ease-out;\n ",document.getElementById("mic-permission-styles")||this.injectStyles(),e}injectStyles(){if(!document.getElementById("mic-permission-styles")){var e=document.createElement("style");e.id="mic-permission-styles",e.textContent="\n @keyframes mic-fadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes mic-slideUp {\n from {\n opacity: 0;\n transform: translateY(20px);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n \n @keyframes mic-bounce {\n 0%, 100% { transform: translateY(0); }\n 50% { transform: translateY(-5px); }\n }\n \n .mic-permission-overlay {\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.6);\n backdrop-filter: blur(4px);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10000;\n padding: 20px;\n animation: mic-fadeIn 0.2s ease-out;\n }\n \n .mic-permission-modal {\n background: #ffffff;\n border-radius: 16px;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);\n max-width: 480px;\n width: 100%;\n padding: 32px;\n position: relative;\n animation: mic-slideUp 0.3s ease-out;\n max-height: 90vh;\n overflow-y: auto;\n }\n \n .mic-permission-modal__close {\n position: absolute;\n top: 16px;\n right: 16px;\n background: none;\n border: none;\n font-size: 20px;\n cursor: pointer;\n color: #6b7280;\n width: 32px;\n height: 32px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.2s;\n }\n \n .mic-permission-modal__close:hover {\n background: #e5e7eb;\n }\n \n .mic-permission-modal__icon {\n font-size: 48px;\n text-align: center;\n margin-bottom: 16px;\n }\n \n .mic-permission-modal__title {\n font-size: 24px;\n font-weight: 700;\n color: #111827;\n margin: 0 0 12px;\n line-height: 1.3;\n text-align: center;\n }\n \n .mic-permission-modal__description {\n color: #6b7280;\n font-size: 16px;\n line-height: 1.6;\n margin: 0 0 20px;\n text-align: center;\n }\n \n .mic-permission-modal__highlight {\n display: flex;\n align-items: center;\n gap: 12px;\n background: linear-gradient(135deg, #dbeafe, #ede9fe);\n padding: 16px 20px;\n border-radius: 8px;\n margin-bottom: 20px;\n border: 1px solid #bfdbfe;\n }\n \n .mic-permission-modal__highlight-icon {\n font-size: 24px;\n animation: mic-bounce 1s infinite;\n }\n \n .mic-permission-modal__status {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n background: #fef2f2;\n color: #ef4444;\n padding: 12px 16px;\n border-radius: 8px;\n margin-bottom: 20px;\n font-weight: 500;\n }\n \n .mic-permission-modal__note {\n display: flex;\n align-items: flex-start;\n gap: 10px;\n background: #fffbeb;\n color: #92400e;\n padding: 12px 16px;\n border-radius: 8px;\n margin-bottom: 20px;\n font-size: 14px;\n line-height: 1.5;\n border: 1px solid #fde68a;\n }\n \n .mic-permission-modal__steps {\n margin-bottom: 20px;\n }\n \n .mic-permission-modal__steps h3 {\n font-size: 14px;\n font-weight: 600;\n color: #6b7280;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin: 0 0 12px;\n }\n \n .mic-permission-modal__steps ol {\n margin: 0;\n padding-left: 24px;\n counter-reset: step-counter;\n list-style: none;\n }\n \n .mic-permission-modal__steps li {\n position: relative;\n padding: 12px 0 12px 16px;\n border-left: 2px solid #e5e7eb;\n color: #111827;\n font-size: 15px;\n line-height: 1.5;\n counter-increment: step-counter;\n }\n \n .mic-permission-modal__steps li::before {\n content: counter(step-counter);\n position: absolute;\n left: -14px;\n top: 10px;\n width: 24px;\n height: 24px;\n background: #4f46e5;\n color: white;\n border-radius: 50%;\n font-size: 12px;\n font-weight: 600;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n \n .mic-permission-modal__steps li:last-child {\n border-left-color: transparent;\n }\n \n .mic-permission-modal__actions {\n display: flex;\n flex-direction: column;\n gap: 10px;\n margin-top: 24px;\n }\n \n .mic-permission-modal__btn {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n padding: 14px 24px;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition: all 0.2s;\n border: none;\n width: 100%;\n }\n \n .mic-permission-modal__btn--primary {\n background: #4f46e5;\n color: white;\n }\n \n .mic-permission-modal__btn--primary:hover {\n background: #4338ca;\n transform: translateY(-1px);\n }\n \n .mic-permission-modal__btn--secondary {\n background: #e5e7eb;\n color: #111827;\n }\n \n .mic-permission-modal__btn--secondary:hover {\n background: #d1d5db;\n }\n \n .mic-permission-modal__footer {\n text-align: center;\n font-size: 13px;\n color: #6b7280;\n margin-top: 20px;\n margin-bottom: 0;\n }\n \n .mic-permission-modal__visual-guide {\n width: 100%;\n max-width: 380px;\n height: auto;\n margin: 20px auto;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);\n display: block;\n }\n \n .mic-permission-modal__visual-guide-container {\n text-align: center;\n margin: 20px 0;\n }\n \n @media (max-width: 480px) {\n .mic-permission-modal {\n padding: 24px 20px;\n margin: 10px;\n max-height: 85vh;\n }\n \n .mic-permission-modal__title {\n font-size: 20px;\n }\n \n .mic-permission-modal__icon {\n font-size: 40px;\n }\n \n .mic-permission-modal__visual-guide {\n max-width: 100%;\n }\n }\n ",document.head.appendChild(e)}}close(){this.overlay&&this.overlay.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.modal=null}show(){this.overlay&&this.modal&&document.body.appendChild(this.overlay)}}function ke(e,t){var n=new Ce,o=n.createOverlay(),i=ye(),r=document.createElement("div");return r.className="mic-permission-modal",r.innerHTML='\n <div class="mic-permission-modal__icon">đ¤</div>\n <h2 class="mic-permission-modal__title">Enable Your Microphone</h2>\n <p class="mic-permission-modal__description">\n To start a voice call with our agent, we need access to your microphone.\n </p>\n <div class="mic-permission-modal__highlight">\n <span class="mic-permission-modal__highlight-icon">đ</span>\n <span>Please click <strong>"Allow"</strong> on the next popup</span>\n </div>\n '.concat(i.isIOS?'\n <div class="mic-permission-modal__note">\n <span>âšī¸</span>\n <span>On iPhone/iPad, you may need to allow microphone access in your device Settings.</span>\n </div>\n ':"",'\n <div class="mic-permission-modal__actions">\n <button class="mic-permission-modal__btn mic-permission-modal__btn--primary" data-action="accept">\n Continue\n </button>\n <button class="mic-permission-modal__btn mic-permission-modal__btn--secondary" data-action="cancel">\n Not Now\n </button>\n </div>\n '),o.appendChild(r),n.overlay=o,n.modal=r,r.querySelector('[data-action="accept"]').addEventListener("click",()=>{n.close(),e()}),r.querySelector('[data-action="cancel"]').addEventListener("click",()=>{n.close(),t()}),o.addEventListener("click",e=>{e.target===o&&(n.close(),t())}),n.show(),n}function Pe(e,t){var n,o,i,r=new Ce,a=r.createOverlay(),s=ye(),c=we(s),l=document.createElement("div");l.className="mic-permission-modal";var d="";c.altSteps&&c.altSteps.length>0&&(d='\n <div style="margin-top: 20px; border-top: 1px solid #e5e7eb; padding-top: 16px;">\n <button class="mic-permission-modal__alt-toggle" style="background: none; border: none; color: #4f46e5; font-size: 14px; font-weight: 500; cursor: pointer; padding: 0; margin-bottom: 12px;">\n âŧ '.concat(c.altTitle||"Alternative method",'\n </button>\n <ol style="margin: 0; padding-left: 20px; display: none;">\n ').concat(c.altSteps.map(e=>'<li style="padding: 8px 0; font-size: 14px; color: #6b7280;">'.concat(e,"</li>")).join(""),"\n </ol>\n </div>\n "));var u=function(e){var{platform:t,browser:n}=e,o=document.getElementsByTagName("script"),i="";for(var r of o){var a=r.src;if(a&&(a.includes("agent-widget.js")||a.includes("ttp-agent-sdk")||a.includes("ttp-sdk-front")))try{new URL(a),i=a.substring(0,a.lastIndexOf("/"));break}catch(e){var s=a.match(/^(.*\/)[^\/]+$/);if(s){i=s[1];break}}}var c;if(c="ios"===t?"ios-settings.svg":"android"===t?"android-chrome.svg":"chrome"===n?"desktop-chrome.svg":"safari"===n?"desktop-safari.svg":"firefox"===n?"desktop-firefox.svg":"edge"===n?"desktop-edge.svg":"desktop-chrome.svg",!i||""===i||i.startsWith("/")){for(var l of o){var d=l.src;if(d&&(d.includes("cdn.talktopc.com")||d.includes("talktopc.com"))){if(d.includes("/ttp-agent-sdk/")||d.includes("/ttp-sdk-front/")){var u=d.match(/(https?:\/\/[^\/]+(?:\/[^\/]+)*)/);if(u){i=u[1].replace(/\/[^\/]+\.js$/,"");break}}if(!i&&(d.includes("cdn.talktopc.com")||d.includes("talktopc.com"))){i="https://cdn.talktopc.com/ttp-agent-sdk";break}}}if(!i||""===i)if(window.location.hostname.includes("cdn.talktopc.com")||window.location.hostname.includes("talktopc.com"))i="https://cdn.talktopc.com/ttp-agent-sdk";else{var h=window.location.pathname.split("/");h.pop(),(i=window.location.origin+h.join("/"))&&i!==window.location.origin||(i=window.location.origin)}}i=i.replace(/\/$/,"");var p="".concat(i,"/shared/mic-permission-assets/").concat(c);return"undefined"!=typeof console&&console.log&&console.log("[MicPermission] Visual guide path:",p,"Base path:",i,"Platform:",t,"Browser:",n),p}(s);l.innerHTML='\n <button class="mic-permission-modal__close" data-action="close">â</button>\n <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 20px;">\n <span style="font-size: 32px;">'.concat(c.icon,'</span>\n <h2 class="mic-permission-modal__title" style="text-align: left; margin: 0;">').concat(c.title,'</h2>\n </div>\n <div class="mic-permission-modal__status">\n <span>đĢ</span>\n <span>Microphone access is currently blocked</span>\n </div>\n ').concat(c.note?'\n <div class="mic-permission-modal__note">\n <span>âšī¸</span>\n <span>'.concat(c.note,"</span>\n </div>\n "):"",'\n <div class="mic-permission-modal__visual-guide-container">\n <img src="').concat(u,'" alt="Visual guide for enabling microphone" class="mic-permission-modal__visual-guide" \n onerror="console.error(\'[MicPermission] Failed to load image:\', this.src); this.style.display=\'none\';" \n onload="console.log(\'[MicPermission] Image loaded successfully:\', this.src);" />\n </div>\n <div class="mic-permission-modal__steps">\n <h3>Follow these steps:</h3>\n <ol>\n ').concat(c.steps.map(e=>"<li>".concat(e,"</li>")).join(""),"\n </ol>\n </div>\n ").concat(d,'\n <div class="mic-permission-modal__actions">\n ').concat(c.canOpenSettings?'\n <button class="mic-permission-modal__btn mic-permission-modal__btn--primary" data-action="open-settings">\n '.concat(c.settingsButtonText||"Open Settings","\n </button>\n "):"","\n ").concat(c.showAddressBarHint?'\n <button class="mic-permission-modal__btn mic-permission-modal__btn--primary" data-action="show-hint">\n Show Me Where\n </button>\n ':"",'\n <button class="mic-permission-modal__btn mic-permission-modal__btn--secondary" data-action="refresh">\n đ Refresh Page\n </button>\n </div>\n <p class="mic-permission-modal__footer">\n After enabling microphone access, return here and click "Refresh Page"\n </p>\n '),a.appendChild(l),r.overlay=a,r.modal=l,null===(n=l.querySelector('[data-action="close"]'))||void 0===n||n.addEventListener("click",()=>{r.close(),e()}),null===(o=l.querySelector('[data-action="open-settings"]'))||void 0===o||o.addEventListener("click",()=>{Se(s)}),null===(i=l.querySelector('[data-action="refresh"]'))||void 0===i||i.addEventListener("click",()=>{window.location.reload()});var h=l.querySelector('[data-action="show-hint"]');h&&h.addEventListener("click",()=>{r.close(),e(),function(){var e=document.getElementById("mic-address-bar-hint");e&&e.remove(),ye();var t=document.getElementsByTagName("script"),n="";for(var o of t){var i=o.src;if(i&&(i.includes("agent-widget.js")||i.includes("ttp-agent-sdk")||i.includes("ttp-sdk-front")))try{new URL(i),n=i.substring(0,i.lastIndexOf("/"));break}catch(e){var r=i.match(/^(.*\/)[^\/]+$/);if(r){n=r[1];break}}}if(!n||""===n||n.startsWith("/")){for(var a of t){var s=a.src;if(s&&(s.includes("cdn.talktopc.com")||s.includes("talktopc.com"))){if(s.includes("/ttp-agent-sdk/")||s.includes("/ttp-sdk-front/")){var c=s.match(/(https?:\/\/[^\/]+(?:\/[^\/]+)*)/);if(c){n=c[1].replace(/\/[^\/]+\.js$/,"");break}}if(!n&&(s.includes("cdn.talktopc.com")||s.includes("talktopc.com"))){n="https://cdn.talktopc.com/ttp-agent-sdk";break}}}if(!n||""===n)if(window.location.hostname.includes("cdn.talktopc.com")||window.location.hostname.includes("talktopc.com"))n="https://cdn.talktopc.com/ttp-agent-sdk";else{var l=window.location.pathname.split("/");l.pop(),(n=window.location.origin+l.join("/"))&&n!==window.location.origin||(n=window.location.origin)}}n=n.replace(/\/$/,"");var d="".concat(n,"/shared/mic-permission-assets/address-bar-hint.svg"),u=document.createElement("div");u.id="mic-address-bar-hint",u.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n z-index: 10001;\n padding: 10px 20px;\n pointer-events: none;\n animation: mic-fadeIn 0.3s ease-out;\n display: flex;\n justify-content: center;\n ";var h=document.createElement("div");h.style.cssText="\n display: flex;\n align-items: center;\n gap: 12px;\n background: #f59e0b;\n color: white;\n padding: 12px 20px;\n border-radius: 0 0 8px 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n pointer-events: all;\n animation: mic-slideDown 0.3s ease-out;\n max-width: 540px;\n ";var p=document.createElement("div");p.style.cssText="\n flex-shrink: 0;\n ";var g=document.createElement("img");g.src=d,g.alt="Address bar hint",g.style.cssText="\n width: auto;\n height: 80px;\n display: block;\n ",g.onerror=()=>{p.style.display="none"},p.appendChild(g);var m=document.createElement("div");m.style.cssText="\n display: flex;\n flex-direction: column;\n gap: 4px;\n flex: 1;\n ";var v=document.createElement("div");v.style.cssText="\n font-size: 15px;\n font-weight: 500;\n ",v.innerHTML="Click the <strong>lock icon đ</strong>, <strong>information icon âšī¸</strong>, or <strong>settings icon âŽ</strong> in the address bar to enable microphone";var f=document.createElement("button");if(f.style.cssText="\n background: rgba(255, 255, 255, 0.2);\n border: none;\n color: white;\n width: 28px;\n height: 28px;\n border-radius: 50%;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 14px;\n transition: background 0.2s;\n flex-shrink: 0;\n ",f.textContent="â",f.addEventListener("click",()=>{u.remove()}),f.addEventListener("mouseenter",()=>{f.style.background="rgba(255, 255, 255, 0.3)"}),f.addEventListener("mouseleave",()=>{f.style.background="rgba(255, 255, 255, 0.2)"}),!document.getElementById("mic-address-bar-hint-styles")){var y=document.createElement("style");y.id="mic-address-bar-hint-styles",y.textContent="\n @keyframes mic-slideDown {\n from {\n opacity: 0;\n transform: translateY(-100%);\n }\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n \n @keyframes mic-pointUp {\n 0%, 100% {\n transform: translate(0, 0);\n }\n 50% {\n transform: translate(-5px, -5px);\n }\n }\n ",document.head.appendChild(y)}m.appendChild(v),h.appendChild(p),h.appendChild(m),h.appendChild(f),u.appendChild(h),document.body.appendChild(u),setTimeout(()=>{u.parentNode&&(u.style.opacity="0",u.style.transition="opacity 0.3s ease-out",setTimeout(()=>{u.parentNode&&u.remove()},300))},1e4)}()});var p=l.querySelector(".mic-permission-modal__alt-toggle");if(p&&c.altSteps){var g=p.nextElementSibling;g&&(g.style.display="none",p.addEventListener("click",()=>{"none"===g.style.display?(g.style.display="block",p.innerHTML="âŧ ".concat(c.altTitle||"Alternative method")):(g.style.display="none",p.innerHTML="âļ ".concat(c.altTitle||"Alternative method"))}))}return a.addEventListener("click",t=>{t.target===a&&(r.close(),e())}),r.show(),r}function Ee(e){var t=new Ce,n=t.createOverlay(),o=document.createElement("div");return o.className="mic-permission-modal",o.innerHTML='\n <div class="mic-permission-modal__icon">đ¤â</div>\n <h2 class="mic-permission-modal__title">No Microphone Found</h2>\n <p class="mic-permission-modal__description">\n We couldn\'t detect a microphone on your device. Please make sure:\n </p>\n <ul style="list-style: none; padding: 0; margin: 0 0 24px;">\n <li style="padding: 10px 0 10px 32px; position: relative; color: #111827; border-bottom: 1px solid #e5e7eb;">\n <span style="position: absolute; left: 0; font-size: 18px;">â</span>\n Your microphone is properly connected\n </li>\n <li style="padding: 10px 0 10px 32px; position: relative; color: #111827; border-bottom: 1px solid #e5e7eb;">\n <span style="position: absolute; left: 0; font-size: 18px;">â</span>\n Your microphone is not muted at the hardware level\n </li>\n <li style="padding: 10px 0 10px 32px; position: relative; color: #111827;">\n <span style="position: absolute; left: 0; font-size: 18px;">â</span>\n No other app is exclusively using the microphone\n </li>\n </ul>\n <div class="mic-permission-modal__actions">\n <button class="mic-permission-modal__btn mic-permission-modal__btn--primary" data-action="retry">\n Retry\n </button>\n <button class="mic-permission-modal__btn mic-permission-modal__btn--secondary" data-action="close">\n Close\n </button>\n </div>\n ',n.appendChild(o),t.overlay=n,t.modal=o,o.querySelector('[data-action="retry"]').addEventListener("click",()=>{window.location.reload()}),o.querySelector('[data-action="close"]').addEventListener("click",()=>{t.close(),e()}),n.addEventListener("click",o=>{o.target===n&&(t.close(),e())}),t.show(),t}function Te(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function Ie(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){Te(r,o,i,a,s,"next",e)}function s(e){Te(r,o,i,a,s,"throw",e)}a(void 0)})}}class Ae{constructor(e){this.config=e,this.audioStream=null,this.callStartTime=null,this.callTimerInterval=null,this.sdk=null,this.isActive=!1,this.shadowRoot=e.shadowRoot||document,this.sdk=new ve({agentId:e.agentId,appId:e.appId,signedUrl:e.signedUrl,agentSettingsOverride:e.agentSettingsOverride,variables:e.variables||{},language:e.language||"en",outputContainer:e.outputContainer,outputEncoding:e.outputEncoding,outputSampleRate:e.outputSampleRate,outputChannels:e.outputChannels,outputBitDepth:e.outputBitDepth,onConversationStart:e.onConversationStart,onConversationEnd:e.onConversationEnd,onBargeIn:e.onBargeIn,onAudioStartPlaying:e.onAudioStartPlaying,onAudioStoppedPlaying:e.onAudioStoppedPlaying,onSubtitleDisplay:e.onSubtitleDisplay}),this.setupSDKEventHandlers(),this.checkAndHandleResume()}checkAndHandleResume(){if(this._resumeInfo)return console.log("đ [VOICE INTERFACE] Returning cached resume info:",this._resumeInfo),this._resumeInfo;var e=this.sdk.checkResumeBeforeConnect();return e?(console.log("đ [WIDGET] Auto-resuming call:",e),console.log(" From:",e.fromPage,"â To:",e.toPage),this._resumeInfo=e,this.config.onResume&&this.config.onResume(e),e):null}setupSDKEventHandlers(){this.sdk.onTranscript=e=>{console.log("đ [VOICE INTERFACE] onTranscript called with text:",e),this.updateTranscript(e)},this.sdk.onAgentSpeaking=e=>{var t=this.shadowRoot.getElementById("voiceAvatarActive");t&&(e?t.classList.add("speaking"):t.classList.remove("speaking"))},this.sdk.onDisconnected=()=>{console.log("đ WebSocket disconnected, hanging up call..."),this.isActive&&(this.isActive=!1,this.endVoiceCall())},this.sdk.onError=e=>{console.error("â Voice SDK Error:",e),e&&("DOMAIN_NOT_WHITELISTED"===e.message||e.message&&e.message.includes("Domain not whitelisted"))?this.showDomainError():this.showError(e.message||e)}}t(e){var t,n,o=this.config.language||"en";return((null===(t=this.config.translations)||void 0===t?void 0:t[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[e]||e}getText(e,t){return void 0!==this.config[e]&&null!==this.config[e]?this.config[e]:this.t(t)}getTooltip(e){var t,n=null===(t=this.config.tooltips)||void 0===t?void 0:t[e];return null!=n?n:{mute:this.t("mute"),speaker:this.t("speaker"),endCall:this.t("endCall")}[e]||""}generateHTML(){return'<div class="voice-interface" id="voiceInterface">\n \x3c!-- Before Call State --\x3e\n <div id="voiceIdleState">\n <div class="voice-avatar" id="voiceAvatar">đ¤</div>\n <div class="voice-status">\n <div class="voice-status-title">'.concat(this.getText("startCallTitle","clickToStartCall"),'</div>\n <div class="voice-status-subtitle">').concat(this.getText("startCallSubtitle","realTimeVoice"),'</div>\n </div>\n <button class="start-call-btn" id="startCallBtn">\n <svg width="32" height="32" viewBox="0 0 24 24" fill="currentColor">\n <path d="M20.01 15.38c-1.23 0-2.42-.2-3.53-.56-.35-.12-.74-.03-1.01.24l-1.57 1.97c-2.83-1.35-5.48-3.9-6.89-6.83l1.95-1.66c.27-.28.35-.67.24-1.02-.37-1.11-.56-2.3-.56-3.53 0-.54-.45-.99-.99-.99H4.19C3.65 3 3 3.24 3 3.99 3 13.28 10.73 21 20.01 21c.71 0 .99-.63.99-1.18v-3.45c0-.54-.45-.99-.99-.99z"/>\n </svg>\n <span>').concat(this.getText("startCallButtonText","startCall"),'</span>\n </button>\n </div>\n \x3c!-- During Call State --\x3e\n <div id="voiceActiveState" style="display: none;">\n <div class="voice-avatar-active" id="voiceAvatarActive">\n <div class="voice-rings">\n <div class="voice-ring"></div>\n <div class="voice-ring"></div>\n <div class="voice-ring"></div>\n </div>\n đ¤\n </div>\n <div class="voice-status">\n <div class="voice-status-title" id="voiceStatusTitleActive">').concat(this.t("listening"),'</div>\n <div class="voice-status-subtitle" id="voiceStatusSubtitleActive">').concat(this.t("speakFreely"),'</div>\n </div>\n <div class="voice-transcript">\n <div class="transcript-label">').concat(this.t("liveTranscript"),'</div>\n <div class="transcript-text empty" id="transcriptText">\n ').concat(this.t("transcriptWillAppear"),'\n </div>\n </div>\n <div class="voice-controls">\n <button class="voice-control-btn secondary" id="muteBtn" title="').concat(this.getTooltip("mute"),'">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="mute-icon">\n <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>\n <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>\n <line x1="12" y1="19" x2="12" y2="23"/>\n <line x1="8" y1="23" x2="16" y2="23"/>\n <line x1="2" y1="2" x2="22" y2="22" class="mute-cross" style="display: none; stroke: #ef4444; stroke-width: 3.5;"/>\n </svg>\n </button>\n <button class="voice-control-btn primary active" id="endCallBtn" title="').concat(this.getTooltip("endCall"),'">\n <svg width="56" height="56" viewBox="0 0 24 24" fill="#ef4444">\n <rect x="6" y="6" width="12" height="12" rx="2"/>\n </svg>\n <div class="voice-timer" id="voiceTimer">00:00</div>\n </button>\n <button class="voice-control-btn secondary" id="speakerBtn" title="').concat(this.getTooltip("speaker"),'">\n <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">\n <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>\n <path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>\n <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>\n </svg>\n </button>\n </div>\n </div>\n </div>')}generateCSS(){var e=this.config.avatarBackgroundColor||"#667eea",t=this.config.avatarActiveBackgroundColor||this.config.avatarBackgroundColor||"#667eea",n=this.config.statusTitleColor||"#1e293b",o=this.config.statusSubtitleColor||"#64748b",i=this.config.startCallButtonColor||"#667eea",r=this.config.startCallButtonTextColor||"#FFFFFF",a=this.config.transcriptBackgroundColor||"#FFFFFF",s=this.config.transcriptTextColor||"#1e293b",c=this.config.transcriptLabelColor||"#94a3b8",l=this.config.controlButtonColor||"#FFFFFF",d=this.config.controlButtonSecondaryColor||"#64748b",u=(this.config.endCallButtonColor,!1===this.config.useShadowDOM?" !important":"");return"\n /* Voice Interface Styles - Ultra-compact for Wix iframes */\n .voice-interface { \n display: none".concat(u,"; \n flex: 1; \n flex-direction: column;\n align-items: center; \n justify-content: center; \n padding: 6px 10px 6px 10px; \n background: linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%);\n overflow: hidden;\n min-height: 0;\n height: 100%;\n width: 100%;\n box-sizing: border-box;\n }\n .voice-interface.active { display: flex").concat(u,'; }\n \n /* Voice States - Better scaling gaps */\n #voiceIdleState,\n #voiceActiveState {\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n height: 100%;\n min-height: 0;\n justify-content: center;\n overflow: hidden;\n flex: 1;\n box-sizing: border-box;\n gap: clamp(6px, 1.5vh, 12px);\n }\n \n #voiceActiveState[style*="display: none"] {\n display: none !important;\n }\n \n /* Voice Avatar - Scales better from small to large */\n .voice-avatar,\n .voice-avatar-active {\n width: clamp(80px, 18vh, 160px);\n height: clamp(80px, 18vh, 160px);\n aspect-ratio: 1;\n border-radius: 50%;\n background: linear-gradient(135deg, ').concat(e," 0%, ").concat(t," 100%);\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: clamp(40px, 9vh, 80px);\n margin: 0;\n box-shadow: 0 8px 30px rgba(102, 126, 234, 0.3);\n transition: all 0.3s ease;\n flex-shrink: 1;\n position: relative;\n }\n \n .voice-avatar-active {\n animation: avatarPulse 2s ease-in-out infinite;\n }\n \n @keyframes avatarPulse {\n 0%, 100% { \n transform: scale(1);\n }\n 50% { \n transform: scale(1.05);\n }\n }\n \n .voice-avatar-active.speaking {\n animation: avatarSpeak 0.5s ease-in-out infinite;\n }\n \n @keyframes avatarSpeak {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.08); }\n }\n \n /* Voice Rings Animation */\n .voice-rings {\n position: absolute;\n width: 100%;\n height: 100%;\n border-radius: 50%;\n }\n \n .voice-ring {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n border: 2px solid rgba(102, 126, 234, 0.3);\n border-radius: 50%;\n opacity: 0;\n animation: ringExpand 2s ease-out infinite;\n }\n \n .voice-ring:nth-child(2) { animation-delay: 0.5s; }\n .voice-ring:nth-child(3) { animation-delay: 1s; }\n \n @keyframes ringExpand {\n 0% {\n width: 100%;\n height: 100%;\n opacity: 0.6;\n }\n 100% {\n width: 160%;\n height: 160%;\n opacity: 0;\n }\n }\n \n /* Voice Status - Scales with container */\n .voice-status {\n text-align: center;\n margin: 0;\n flex-shrink: 1;\n min-height: 0;\n }\n \n .voice-status-title {\n font-size: clamp(12px, 3vh, 20px);\n font-weight: 600;\n color: ").concat(n,";\n margin-bottom: clamp(2px, 0.5vh, 4px);\n line-height: 1.2;\n }\n \n .voice-status-subtitle {\n font-size: clamp(10px, 2vh, 14px);\n color: ").concat(o,";\n line-height: 1.2;\n }\n \n /* Start Call Button - Scales with container */\n .start-call-btn {\n margin: 0;\n width: min(280px, 70vw);\n height: clamp(48px, 8vh, 64px);\n border-radius: clamp(24px, 4vh, 32px);\n border: none;\n background: ").concat(i,";\n color: ").concat(r,";\n font-size: clamp(14px, 2.5vh, 18px);\n font-weight: 600;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: clamp(8px, 1.5vh, 12px);\n box-shadow: 0 12px 30px rgba(102, 126, 234, 0.4);\n transition: all 0.3s ease;\n flex-shrink: 0;\n }\n \n .start-call-btn svg {\n width: clamp(22px, 4vh, 32px);\n height: clamp(22px, 4vh, 32px);\n }\n \n .start-call-btn:hover {\n transform: translateY(-2px);\n box-shadow: 0 12px 28px rgba(102, 126, 234, 0.5);\n }\n \n .start-call-btn:active {\n transform: translateY(-1px);\n }\n \n /* Voice Transcript - Scales with container */\n .voice-transcript {\n background: ").concat(a,";\n padding: clamp(6px, 1.5vh, 12px);\n border-radius: 10px;\n width: min(360px, calc(100% - 40px));\n margin: 0;\n min-height: clamp(100px, 18vh, 140px);\n max-height: clamp(120px, 22vh, 160px);\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n flex-shrink: 1;\n overflow-y: auto;\n overflow-x: hidden;\n display: flex;\n flex-direction: column;\n box-sizing: border-box;\n }\n \n .transcript-label {\n font-size: clamp(8px, 1.4vh, 11px);\n color: ").concat(c,";\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.3px;\n margin-bottom: clamp(3px, 0.6vh, 6px);\n flex-shrink: 0;\n word-wrap: break-word;\n }\n \n .transcript-text {\n font-size: clamp(11px, 2vh, 15px);\n color: ").concat(s,";\n line-height: 1.4;\n flex: 1;\n overflow-y: auto;\n overflow-x: hidden;\n word-wrap: break-word;\n overflow-wrap: break-word;\n }\n \n .transcript-text.empty {\n color: #cbd5e1;\n font-style: italic;\n }\n \n /* Voice Controls - Scales with container */\n .voice-controls {\n display: flex;\n gap: clamp(8px, 1.8vh, 14px);\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n margin: 0;\n padding-top: clamp(5px, 1.2vh, 10px);\n }\n \n .voice-control-btn {\n width: clamp(48px, 9vh, 72px);\n height: clamp(48px, 9vh, 72px);\n aspect-ratio: 1;\n border-radius: 50%;\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s;\n position: relative;\n flex-shrink: 0;\n }\n \n .voice-control-btn svg {\n width: 48%;\n height: 48%;\n }\n \n .voice-control-btn.primary {\n width: clamp(54px, 10vh, 80px);\n height: clamp(54px, 10vh, 80px);\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n box-shadow: 0 6px 18px rgba(102, 126, 234, 0.4);\n }\n \n .voice-control-btn.primary:hover {\n transform: scale(1.05);\n }\n \n .voice-control-btn.primary.active {\n background: white;\n animation: recordingPulse 1.5s ease-in-out infinite;\n }\n \n @keyframes recordingPulse {\n 0%, 100% { \n box-shadow: 0 6px 16px rgba(239, 68, 68, 0.4);\n }\n 50% { \n box-shadow: 0 6px 24px rgba(239, 68, 68, 0.7);\n }\n }\n \n .voice-control-btn.secondary {\n background: ").concat(l,";\n color: ").concat(d,";\n box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);\n }\n \n .voice-control-btn.secondary:hover {\n background: #f8fafc;\n transform: scale(1.05);\n }\n \n .voice-control-btn.secondary.muted {\n background: #f3f4f6;\n }\n \n .voice-control-btn.secondary.muted .mute-icon {\n stroke: #9ca3af !important;\n }\n \n .voice-timer {\n position: absolute;\n bottom: clamp(-18px, -3vh, -24px);\n font-size: clamp(9px, 1.6vh, 12px);\n color: #64748b;\n font-weight: 500;\n white-space: nowrap;\n }\n \n /* Mobile optimization */\n @media (max-width: 768px) {\n .voice-interface {\n padding: 6px 10px;\n }\n }\n \n @media (max-width: 480px) {\n .voice-interface {\n padding: 5px 8px;\n }\n }\n ")}setupEventHandlers(e){var t=this,n=this.shadowRoot.getElementById("startCallBtn"),o=this.shadowRoot.getElementById("endCallBtn"),i=this.shadowRoot.getElementById("muteBtn"),r=this.shadowRoot.getElementById("speakerBtn");n&&(n.onclick=()=>this.startVoiceCall()),o&&(o.onclick=()=>this.endVoiceCall()),i&&(i.onclick=()=>this.toggleMute()),r&&(r.onclick=()=>this.toggleSpeaker());var a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=t.shadowRoot.getElementById("voiceInterface");n&&n.classList.contains("active")&&n.clientHeight>100?(console.log("â
Interface is active and has proper dimensions, adjusting sizes (attempt",e+1,")"),t.adjustSizesForContainer(),0===e&&setTimeout(()=>t.adjustSizesForContainer(),500)):e<15?(console.log("âŗ Interface not ready yet (height:",null==n?void 0:n.clientHeight,"), retrying... (attempt",e+1,")"),setTimeout(()=>a(e+1),250)):(console.warn("â ī¸ Interface never became fully ready, adjusting sizes anyway"),t.adjustSizesForContainer())};setTimeout(()=>a(),200),window.addEventListener("resize",()=>{console.log("đ Window resized, re-adjusting sizes"),this.adjustSizesForContainer()})}getSignedUrl(){var e=this;return Ie(function*(){if(e.config.signedUrl)return e.config.signedUrl;if(!e.config.agentId)throw new Error("agentId is required when signedUrl is not provided");var t=e.config.websocketUrl||"wss://speech.talktopc.com/ws/conv",n=new URLSearchParams;return n.append("agentId",e.config.agentId),e.config.appId&&n.append("appId",e.config.appId),!1!==e.config.demo&&n.append("demo","true"),"".concat(t,"?").concat(n.toString())})()}adjustSizesForContainer(){var e=this.shadowRoot.getElementById("voiceInterface");if(e){var t=e.clientHeight,n=e.clientWidth;console.log("đ Container size:",t,"x",n);var o,i,r,a,s,c,l,d,u,h=this.shadowRoot.getElementById("voiceIdleState"),p=this.shadowRoot.getElementById("voiceActiveState"),g=h&&"none"!==h.style.display,m=p&&"none"!==p.style.display;console.log("đī¸ Visible state - Idle:",g,"Active:",m),t<=350?(u=5,o=70,i=35,r=11,a=9,s=32,c=100,l=42,d=48):t<=450?(u=7,o=110,i=55,r=15,a=11,s=38,c=110,l=52,d=58):t<=550?(u=8,o=140,i=70,r=16,a=12,s=42,c=120,l=56,d=64):t<=700?(u=10,o=130,i=65,r=18,a=13,s=46,c=130,l=60,d=70):(u=12,o=150,i=75,r=20,a=14,s=50,c=140,l=66,d=76),this.shadowRoot.querySelectorAll("#voiceIdleState, #voiceActiveState").forEach(e=>{e.style.gap="".concat(u,"px")});var v=this.shadowRoot.querySelectorAll(".voice-avatar, .voice-avatar-active");console.log("đ¤ Found",v.length,"avatars, setting size to",o,"px"),v.forEach(e=>{e.style.width="".concat(o,"px"),e.style.height="".concat(o,"px"),e.style.fontSize="".concat(i,"px")}),this.shadowRoot.querySelectorAll(".voice-status-title").forEach(e=>e.style.fontSize="".concat(r,"px")),this.shadowRoot.querySelectorAll(".voice-status-subtitle").forEach(e=>e.style.fontSize="".concat(a,"px"));var f=this.shadowRoot.querySelector(".voice-transcript");f&&(f.style.minHeight="".concat(c,"px"),f.style.maxHeight="".concat(c,"px"),f.style.height="".concat(c,"px"),f.style.width="min(360px, ".concat(n-40,"px)"),f.style.boxSizing="border-box");var y=this.shadowRoot.querySelector(".transcript-label");y&&(y.style.fontSize="".concat(Math.max(8,r-4),"px"));var x=this.shadowRoot.querySelector(".transcript-text");x&&(x.style.fontSize="".concat(Math.max(10,r-2),"px")),this.shadowRoot.querySelectorAll(".voice-control-btn.secondary").forEach(e=>{e.style.width="".concat(l,"px"),e.style.height="".concat(l,"px");var t=e.querySelector("svg");if(t){var n=.65*l;t.style.setProperty("width","".concat(n,"px"),"important"),t.style.setProperty("height","".concat(n,"px"),"important"),t.style.setProperty("min-width","".concat(n,"px"),"important"),t.style.setProperty("min-height","".concat(n,"px"),"important")}});var b=this.shadowRoot.querySelector(".voice-control-btn.primary");if(b){b.style.width="".concat(d,"px"),b.style.height="".concat(d,"px");var w=b.querySelector("svg");if(w){var S=.7*d;w.style.setProperty("width","".concat(S,"px"),"important"),w.style.setProperty("height","".concat(S,"px"),"important"),w.style.setProperty("min-width","".concat(S,"px"),"important"),w.style.setProperty("min-height","".concat(S,"px"),"important")}}var C=this.shadowRoot.querySelector(".start-call-btn");if(C){var k,P;t<=350?(k=48,P=14):t<=450?(k=52,P=15):t<=550?(k=58,P=17):t<=700?(k=62,P=18):(k=64,P=18),C.style.height="".concat(k,"px"),C.style.fontSize="".concat(P,"px");var E=C.querySelector("svg");if(E){var T=Math.max(22,.5*k);E.style.width="".concat(T,"px"),E.style.height="".concat(T,"px")}}console.log("â
Sizes adjusted - Avatar:",o,"Status:",s,"Transcript:",c,"Buttons:",l)}else console.warn("â ī¸ voiceInterface not found, skipping size adjustment")}startVoiceCall(){var e=this;return Ie(function*(){if(e.isActive)console.log("â ī¸ Voice call already active");else{console.log("đ¤ Starting voice call...");var t=yield xe();if(console.log("đ Current permission state: ".concat(t)),"denied"!==t){if("prompt"===t||"unknown"===t)return console.log("đ Permission is in prompt state, showing pre-prompt modal..."),new Promise(t=>{ke(Ie(function*(){console.log("â
Pre-prompt accepted, proceeding with voice call..."),yield e.proceedWithVoiceCall(),t()}),()=>{console.log("â Pre-prompt cancelled"),t()})});yield e.proceedWithVoiceCall()}else console.log("đĢ Permission is denied, showing blocked modal..."),ye(),Pe(()=>{console.log("Blocked modal closed")})}})()}proceedWithVoiceCall(){var e=this;return Ie(function*(){try{var t=e.shadowRoot.getElementById("voiceIdleState"),n=e.shadowRoot.getElementById("voiceActiveState"),o=e.shadowRoot.getElementById("voiceInterface");t&&(t.style.display="none"),n&&(n.style.display="flex"),setTimeout(()=>e.adjustSizesForContainer(),50),o&&(o.scrollTop=0);var i=ye(),r=yield xe();if(i.isMobile&&"granted"!==r){console.log("đą Mobile device detected - requesting mic permission before connecting..."),console.log("đ Current permission state: ".concat(r));try{var a=e.config.outputSampleRate||44100;(yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:a,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})).getTracks().forEach(e=>e.stop()),console.log("â
Microphone permission granted on mobile - proceeding with connection")}catch(t){return console.log("đĢ Permission denied on mobile, showing blocked modal..."),void Pe(()=>{e.resetUIState()})}}var s=yield e.getSignedUrl();if(console.log("đ Got signed URL:",s),e.sdk&&e.sdk.isConnected){console.log("đ SDK already connected, disconnecting for clean retry...");try{e.sdk.disconnect(),yield new Promise(e=>setTimeout(e,100))}catch(e){console.warn("Warning: Error disconnecting existing connection:",e)}}var c=yield e.sdk.connect(s);console.log("â
Connected to WebSocket, connected:",c);for(var l=0;l<50&&!(e.sdk.isConnected&&e.sdk.voiceSDK&&e.sdk.voiceSDK.isConnected&&e.sdk.voiceSDK.websocket&&e.sdk.voiceSDK.websocket.readyState===WebSocket.OPEN);)yield new Promise(e=>setTimeout(e,100)),l++;e.sdk.isConnected&&e.sdk.voiceSDK&&e.sdk.voiceSDK.websocket&&e.sdk.voiceSDK.websocket.readyState===WebSocket.OPEN?(console.log("â
WebSocket ready, starting listening..."),yield e.sdk.startListening(),console.log("đ¤ Started listening"),e.isActive=!0,e.callStartTime=Date.now(),e.callTimerInterval=setInterval(()=>{var t=Date.now()-e.callStartTime,n=Math.floor(t/6e4),o=Math.floor(t%6e4/1e3),i=e.shadowRoot.getElementById("voiceTimer");i&&(i.textContent="".concat(n.toString().padStart(2,"0"),":").concat(o.toString().padStart(2,"0")))},1e3)):(console.warn("â ī¸ Connection not fully ready, but trying to start listening anyway..."),yield e.sdk.startListening(),console.log("đ¤ Started listening"),e.isActive=!0,e.callStartTime=Date.now(),e.callTimerInterval=setInterval(()=>{var t=Date.now()-e.callStartTime,n=Math.floor(t/6e4),o=Math.floor(t%6e4/1e3),i=e.shadowRoot.getElementById("voiceTimer");i&&(i.textContent="".concat(n.toString().padStart(2,"0"),":").concat(o.toString().padStart(2,"0")))},1e3)),console.log("â
Voice call started successfully")}catch(t){if(console.error("â Error starting voice call:",t),e.isActive=!1,e.callTimerInterval&&(clearInterval(e.callTimerInterval),e.callTimerInterval=null),e.sdk&&e.sdk.isConnected)try{e.sdk.disconnect()}catch(e){console.warn("Error disconnecting SDK on error:",e)}"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?(ye(),Pe(()=>{e.resetUIState()})):"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?Ee(()=>{e.resetUIState()}):(e.showError(t.message||t),e.resetUIState())}})()}resetUIState(){var e=this.shadowRoot.getElementById("voiceIdleState"),t=this.shadowRoot.getElementById("voiceActiveState");e&&(e.style.display="flex"),t&&(t.style.display="none")}endVoiceCall(){console.log("đ´ Ending voice call..."),this.sdk&&this.isActive&&(this.sdk.stopListening(),this.sdk.hangup(),this.isActive=!1),this.audioStream&&(this.audioStream.getTracks().forEach(e=>e.stop()),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null);var e=this.shadowRoot.getElementById("voiceIdleState"),t=this.shadowRoot.getElementById("voiceActiveState");e&&(e.style.display="flex"),t&&(t.style.display="none"),setTimeout(()=>this.adjustSizesForContainer(),50);var n=this.shadowRoot.getElementById("transcriptText");n&&(n.textContent=this.t("transcriptWillAppear"),n.classList.add("empty"));var o=this.shadowRoot.getElementById("voiceAvatarActive");o&&o.classList.remove("speaking"),console.log("â
Voice call ended")}updateTranscript(e){console.log("đ [VOICE INTERFACE] updateTranscript called with text:",e);var t=this.shadowRoot.getElementById("transcriptText");t?(console.log("đ [VOICE INTERFACE] Found transcript element, updating text"),t.textContent=e,t.classList.remove("empty")):console.warn("đ [VOICE INTERFACE] â ī¸ transcriptText element not found!")}showError(e){var t=this.shadowRoot.getElementById("transcriptText");t&&(t.textContent="".concat(this.t("error"),": ").concat(e),t.classList.remove("empty"))}showDomainError(){var e=this.shadowRoot.getElementById("transcriptText");if(e){var t=this.t("domainNotValidated"),n=this.t("domainErrorMessage");e.innerHTML='<div style="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;">'.concat(t,'</div><div style="font-size: 14px; color: #991B1B; line-height: 1.5;">').concat(n,"</div>"),e.classList.remove("empty")}}toggleMute(){if(this.sdk&&this.isActive){var e=null;if(this.sdk.voiceSDK&&this.sdk.voiceSDK.audioRecorder&&this.sdk.voiceSDK.audioRecorder.mediaStream&&(e=this.sdk.voiceSDK.audioRecorder.mediaStream.getAudioTracks()[0]),!e&&this.audioStream&&(e=this.audioStream.getAudioTracks()[0]),e){e.enabled=!e.enabled;var t=this.shadowRoot.getElementById("muteBtn"),n=null==t?void 0:t.querySelector(".mute-icon"),o=null==t?void 0:t.querySelector(".mute-cross");t&&n&&o&&(e.enabled?(n.style.stroke="",o.style.display="none",t.classList.remove("muted")):(n.style.stroke="#9ca3af",o.style.display="block",t.classList.add("muted"))),console.log(e.enabled?"đ Unmuted":"đ Muted")}else console.warn("â ī¸ No audio track available for mute toggle")}}toggleSpeaker(){console.log("đ Speaker toggle")}destroy(){this.isActive&&this.endVoiceCall(),this.audioStream&&(this.audioStream.getTracks().forEach(e=>e.stop()),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null),this.sdk&&(this.sdk.disconnect(),this.sdk=null)}}function Re(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function De(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){Re(r,o,i,a,s,"next",e)}function s(e){Re(r,o,i,a,s,"throw",e)}a(void 0)})}}class Fe{constructor(e,t){this.config=e,this.sdk=t,this.streamingEl=null,this.hasStartedStreaming=!1,this.isActive=!1,this.shadowRoot=e.shadowRoot||document,this.eventHandlers={autoResize:null,keydown:null},this.eventHandlersSetup=!1}t(e){var t,n,o=this.config.language||"en";return((null===(t=this.config.translations)||void 0===t?void 0:t[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[e]||e}generateHTML(){var e,t,n,o,i,r,a,s,c,l=this.config.inputPlaceholder||(null===(e=this.config.panel)||void 0===e?void 0:e.inputPlaceholder)||this.t("typeMessage")||"Type your message...";return'<div class="text-interface" id="textInterface">\n <div class="messages-container" id="messagesContainer">\n <div class="empty-state">\n <div class="empty-state-icon">đŦ</div>\n <div class="empty-state-title">'.concat(this.t("hello"),'</div>\n <div class="empty-state-text">').concat(this.t("sendMessage"),'</div>\n </div>\n </div>\n <div class="input-container">\n <div class="input-wrapper" style="flex:1;">\n <textarea class="message-input" id="messageInput" placeholder="').concat(l,'" rows="1" dir="').concat(this.config.direction||"ltr",'"></textarea>\n </div>\n <button class="send-button" id="sendButton" aria-label="').concat(this.t("sendMessageAria"),'">').concat(this.config.sendButtonText||"â¤","</button>\n ").concat(null!==(t=this.config.sendButtonHint)&&void 0!==t&&t.text||null!==(n=this.config.panel)&&void 0!==n&&null!==(n=n.sendButtonHint)&&void 0!==n&&n.text?'\n <div class="send-button-hint" style="color: '.concat((null===(o=this.config.sendButtonHint)||void 0===o?void 0:o.color)||(null===(i=this.config.panel)||void 0===i||null===(i=i.sendButtonHint)||void 0===i?void 0:i.color)||"#6B7280","; font-size: ").concat((null===(r=this.config.sendButtonHint)||void 0===r?void 0:r.fontSize)||(null===(a=this.config.panel)||void 0===a||null===(a=a.sendButtonHint)||void 0===a?void 0:a.fontSize)||"12px",'; text-align: center; margin-top: 4px;">\n ').concat((null===(s=this.config.sendButtonHint)||void 0===s?void 0:s.text)||(null===(c=this.config.panel)||void 0===c||null===(c=c.sendButtonHint)||void 0===c?void 0:c.text),"\n </div>\n "):"","\n </div>\n </div>")}generateCSS(){var e,t,n,o,i,r,a,s,c,l,d,u,h,p=this.config.messages,g=(this.config.panel,this.config.animation,this.config.sendButtonColor||(null===(e=this.config.panel)||void 0===e?void 0:e.sendButtonColor)||"#7C3AED"),m=this.config.sendButtonHoverColor||(null===(t=this.config.panel)||void 0===t?void 0:t.sendButtonHoverColor)||"#6D28D9",v=this.config.sendButtonTextColor||(null===(n=this.config.panel)||void 0===n?void 0:n.sendButtonTextColor)||"#FFFFFF",f=(this.config.inputPlaceholder||null===(o=this.config.panel)||void 0===o||o.inputPlaceholder,this.config.inputBorderColor||(null===(i=this.config.panel)||void 0===i?void 0:i.inputBorderColor)||"#E5E7EB"),y=this.config.inputFocusColor||(null===(r=this.config.panel)||void 0===r?void 0:r.inputFocusColor)||"#7C3AED",x=this.config.inputBackgroundColor||(null===(a=this.config.panel)||void 0===a?void 0:a.inputBackgroundColor)||"#FFFFFF",b=this.config.inputTextColor||(null===(s=this.config.panel)||void 0===s?void 0:s.inputTextColor)||"#1F2937",w=this.config.inputFontSize||(null===(c=this.config.panel)||void 0===c?void 0:c.inputFontSize)||"14px",S=this.config.inputBorderRadius||(null===(l=this.config.panel)||void 0===l?void 0:l.inputBorderRadius)||20,C=this.config.inputPadding||(null===(d=this.config.panel)||void 0===d?void 0:d.inputPadding)||"6px 14px",k=!1===this.config.useShadowDOM?" !important":"";return"\n /* Messages container using new classes */\n #messagesContainer { \n flex: 1; \n overflow-y: auto; \n overflow-x: hidden; \n padding: 20px; \n background: #f8fafc; \n display: flex; \n flex-direction: column; \n gap: 16px; \n min-height: 0; \n }\n .empty-state { \n flex: 1; \n display: flex; \n flex-direction: column; \n align-items: center; \n justify-content: center; \n gap: 12px; \n color: #64748b; \n text-align: center; \n padding: 20px; \n }\n .empty-state-icon { font-size: 48px; opacity: 0.3; }\n .empty-state-title { font-size: 20px; font-weight: 700; color: #334155; }\n .empty-state-text { font-size: 13px; max-width: 280px; }\n\n .text-interface { \n display: none".concat(k,"; \n flex: 1; \n flex-direction: column; \n min-height: 0; \n overflow: hidden; \n }\n .text-interface.active { display: flex").concat(k,"; }\n \n .message { \n display: flex; \n gap: 8px; \n padding: 4px 0; \n max-width: 100%; \n align-items: center; \n }\n .message.edge-left { flex-direction: row; }\n .message.edge-right { flex-direction: row-reverse; }\n .message-bubble { \n padding: 12px; \n border-radius: ").concat(p.borderRadius,"px; \n max-width: 80%; \n font-size: ").concat(p.fontSize,"; \n color: ").concat(p.textColor,"; \n word-wrap: break-word; \n text-align: ").concat("rtl"===this.config.direction?"right":"left","; \n direction: ").concat(this.config.direction||"ltr",";\n }\n .message.user { \n background: ").concat(p.userBackgroundColor,"; \n align-self: ").concat("rtl"===this.config.direction?"flex-start":"flex-end","; \n }\n .message.agent { \n background: ").concat(p.agentBackgroundColor,"; \n align-self: ").concat("rtl"===this.config.direction?"flex-end":"flex-start","; \n }\n .message .message-bubble { \n text-align: ").concat("rtl"===this.config.direction?"right":"left"," !important; \n }\n ").concat("rtl"===this.config.direction?"\n .message-bubble {\n text-align: right !important;\n }\n ":"","\n .message-avatar { \n width: 20px; \n height: 20px; \n display: flex; \n align-items: center; \n justify-content: center; \n flex-shrink: 0; \n color: inherit; \n font-size: 18px; \n line-height: 1; \n background: transparent; \n border: none; \n }\n .message-avatar.user { background: transparent; }\n .message-avatar.agent { background: transparent; }\n \n .message.system {\n background: ").concat(p.systemBackgroundColor,";\n align-self: flex-start;\n }\n .message.error {\n background: ").concat(p.errorBackgroundColor,";\n align-self: flex-start;\n }\n \n .input-container {\n display: flex;\n gap: 8px;\n padding: 12px 16px;\n background: #FFFFFF;\n border-top: 1px solid #E5E7EB;\n align-items: center;\n flex-shrink: 0;\n flex-direction: ").concat("rtl"===this.config.direction?"row-reverse":"row",";\n }\n \n .input-wrapper {\n position: relative;\n display: flex;\n align-items: center;\n }\n \n .message-input {\n width: 100%;\n min-height: 32px;\n max-height: 120px;\n padding: ").concat(C,";\n border: 1px solid ").concat(f,";\n border-radius: ").concat(S,"px;\n font-size: ").concat(w,";\n font-family: inherit;\n line-height: 1.3;\n resize: none;\n overflow-y: auto;\n background: ").concat(x,";\n color: ").concat(b,";\n vertical-align: top;\n margin: 0;\n display: block;\n white-space: pre-wrap;\n word-wrap: break-word;\n text-align: ").concat("rtl"===this.config.direction?"right":"left",";\n direction: ").concat(this.config.direction||"ltr",";\n -webkit-appearance: none;\n appearance: none;\n box-sizing: border-box;\n }\n \n .message-input:focus {\n outline: none;\n border-color: ").concat(y,";\n background: ").concat("#FFFFFF"===x?"#FFFFFF":x,";\n box-shadow: 0 0 0 3px ").concat(y,"33;\n }\n \n .message-input::placeholder {\n color: #9CA3AF;\n text-align: ").concat("rtl"===this.config.direction?"right":"left",";\n }\n \n .send-button {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n border: none;\n background: ").concat(g,";\n color: ").concat(v,";\n font-size: ").concat(this.config.sendButtonFontSize||(null===(u=this.config.panel)||void 0===u?void 0:u.sendButtonFontSize)||"18px",";\n font-weight: ").concat(this.config.sendButtonFontWeight||(null===(h=this.config.panel)||void 0===h?void 0:h.sendButtonFontWeight)||"500",";\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n transition: all 0.2s ease;\n box-shadow: 0 4px 12px rgba(124, 60, 237, 0.3);\n }\n \n .send-button:hover:not(:disabled) {\n background: ").concat(m,";\n transform: scale(1.05);\n box-shadow: 0 6px 16px rgba(124, 60, 237, 0.4);\n }\n \n .send-button-hint {\n width: 100%;\n text-align: center;\n margin-top: 4px;\n }\n \n .send-button:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n }\n \n .typing-indicator {\n display: inline-flex;\n gap: 4px;\n align-items: center;\n }\n \n .typing-dot {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: #64748b;\n animation: typingDot 1.4s ease-in-out infinite;\n }\n \n .typing-dot:nth-child(2) { animation-delay: 0.2s; }\n .typing-dot:nth-child(3) { animation-delay: 0.4s; }\n \n @keyframes typingDot {\n 0%, 60%, 100% { transform: translateY(0); opacity: 0.7; }\n 30% { transform: translateY(-8px); opacity: 1; }\n }\n \n .error-message {\n padding: 12px;\n background: ").concat(p.errorBackgroundColor,";\n border-radius: ").concat(p.borderRadius,"px;\n color: #991B1B;\n font-size: ").concat(p.fontSize,";\n margin: 8px 0;\n }\n \n @media (max-width: 768px) {\n #messagesContainer {\n padding: 12px;\n gap: 12px;\n }\n \n .message-bubble {\n max-width: 85%;\n font-size: 14px;\n padding: 10px;\n }\n \n .text-input-container {\n padding: 10px;\n gap: 8px;\n }\n \n #text-chat-input {\n font-size: 16px !important; /* Prevents iOS zoom on focus */\n padding: 10px 14px;\n min-height: 44px;\n }\n \n #text-chat-send {\n min-width: 56px;\n min-height: 44px;\n width: 56px;\n height: 44px;\n }\n \n .empty-state-icon {\n font-size: 40px;\n }\n \n .empty-state-title {\n font-size: 18px;\n }\n \n .empty-state-text {\n font-size: 12px;\n }\n }\n \n @media (max-width: 480px) {\n #messagesContainer {\n padding: 10px;\n gap: 10px;\n }\n \n .message-bubble {\n max-width: 90%;\n font-size: 13px;\n padding: 8px;\n }\n \n .text-input-container {\n padding: 8px;\n }\n \n #text-chat-input {\n font-size: 16px !important;\n padding: 8px 12px;\n }\n }\n ")}setupEventHandlers(){var e=this.shadowRoot.getElementById("sendButton"),t=this.shadowRoot.getElementById("messageInput"),n=this.shadowRoot.getElementById("newChatBtn");if(e&&(e.onclick=()=>this.sendMessage()),n&&(n.onclick=()=>this.startNewChat()),this.updateInputAttributes(),t){t.style.height="32px",t.style.overflow="hidden";var o=()=>{t.style.height="auto";var e=Math.min(t.scrollHeight,120);t.style.height=e+"px",t.style.overflowY=e>=120?"auto":"hidden",e>=120&&setTimeout(()=>{t.scrollTop=t.scrollHeight},0)};t.addEventListener("input",o),t.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey?"Enter"===e.key&&e.shiftKey&&setTimeout(o,0):(e.preventDefault(),this.sendMessage())})}}startNewChat(){try{localStorage.removeItem("ttp_text_chat_conversation_id")}catch(e){}this.sdk&&(this.sdk.config.conversationId=null);var e=this.shadowRoot.getElementById("messagesContainer");e&&(e.innerHTML='\n <div class="empty-state">\n <div class="empty-state-icon">đŦ</div>\n <div class="empty-state-title">'.concat(this.t("hello"),'</div>\n <div class="empty-state-text">').concat(this.t("sendMessage"),"</div>\n </div>"));var t=this.shadowRoot.getElementById("messageInput");t&&t.focus()}updateInputAttributes(){var e=this.shadowRoot.getElementById("messageInput");if(e){var t,n=this.config.inputPlaceholder||(null===(t=this.config.panel)||void 0===t?void 0:t.inputPlaceholder)||this.t("typeMessage")||"Type your message...";e.placeholder=n,e.dir=this.config.direction||"ltr",e.style.textAlign="rtl"===this.config.direction?"right":"left"}}show(){var e=this.shadowRoot.getElementById("textInterface");e&&e.classList.add("active"),setTimeout(()=>{var e=this.shadowRoot.getElementById("messageInput");e&&e.focus()},50)}hide(){var e=this.shadowRoot.getElementById("textInterface");e&&e.classList.remove("active")}startChat(){var e=this;return De(function*(){e.isActive=!0,e.updateSendButtonState()})()}sendMessage(){var e=this;return De(function*(){var t=e.shadowRoot.getElementById("messageInput"),n=t.value.trim();if(n){e.isActive||(yield e.startChat()),e.addMessage("user",n),t.value="",t.style.height="32px",t.style.overflow="hidden";try{e.beginStreaming(),yield e.sdk.sendMessage(n)}catch(t){console.error("â Failed to send message:",t),t&&("DOMAIN_NOT_WHITELISTED"===t.message||t.message&&t.message.includes("Domain not whitelisted"))||e.showError(t),e.stopStreamingState()}}})()}updateSendButtonState(){var e=this.shadowRoot.getElementById("sendButton");e&&(e.disabled=!this.isActive)}addMessage(e,t){var n=this.shadowRoot.getElementById("messagesContainer");if(n){var o=n.querySelector(".empty-state");o&&o.remove();var i=document.createElement("div"),r="rtl"===this.config.direction?"user"===e?"edge-left":"edge-right":"user"===e?"edge-right":"edge-left";i.className="message ".concat(e," ").concat(r);var a=document.createElement("div");a.className="message-avatar ".concat(e),a.textContent="user"===e?"đ¤":"đ¤";var s=document.createElement("div");s.className="message-bubble",s.textContent=t,i.appendChild(a),i.appendChild(s),n.appendChild(i),n.scrollTop=n.scrollHeight}}beginStreaming(){var e=this.shadowRoot.getElementById("messagesContainer");if(e){this.stopStreamingState();var t=document.createElement("div"),n="rtl"===this.config.direction?"edge-right":"edge-left";t.className="message agent ".concat(n),t.id="agent-streaming";var o=document.createElement("div");o.className="message-avatar agent",o.textContent="đ¤";var i=document.createElement("div");i.className="message-bubble",i.innerHTML='<span class="typing-indicator"><span class="typing-dot"></span><span class="typing-dot"></span><span class="typing-dot"></span></span>',t.appendChild(o),t.appendChild(i),e.appendChild(t),this.streamingEl=i,this.hasStartedStreaming=!1,e.scrollTop=e.scrollHeight}}appendStreamingChunk(e){if(this.streamingEl){this.hasStartedStreaming||(this.streamingEl.textContent="",this.hasStartedStreaming=!0),this.streamingEl.textContent+=e;var t=this.shadowRoot.getElementById("messagesContainer");t&&(t.scrollTop=t.scrollHeight)}}finalizeStreaming(e){if(this.streamingEl){this.streamingEl.textContent=e||this.streamingEl.textContent;var t=this.shadowRoot.getElementById("agent-streaming");t&&(t.id=""),this.streamingEl=null}this.updateSendButtonState()}stopStreamingState(){var e=this.shadowRoot.getElementById("agent-streaming");e&&e.remove(),this.streamingEl=null,this.hasStartedStreaming=!1}showError(e){var t=this.shadowRoot.getElementById("messagesContainer");if(t){if(e&&("DOMAIN_NOT_WHITELISTED"===e.message||"string"==typeof e&&e.includes("DOMAIN_NOT_WHITELISTED")||e.message&&e.message.includes("Domain not whitelisted")||"string"==typeof e&&e.includes("Domain not whitelisted"))){var n,o=document.createElement("div");o.className="error-message",o.style.cssText="padding: 16px; margin: 12px; border-radius: 8px; background: "+((null===(n=this.config.messages)||void 0===n?void 0:n.errorBackgroundColor)||"#FEE2E2")+";";var i=document.createElement("div");i.style.cssText="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;",i.textContent=this.t("domainNotValidated");var r=document.createElement("div");r.style.cssText="font-size: 14px; color: #991B1B; line-height: 1.5;",r.textContent=this.t("domainErrorMessage"),o.appendChild(i),o.appendChild(r),t.appendChild(o)}else{var a=document.createElement("div");a.className="error-message",a.textContent="string"==typeof e?e:(null==e?void 0:e.message)||e,t.appendChild(a)}t.scrollTop=t.scrollHeight}}setActive(e){this.isActive=e,this.updateSendButtonState()}}const Be={en:{landingTitle:"How would you like to communicate?",voiceCall:"Voice Call",textChat:"Text Chat",clickToStartCall:"Click to Start Call",realTimeVoice:"Real-time voice conversation",startCall:"Start Call",listening:"Listening...",speakFreely:"Speak freely",liveTranscript:"Live Transcript",transcriptWillAppear:"Transcript will appear here during the call...",mute:"Mute",speaker:"Speaker",endCall:"End Call",hello:"Hello! How can I help?",sendMessage:"Send a message to get started",online:"Online",newChat:"New Chat",back:"Back",close:"Close",error:"Error",typeMessage:"Type your message...",sendMessageAria:"Send message",domainNotValidated:"Domain not validated",domainErrorMessage:"This domain is not whitelisted. Please contact the administrator to whitelist your website URL."},he:{landingTitle:"××× ×Ēר×Ļ× ××Ēק׊ר?",voiceCall:"׊××× ×§××××Ē",textChat:"×Ļ'×× ×קץ×",clickToStartCall:"×××Ĩ ×××Ē×××Ē ×Š×××",realTimeVoice:"׊××× ×§××××Ē ×××× ×××Ē",startCall:"××Ē×× ×Š×××",listening:"×ק׊××...",speakFreely:"××ר ×××פ׊×××Ē",liveTranscript:"×Ē×××× ×××× ×××Ē",transcriptWillAppear:"××Ē×××× ××פ××ĸ ××× ××××× ×׊×××...",mute:"×׊×Ē×§",speaker:"ר××§××",endCall:"ץ××× ×Š×××",hello:"׊×××! ××× ×פ׊ר ××ĸ××ר?",sendMessage:"׊×× ××××ĸ× ×× ×ĸ××ר ×××Ļ× ×§××× ×׊××× ×××× ×××Ē",online:"××§×××",newChat:"×Ļ'×× ××׊",back:"×××ר",close:"ץ××ר",error:"׊××××",typeMessage:"××§×× ××××ĸ×...",sendMessageAria:"׊×× ××××ĸ×",domainNotValidated:"×××××× ×× ×××××Ē",domainErrorMessage:"×××××× ×× ×× ×ר׊×××Ē ×××ר׊××. ×× × ×¤× × ××× ×× ×××ĸר××Ē ××× ×××ץ××Ŗ ××Ē ××Ē×××Ē ×××Ēר ׊×× ×ר׊×××."},ar:{landingTitle:"ŲŲŲ ØĒØąŲØ¯ Ø§ŲØĒŲØ§ØĩŲØ",voiceCall:"Ų
ŲØ§ŲŲ
ØŠ ØĩŲØĒŲØŠ",textChat:"Ø¯ØąØ¯Ø´ØŠ ŲØĩŲØŠ",clickToStartCall:"اŲŲØą ŲØ¨Ø¯ØĄ اŲŲ
ŲØ§ŲŲ
ØŠ",realTimeVoice:"Ų
ØØ§Ø¯ØĢØŠ ØĩŲØĒŲØŠ ŲŲ Ø§ŲŲŲØĒ Ø§ŲŲØšŲŲ",startCall:"Ø§Ø¨Ø¯ØŖ اŲŲ
ŲØ§ŲŲ
ØŠ",listening:"Ø§ŲØ§ØŗØĒŲ
اؚ...",speakFreely:"ØĒŲŲŲ
Ø¨ØØąŲØŠ",liveTranscript:"ŲØĩ Ų
Ø¨Ø§Ø´Øą",transcriptWillAppear:"ØŗŲØ¸ŲØą اŲŲØĩ ŲŲØ§ ØŖØĢŲØ§ØĄ اŲŲ
ŲØ§ŲŲ
ØŠ...",mute:"ŲØĒŲ
Ø§ŲØĩŲØĒ",speaker:"Ų
ŲØ¨Øą Ø§ŲØĩŲØĒ",endCall:"ØĨŲŲØ§ØĄ اŲŲ
ŲØ§ŲŲ
ØŠ",hello:"Ų
ØąØØ¨Ø§! ŲŲŲ ŲŲ
ŲŲŲŲ Ø§ŲŲ
ØŗØ§ØšØ¯ØŠØ",sendMessage:"ØŖØąØŗŲ ØąØŗØ§ŲØŠ ŲŲØ¨Ø¯ØĄ",online:"Ų
ØĒØĩŲ",newChat:"Ų
ØØ§Ø¯ØĢØŠ ØŦØ¯ŲØ¯ØŠ",back:"ØąØŦŲØš",close:"ØĨØēŲØ§Ų",error:"ØŽØˇØŖ",typeMessage:"Ø§ŲØĒØ¨ ØąØŗØ§ŲØŠ...",sendMessageAria:"ØĨØąØŗØ§Ų ØąØŗØ§ŲØŠ",domainNotValidated:"اŲŲØˇØ§Ų ØēŲØą Ų
ØšØĒŲ
د",domainErrorMessage:"ŲØ°Ø§ اŲŲØˇØ§Ų ØēŲØą Ų
ØŗŲ
ŲØ بŲ. ŲØąØŦŲ Ø§ŲØ§ØĒØĩØ§Ų Ø¨Ø§ŲŲ
ØŗØ¤ŲŲ ŲØĨØļØ§ŲØŠ ØšŲŲØ§Ų Ų
Ųب𠨧ŲŲŲØ¨ Ø§ŲØŽØ§Øĩ Ø¨Ų ØĨŲŲ Ø§ŲŲØ§ØĻŲ
ØŠ."},ru:{landingTitle:"ĐаĐē Đ˛Ņ Ņ
ĐžŅиŅĐĩ ОйŅаŅŅŅŅ?",voiceCall:"ĐĐžĐģĐžŅОвОК СвОĐŊĐžĐē",textChat:"ĐĸĐĩĐēŅŅОвŅĐš ŅаŅ",clickToStartCall:"ĐаĐļĐŧиŅĐĩ, ŅŅĐžĐąŅ ĐŊаŅаŅŅ ĐˇĐ˛ĐžĐŊĐžĐē",realTimeVoice:"ĐĐžĐģĐžŅОвОК ŅĐ°ĐˇĐŗĐžĐ˛ĐžŅ Đ˛ ŅĐĩаĐģŅĐŊĐžĐŧ вŅĐĩĐŧĐĩĐŊи",startCall:"ĐаŅаŅŅ ĐˇĐ˛ĐžĐŊĐžĐē",listening:"ĐĄĐģŅŅаŅ...",speakFreely:"ĐОвОŅиŅĐĩ ŅвОйОдĐŊĐž",liveTranscript:"ĐĐ¸Đ˛Đ°Ņ ŅŅаĐŊŅĐēŅиĐŋŅиŅ",transcriptWillAppear:"ĐĸŅаĐŊŅĐēŅиĐŋŅĐ¸Ņ ĐŋĐžŅвиŅŅŅ ĐˇĐ´ĐĩŅŅ Đ˛Đž вŅĐĩĐŧŅ ĐˇĐ˛ĐžĐŊĐēа...",mute:"ĐŅĐēĐģŅŅиŅŅ ĐˇĐ˛ŅĐē",speaker:"ĐиĐŊаĐŧиĐē",endCall:"ĐавĐĩŅŅиŅŅ ĐˇĐ˛ĐžĐŊĐžĐē",hello:"ĐŅивĐĩŅ! ĐаĐē Ņ ĐŧĐžĐŗŅ ĐŋĐžĐŧĐžŅŅ?",sendMessage:"ĐŅĐŋŅавŅŅĐĩ ŅООйŅĐĩĐŊиĐĩ Đ´ĐģŅ ĐŊаŅаĐģа",online:"Đ ŅĐĩŅи",newChat:"ĐОвŅĐš ŅаŅ",back:"ĐаСад",close:"ĐаĐēŅŅŅŅ",error:"ĐŅийĐēа",typeMessage:"ĐвĐĩдиŅĐĩ ŅООйŅĐĩĐŊиĐĩ...",sendMessageAria:"ĐŅĐŋŅавиŅŅ ŅООйŅĐĩĐŊиĐĩ",domainNotValidated:"ĐĐžĐŧĐĩĐŊ ĐŊĐĩ ĐŋŅОвĐĩŅĐĩĐŊ",domainErrorMessage:"ĐŅĐžŅ Đ´ĐžĐŧĐĩĐŊ ĐŊĐĩ в ĐąĐĩĐģĐžĐŧ ŅĐŋиŅĐēĐĩ. ĐĐžĐļаĐģŅĐšŅŅа, ŅвŅĐļиŅĐĩŅŅ Ņ Đ°Đ´ĐŧиĐŊиŅŅŅаŅĐžŅĐžĐŧ, ŅŅĐžĐąŅ Đ´ĐžĐąĐ°Đ˛Đ¸ŅŅ URL ваŅĐĩĐŗĐž вĐĩĐą-ŅаКŅа в ŅĐŋиŅĐžĐē."},es:{landingTitle:"ÂŋCÃŗmo te gustarÃa comunicarte?",voiceCall:"Llamada de voz",textChat:"Chat de texto",clickToStartCall:"Haz clic para iniciar la llamada",realTimeVoice:"ConversaciÃŗn de voz en tiempo real",startCall:"Iniciar llamada",listening:"Escuchando...",speakFreely:"Habla libremente",liveTranscript:"TranscripciÃŗn en vivo",transcriptWillAppear:"La transcripciÃŗn aparecerÃĄ aquà durante la llamada...",mute:"Silenciar",speaker:"Altavoz",endCall:"Terminar llamada",hello:"ÂĄHola! ÂŋCÃŗmo puedo ayudarte?",sendMessage:"EnvÃa un mensaje para comenzar",online:"En lÃnea",newChat:"Nuevo chat",back:"AtrÃĄs",close:"Cerrar",error:"Error",typeMessage:"Escribe un mensaje...",sendMessageAria:"Enviar mensaje",domainNotValidated:"Dominio no validado",domainErrorMessage:"Este dominio no estÃĄ en la lista blanca. Por favor, contacte al administrador para agregar la URL de su sitio web a la lista."},fr:{landingTitle:"Comment souhaitez-vous communiquer?",voiceCall:"Appel vocal",textChat:"Chat texte",clickToStartCall:"Cliquez pour dÊmarrer l'appel",realTimeVoice:"Conversation vocale en temps rÊel",startCall:"DÊmarrer l'appel",listening:"Ãcoute...",speakFreely:"Parlez librement",liveTranscript:"TranscripciÃŗn en direct",transcriptWillAppear:"La transcription apparaÃŽtra ici pendant l'appel...",mute:"Muet",speaker:"Haut-parleur",endCall:"Terminer l'appel",hello:"Bonjour! Comment puis-je vous aider?",sendMessage:"Envoyez un message pour commencer",online:"En ligne",newChat:"Nouveau chat",back:"Retour",close:"Fermer",error:"Erreur",typeMessage:"Tapez votre message...",sendMessageAria:"Envoyer un message",domainNotValidated:"Domaine non validÊ",domainErrorMessage:"Ce domaine n'est pas sur la liste blanche. Veuillez contacter l'administrateur pour ajouter l'URL de votre site Web à la liste."},de:{landingTitle:"Wie mÃļchten Sie kommunizieren?",voiceCall:"Sprachanruf",textChat:"Text-Chat",clickToStartCall:"Klicken Sie, um den Anruf zu starten",realTimeVoice:"Sprachanruf in Echtzeit",startCall:"Anruf starten",listening:"HÃļren...",speakFreely:"Sprechen Sie frei",liveTranscript:"Live-Transkription",transcriptWillAppear:"Die Transkription erscheint hier während des Anrufs...",mute:"Stumm",speaker:"Lautsprecher",endCall:"Anruf beenden",hello:"Hallo! Wie kann ich helfen?",sendMessage:"Senden Sie eine Nachricht zum Starten",online:"Online",newChat:"Neuer Chat",back:"ZurÃŧck",close:"SchlieÃen",error:"Fehler",typeMessage:"Geben Sie eine Nachricht ein...",sendMessageAria:"Nachricht senden",domainNotValidated:"Domain nicht validiert",domainErrorMessage:"Diese Domain steht nicht auf der Whitelist. Bitte kontaktieren Sie den Administrator, um die URL Ihrer Website zur Liste hinzuzufÃŧgen."}};function _e(e,t,n,o,i,r,a){try{var s=e[r](a),c=s.value}catch(e){return void n(e)}s.done?t(c):Promise.resolve(c).then(o,i)}function Oe(e){return function(){var t=this,n=arguments;return new Promise(function(o,i){var r=e.apply(t,n);function a(e){_e(r,o,i,a,s,"next",e)}function s(e){_e(r,o,i,a,s,"throw",e)}a(void 0)})}}function Me(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function Ue(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Me(Object(n),!0).forEach(function(t){Ne(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Me(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Ne(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class ze{constructor(){var e,t,n,o,i,r,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.config=this.mergeWithDefaults(a),this.sdk=new q(this.config),this.isOpen=!1,this.isActive=!1,this.translations=Be,this.currentView="landing",this.shadowRoot=null,this.container=null,this._pendingClientTools=null,this.config.useShadowDOM?(this.createShadowHost(),this.container=this.shadowRoot):(this.createRegularContainer(),this.container=this.regularContainer,this.shadowRoot=document);var s=Ue(Ue(Ue({},this.config),this.config.voice),{},{language:(null===(e=this.config.voice)||void 0===e?void 0:e.language)||this.config.language||"en",signedUrl:this.config.signedUrl,agentSettingsOverride:this.config.agentSettingsOverride,translations:this.translations,shadowRoot:this.shadowRoot,outputContainer:(null===(t=this.config.voice)||void 0===t?void 0:t.outputContainer)||"raw",outputEncoding:(null===(n=this.config.voice)||void 0===n?void 0:n.outputEncoding)||"pcm",outputSampleRate:(null===(o=this.config.voice)||void 0===o?void 0:o.outputSampleRate)||44100,outputChannels:(null===(i=this.config.voice)||void 0===i?void 0:i.outputChannels)||1,outputBitDepth:(null===(r=this.config.voice)||void 0===r?void 0:r.outputBitDepth)||16,onConversationStart:this.config.onConversationStart,onConversationEnd:this.config.onConversationEnd,onBargeIn:this.config.onBargeIn,onAudioStartPlaying:this.config.onAudioStartPlaying,onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,onSubtitleDisplay:this.config.onSubtitleDisplay});this.voiceInterface=new Ae(s);var c=Ue(Ue(Ue({},this.config),this.config.text),{},{translations:this.translations,shadowRoot:this.shadowRoot});if(this.textInterface=new Fe(c,this.sdk),this.createWidget(),this.setupEventHandlers(),this.config.behavior.startOpen||this.config.behavior.autoOpen){var l,d=null===(l=this.shadowRoot)||void 0===l?void 0:l.getElementById("text-chat-panel");d&&(this.isOpen=!0,d.classList.add("open"))}this.checkAndHandleResume()}checkAndHandleResume(){var e=this.voiceInterface.checkAndHandleResume();e&&(console.log("đ [WIDGET] Auto-resuming call from page navigation"),console.log(" From:",e.fromPage,"â To:",e.toPage),this.open(),this.showVoice(),setTimeout(()=>{this.startVoiceCall().then(()=>{console.log("â
[WIDGET] Auto-resumed call successfully")}).catch(e=>{console.error("â [WIDGET] Failed to auto-resume call:",e)})},100))}open(){var e;if(!this.isOpen){var t=null===(e=this.shadowRoot)||void 0===e?void 0:e.getElementById("text-chat-panel");t&&(this.isOpen=!0,t.classList.add("open"))}}mergeWithDefaults(e){var t,n,o,i,r,a,s,c,l,d,u,h,p,g,m,v,f,y,x,b,w,S,C,k,P,E,T,I,A,R,D,F,B,_,O,M,U,N,z,H,L,K,V,j,W,q,Q,G,Y,J,$,X,Z,ee,te,ne,oe,ie,re,ae,se,ce,le,de,ue,he,pe,ge,me,ve,fe,ye,xe,be,we,Se,Ce,ke,Pe,Ee,Te,Ie,Ae,Re,De,Fe,Be,_e,Oe,Me,Ne,ze,He,Le,Ke,Ve,je,We,qe,Qe,Ge,Ye,Je,$e,Xe,Ze,et,tt,nt,ot,it,rt,at,st,ct,lt,dt,ut,ht,pt,gt,mt,vt,ft,yt,xt,bt,wt,St,Ct,kt,Pt,Et,Tt,It,At,Rt,Dt,Ft,Bt,_t=e.position||"bottom-right";if("string"==typeof _t){var Ot=_t.split("-");_t={vertical:Ot[0]||"bottom",horizontal:Ot[1]||"right",offset:e.positionOffset||{x:20,y:20}}}var Mt=e.primaryColor||(null===(t=e.button)||void 0===t?void 0:t.primaryColor)||(null===(n=e.button)||void 0===n?void 0:n.backgroundColor)||"#FFFFFF",Ut=(null===(o=e.header)||void 0===o?void 0:o.backgroundColor)||"#7C3AED";return Ue({agentId:e.agentId,appId:e.appId,signedUrl:e.signedUrl,agentSettingsOverride:e.agentSettingsOverride,demo:!1!==e.demo,direction:e.direction||"ltr",language:e.language||"en",icon:Ue({type:(null===(i=e.icon)||void 0===i?void 0:i.type)||"custom",customImage:(null===(r=e.icon)||void 0===r?void 0:r.customImage)||"https://talktopc.com/logo192.png",emoji:(null===(a=e.icon)||void 0===a?void 0:a.emoji)||"đ¤",text:(null===(s=e.icon)||void 0===s?void 0:s.text)||"AI",size:(null===(c=e.icon)||void 0===c?void 0:c.size)||"medium",backgroundColor:(null===(l=e.icon)||void 0===l?void 0:l.backgroundColor)||"#FFFFFF"},e.icon),position:Ue({vertical:_t.vertical||"bottom",horizontal:_t.horizontal||"right",offset:_t.offset||{x:20,y:20}},"object"==typeof e.position?e.position:{}),button:Ue({size:(null===(d=e.button)||void 0===d?void 0:d.size)||"medium",shape:(null===(u=e.button)||void 0===u?void 0:u.shape)||"circle",backgroundColor:(null===(h=e.button)||void 0===h?void 0:h.backgroundColor)||(null===(p=e.icon)||void 0===p?void 0:p.backgroundColor)||"#FFFFFF",hoverColor:(null===(g=e.button)||void 0===g?void 0:g.hoverColor)||"#D3D3D3",shadow:!1!==(null===(m=e.button)||void 0===m?void 0:m.shadow),shadowColor:(null===(v=e.button)||void 0===v?void 0:v.shadowColor)||"rgba(0,0,0,0.15)",primaryColor:(null===(f=e.button)||void 0===f?void 0:f.backgroundColor)||(null===(y=e.icon)||void 0===y?void 0:y.backgroundColor)||"#FFFFFF"},e.button),panel:Ue({width:(null===(x=e.panel)||void 0===x?void 0:x.width)||350,height:(null===(b=e.panel)||void 0===b?void 0:b.height)||500,borderRadius:(null===(w=e.panel)||void 0===w?void 0:w.borderRadius)||12,backgroundColor:(null===(S=e.panel)||void 0===S?void 0:S.backgroundColor)||"#FFFFFF",backdropFilter:(null===(C=e.panel)||void 0===C?void 0:C.backdropFilter)||null,border:(null===(k=e.panel)||void 0===k?void 0:k.border)||"1px solid #E5E7EB"},e.panel),voice:Ue({micButtonColor:(null===(P=e.voice)||void 0===P?void 0:P.micButtonColor)||(null===(E=e.panel)||void 0===E?void 0:E.micButtonColor)||Mt,micButtonActiveColor:(null===(T=e.voice)||void 0===T?void 0:T.micButtonActiveColor)||(null===(I=e.panel)||void 0===I?void 0:I.micButtonActiveColor)||"#EF4444",micButtonHint:Ue(Ue({text:(null===(A=e.voice)||void 0===A||null===(A=A.micButtonHint)||void 0===A?void 0:A.text)||(null===(R=e.panel)||void 0===R||null===(R=R.micButtonHint)||void 0===R?void 0:R.text)||"Click the button to start voice conversation",color:(null===(D=e.voice)||void 0===D||null===(D=D.micButtonHint)||void 0===D?void 0:D.color)||(null===(F=e.panel)||void 0===F||null===(F=F.micButtonHint)||void 0===F?void 0:F.color)||"#6B7280",fontSize:(null===(B=e.voice)||void 0===B||null===(B=B.micButtonHint)||void 0===B?void 0:B.fontSize)||(null===(_=e.panel)||void 0===_||null===(_=_.micButtonHint)||void 0===_?void 0:_.fontSize)||"12px"},null===(O=e.voice)||void 0===O?void 0:O.micButtonHint),null===(M=e.panel)||void 0===M?void 0:M.micButtonHint),avatarBackgroundColor:(null===(U=e.voice)||void 0===U?void 0:U.avatarBackgroundColor)||"#667eea",avatarActiveBackgroundColor:(null===(N=e.voice)||void 0===N?void 0:N.avatarActiveBackgroundColor)||"#667eea",statusTitleColor:(null===(z=e.voice)||void 0===z?void 0:z.statusTitleColor)||"#1e293b",statusSubtitleColor:(null===(H=e.voice)||void 0===H?void 0:H.statusSubtitleColor)||"#64748b",startCallButtonColor:(null===(L=e.voice)||void 0===L?void 0:L.startCallButtonColor)||"#667eea",startCallButtonTextColor:(null===(K=e.voice)||void 0===K?void 0:K.startCallButtonTextColor)||"#FFFFFF",startCallTitle:(null===(V=e.voice)||void 0===V?void 0:V.startCallTitle)||null,startCallSubtitle:(null===(j=e.voice)||void 0===j?void 0:j.startCallSubtitle)||null,startCallButtonText:(null===(W=e.voice)||void 0===W?void 0:W.startCallButtonText)||null,transcriptBackgroundColor:(null===(q=e.voice)||void 0===q?void 0:q.transcriptBackgroundColor)||"#FFFFFF",transcriptTextColor:(null===(Q=e.voice)||void 0===Q?void 0:Q.transcriptTextColor)||"#1e293b",transcriptLabelColor:(null===(G=e.voice)||void 0===G?void 0:G.transcriptLabelColor)||"#94a3b8",controlButtonColor:(null===(Y=e.voice)||void 0===Y?void 0:Y.controlButtonColor)||"#FFFFFF",controlButtonSecondaryColor:(null===(J=e.voice)||void 0===J?void 0:J.controlButtonSecondaryColor)||"#64748b",endCallButtonColor:(null===($=e.voice)||void 0===$?void 0:$.endCallButtonColor)||"#ef4444",language:(null===(X=e.voice)||void 0===X?void 0:X.language)||e.language||"en"},e.voice),text:Ue({sendButtonColor:(null===(Z=e.text)||void 0===Z?void 0:Z.sendButtonColor)||(null===(ee=e.panel)||void 0===ee?void 0:ee.sendButtonColor)||"#7C3AED",sendButtonHoverColor:(null===(te=e.text)||void 0===te?void 0:te.sendButtonHoverColor)||(null===(ne=e.panel)||void 0===ne?void 0:ne.sendButtonHoverColor)||"#6D28D9",sendButtonActiveColor:(null===(oe=e.text)||void 0===oe?void 0:oe.sendButtonActiveColor)||(null===(ie=e.panel)||void 0===ie?void 0:ie.sendButtonActiveColor)||"#6D28D9",sendButtonText:(null===(re=e.text)||void 0===re?void 0:re.sendButtonText)||(null===(ae=e.panel)||void 0===ae?void 0:ae.sendButtonText)||"â¤",sendButtonTextColor:(null===(se=e.text)||void 0===se?void 0:se.sendButtonTextColor)||(null===(ce=e.panel)||void 0===ce?void 0:ce.sendButtonTextColor)||"#FFFFFF",sendButtonFontSize:(null===(le=e.text)||void 0===le?void 0:le.sendButtonFontSize)||(null===(de=e.panel)||void 0===de?void 0:de.sendButtonFontSize)||"18px",sendButtonFontWeight:(null===(ue=e.text)||void 0===ue?void 0:ue.sendButtonFontWeight)||(null===(he=e.panel)||void 0===he?void 0:he.sendButtonFontWeight)||"500",sendButtonHint:Ue(Ue({text:(null===(pe=e.text)||void 0===pe||null===(pe=pe.sendButtonHint)||void 0===pe?void 0:pe.text)||(null===(ge=e.panel)||void 0===ge||null===(ge=ge.sendButtonHint)||void 0===ge?void 0:ge.text)||"",color:(null===(me=e.text)||void 0===me||null===(me=me.sendButtonHint)||void 0===me?void 0:me.color)||(null===(ve=e.panel)||void 0===ve||null===(ve=ve.sendButtonHint)||void 0===ve?void 0:ve.color)||"#6B7280",fontSize:(null===(fe=e.text)||void 0===fe||null===(fe=fe.sendButtonHint)||void 0===fe?void 0:fe.fontSize)||(null===(ye=e.panel)||void 0===ye||null===(ye=ye.sendButtonHint)||void 0===ye?void 0:ye.fontSize)||"12px"},null===(xe=e.text)||void 0===xe?void 0:xe.sendButtonHint),null===(be=e.panel)||void 0===be?void 0:be.sendButtonHint),inputPlaceholder:(null===(we=e.text)||void 0===we?void 0:we.inputPlaceholder)||(null===(Se=e.panel)||void 0===Se?void 0:Se.inputPlaceholder)||"Type your message...",inputBorderColor:(null===(Ce=e.text)||void 0===Ce?void 0:Ce.inputBorderColor)||(null===(ke=e.panel)||void 0===ke?void 0:ke.inputBorderColor)||"#E5E7EB",inputFocusColor:(null===(Pe=e.text)||void 0===Pe?void 0:Pe.inputFocusColor)||(null===(Ee=e.panel)||void 0===Ee?void 0:Ee.inputFocusColor)||"#7C3AED",inputBackgroundColor:(null===(Te=e.text)||void 0===Te?void 0:Te.inputBackgroundColor)||(null===(Ie=e.panel)||void 0===Ie?void 0:Ie.inputBackgroundColor)||"#FFFFFF",inputTextColor:(null===(Ae=e.text)||void 0===Ae?void 0:Ae.inputTextColor)||(null===(Re=e.panel)||void 0===Re?void 0:Re.inputTextColor)||"#1F2937",inputFontSize:(null===(De=e.text)||void 0===De?void 0:De.inputFontSize)||(null===(Fe=e.panel)||void 0===Fe?void 0:Fe.inputFontSize)||"14px",inputBorderRadius:(null===(Be=e.text)||void 0===Be?void 0:Be.inputBorderRadius)||(null===(_e=e.panel)||void 0===_e?void 0:_e.inputBorderRadius)||20,inputPadding:(null===(Oe=e.text)||void 0===Oe?void 0:Oe.inputPadding)||(null===(Me=e.panel)||void 0===Me?void 0:Me.inputPadding)||"6px 14px"},e.text),landing:Ue({backgroundColor:(null===(Ne=e.landing)||void 0===Ne?void 0:Ne.backgroundColor)||"linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%)",logo:(null===(ze=e.landing)||void 0===ze?void 0:ze.logo)||"đ¤",title:(null===(He=e.landing)||void 0===He?void 0:He.title)||null,titleColor:(null===(Le=e.landing)||void 0===Le?void 0:Le.titleColor)||"#1e293b",modeCardBackgroundColor:(null===(Ke=e.landing)||void 0===Ke?void 0:Ke.modeCardBackgroundColor)||"#FFFFFF",modeCardBorderColor:(null===(Ve=e.landing)||void 0===Ve?void 0:Ve.modeCardBorderColor)||"#E2E8F0",modeCardHoverBorderColor:(null===(je=e.landing)||void 0===je?void 0:je.modeCardHoverBorderColor)||Ut,modeCardIconBackgroundColor:(null===(We=e.landing)||void 0===We?void 0:We.modeCardIconBackgroundColor)||Ut,modeCardTitleColor:(null===(qe=e.landing)||void 0===qe?void 0:qe.modeCardTitleColor)||"#111827",voiceCardIcon:(null===(Qe=e.landing)||void 0===Qe?void 0:Qe.voiceCardIcon)||"đ¤",textCardIcon:(null===(Ge=e.landing)||void 0===Ge?void 0:Ge.textCardIcon)||"đŦ",voiceCardTitle:(null===(Ye=e.landing)||void 0===Ye?void 0:Ye.voiceCardTitle)||null,textCardTitle:(null===(Je=e.landing)||void 0===Je?void 0:Je.textCardTitle)||null},e.landing),header:Ue({title:(null===($e=e.header)||void 0===$e?void 0:$e.title)||"Chat Assistant",showTitle:!1!==(null===(Xe=e.header)||void 0===Xe?void 0:Xe.showTitle),backgroundColor:(null===(Ze=e.header)||void 0===Ze?void 0:Ze.backgroundColor)||"#7C3AED",textColor:(null===(et=e.header)||void 0===et?void 0:et.textColor)||"#FFFFFF",showCloseButton:!1!==(null===(tt=e.header)||void 0===tt?void 0:tt.showCloseButton)},e.header),footer:Ue({show:!1!==(null===(nt=e.footer)||void 0===nt?void 0:nt.show),backgroundColor:(null===(ot=e.footer)||void 0===ot?void 0:ot.backgroundColor)||"#f9fafb",textColor:(null===(it=e.footer)||void 0===it?void 0:it.textColor)||"#9ca3af",hoverColor:(null===(rt=e.footer)||void 0===rt?void 0:rt.hoverColor)||"#7C3AED"},e.footer),tooltips:Ue({newChat:(null===(at=e.tooltips)||void 0===at?void 0:at.newChat)||null,back:(null===(st=e.tooltips)||void 0===st?void 0:st.back)||null,close:(null===(ct=e.tooltips)||void 0===ct?void 0:ct.close)||null,mute:(null===(lt=e.tooltips)||void 0===lt?void 0:lt.mute)||null,speaker:(null===(dt=e.tooltips)||void 0===dt?void 0:dt.speaker)||null,endCall:(null===(ut=e.tooltips)||void 0===ut?void 0:ut.endCall)||null},e.tooltips),messages:Ue({userBackgroundColor:(null===(ht=e.messages)||void 0===ht?void 0:ht.userBackgroundColor)||"#E5E7EB",agentBackgroundColor:(null===(pt=e.messages)||void 0===pt?void 0:pt.agentBackgroundColor)||"#F3F4F6",systemBackgroundColor:(null===(gt=e.messages)||void 0===gt?void 0:gt.systemBackgroundColor)||"#DCFCE7",errorBackgroundColor:(null===(mt=e.messages)||void 0===mt?void 0:mt.errorBackgroundColor)||"#FEE2E2",textColor:(null===(vt=e.messages)||void 0===vt?void 0:vt.textColor)||"#1F2937",fontSize:(null===(ft=e.messages)||void 0===ft?void 0:ft.fontSize)||"14px",borderRadius:(null===(yt=e.messages)||void 0===yt?void 0:yt.borderRadius)||8},e.messages),animation:Ue({enableHover:!1!==(null===(xt=e.animation)||void 0===xt?void 0:xt.enableHover),enablePulse:!1!==(null===(bt=e.animation)||void 0===bt?void 0:bt.enablePulse),enableSlide:!1!==(null===(wt=e.animation)||void 0===wt?void 0:wt.enableSlide),duration:(null===(St=e.animation)||void 0===St?void 0:St.duration)||.3},e.animation),behavior:Ue({autoOpen:(null===(Ct=e.behavior)||void 0===Ct?void 0:Ct.autoOpen)||!1,startOpen:(null===(kt=e.behavior)||void 0===kt?void 0:kt.startOpen)||!1,hidden:(null===(Pt=e.behavior)||void 0===Pt?void 0:Pt.hidden)||!1,autoConnect:(null===(Et=e.behavior)||void 0===Et?void 0:Et.autoConnect)||!1,showWelcomeMessage:!1!==(null===(Tt=e.behavior)||void 0===Tt?void 0:Tt.showWelcomeMessage),welcomeMessage:(null===(It=e.behavior)||void 0===It?void 0:It.welcomeMessage)||"Hello! How can I help you today?",enableVoiceMode:void 0===(null===(At=e.behavior)||void 0===At?void 0:At.enableVoiceMode)||e.behavior.enableVoiceMode,mode:(null===(Rt=e.behavior)||void 0===Rt?void 0:Rt.mode)||"unified"},e.behavior),accessibility:Ue({ariaLabel:(null===(Dt=e.accessibility)||void 0===Dt?void 0:Dt.ariaLabel)||"Chat Assistant",ariaDescription:(null===(Ft=e.accessibility)||void 0===Ft?void 0:Ft.ariaDescription)||"Click to open chat assistant",keyboardNavigation:!1!==(null===(Bt=e.accessibility)||void 0===Bt?void 0:Bt.keyboardNavigation)},e.accessibility),customStyles:e.customStyles||"",useShadowDOM:!1!==e.useShadowDOM,variables:e.variables||{},forceConversationId:e.forceConversationId,onConversationStart:e.onConversationStart,onConversationEnd:e.onConversationEnd,onBargeIn:e.onBargeIn,onAudioStartPlaying:e.onAudioStartPlaying,onAudioStoppedPlaying:e.onAudioStoppedPlaying,onSubtitleDisplay:e.onSubtitleDisplay,primaryColor:Mt},"string"==typeof e.position?{positionString:e.position}:{})}setupEventHandlers(){this.sdk.on("domainError",e=>{this.textInterface.showError(e),this.textInterface.stopStreamingState()}),this.sdk.on("error",e=>{e&&("DOMAIN_NOT_WHITELISTED"===e.message||e.message&&e.message.includes("Domain not whitelisted"))||(this.textInterface.showError(e.message||e),this.textInterface.stopStreamingState())}),this.sdk.on("chunk",e=>{this.textInterface.appendStreamingChunk(e)}),this.sdk.on("done",e=>{var{text:t}=e;this.textInterface.finalizeStreaming(t)})}createShadowHost(){var e=document.getElementById("ttp-widget-shadow-host");e&&e.remove();var t=document.createElement("div");t.id="ttp-widget-shadow-host",t.style.cssText="position: fixed; z-index: 10000; pointer-events: none; top: 0; left: 0; width: 100%; height: 100%; overflow: visible;",this.shadowRoot=t.attachShadow({mode:"open"}),document.body.appendChild(t)}createRegularContainer(){var e=document.getElementById("ttp-widget-container");e&&e.remove();var t=document.createElement("div");t.id="ttp-widget-container",t.style.cssText="position: fixed; z-index: 10000; pointer-events: none; top: 0; left: 0; width: 100%; height: 100%; overflow: visible;",document.body.appendChild(t),this.regularContainer=t}createWidget(){this.container||(this.config.useShadowDOM?(this.createShadowHost(),this.container=this.shadowRoot):(this.createRegularContainer(),this.container=this.regularContainer,this.shadowRoot=document));var e;e=this.config.useShadowDOM?"\n :host {\n all: initial;\n display: block;\n pointer-events: none;\n }\n img {\n max-width: none !important;\n }\n #text-chat-button img {\n width: 28px !important;\n height: 28px !important;\n }\n #text-chat-button {\n pointer-events: auto;\n }\n #text-chat-panel {\n pointer-events: auto;\n }\n ":'\n /* Reset only problematic inherited styles, not all styles */\n #text-chat-button,\n #text-chat-panel,\n #text-chat-panel * {\n box-sizing: border-box;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n }\n \n /* Prevent theme CSS from affecting images */\n #text-chat-button img,\n #text-chat-panel img {\n max-width: none !important;\n width: auto;\n height: auto;\n }\n \n #text-chat-button img {\n width: 28px !important;\n height: 28px !important;\n }\n \n /* Ensure button and panel can receive clicks */\n #text-chat-button,\n #text-chat-panel {\n pointer-events: auto;\n }\n \n /* Reset any inherited text styles that might break layout */\n #text-chat-panel {\n text-align: left;\n line-height: normal;\n letter-spacing: normal;\n word-spacing: normal;\n text-transform: none;\n text-indent: 0;\n text-shadow: none;\n white-space: normal;\n }\n \n /* Ensure flexbox works properly */\n #text-chat-panel .widget-shell,\n #text-chat-panel .panel-inner,\n #text-chat-panel .widget-container,\n #text-chat-panel .landing-screen,\n #text-chat-panel .voice-interface,\n #text-chat-panel .text-interface,\n #text-chat-panel .widget-header,\n #text-chat-panel .mode-selection {\n display: flex;\n }\n \n #text-chat-panel .widget-shell,\n #text-chat-panel .panel-inner,\n #text-chat-panel .widget-container,\n #text-chat-panel .landing-screen,\n #text-chat-panel .voice-interface,\n #text-chat-panel .text-interface {\n flex-direction: column;\n }\n \n #text-chat-panel .mode-selection {\n flex-direction: row;\n }\n \n /* Ensure proper stacking */\n #text-chat-button {\n z-index: 10001 !important;\n }\n \n #text-chat-panel {\n z-index: 10000 !important;\n }\n ';var t=this.generateWidgetHTML();if(this.config.useShadowDOM){var n="\n <style>".concat(e,"</style>\n ").concat(t,"\n ");this.shadowRoot.innerHTML=n}else this.injectStylesIntoHead(e),this.container.innerHTML=t;this.setupWidgetEvents();var o=this.shadowRoot.getElementById("text-chat-panel");o&&(this.config.behavior.startOpen||this.config.behavior.autoOpen)&&(this.isOpen=!0,o.classList.add("open"))}injectStylesIntoHead(e){var t,n,o=document.getElementById("ttp-widget-styles");o&&o.remove();var i={small:50,medium:60,large:70,xl:80}[null===(t=this.config.button)||void 0===t?void 0:t.size]||60,r={small:20,medium:28,large:36,xl:44}[null===(n=this.config.icon)||void 0===n?void 0:n.size]||28,a=this.generatePositionStyles(),s=this.generateCSS(a,i,r),c=document.createElement("style");c.id="ttp-widget-styles",c.textContent=e+"\n"+s,this.config.customStyles&&(c.textContent+="\n"+this.config.customStyles),document.head.appendChild(c)}generateWidgetHTML(){this.config.position;var e,t,n,o,i=this.config.button,r=this.config.icon,a=(this.config.panel,this.config.header),s=(this.config.animation,{small:50,medium:60,large:70,xl:80}[i.size]||60),c={small:20,medium:28,large:36,xl:44}[r.size]||28,l=this.generatePositionStyles(),d=this.generateIconHTML(c),u=this.config.behavior.mode||"unified",h="unified"===u,p="unified"===u||"voice-only"===u,g="unified"===u||"text-only"===u,m=e=>{var t=this.config.language||"en";return(this.translations[t]||this.translations.en)[e]||e},v=e=>{var t,n=null===(t=this.config.tooltips)||void 0===t?void 0:t[e];return null!=n?n:{newChat:m("newChat"),back:m("back"),close:m("close"),mute:m("mute"),speaker:m("speaker"),endCall:m("endCall")}[e]||""},f=this.config.useShadowDOM?"\n <style>\n ".concat(this.generateCSS(l,s,c),"\n ").concat(this.config.customStyles,"\n </style>\n "):"";return"\n ".concat(f,"\n \n ").concat(this.config.behavior.hidden?"":'\n <button id="text-chat-button" \n aria-label="'.concat(this.config.accessibility.ariaLabel,'"\n aria-description="').concat(this.config.accessibility.ariaDescription,'">\n ').concat(d,"\n </button>\n "),'\n \n <div id="text-chat-panel">\n <div class="widget-shell">\n <div class="panel-inner widget-container" style="direction: ').concat(this.config.direction,';">\n <div class="widget-header" style="background: ').concat(a.backgroundColor,"; color: ").concat(a.textColor,';">\n <div>\n ').concat(a.showTitle?'<div class="header-title">'.concat(a.title,"</div>"):"",'\n <div class="header-status">\n <span class="status-dot"></span>\n <span>').concat(m("online"),'</span>\n </div>\n </div>\n \n <div style="display: flex; gap: 12px; align-items: center;">\n \x3c!-- New Chat Button (hide on landing screen, show otherwise) --\x3e\n <button class="header-icon new-chat-btn" id="newChatBtn" title="').concat(v("newChat"),'" style="').concat(h?"display: none;":"",'">\n <span style="font-size: 18px; font-weight: bold;">+</span>\n </button>\n \n \x3c!-- Back Button (only show in unified mode) --\x3e\n ').concat("unified"===u?'<button class="header-icon back-btn" id="backBtn" title="'.concat(v("back"),'" style="display: none;">\n <span style="font-size: 16px;">âš</span>\n </button>'):"","\n \n \x3c!-- Close Button --\x3e\n ").concat(a.showCloseButton?'<button class="header-icon close-btn" id="closeBtn" title="'+v("close")+'"><span style="font-size: 18px; font-weight: bold;">Ã</span></button>':"","\n </div>\n </div>\n\n ").concat(h?'\n <div class="landing-screen" id="landingScreen">\n <div class="landing-logo">'.concat((null===(e=this.config.landing)||void 0===e?void 0:e.logo)||"đ¤",'</div>\n <div class="landing-title">').concat((null===(t=this.config.landing)||void 0===t?void 0:t.title)||m("landingTitle"),'</div>\n <div class="mode-selection">\n ').concat(p?'<div class="mode-card voice" id="mode-card-voice">\n <div class="mode-card-icon">đ¤</div>\n <div class="mode-card-title">'.concat((null===(n=this.config.landing)||void 0===n?void 0:n.voiceCardTitle)||m("voiceCall"),"</div>\n </div>"):"","\n ").concat(g?'<div class="mode-card text" id="mode-card-text">\n <div class="mode-card-icon">đŦ</div>\n <div class="mode-card-title">'.concat((null===(o=this.config.landing)||void 0===o?void 0:o.textCardTitle)||m("textChat"),"</div>\n </div>"):"","\n </div>\n </div>"):"","\n\n ").concat(p?this.voiceInterface.generateHTML():"","\n ").concat(g?this.textInterface.generateHTML():"","\n ").concat(this.generateFooterHTML(),"\n </div>\n </div>\n </div>\n ")}generateFooterHTML(){var e=this.config.footer;if(!e.show)return"";var t=encodeURIComponent(window.location.hostname||"widget"),n="https://talktopc.com?ref=widget&source=".concat(t);return'\n <div class="widget-footer" style="\n height: 36px;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background-color: '.concat(e.backgroundColor,';\n border-top: 1px solid #e5e7eb;\n flex-shrink: 0;\n ">\n <a \n href="').concat(n,'" \n target="_blank" \n rel="noopener noreferrer"\n aria-label="Visit TalkToPC website"\n class="footer-brand-link"\n style="\n display: flex;\n flex-direction: column;\n align-items: center;\n text-decoration: none;\n color: ').concat(e.textColor,';\n transition: color 0.2s ease;\n "\n onmouseover="this.style.color=\'').concat(e.hoverColor,"'\"\n onmouseout=\"this.style.color='").concat(e.textColor,'\'"\n >\n <span style="font-size: 11px; line-height: 1.3;">\n ⥠Powered by <strong>TalkToPC</strong>\n </span>\n <span style="font-size: 9px; opacity: 0.7; line-height: 1.2;">\n https://talktopc.com\n </span>\n </a>\n </div>\n ')}generatePositionStyles(){var e=this.config.position,t=e.offset||{x:20,y:20},n="";return"top"===e.vertical?n+="top: ".concat(t.y,"px;"):"bottom"===e.vertical?n+="bottom: ".concat(t.y,"px;"):"center"===e.vertical&&(n+="top: 50%; transform: translateY(-50%);"),"left"===e.horizontal?n+="left: ".concat(t.x,"px;"):"right"===e.horizontal?n+="right: ".concat(t.x,"px;"):"center"===e.horizontal&&(n+="left: 50%; transform: translateX(-50%);"),n}generateIconHTML(e){var t=this.config.icon;switch(t.type){case"custom":return'<img src="'.concat(t.customImage,'" alt="Chat Assistant" style="width: ').concat(e,"px; height: ").concat(e,'px; object-fit: contain;" />');case"emoji":return'<span style="font-size: '.concat(e,'px; line-height: 1;">').concat(t.emoji,"</span>");case"text":return'<span style="font-size: '.concat(Math.floor(.6*e),'px; font-weight: bold; color: white;">').concat(t.text,"</span>");case"microphone":default:return'<svg viewBox="0 0 24 24" style="width: '.concat(e,"px; height: ").concat(e,'px; fill: white;">\n <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/>\n <path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/>\n </svg>');case"chat":return'<svg viewBox="0 0 24 24" style="width: '.concat(e,"px; height: ").concat(e,'px; fill: white;">\n <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>\n </svg>')}}generateCSS(e,t,n){var o,i,r,a,s,c,l,d,u,h,p,g=this.config.button,m=this.config.icon,v=this.config.panel,f=this.config.header,y=(this.config.messages,this.config.animation),x=this.config.behavior.mode||"unified",b="unified"===x||"voice-only"===x,w="unified"===x||"text-only"===x,S=!1===this.config.useShadowDOM?" !important":"",C=f.backgroundColor;return'\n /* MOBILE FIRST - Default styles for all devices */\n #text-chat-widget {\n position: fixed !important;\n z-index: 10000;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n /* Mobile defaults */\n right: 10px;\n bottom: 10px;\n left: auto;\n top: auto;\n }\n \n /* Desktop positioning (only on larger screens) */\n @media (min-width: 769px) {\n #text-chat-widget {\n '.concat(e,"\n right: ").concat("right"===this.config.position.horizontal?"20px":"auto",";\n left: ").concat("left"===this.config.position.horizontal?"20px":"auto",";\n bottom: ").concat("bottom"===this.config.position.vertical?"20px":"auto",";\n top: ").concat("top"===this.config.position.vertical?"20px":"auto",";\n }\n }\n \n /* Mobile override (force mobile positioning) */\n @media (max-width: 768px) {\n #text-chat-widget {\n right: 10px !important;\n bottom: 10px !important;\n left: auto !important;\n top: auto !important;\n transform: none !important;\n }\n }\n \n @media (max-width: 480px) {\n #text-chat-widget {\n right: 8px !important;\n bottom: 8px !important;\n left: auto !important;\n top: auto !important;\n }\n }\n \n #text-chat-button {\n position: fixed;\n ").concat("bottom"===this.config.position.vertical?"bottom: ".concat((null===(o=this.config.position.offset)||void 0===o?void 0:o.y)||20,"px;"):"top: ".concat((null===(i=this.config.position.offset)||void 0===i?void 0:i.y)||20,"px;"),"\n ").concat("right"===this.config.position.horizontal?"right: ".concat((null===(r=this.config.position.offset)||void 0===r?void 0:r.x)||20,"px;"):"left: ".concat((null===(a=this.config.position.offset)||void 0===a?void 0:a.x)||20,"px;"),"\n width: ").concat(t,"px;\n height: ").concat(t,"px;\n border-radius: ").concat("circle"===g.shape?"50%":"square"===g.shape?"0":"12px",";\n background: ").concat(g.backgroundColor||m.backgroundColor||"#7C3AED",";\n border: none;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all ").concat(y.duration,"s ease;\n box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);\n touch-action: manipulation;\n -webkit-tap-highlight-color: transparent;\n -webkit-touch-callout: none;\n user-select: none;\n min-width: 44px;\n min-height: 44px;\n z-index: 10001;\n }\n \n @media (max-width: 768px) {\n #text-chat-widget {\n right: 10px !important;\n bottom: 10px !important;\n left: auto !important;\n top: auto !important;\n transform: none !important;\n }\n \n #text-chat-button {\n right: 10px !important;\n bottom: 10px !important;\n left: auto !important;\n top: auto !important;\n width: 56px !important;\n height: 56px !important;\n min-width: 56px !important;\n min-height: 56px !important;\n max-width: 56px !important;\n max-height: 56px !important;\n }\n \n #text-chat-panel {\n position: fixed !important;\n left: 10px !important;\n right: 10px !important;\n bottom: 92px !important; /* 56px button + 20px gap + 16px footer */\n top: 60px !important; /* Add top spacing */\n width: auto !important;\n max-width: none !important;\n height: auto !important; /* Change from max-height to auto */\n max-height: none !important; /* Remove max-height */\n transform: none !important;\n margin: 0 !important;\n }\n \n #text-chat-panel .widget-header {\n padding: 10px 14px;\n min-height: 56px;\n }\n \n #text-chat-panel .header-title {\n font-size: 15px;\n }\n \n #text-chat-panel .header-icon {\n width: 40px;\n height: 40px;\n min-width: 40px;\n min-height: 40px;\n }\n \n #text-chat-input {\n font-size: 16px !important; /* Prevents iOS zoom on focus */\n padding: 12px 16px !important;\n min-height: 48px !important;\n }\n \n #text-chat-send {\n min-width: 48px !important;\n min-height: 48px !important;\n width: 48px !important;\n height: 48px !important;\n }\n \n .landing-screen {\n padding: 16px;\n }\n \n .landing-logo {\n font-size: 40px;\n }\n \n .landing-title {\n font-size: 18px;\n margin-bottom: 16px;\n }\n \n .mode-selection {\n flex-direction: column;\n gap: 12px;\n align-items: center;\n }\n \n .mode-card {\n max-width: 100%;\n width: 100%;\n padding: 16px;\n }\n \n .mode-card-icon {\n width: 50px;\n height: 50px;\n font-size: 28px;\n }\n \n .mode-card-title {\n font-size: 14px;\n }\n }\n \n @media (max-width: 480px) {\n #text-chat-widget {\n right: 8px !important;\n bottom: 8px !important;\n left: auto !important;\n top: auto !important;\n }\n \n #text-chat-button {\n right: 8px !important;\n bottom: 8px !important;\n left: auto !important;\n top: auto !important;\n width: 54px !important;\n height: 54px !important;\n min-width: 54px !important;\n min-height: 54px !important;\n }\n \n #text-chat-panel {\n left: 8px !important;\n right: 8px !important;\n bottom: 86px !important; /* 54px button + 20px gap + 12px footer */\n top: 50px !important; /* Add top spacing for very small screens */\n height: auto !important;\n max-height: none !important;\n }\n \n #text-chat-panel .widget-header {\n padding: 8px 12px;\n min-height: 52px;\n }\n \n #text-chat-panel .header-title {\n font-size: 14px;\n }\n \n .landing-logo {\n font-size: 36px;\n }\n \n .landing-title {\n font-size: 16px;\n }\n }\n \n ").concat(y.enableHover?"\n #text-chat-button:hover {\n ".concat(g.hoverColor?"background: ".concat(g.hoverColor,";"):"","\n transform: scale(1.05);\n box-shadow: 0 8px 20px rgba(102, 126, 234, 0.5);\n }\n "):"","\n \n #text-chat-panel {\n display: none").concat(S,";\n position: fixed;\n bottom: calc(").concat(t,"px + 20px + 20px); /* Button + gap + reduced footer offset */\n ").concat("right"===this.config.position.horizontal?"right: 20px;":"left: 20px;","\n width: ").concat(v.width,"px;\n max-width: calc(100vw - 40px);\n height: ").concat(v.height,"px;\n max-height: calc(100vh - ").concat(t,"px - 40px - 20px); /* Account for footer height */\n background: transparent;\n border-radius: ").concat(v.borderRadius,"px;\n border: none;\n flex-direction: column;\n overflow: hidden;\n ").concat(v.backdropFilter?"backdrop-filter: ".concat(v.backdropFilter,";"):"","\n ").concat(y.enableSlide?"transition: all ".concat(y.duration,"s ease;"):"","\n box-sizing: border-box;\n }\n \n #text-chat-panel.open {\n display: flex").concat(S,";\n ").concat(y.enableSlide?"transform: translateY(0); opacity: 1;":"","\n }\n\n /* Shell for gradient border/background */\n .widget-shell { width: 100%; height: 100%; padding: 0; border-radius: ").concat(v.borderRadius,"px; background: transparent; box-shadow: 0 20px 60px rgba(0,0,0,0.15); overflow: hidden; display: flex; flex-direction: column; box-sizing: border-box; }\n .panel-inner { width: 100%; height: 100%; background: #ffffff; border-radius: ").concat(v.borderRadius,"px; border: ").concat(v.border,"; overflow: hidden; display:flex; flex-direction: column; padding: 0; box-sizing: border-box; max-width: 100%; }\n\n /* New structure styles matching provided design */\n #text-chat-panel .widget-container {\n width: 100%; height: 100%; min-height: 0; background: #FFFFFF; overflow: hidden; display: flex; flex-direction: column; border-radius: ").concat(v.borderRadius,"px;\n container-type: size;\n }\n \n /* Ensure content areas can scroll when height is constrained */\n #text-chat-panel .widget-container > .landing-screen,\n #text-chat-panel .widget-container > .voice-interface,\n #text-chat-panel .widget-container > .text-interface {\n flex: 1;\n min-height: 0;\n overflow-y: auto;\n overflow-x: hidden;\n }\n \n /* Header should not scroll */\n #text-chat-panel .widget-header {\n padding: 12px 16px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n border-top-left-radius: ").concat(v.borderRadius,"px;\n border-top-right-radius: ").concat(v.borderRadius,"px;\n flex-shrink: 0;\n min-height: 60px;\n box-sizing: border-box;\n }\n #text-chat-panel .header-title { font-size: 16px; font-weight: 600; }\n #text-chat-panel .header-status { display: flex; align-items: center; gap: 8px; font-size: 12px; opacity: 0.9; }\n #text-chat-panel .status-dot { width: 8px; height: 8px; background: #4ade80; border-radius: 50%; animation: pulse 2s ease-in-out infinite; }\n @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }\n /* Header icon buttons */\n .header-icon {\n background: rgba(255, 255, 255, 0.2);\n border: none;\n color: white;\n width: 36px;\n height: 36px;\n min-width: 36px;\n min-height: 36px;\n border-radius: 50%;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.2s;\n flex-shrink: 0;\n font-size: 16px;\n padding: 0;\n box-sizing: border-box;\n }\n \n .header-icon:hover {\n background: rgba(255, 255, 255, 0.3);\n }\n \n .header-icon svg {\n pointer-events: none;\n stroke: white;\n fill: none;\n }\n \n .back-btn.visible {\n display: flex !important;\n }\n\n /* Landing and mode selection (shown only if voice enabled) */\n .landing-screen { \n display: none").concat(S,"; \n flex: 1; \n padding: 20px; \n background: ").concat((null===(s=this.config.landing)||void 0===s?void 0:s.backgroundColor)||"linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%)","; \n align-items: center; \n justify-content: flex-start; \n flex-direction: column; \n gap: 16px; \n overflow-y: auto; \n min-height: 0; \n }\n .landing-screen.active { display: flex").concat(S,"; }\n .landing-logo { font-size: 48px; }\n .landing-title { \n font-size: 20px; \n color: ").concat((null===(c=this.config.landing)||void 0===c?void 0:c.titleColor)||"#1e293b","; \n font-weight: 700; \n margin-bottom: 20px; \n text-align: center;\n width: 100%;\n }\n .mode-selection { display: flex; gap: 16px; width: 100%; justify-content: center; }\n .mode-card { \n flex: 1; \n max-width: 180px; \n background: ").concat((null===(l=this.config.landing)||void 0===l?void 0:l.modeCardBackgroundColor)||"#FFFFFF","; \n border: 2px solid ").concat((null===(d=this.config.landing)||void 0===d?void 0:d.modeCardBorderColor)||"#E2E8F0","; \n border-radius: 20px; \n padding: 20px 12px; \n cursor: pointer; \n display: flex; \n flex-direction: column; \n align-items: center; \n gap: 8px; \n transition: transform ").concat(y.duration,"s ease, box-shadow ").concat(y.duration,"s ease, border-color ").concat(y.duration,"s ease; \n box-shadow: 0 4px 12px rgba(0,0,0,0.05); \n }\n .mode-card:hover { \n transform: translateY(-6px); \n box-shadow: 0 12px 24px rgba(102, 126, 234, 0.2); \n border-color: ").concat((null===(u=this.config.landing)||void 0===u?void 0:u.modeCardHoverBorderColor)||C,"; \n }\n .mode-card-icon { \n width: 60px; \n height: 60px; \n display: flex; \n align-items: center; \n justify-content: center; \n border-radius: 50%; \n background: ").concat((null===(h=this.config.landing)||void 0===h?void 0:h.modeCardIconBackgroundColor)||C,"; \n color: #fff; \n font-size: 32px; \n }\n .mode-card-title { \n color: ").concat((null===(p=this.config.landing)||void 0===p?void 0:p.modeCardTitleColor)||"#111827","; \n font-weight: 600; \n text-align: center;\n width: 100%;\n }\n\n ").concat(b?this.voiceInterface.generateCSS():"","\n ").concat(w?this.textInterface.generateCSS():"","\n \n /* Footer Branding */\n .widget-footer {\n box-sizing: border-box;\n }\n \n .footer-brand-link {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n }\n \n .footer-brand-link:hover {\n opacity: 0.9;\n }\n \n @media (max-width: 768px) {\n .widget-footer {\n height: 32px;\n }\n .widget-footer span {\n font-size: 10px;\n }\n .widget-footer span:last-child {\n font-size: 8px;\n }\n }\n \n #text-chat-send-hint {\n text-align: center;\n line-height: 1.4;\n }\n \n .agent-thinking {\n font-style: italic;\n color: #6B7280;\n }\n ")}setupWidgetEvents(){if(this.shadowRoot){var e=this.shadowRoot.getElementById("text-chat-button");e&&(e.onclick=()=>this.togglePanel());var t=this.shadowRoot.getElementById("closeBtn");t&&(t.onclick=()=>this.togglePanel());var n=this.config.behavior.mode||"unified",o="unified"===n,i="unified"===n||"voice-only"===n,r="unified"===n||"text-only"===n,a=this.shadowRoot.getElementById("backBtn"),s=this.shadowRoot.getElementById("landingScreen"),c=this.shadowRoot.getElementById("mode-card-voice"),l=this.shadowRoot.getElementById("mode-card-text"),d=this.shadowRoot.getElementById("textInterface"),u=this.shadowRoot.getElementById("voiceInterface");a&&(a.onclick=()=>this.showLanding()),o?(c&&(c.onclick=()=>this.showVoice()),l&&(l.onclick=()=>this.showText()),"text"===this.currentView?(s&&s.classList.remove("active"),d&&d.classList.add("active"),u&&u.classList.remove("active"),a&&"unified"===n&&a.classList.add("visible"),h&&(h.style.display="")):"voice"===this.currentView?(s&&s.classList.remove("active"),d&&d.classList.remove("active"),u&&u.classList.add("active"),a&&"unified"===n&&a.classList.add("visible"),h&&(h.style.display="none")):(this.currentView="landing",s&&s.classList.add("active"),d&&d.classList.remove("active"),u&&u.classList.remove("active"),a&&"unified"===n&&a.classList.remove("visible"))):"voice-only"===n?(u&&u.classList.add("active"),d&&d.classList.remove("active"),s&&s.classList.remove("active")):"text-only"===n&&(d&&d.classList.add("active"),u&&u.classList.remove("active"),s&&s.classList.remove("active")),i&&(console.log("âī¸ Setting up voice interface event handlers"),this.voiceInterface.setupEventHandlers()),r&&(console.log("âī¸ Setting up text interface event handlers"),this.textInterface.setupEventHandlers());var h=this.shadowRoot.getElementById("newChatBtn");h&&(h.onclick=()=>this.textInterface.startNewChat(),o&&(h.style.display="none")),this.config.accessibility.keyboardNavigation&&this.setupKeyboardNavigation()}}startNewChat(){this.textInterface.startNewChat()}showLanding(){if(this.shadowRoot&&"unified"===(this.config.behavior.mode||"unified")){this.currentView="landing";var e=this.shadowRoot.getElementById("landingScreen"),t=this.shadowRoot.getElementById("textInterface"),n=this.shadowRoot.getElementById("voiceInterface"),o=this.shadowRoot.getElementById("backBtn"),i=this.shadowRoot.getElementById("newChatBtn");e&&e.classList.add("active"),t&&t.classList.remove("active"),n&&n.classList.remove("active"),o&&o.classList.remove("visible"),i&&(i.style.display="none")}}showText(){if(this.shadowRoot){this.currentView="text";var e=this.shadowRoot.getElementById("landingScreen"),t=this.shadowRoot.getElementById("voiceInterface"),n=this.shadowRoot.getElementById("backBtn"),o=this.shadowRoot.getElementById("newChatBtn");e&&e.classList.remove("active"),t&&t.classList.remove("active"),this.textInterface.show();var i=this.config.behavior.mode||"unified";n&&"unified"===i&&n.classList.add("visible"),o&&(o.style.display="")}}showVoice(){if(this.shadowRoot){this.currentView="voice";var e=this.shadowRoot.getElementById("landingScreen"),t=this.shadowRoot.getElementById("textInterface"),n=this.shadowRoot.getElementById("voiceInterface"),o=this.shadowRoot.getElementById("backBtn"),i=this.shadowRoot.getElementById("newChatBtn");e&&e.classList.remove("active"),t&&t.classList.remove("active"),n&&n.classList.add("active");var r=this.config.behavior.mode||"unified";o&&"unified"===r&&o.classList.add("visible"),i&&(i.style.display="none")}}setupKeyboardNavigation(){document.addEventListener("keydown",e=>{"Escape"===e.key&&this.isOpen&&this.togglePanel()})}togglePanel(){if(this.shadowRoot){this.isOpen=!this.isOpen;var e=this.shadowRoot.getElementById("text-chat-panel");e&&e.classList.toggle("open"),this.isOpen&&setTimeout(()=>{var e=this.shadowRoot.getElementById("messageInput");e&&e.focus()},100),this.isOpen&&!this.isActive&&this.config.behavior.autoConnect&&this.startChat()}}startChat(){var e=this;return Oe(function*(){e.isActive=!0,e.textInterface.setActive(!0)})()}sendMessage(){var e=this;return Oe(function*(){yield e.textInterface.sendMessage()})()}updateSendButtonState(){this.textInterface.updateSendButtonState()}getSignedUrl(){var e=this;return Oe(function*(){if(e.config.signedUrl)return e.config.signedUrl;if(!e.config.agentId)throw new Error("agentId is required when signedUrl is not provided");var t=e.config.websocketUrl||"wss://backend.talktopc.com/ws/conv",n=new URLSearchParams;return n.append("agentId",e.config.agentId),e.config.appId&&n.append("appId",e.config.appId),!1!==e.config.demo&&n.append("demo","true"),"".concat(t,"?").concat(n.toString())})()}addMessage(e,t){this.textInterface.addMessage(e,t)}beginStreaming(){this.textInterface.beginStreaming()}appendStreamingChunk(e){this.textInterface.appendStreamingChunk(e)}finalizeStreaming(e){this.textInterface.finalizeStreaming(e)}stopStreamingState(){this.textInterface.stopStreamingState()}showError(e){this.textInterface.showError(e)}updateStatus(e){}updateConfig(e){var t,n,o,i,r,a,s,c,l,d=Ue({},this.config);e.panel&&(d.panel=Ue(Ue({},this.config.panel),e.panel)),e.voice&&(d.voice=Ue(Ue({},this.config.voice),e.voice),e.voice.micButtonHint&&(d.voice.micButtonHint=Ue(Ue({},null===(c=this.config.voice)||void 0===c?void 0:c.micButtonHint),e.voice.micButtonHint))),e.text&&(d.text=Ue(Ue({},this.config.text),e.text),e.text.sendButtonHint&&(d.text.sendButtonHint=Ue(Ue({},null===(l=this.config.text)||void 0===l?void 0:l.sendButtonHint),e.text.sendButtonHint))),void 0!==e.language&&(d.language=e.language),void 0!==e.language&&(["he","ar"].includes(e.language)?d.direction="rtl":void 0===e.direction&&(d.direction="ltr")),e.translations&&(d.translations=e.translations,this.translations=e.translations),e.button&&(d.button=Ue(Ue({},this.config.button),e.button)),e.header&&(d.header=Ue(Ue({},this.config.header),e.header)),e.icon&&(d.icon=Ue(Ue({},this.config.icon),e.icon)),e.messages&&(d.messages=Ue(Ue({},this.config.messages),e.messages)),e.animation&&(d.animation=Ue(Ue({},this.config.animation),e.animation)),e.behavior&&(d.behavior=Ue(Ue({},this.config.behavior),e.behavior)),e.accessibility&&(d.accessibility=Ue(Ue({},this.config.accessibility),e.accessibility)),e.tooltips&&(d.tooltips=Ue(Ue({},this.config.tooltips),e.tooltips)),e.landing&&(d.landing=Ue(Ue({},this.config.landing),e.landing)),e.footer&&(d.footer=Ue(Ue({},this.config.footer),e.footer)),void 0!==e.direction&&void 0===d.direction&&(d.direction=e.direction),void 0!==e.primaryColor&&(d.primaryColor=e.primaryColor),d.onConversationStart=void 0!==e.onConversationStart?e.onConversationStart:this.config.onConversationStart,d.onConversationEnd=void 0!==e.onConversationEnd?e.onConversationEnd:this.config.onConversationEnd,d.onBargeIn=void 0!==e.onBargeIn?e.onBargeIn:this.config.onBargeIn,d.onAudioStartPlaying=void 0!==e.onAudioStartPlaying?e.onAudioStartPlaying:this.config.onAudioStartPlaying,d.onAudioStoppedPlaying=void 0!==e.onAudioStoppedPlaying?e.onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,d.onSubtitleDisplay=void 0!==e.onSubtitleDisplay?e.onSubtitleDisplay:this.config.onSubtitleDisplay,void 0!==e.useShadowDOM&&(d.useShadowDOM=e.useShadowDOM),Object.keys(e).forEach(t=>{["panel","button","header","footer","icon","messages","direction","voice","text","animation","behavior","accessibility","language","tooltips","landing","primaryColor","useShadowDOM","onConversationStart","onConversationEnd","onBargeIn","onAudioStartPlaying","onAudioStoppedPlaying","onSubtitleDisplay"].includes(t)||(d[t]=e[t])}),null===(t=this.config)||void 0===t||t.language;var u=!1!==(null===(n=this.config)||void 0===n?void 0:n.useShadowDOM);if(this.config=this.mergeWithDefaults(d),!1!==this.config.useShadowDOM===u&&this.container){var h=document.getElementById("ttp-widget-shadow-host");h&&!this.config.useShadowDOM&&h.remove();var p=document.getElementById("ttp-widget-container");if(p&&this.config.useShadowDOM&&p.remove(),this.config.useShadowDOM)if(this.shadowRoot)this.container=this.shadowRoot;else{var g=document.getElementById("ttp-widget-shadow-host");g?(this.shadowRoot=g.shadowRoot,this.container=this.shadowRoot):(this.createShadowHost(),this.container=this.shadowRoot)}else{if(this.regularContainer)this.container=this.regularContainer;else{var m=document.getElementById("ttp-widget-container");m?(this.regularContainer=m,this.container=m):(this.createRegularContainer(),this.container=this.regularContainer)}this.shadowRoot=document}}else{var v=document.getElementById("ttp-widget-shadow-host");v&&v.remove();var f=document.getElementById("ttp-widget-container");if(f&&f.remove(),!1===u){var y=document.getElementById("ttp-widget-styles");y&&y.remove()}this.config.useShadowDOM?(this.createShadowHost(),this.container=this.shadowRoot):(this.createRegularContainer(),this.container=this.regularContainer,this.shadowRoot=document)}var x=this.config.language||"en",b=Ue(Ue(Ue({},this.config),this.config.voice),{},{language:x,translations:this.translations,shadowRoot:this.shadowRoot,outputContainer:(null===(o=this.config.voice)||void 0===o?void 0:o.outputContainer)||"raw",outputEncoding:(null===(i=this.config.voice)||void 0===i?void 0:i.outputEncoding)||"pcm",outputSampleRate:(null===(r=this.config.voice)||void 0===r?void 0:r.outputSampleRate)||44100,outputChannels:(null===(a=this.config.voice)||void 0===a?void 0:a.outputChannels)||1,outputBitDepth:(null===(s=this.config.voice)||void 0===s?void 0:s.outputBitDepth)||16,onConversationStart:this.config.onConversationStart,onConversationEnd:this.config.onConversationEnd,onBargeIn:this.config.onBargeIn,onAudioStartPlaying:this.config.onAudioStartPlaying,onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,onSubtitleDisplay:this.config.onSubtitleDisplay});this.voiceInterface=new Ae(b);var w=Ue(Ue(Ue({},this.config),this.config.text),{},{language:x,translations:this.translations,shadowRoot:this.shadowRoot});this.textInterface=new Fe(w,this.sdk),this.createWidget(),this.textInterface&&this.textInterface.updateInputAttributes&&this.textInterface.updateInputAttributes()}destroy(){var e=document.getElementById("ttp-widget-shadow-host");e&&e.remove();var t=document.getElementById("ttp-widget-container");t&&t.remove();var n=document.getElementById("ttp-widget-styles");n&&n.remove(),this.sdk&&this.sdk.destroy(),this.voiceInterface&&this.voiceInterface.destroy()}startVoiceCall(){var e=this;return Oe(function*(){yield e.voiceInterface.startVoiceCall(),e._flushPendingClientTools()})()}endVoiceCall(){this.voiceInterface.endVoiceCall()}toggleMute(){this.voiceInterface.toggleMute()}toggleSpeaker(){this.voiceInterface.toggleSpeaker()}registerToolHandler(e,t){var n;return null!==(n=this.voiceInterface)&&void 0!==n&&n.sdk?this.voiceInterface.sdk.registerToolHandler(e,t):(this._pendingClientTools=this._pendingClientTools||[],this._pendingClientTools.push({name:e,handler:t}),console.warn("TTPChatWidget: Tool handler queued - voice interface SDK not ready yet"),this._flushPendingClientTools(),this)}unregisterToolHandler(e){var t;return null!==(t=this.voiceInterface)&&void 0!==t&&t.sdk?this.voiceInterface.sdk.unregisterToolHandler(e):(this._pendingClientTools&&(this._pendingClientTools=this._pendingClientTools.filter(t=>t.name!==e)),this)}hasToolHandler(e){var t;return!(null===(t=this.voiceInterface)||void 0===t||!t.sdk)&&this.voiceInterface.sdk.hasToolHandler(e)}getRegisteredTools(){var e;return null!==(e=this.voiceInterface)&&void 0!==e&&e.sdk?this.voiceInterface.sdk.getRegisteredTools():this._pendingClientTools?this._pendingClientTools.map(e=>e.name):[]}_flushPendingClientTools(){var e;this._pendingClientTools&&null!==(e=this.voiceInterface)&&void 0!==e&&e.sdk&&(this._pendingClientTools.forEach(e=>{var{name:t,handler:n}=e;this.voiceInterface.sdk.registerToolHandler(t,n)}),this._pendingClientTools=null,console.log("TTPChatWidget: Flushed pending client tools"))}registerClientTool(e,t){return this.registerToolHandler(e,t)}unregisterClientTool(e){return this.unregisterToolHandler(e)}hasClientTool(e){return this.hasToolHandler(e)}getRegisteredClientTools(){return this.getRegisteredTools()}}var He="2.18.0";const Le={VoiceSDK_v2:H,TextChatSDK:q,WebSocketManager:J,AudioRecorder:Z,AudioPlayer:ne,EventEmitter:L,VoiceButton:ce,VanillaVoiceButton:pe,AgentSDK:ve,TTPChatWidget:ze,VERSION:He};export{ve as AgentSDK,ne as AudioPlayer,Z as AudioRecorder,L as EventEmitter,s as MicPermissionModals,a as MicPermissionUtils,ze as TTPChatWidget,q as TextChatSDK,He as VERSION,pe as VanillaVoiceButton,ce as VoiceButton,H as VoiceSDK_v2,J as WebSocketManager,Le as default};
|
|
3
3
|
//# sourceMappingURL=agent-widget.esm.js.map
|