ttp-agent-sdk 2.20.0 → 2.22.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.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/*! For license information please see agent-widget.js.LICENSE.txt */
|
|
2
|
-
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.TTPAgentSDK=e():t.TTPAgentSDK=e()}(window,()=>(()=>{"use strict";var t={540:(t,e,n)=>{t.exports=n(869)},698:(t,e)=>{var n=Symbol.for("react.transitional.element");function o(t,e,o){var r=null;if(void 0!==o&&(r=""+o),void 0!==e.key&&(r=""+e.key),"key"in e)for(var i in o={},e)"key"!==i&&(o[i]=e[i]);else o=e;return e=o.ref,{$$typeof:n,type:t,key:r,ref:void 0!==e?e:null,props:o}}Symbol.for("react.fragment"),e.jsx=o,e.jsxs=o},848:(t,e,n)=>{t.exports=n(698)},869:(t,e)=>{Symbol.for("react.transitional.element"),Symbol.for("react.portal"),Symbol.for("react.fragment"),Symbol.for("react.strict_mode"),Symbol.for("react.profiler"),Symbol.for("react.consumer"),Symbol.for("react.context"),Symbol.for("react.forward_ref"),Symbol.for("react.suspense"),Symbol.for("react.memo"),Symbol.for("react.lazy"),Symbol.for("react.activity"),Symbol.iterator;var n={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},o=Object.assign,r={};function i(t,e,o){this.props=t,this.context=e,this.refs=r,this.updater=o||n}function a(){}function s(t,e,o){this.props=t,this.context=e,this.refs=r,this.updater=o||n}i.prototype.isReactComponent={},i.prototype.setState=function(t,e){if("object"!=typeof t&&"function"!=typeof t&&null!=t)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")},i.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")},a.prototype=i.prototype;var c=s.prototype=new a;c.constructor=s,o(c,i.prototype),c.isPureReactComponent=!0;Array.isArray;var l={H:null,A:null,T:null,S:null};Object.prototype.hasOwnProperty;"function"==typeof reportError&&reportError;e.useEffect=function(t,e){return l.H.useEffect(t,e)},e.useRef=function(t){return l.H.useRef(t)},e.useState=function(t){return l.H.useState(t)}}},e={};function n(o){var r=e[o];if(void 0!==r)return r.exports;var i=e[o]={exports:{}};return t[o](i,i.exports,n),i.exports}n.d=(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var o={};n.r(o),n.d(o,{AgentSDK:()=>eo,AudioPlayer:()=>nt,AudioRecorder:()=>W,EventEmitter:()=>l,MicPermissionModals:()=>i,MicPermissionUtils:()=>r,TTPChatWidget:()=>qo,TextChatSDK:()=>Sn,VERSION:()=>Qo,VanillaVoiceButton:()=>Vn,VoiceButton:()=>Dn,VoiceSDK:()=>kt,VoiceSDK_v2:()=>cn,WebSocketManager:()=>D,default:()=>Yo});var r={};n.r(r),n.d(r,{checkPermissionState:()=>ao,getDeviceInfo:()=>io,getPermissionInstructions:()=>co,openSettings:()=>lo});var i={};function a(t){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a(t)}function s(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,c(o.key),o)}}function c(t){var e=function(t){if("object"!=a(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=a(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==a(e)?e:e+""}n.r(i),n.d(i,{showBlockedModal:()=>yo,showNoMicrophoneModal:()=>bo,showPrePromptModal:()=>mo});var l=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.events={}},e=[{key:"on",value:function(t,e){this.events[t]||(this.events[t]=[]),this.events[t].push(e)}},{key:"off",value:function(t,e){this.events[t]&&(this.events[t]=this.events[t].filter(function(t){return t!==e}))}},{key:"emit",value:function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),o=1;o<e;o++)n[o-1]=arguments[o];this.events[t]&&this.events[t].forEach(function(e){try{e.apply(void 0,n)}catch(e){console.error("Error in event listener for ".concat(t,":"),e)}})}},{key:"removeAllListeners",value:function(t){t?delete this.events[t]:this.events={}}}],e&&s(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function u(t){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u(t)}function d(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var o,r,i,a,s=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(o=i.call(n)).done)&&(s.push(o.value),s.length!==e);c=!0);}catch(t){l=!0,r=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw r}}return s}}(t,e)||f(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=f(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}function f(t,e){if(t){if("string"==typeof t)return h(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?h(t,e):void 0}}function h(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}function g(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return v(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(v(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,v(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,v(d,"constructor",l),v(l,"constructor",c),c.displayName="GeneratorFunction",v(l,r,"GeneratorFunction"),v(d),v(d,r,"Generator"),v(d,o,function(){return this}),v(d,"toString",function(){return"[object Generator]"}),(g=function(){return{w:i,m:p}})()}function v(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}v=function(t,e,n,o){function i(e,n){v(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},v(t,e,n,o)}function m(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function y(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,b(o.key),o)}}function b(t){var e=function(t){if("object"!=u(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=u(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==u(e)?e:e+""}function w(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(w=function(){return!!t})()}function S(t){return S=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},S(t)}function x(t,e){return x=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},x(t,e)}const k=new(function(t){function e(){var t;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(t=function(t,e,n){return e=S(e),function(t,e){if(e&&("object"==u(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,w()?Reflect.construct(e,n||[],S(t).constructor):e.apply(t,n))}(this,e)).connections=new Map,t.connectionCounts=new Map,t.creatingConnections=new Set,t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&x(t,e)}(e,t),n=e,o=[{key:"getConnection",value:(r=g().m(function t(e){var n,o,r=this;return g().w(function(t){for(;;)switch(t.n){case 0:if(!this.connections.has(e)){t.n=1;break}return n=this.connections.get(e),this.connectionCounts.set(e,(this.connectionCounts.get(e)||0)+1),t.a(2,n);case 1:if(!this.creatingConnections||!this.creatingConnections.has(e)){t.n=2;break}return t.a(2,new Promise(function(t){var n=function(){if(r.connections.has(e)){var o=r.connections.get(e);r.connectionCounts.set(e,(r.connectionCounts.get(e)||0)+1),t(o)}else setTimeout(n,50)};n()}));case 2:return this.creatingConnections.add(e),o=new WebSocket(e),this.connections.set(e,o),this.connectionCounts.set(e,1),o.addEventListener("open",function(t){r.creatingConnections.delete(e),r.emit("open",t,e)}),o.addEventListener("close",function(t){r.creatingConnections.delete(e),r.connections.delete(e),r.connectionCounts.delete(e),r.emit("close",t,e)}),o.addEventListener("error",function(t){r.creatingConnections.delete(e),r.emit("error",t,e)}),o.addEventListener("message",function(t){r.emit("message",t,e)}),t.a(2,o)}},t,this)}),i=function(){var t=this,e=arguments;return new Promise(function(n,o){var i=r.apply(t,e);function a(t){m(i,n,o,a,s,"next",t)}function s(t){m(i,n,o,a,s,"throw",t)}a(void 0)})},function(t){return i.apply(this,arguments)})},{key:"releaseConnection",value:function(t){if(this.connections.has(t)){var e=this.connectionCounts.get(t)||0,n=Math.max(0,e-1);if(this.connectionCounts.set(t,n),0===n){var o=this.connections.get(t);o&&o.readyState===WebSocket.OPEN&&o.close(1e3,"No more subscribers"),this.connections.delete(t),this.connectionCounts.delete(t)}}}},{key:"forceClose",value:function(t){if(this.connections.has(t)){var e=this.connections.get(t);e&&e.readyState===WebSocket.OPEN&&e.close(1e3,"Force close"),this.connections.delete(t),this.connectionCounts.delete(t)}}},{key:"getConnectionStatus",value:function(t){return this.connections.has(t)?{exists:!0,readyState:this.connections.get(t).readyState,subscribers:this.connectionCounts.get(t)||0}:{exists:!1,readyState:null,subscribers:0}}},{key:"getAllConnections",value:function(){var t,e={},n=p(this.connections.entries());try{for(n.s();!(t=n.n()).done;){var o=d(t.value,2),r=o[0],i=o[1];e[r]={readyState:i.readyState,subscribers:this.connectionCounts.get(r)||0}}}catch(t){n.e(t)}finally{n.f()}return e}},{key:"clearAll",value:function(){var t,e=p(this.connections.entries());try{for(e.s();!(t=e.n()).done;){var n=d(t.value,2),o=(n[0],n[1]);o&&o.readyState===WebSocket.OPEN&&o.close(1e3,"Clear all")}}catch(t){e.e(t)}finally{e.f()}this.connections.clear(),this.connectionCounts.clear(),this.creatingConnections.clear()}}],o&&y(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(l));function C(t){return C="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},C(t)}function P(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return T(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(T(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,T(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,T(d,"constructor",l),T(l,"constructor",c),c.displayName="GeneratorFunction",T(l,r,"GeneratorFunction"),T(d),T(d,r,"Generator"),T(d,o,function(){return this}),T(d,"toString",function(){return"[object Generator]"}),(P=function(){return{w:i,m:p}})()}function T(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}T=function(t,e,n,o){function i(e,n){T(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},T(t,e,n,o)}function E(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function O(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,A(o.key),o)}}function A(t){var e=function(t){if("object"!=C(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=C(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==C(e)?e:e+""}function I(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(I=function(){return!!t})()}function R(t){return R=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},R(t)}function j(t,e){return j=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},j(t,e)}var D=function(t){function e(t){var n;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(n=function(t,e,n){return e=R(e),function(t,e){if(e&&("object"==C(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,I()?Reflect.construct(e,n||[],R(t).constructor):e.apply(t,n))}(this,e)).config=t,n.ws=null,n.isConnected=!1,n.connectionId=null,n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&j(t,e)}(e,t),n=e,o=[{key:"connect",value:(i=P().m(function t(){var e=this;return P().w(function(t){for(;;)if(0===t.n)return t.a(2,new Promise(function(t,n){try{e.connectionId=Date.now()+"_"+Math.random().toString(36).substr(2,9),e.connectResolve=t,e.connectReject=n;var o=e.config.signedUrl||e.config.websocketUrl;k.getConnection(o,e.config).then(function(n){e.ws=n,e.setupEventListeners(),n.readyState===WebSocket.OPEN&&(e.isConnected=!0,e.emit("connected"),t(),e.connectResolve=null,e.connectReject=null)}).catch(function(t){console.error("🔌 WebSocketManager: Connection failed ".concat(e.connectionId),t),n(t),e.connectResolve=null,e.connectReject=null})}catch(t){console.error("🔌 WebSocketManager: Connection error ".concat(e.connectionId),t),n(t),e.connectResolve=null,e.connectReject=null}}))},t)}),a=function(){var t=this,e=arguments;return new Promise(function(n,o){var r=i.apply(t,e);function a(t){E(r,n,o,a,s,"next",t)}function s(t){E(r,n,o,a,s,"throw",t)}a(void 0)})},function(){return a.apply(this,arguments)})},{key:"setupEventListeners",value:function(){var t=this;if(this.ws){var e=function(e,n){n===(t.config.signedUrl||t.config.websocketUrl)&&(t.isConnected=!0,t.emit("connected"),t.connectResolve&&(t.connectResolve(),t.connectResolve=null,t.connectReject=null))},n=function(e,n){n===(t.config.signedUrl||t.config.websocketUrl)&&(t.isConnected=!1,t.emit("disconnected",e))},o=function(e,n){n===(t.config.signedUrl||t.config.websocketUrl)&&(t.emit("error",e),t.connectReject&&(t.connectReject(e),t.connectResolve=null,t.connectReject=null))},r=function(e,n){n===(t.config.signedUrl||t.config.websocketUrl)&&t.handleMessage(e)};k.on("open",e),k.on("close",n),k.on("error",o),k.on("message",r),this.eventHandlers={open:e,close:n,error:o,message:r}}}},{key:"disconnect",value:function(){this.eventHandlers&&(k.off("open",this.eventHandlers.open),k.off("close",this.eventHandlers.close),k.off("error",this.eventHandlers.error),k.off("message",this.eventHandlers.message));var t=this.config.signedUrl||this.config.websocketUrl;t&&k.releaseConnection(t),this.ws=null,this.isConnected=!1}},{key:"sendMessage",value:function(t){if(this.isConnected&&this.ws)try{this.ws.send(JSON.stringify(t))}catch(t){console.warn("🔌 WebSocketManager: Failed to send message:",t.message)}}},{key:"sendBinary",value:function(t){if(this.isConnected&&this.ws)try{this.ws.send(t)}catch(t){console.warn("🔌 WebSocketManager: Failed to send binary data:",t.message)}}},{key:"handleMessage",value:function(t){var e=this;if(t.data instanceof ArrayBuffer)this.emit("binaryAudio",t.data);else if(t.data instanceof Blob)t.data.arrayBuffer().then(function(t){e.emit("binaryAudio",t)}).catch(function(t){console.error("🔌 WebSocketManager: Error converting Blob to ArrayBuffer:",t)});else try{var n=JSON.parse(t.data);"barge_in_ack"!==n.t&&"stop_sending"!==n.t||this.emit("bargeIn",n),"stop_playing"===n.t&&this.emit("stopPlaying",n),this.emit("message",n)}catch(t){this.emit("error",t)}}},{key:"getStatus",value:function(){return{isConnected:this.isConnected,readyState:this.ws?this.ws.readyState:null,connectionId:this.connectionId}}}],r=[{key:"getSingletonStatus",value:function(){return k.getAllConnections()}},{key:"clearAllConnections",value:function(){k.clearAll()}}],o&&O(n.prototype,o),r&&O(n,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a}(l);function F(t){return F="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},F(t)}function _(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return B(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(B(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,B(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,B(d,"constructor",l),B(l,"constructor",c),c.displayName="GeneratorFunction",B(l,r,"GeneratorFunction"),B(d),B(d,r,"Generator"),B(d,o,function(){return this}),B(d,"toString",function(){return"[object Generator]"}),(_=function(){return{w:i,m:p}})()}function B(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}B=function(t,e,n,o){function i(e,n){B(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},B(t,e,n,o)}function M(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function U(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){M(i,o,r,a,s,"next",t)}function s(t){M(i,o,r,a,s,"throw",t)}a(void 0)})}}function N(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}function z(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,H(o.key),o)}}function H(t){var e=function(t){if("object"!=F(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=F(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==F(e)?e:e+""}function L(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(L=function(){return!!t})()}function V(t){return V=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},V(t)}function K(t,e){return K=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},K(t,e)}var W=function(t){function e(t){var n;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(n=function(t,e,n){return e=V(e),function(t,e){if(e&&("object"==F(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,L()?Reflect.construct(e,n||[],V(t).constructor):e.apply(t,n))}(this,e)).config=t,n.audioContext=null,n.audioWorkletNode=null,n.mediaStream=null,n.isRecording=!1,n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&K(t,e)}(e,t),n=e,o=[{key:"getAudioProcessorPath",value:function(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var t,e=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return N(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?N(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}(document.getElementsByTagName("script"));try{for(e.s();!(t=e.n()).done;){var n=t.value.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(t){var r=n.substring(0,n.lastIndexOf("/"));return"".concat(r,"/audio-processor.js")}}}catch(t){e.e(t)}finally{e.f()}return"https://cdn.talktopc.com/audio-processor.js"}},{key:"checkPermissionState",value:function(){var t=U(_().m(function t(){var e;return _().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,!navigator.permissions||!navigator.permissions.query){t.n=2;break}return t.n=1,navigator.permissions.query({name:"microphone"});case 1:return e=t.v,t.a(2,e.state);case 2:t.n=4;break;case 3:t.p=3,t.v,console.log("⚠️ AudioRecorder: Permissions API not available or not supported for microphone");case 4:return t.a(2,null)}},t,null,[[0,3]])}));return function(){return t.apply(this,arguments)}}()},{key:"requestPermission",value:(a=U(_().m(function t(){var e,n;return _().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,t.n=1,this.checkPermissionState();case 1:if("granted"!==t.v){t.n=2;break}return console.log("✅ AudioRecorder: Microphone permission already granted"),t.a(2,!0);case 2:return console.log("🎤 AudioRecorder: Requesting microphone permission..."),e=this.config.sampleRate||this.config.outputSampleRate||44100,t.n=3,navigator.mediaDevices.getUserMedia({audio:{sampleRate:e,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 3:return t.v.getTracks().forEach(function(t){return t.stop()}),console.log("✅ AudioRecorder: Microphone permission granted"),t.a(2,!0);case 4:return t.p=4,n=t.v,console.error("❌ AudioRecorder: Failed to get microphone permission:",n),t.a(2,!1)}},t,this,[[0,4]])})),function(){return a.apply(this,arguments)})},{key:"start",value:(i=U(_().m(function t(){var e,n,o,r,i,a,s,c=this;return _().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,console.log("🎤 AudioRecorder: Requesting microphone access..."),t.n=1,this.checkPermissionState();case 1:return(e=t.v)&&(console.log("📋 AudioRecorder: Current permission state: ".concat(e)),"denied"===e&&console.warn('⚠️ AudioRecorder: Permission state is "denied" - browser may not show prompt. User may need to change in browser settings.')),n=this.config.sampleRate||this.config.outputSampleRate||44100,t.n=2,navigator.mediaDevices.getUserMedia({audio:{sampleRate:n,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 2:if(this.mediaStream=t.v,this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:n}),"suspended"!==this.audioContext.state){t.n=3;break}return t.n=3,this.audioContext.resume();case 3:return o=this.getAudioProcessorPath(),t.n=4,this.audioContext.audioWorklet.addModule(o);case 4:this.audioWorkletNode=new AudioWorkletNode(this.audioContext,"audio-processor",{processorOptions:{sampleRate:n,outputSampleRate:this.config.outputSampleRate}}),this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.audioWorkletNode),this.audioWorkletNode.port.onmessage=function(t){var e=t.data,n=e.type,o=e.data;"pcm_audio_data"===n&&c.emit("audioData",o)},this.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),console.log("✅ AudioRecorder: Microphone access granted"),this.isRecording=!0,this.emit("recordingStarted"),t.n=9;break;case 5:if(t.p=5,s=t.v,r=s.message,"NotAllowedError"!==s.name&&"PermissionDeniedError"!==s.name){t.n=7;break}return t.n=6,this.checkPermissionState();case 6:"denied"===(i=t.v)?(r='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"===i?(r='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.')):(r="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.")),t.n=8;break;case 7:"NotFoundError"===s.name||"DevicesNotFoundError"===s.name?(r="No microphone found. Please connect a microphone and try again.",console.error("❌ AudioRecorder: No microphone device found.")):"NotReadableError"===s.name||"TrackStartError"===s.name?(r="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"!==s.name&&"PermissionDeniedError"!==s.name||(r="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."));case 8:throw(a=new Error(r)).name=s.name,a.originalError=s,this.emit("error",a),a;case 9:return t.a(2)}},t,this,[[0,5]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:(r=U(_().m(function t(){var e;return _().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.isRecording){t.n=1;break}return t.a(2);case 1:if(t.p=1,!this.audioWorkletNode){t.n=2;break}return this.audioWorkletNode.port.postMessage({type:"flush"}),t.n=2,new Promise(function(t){return setTimeout(t,100)});case 2:if(this.mediaStream&&(this.mediaStream.getTracks().forEach(function(t){return t.stop()}),this.mediaStream=null),!this.audioContext||"closed"===this.audioContext.state){t.n=4;break}return t.n=3,this.audioContext.close();case 3:this.audioContext=null;case 4:this.audioWorkletNode=null,this.isRecording=!1,this.emit("recordingStopped"),t.n=6;break;case 5:throw t.p=5,e=t.v,this.emit("error",e),e;case 6:return t.a(2)}},t,this,[[1,5]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop()}}],o&&z(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a}(l);function G(t){return G="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},G(t)}function q(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Q(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Q(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Q(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Q(d,"constructor",l),Q(l,"constructor",c),c.displayName="GeneratorFunction",Q(l,r,"GeneratorFunction"),Q(d),Q(d,r,"Generator"),Q(d,o,function(){return this}),Q(d,"toString",function(){return"[object Generator]"}),(q=function(){return{w:i,m:p}})()}function Q(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Q=function(t,e,n,o){function i(e,n){Q(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Q(t,e,n,o)}function Y(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function $(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){Y(i,o,r,a,s,"next",t)}function s(t){Y(i,o,r,a,s,"throw",t)}a(void 0)})}}function J(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,X(o.key),o)}}function X(t){var e=function(t){if("object"!=G(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=G(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==G(e)?e:e+""}function Z(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(Z=function(){return!!t})()}function tt(t){return tt=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},tt(t)}function et(t,e){return et=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},et(t,e)}var nt=function(t){function e(t){var n;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(n=function(t,e,n){return e=tt(e),function(t,e){if(e&&("object"==G(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,Z()?Reflect.construct(e,n||[],tt(t).constructor):e.apply(t,n))}(this,e)).config=t,n.audioContext=null,n.audioQueue=[],n.isPlaying=!1,n.isProcessingQueue=!1,n.currentSource=null,n.audioContextReady=!1,n.initializeAudioContext().catch(function(){}),n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&et(t,e)}(e,t),n=e,o=[{key:"initializeAudioContext",value:(a=$(q().m(function t(){var e,n,o,r,i,a;return q().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.audioContext||"closed"===this.audioContext.state){t.n=1;break}return t.a(2);case 1:if(t.p=1,e=this.config.sampleRate||this.config.outputSampleRate||44100,n={sampleRate:e},this.audioContext=new(window.AudioContext||window.webkitAudioContext)(n),"suspended"!==this.audioContext.state){t.n=2;break}return t.n=2,this.audioContext.resume();case 2:if("running"===this.audioContext.state)try{o=this.audioContext.sampleRate,r=this.audioContext.createBuffer(1,.01*o,o),(i=this.audioContext.createBufferSource()).buffer=r,i.connect(this.audioContext.destination),i.start(0),i.stop(this.audioContext.currentTime+.01)}catch(t){console.debug("AudioPlayer: AudioContext warmup skipped:",t)}this.audioContextReady=!0,t.n=4;break;case 3:t.p=3,a=t.v,console.warn("AudioPlayer: Failed to pre-initialize AudioContext:",a),this.audioContextReady=!1;case 4:return t.a(2)}},t,this,[[1,3]])})),function(){return a.apply(this,arguments)})},{key:"playAudio",value:function(t){var e=this;try{var n=this.createAudioBlob(t);if(this.audioQueue.push(n),!this.isPlaying&&!this.isProcessingQueue&&!this.currentSource){var o=this.audioContextReady?0:50;setTimeout(function(){return e.processQueue()},o)}}catch(t){this.emit("playbackError",t)}}},{key:"createAudioBlob",value:function(t){var e=new Uint8Array(t);if(e.length>=4){if(82===e[0]&&73===e[1]&&70===e[2]&&70===e[3])return new Blob([t],{type:"audio/wav"});if(255===e[0]&&!(224&~e[1]))return new Blob([t],{type:"audio/mpeg"});if(79===e[0]&&103===e[1]&&103===e[2]&&83===e[3])return new Blob([t],{type:"audio/ogg"})}return new Blob([t],{type:"audio/wav"})}},{key:"processQueue",value:(i=$(q().m(function t(){var e,n,o,r,i,a,s,c,l=this;return q().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isProcessingQueue&&0!==this.audioQueue.length){t.n=1;break}return t.a(2);case 1:if(this.isProcessingQueue=!0,e=this.audioQueue.shift()){t.n=2;break}return this.isProcessingQueue=!1,t.a(2);case 2:if(t.p=2,n=!this.isPlaying&&null===this.currentSource,this.audioContext&&"closed"!==this.audioContext.state){t.n=3;break}return t.n=3,this.initializeAudioContext();case 3:if("suspended"!==(o=this.audioContext).state){t.n=5;break}return t.n=4,o.resume();case 4:if(!n){t.n=5;break}return t.n=5,new Promise(function(t){return setTimeout(t,10)});case 5:if("running"===o.state){t.n=7;break}if(console.warn("AudioPlayer: AudioContext not in running state:",o.state),"suspended"!==o.state){t.n=7;break}return t.n=6,o.resume();case 6:return t.n=7,new Promise(function(t){return setTimeout(t,10)});case 7:return t.n=8,e.arrayBuffer();case 8:return r=t.v,t.n=9,o.decodeAudioData(r);case 9:i=t.v,a=n&&!this.isPlaying&&null===this.currentSource,(s=o.createBufferSource()).buffer=i,s.connect(o.destination),this.currentSource=s,this.isPlaying=!0,a&&this.emit("playbackStarted"),s.onended=function(){l.currentSource=null,l.isProcessingQueue=!1,l.audioQueue.length>0?setTimeout(function(){return l.processQueue()},0):setTimeout(function(){0!==l.audioQueue.length||l.currentSource||(l.isPlaying=!1,l.emit("playbackStopped"))},100)},s.start(),t.n=11;break;case 10:t.p=10,c=t.v,this.currentSource=null,this.emit("playbackError",c),this.audioQueue.length>0?(this.isProcessingQueue=!1,setTimeout(function(){return l.processQueue()},100)):(this.isPlaying=!1,this.isProcessingQueue=!1,this.emit("playbackStopped"));case 11:return t.a(2)}},t,this,[[2,10]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:function(){this.stopImmediate()}},{key:"stopImmediate",value:function(){var t=this.isPlaying||null!==this.currentSource;if(this.currentSource){try{this.currentSource.stop()}catch(t){}this.currentSource=null}this.isPlaying=!1,this.isProcessingQueue=!1,this.audioQueue=[],t&&this.emit("playbackStopped")}},{key:"resumeAudioContext",value:(r=$(q().m(function t(){var e;return q().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.audioContext&&"closed"!==this.audioContext.state){t.n=2;break}return t.n=1,this.initializeAudioContext();case 1:return t.a(2);case 2:if("suspended"!==this.audioContext.state){t.n=6;break}return t.p=3,t.n=4,this.audioContext.resume();case 4:console.log("✅ AudioPlayer: AudioContext resumed after mic permission"),t.n=6;break;case 5:t.p=5,e=t.v,console.warn("⚠️ AudioPlayer: Failed to resume AudioContext:",e);case 6:return t.a(2)}},t,this,[[3,5]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isPlaying:this.isPlaying,isProcessingQueue:this.isProcessingQueue,queueLength:this.audioQueue.length,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.audioContextReady=!1}}],o&&J(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a}(l);function ot(t){return ot="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ot(t)}function rt(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return it(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(it(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,it(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,it(d,"constructor",l),it(l,"constructor",c),c.displayName="GeneratorFunction",it(l,r,"GeneratorFunction"),it(d),it(d,r,"Generator"),it(d,o,function(){return this}),it(d,"toString",function(){return"[object Generator]"}),(rt=function(){return{w:i,m:p}})()}function it(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}it=function(t,e,n,o){function i(e,n){it(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},it(t,e,n,o)}function at(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function st(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,ct(o.key),o)}}function ct(t){var e=function(t){if("object"!=ot(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=ot(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==ot(e)?e:e+""}const lt=function(){return t=function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.handlers=new Map,this.sendMessage=e},e=[{key:"registerHandler",value:function(t,e){if("function"!=typeof e)throw new Error("Handler for tool '".concat(t,"' must be a function"));this.handlers.set(t,e),console.log("🔧 ClientTools: Registered handler for '".concat(t,"'"))}},{key:"unregisterHandler",value:function(t){this.handlers.delete(t),console.log("🔧 ClientTools: Unregistered handler for '".concat(t,"'"))}},{key:"hasHandler",value:function(t){return this.handlers.has(t)}},{key:"getRegisteredTools",value:function(){return Array.from(this.handlers.keys())}},{key:"handleToolCall",value:(n=rt().m(function t(e){var n,o,r,i,a,s,c,l,u,d,p,f;return rt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(n=e.toolCallId,o=e.toolName,r=e.parameters,i=Date.now(),console.log("🔧 ClientTools: Received tool call '".concat(o,"' (id: ").concat(n,")")),a=this.handlers.get(o)){t.n=1;break}return console.warn("🔧 ClientTools: No handler registered for '".concat(o,"'")),this.sendError(n,"No handler registered for tool '".concat(o,"'"),"NO_HANDLER",i),t.a(2);case 1:return t.p=1,t.n=2,a(r);case 2:s=t.v,c=Date.now()-i,console.log("🔧 ClientTools: Tool '".concat(o,"' completed in ").concat(c,"ms")),this.sendResult(n,s,c),t.n=4;break;case 3:t.p=3,f=t.v,d=Date.now()-i,console.error("🔧 ClientTools: Tool '".concat(o,"' failed:"),f),p="EXECUTION_ERROR","NotAllowedError"===f.name||null!==(l=f.message)&&void 0!==l&&l.includes("permission")?p="PERMISSION_DENIED":("NotSupportedError"===f.name||null!==(u=f.message)&&void 0!==u&&u.includes("not supported"))&&(p="API_UNAVAILABLE"),this.sendError(n,f.message||"Unknown error",p,d);case 4:return t.a(2)}},t,this,[[1,3]])}),o=function(){var t=this,e=arguments;return new Promise(function(o,r){var i=n.apply(t,e);function a(t){at(i,o,r,a,s,"next",t)}function s(t){at(i,o,r,a,s,"throw",t)}a(void 0)})},function(t){return o.apply(this,arguments)})},{key:"sendResult",value:function(t,e,n){this.sendMessage({t:"client_tool_result",toolCallId:t,result:e,executionTimeMs:n})}},{key:"sendError",value:function(t,e,n,o){var r="number"==typeof o?Date.now()-o:o;this.sendMessage({t:"client_tool_error",toolCallId:t,error:e,errorCode:n,executionTimeMs:r})}},{key:"setSendMessage",value:function(t){this.sendMessage=t}}],e&&st(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();function ut(t){return ut="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ut(t)}function dt(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return pt(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(pt(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,pt(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,pt(d,"constructor",l),pt(l,"constructor",c),c.displayName="GeneratorFunction",pt(l,r,"GeneratorFunction"),pt(d),pt(d,r,"Generator"),pt(d,o,function(){return this}),pt(d,"toString",function(){return"[object Generator]"}),(dt=function(){return{w:i,m:p}})()}function pt(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}pt=function(t,e,n,o){function i(e,n){pt(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},pt(t,e,n,o)}function ft(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function ht(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){ft(i,o,r,a,s,"next",t)}function s(t){ft(i,o,r,a,s,"throw",t)}a(void 0)})}}function gt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function vt(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?gt(Object(n),!0).forEach(function(e){mt(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):gt(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function mt(t,e,n){return(e=bt(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function yt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,bt(o.key),o)}}function bt(t){var e=function(t){if("object"!=ut(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=ut(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==ut(e)?e:e+""}function wt(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(wt=function(){return!!t})()}function St(t){return St=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},St(t)}function xt(t,e){return xt=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},xt(t,e)}var kt=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(t=function(t,e,n){return e=St(e),function(t,e){if(e&&("object"==ut(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,wt()?Reflect.construct(e,n||[],St(t).constructor):e.apply(t,n))}(this,e)).config=vt({signedUrl:n.signedUrl||n.websocketUrl||"wss://speech.talktopc.com/ws/conv",websocketUrl:n.signedUrl||n.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:n.agentId,appId:n.appId,ttpId:n.ttpId,voice:n.voice||"default",language:n.language||"en",sampleRate:n.sampleRate||n.outputSampleRate||44100,agentSettingsOverride:n.agentSettingsOverride||null,onStartConversation:n.onStartConversation||null,onEndConversation:n.onEndConversation||null},n),t.isConnected=!1,t.isRecording=!1,t.isPlaying=!1,t.isDestroyed=!1,t.conversationStarted=!1,t.webSocketManager=new D(vt(vt({},t.config),{},{autoReconnect:!1!==t.config.autoReconnect})),t.audioRecorder=new W(t.config),t.audioPlayer=new nt(t.config),t.clientToolsRegistry=new lt(function(e){return t.webSocketManager.sendMessage(e)}),t.setupEventHandlers(),t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&xt(t,e)}(e,t),n=e,o=[{key:"setupEventHandlers",value:function(){var t=this;this.webSocketManager.on("connected",function(){t.isConnected=!0,t.sendHelloMessage(),t.emit("connected")}),this.webSocketManager.on("disconnected",function(e){if(t.isConnected=!1,t.conversationStarted&&(t.conversationStarted=!1,console.log("🏁 VoiceSDK: Conversation ended (connection closed)"),t.emit("conversationEnded",{}),t.config.onEndConversation))try{t.config.onEndConversation({})}catch(t){console.error("VoiceSDK: Error in onEndConversation hook:",t)}if(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.emit("domainError",n),t.emit("error",n)}t.isRecording&&t.stopRecording().catch(function(t){console.error("VoiceSDK: Error stopping recording on disconnect:",t)}),t.emit("disconnected",e)}),this.webSocketManager.on("error",function(e){t.emit("error",e)}),this.webSocketManager.on("message",function(e){if("client_tool_call"!==e.t&&"client_tool_call"!==e.type){if(("hello_ack"===e.t||"hello_ack"===e.type)&&!t.conversationStarted&&(t.conversationStarted=!0,console.log("🎬 VoiceSDK: Conversation started"),t.emit("conversationStarted",{conversationId:e.conversationId}),t.config.onStartConversation))try{t.config.onStartConversation({conversationId:e.conversationId})}catch(t){console.error("VoiceSDK: Error in onStartConversation hook:",t)}if("greeting_audio"===e.t&&e.data)try{for(var n=atob(e.data),o=new Uint8Array(n.length),r=0;r<n.length;r++)o[r]=n.charCodeAt(r);t.audioPlayer.playAudio(o),t.emit("greetingStarted")}catch(t){console.error("VoiceSDK: Error playing greeting audio:",t)}else t.emit("message",e)}else t.clientToolsRegistry.handleToolCall(e)}),this.webSocketManager.on("binaryAudio",function(e){t.audioPlayer.playAudio(e)}),this.webSocketManager.on("bargeIn",function(e){t.emit("bargeIn",e)}),this.webSocketManager.on("stopPlaying",function(e){t.emit("stopPlaying",e),t.audioPlayer.stopImmediate()}),this.audioRecorder.on("recordingStarted",function(){if(t.isRecording=!0,!t.conversationStarted&&(t.conversationStarted=!0,console.log("🎬 VoiceSDK: Conversation started (recording)"),t.emit("conversationStarted",{}),t.config.onStartConversation))try{t.config.onStartConversation({})}catch(t){console.error("VoiceSDK: Error in onStartConversation hook:",t)}t.isPlaying&&(t.audioPlayer.stopImmediate(),t.isConnected&&t.webSocketManager.sendMessage({t:"barge_in"})),t.emit("recordingStarted")}),this.audioRecorder.on("recordingStopped",function(){t.isRecording=!1,t.emit("recordingStopped")}),this.audioRecorder.on("audioData",function(e){t.isConnected&&t.webSocketManager.sendBinary(e)}),this.audioPlayer.on("playbackStarted",function(){t.isPlaying=!0,t.emit("playbackStarted"),t.isConnected&&t.webSocketManager.sendMessage({t:"audio_started_playing"})}),this.audioPlayer.on("playbackStopped",function(){t.isPlaying=!1,t.emit("playbackStopped"),t.isConnected&&t.webSocketManager.sendMessage({t:"audio_stopped_playing"})}),this.audioPlayer.on("playbackError",function(e){t.emit("playbackError",e)})}},{key:"connect",value:(l=ht(dt().m(function t(){var e,n;return dt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isDestroyed){t.n=1;break}return console.warn("VoiceSDK: Cannot connect - SDK is destroyed"),t.a(2,!1);case 1:return t.p=1,e=this.buildWebSocketUrl(),this.webSocketManager.config.signedUrl=e,this.webSocketManager.config.websocketUrl=e,t.n=2,this.webSocketManager.connect();case 2:return t.a(2,!0);case 3:return t.p=3,n=t.v,console.error("🔌 VoiceSDK: Connection failed with error:",n),this.emit("error",n),t.a(2,!1)}},t,this,[[1,3]])})),function(){return l.apply(this,arguments)})},{key:"buildWebSocketUrl",value:function(){var t=this.config.signedUrl||this.config.websocketUrl,e=new URLSearchParams;if(this.config.agentId&&e.append("agentId",this.config.agentId),this.config.appId&&e.append("appId",this.config.appId),this.config.voice&&"default"!==this.config.voice&&e.append("voice",this.config.voice),this.config.language&&"en"!==this.config.language&&e.append("language",this.config.language),e.toString()){var n=t.includes("?")?"&":"?";t+=n+e.toString()}return t}},{key:"disconnect",value:function(){if(!this.isDestroyed){if(this.conversationStarted&&(this.conversationStarted=!1,console.log("🏁 VoiceSDK: Conversation ended"),this.emit("conversationEnded",{}),this.config.onEndConversation))try{this.config.onEndConversation({})}catch(t){console.error("VoiceSDK: Error in onEndConversation hook:",t)}this.stopRecording(),this.webSocketManager.disconnect()}}},{key:"resetReconnectionAttempts",value:function(){this.isDestroyed||this.webSocketManager.resetReconnectionAttempts()}},{key:"reconnect",value:(c=ht(dt().m(function t(){var e=this;return dt().w(function(t){for(;;)switch(t.n){case 0:if(!this.isDestroyed){t.n=1;break}return t.a(2,!1);case 1:return this.disconnect(),this.resetReconnectionAttempts(),this.clientToolsRegistry.setSendMessage(function(t){return e.webSocketManager.sendMessage(t)}),t.n=2,this.connect();case 2:return t.a(2,t.v)}},t,this)})),function(){return c.apply(this,arguments)})},{key:"startRecording",value:(s=ht(dt().m(function t(){var e,n;return dt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.isConnected){t.n=1;break}throw new Error("Not connected to voice server");case 1:return t.p=1,console.log("🎤 VoiceSDK: Requesting microphone permission (mobile-friendly)..."),t.n=2,this.audioRecorder.start();case 2:return t.n=3,this.audioPlayer.resumeAudioContext();case 3:return this.webSocketManager.sendMessage({t:"start_continuous_mode",ttpId:this.generateTtpId(),voice:this.config.voice,language:this.config.language}),t.a(2,!0);case 4:return t.p=4,n=t.v,console.error("❌ VoiceSDK: Failed to start recording:",n),"NotAllowedError"===n.name||"PermissionDeniedError"===n.name?((e=new Error("Microphone permission denied. Please allow microphone access in your browser settings and try again.")).name=n.name,e.originalError=n,this.emit("error",e)):this.emit("error",n),t.a(2,!1)}},t,this,[[1,4]])})),function(){return s.apply(this,arguments)})},{key:"stopRecording",value:(a=ht(dt().m(function t(){var e;return dt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.isRecording){t.n=1;break}return t.a(2);case 1:return t.p=1,this.webSocketManager.sendMessage({t:"stop_continuous_mode",ttpId:this.generateTtpId()}),t.n=2,this.audioRecorder.stop();case 2:return this.audioPlayer.stopImmediate(),t.a(2,!0);case 3:return t.p=3,e=t.v,this.emit("error",e),t.a(2,!1)}},t,this,[[1,3]])})),function(){return a.apply(this,arguments)})},{key:"toggleRecording",value:(i=ht(dt().m(function t(){return dt().w(function(t){for(;;)switch(t.n){case 0:if(!this.isRecording){t.n=2;break}return t.n=1,this.stopRecording();case 1:case 3:return t.a(2,t.v);case 2:return t.n=3,this.startRecording();case 4:return t.a(2)}},t,this)})),function(){return i.apply(this,arguments)})},{key:"stopAudioPlayback",value:function(){this.audioPlayer.stopImmediate()}},{key:"handleBargeIn",value:(r=ht(dt().m(function t(){return dt().w(function(t){for(;;)switch(t.n){case 0:if(this.stopAudioPlayback(),this.isRecording){t.n=1;break}return t.n=1,this.startRecording();case 1:return t.a(2)}},t,this)})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying}}},{key:"updateConfig",value:function(t){this.config=vt(vt({},this.config),t)}},{key:"generateTtpId",value:function(){return"sdk_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"registerToolHandler",value:function(t,e){return this.clientToolsRegistry.registerHandler(t,e)}},{key:"unregisterToolHandler",value:function(t){return this.clientToolsRegistry.unregisterHandler(t)}},{key:"hasToolHandler",value:function(t){return this.clientToolsRegistry.hasHandler(t)}},{key:"getRegisteredTools",value:function(){return this.clientToolsRegistry.getRegisteredTools()}},{key:"sendHelloMessage",value:function(){if(this.isConnected){var t={t:"hello"};if(!this.config.appId){var e=new Error("appId is required for connection");return console.error("VoiceSDK: Failed to send hello message:",e),void this.emit("error",e)}t.appId=this.config.appId,this.config.agentSettingsOverride&&Object.keys(this.config.agentSettingsOverride).length>0&&(t.agentSettingsOverride=this.config.agentSettingsOverride,console.log("🔧 VoiceSDK: Sending agent settings override:",Object.keys(this.config.agentSettingsOverride)));try{this.webSocketManager.sendMessage(t)}catch(e){console.error("VoiceSDK: Failed to send hello message:",e),this.emit("error",e)}}else console.warn("VoiceSDK: Cannot send hello message - not connected")}},{key:"destroy",value:function(){this.isDestroyed||(this.disconnect(),this.isDestroyed=!0,this.audioRecorder.destroy(),this.audioPlayer.destroy(),this.removeAllListeners())}}],o&&yt(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,s,c,l}(l);function Ct(t){return Ct="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ct(t)}function Pt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Tt(o.key),o)}}function Tt(t){var e=function(t){if("object"!=Ct(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Ct(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Ct(e)?e:e+""}var Et=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.events={}},e=[{key:"on",value:function(t,e){return this.events[t]||(this.events[t]=[]),this.events[t].push(e),this}},{key:"off",value:function(t,e){return this.events[t]?(this.events[t]=this.events[t].filter(function(t){return t!==e}),this):this}},{key:"emit",value:function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),o=1;o<e;o++)n[o-1]=arguments[o];return!!this.events[t]&&(this.events[t].forEach(function(t){t.apply(void 0,n)}),!0)}},{key:"once",value:function(t,e){var n=this,o=function(){e.apply(void 0,arguments),n.off(t,o)};return this.on(t,o)}},{key:"removeAllListeners",value:function(t){return t?delete this.events[t]:this.events={},this}}],e&&Pt(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();const Ot=Et;function At(t){return At="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},At(t)}function It(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Rt(o.key),o)}}function Rt(t){var e=function(t){if("object"!=At(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=At(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==At(e)?e:e+""}const jt=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.name="PCM"},(e=[{key:"decode",value:function(t){if(t instanceof ArrayBuffer)return t;if(t instanceof Uint8Array)return t.buffer;throw new Error("Invalid PCM data type")}},{key:"encode",value:function(t){return t}}])&&It(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function Dt(t){return Dt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Dt(t)}function Ft(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,_t(o.key),o)}}function _t(t){var e=function(t){if("object"!=Dt(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Dt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Dt(e)?e:e+""}const Bt=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.name="PCMU"},(e=[{key:"decode",value:function(t){for(var e=t instanceof Uint8Array?t:new Uint8Array(t),n=new Int16Array(e.length),o=0;o<e.length;o++)n[o]=this.mulawToLinear(e[o]);return n.buffer}},{key:"encode",value:function(t){for(var e=t instanceof Int16Array?t:new Int16Array(t),n=new Uint8Array(e.length),o=0;o<e.length;o++)n[o]=this.linearToMulaw(e[o]);return n}},{key:"mulawToLinear",value:function(t){var e=1<<3+(t>>4&7);return(128&t?-1:1)*(132+(15&t)*e+(e>>1)-4)}},{key:"linearToMulaw",value:function(t){var e=t>>8&128;e&&(t=-t),t>32635&&(t=32635),t+=132;for(var n=7,o=16384;0===(t&o)&&n>0;n--,o>>=1);return 255&~(e|n<<4|t>>n+3&15)}}])&&Ft(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function Mt(t){return Mt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Mt(t)}function Ut(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Nt(o.key),o)}}function Nt(t){var e=function(t){if("object"!=Mt(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Mt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Mt(e)?e:e+""}const zt=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.name="PCMA"},(e=[{key:"decode",value:function(t){for(var e=t instanceof Uint8Array?t:new Uint8Array(t),n=new Int16Array(e.length),o=0;o<e.length;o++)n[o]=this.alawToLinear(e[o]);return n.buffer}},{key:"encode",value:function(t){for(var e=t instanceof Int16Array?t:new Int16Array(t),n=new Uint8Array(e.length),o=0;o<e.length;o++)n[o]=this.linearToAlaw(e[o]);return n}},{key:"alawToLinear",value:function(t){var e=(t^=85)>>4&7,n=15&t;return(128&t?-1:1)*(0===e?8+(n<<4):264+(n<<4)<<e-1)}},{key:"linearToAlaw",value:function(t){var e,n,o=t>>8&128;if(o&&(t=-t),t>32635&&(t=32635),t<256)e=0,n=t>>4;else{e=7;for(var r=16384;0===(t&r)&&e>0;e--,r>>=1);n=t>>e+3&15}return 85^(o|e<<4|n)}}])&&Ut(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function Ht(t){return Ht="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ht(t)}function Lt(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Vt(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Vt(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}function Vt(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}function Kt(t){if(null!=t){var e=t["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],n=0;if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length))return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}}}throw new TypeError(Ht(t)+" is not iterable")}function Wt(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Gt(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Gt(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Gt(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Gt(d,"constructor",l),Gt(l,"constructor",c),c.displayName="GeneratorFunction",Gt(l,r,"GeneratorFunction"),Gt(d),Gt(d,r,"Generator"),Gt(d,o,function(){return this}),Gt(d,"toString",function(){return"[object Generator]"}),(Wt=function(){return{w:i,m:p}})()}function Gt(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Gt=function(t,e,n,o){function i(e,n){Gt(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Gt(t,e,n,o)}function qt(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Qt(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){qt(i,o,r,a,s,"next",t)}function s(t){qt(i,o,r,a,s,"throw",t)}a(void 0)})}}function Yt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,$t(o.key),o)}}function $t(t){var e=function(t){if("object"!=Ht(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Ht(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Ht(e)?e:e+""}function Jt(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(Jt=function(){return!!t})()}function Xt(t){return Xt=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Xt(t)}function Zt(t,e){return Zt=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},Zt(t,e)}var te=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(t=function(t,e,n){return e=Xt(e),function(t,e){if(e&&("object"==Ht(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,Jt()?Reflect.construct(e,n||[],Xt(t).constructor):e.apply(t,n))}(this,e)).config=n,t.audioContext=null,t.audioQueue=[],t.isPlaying=!1,t.isProcessingQueue=!1,t.currentSource=null,t.outputFormat=null,t.nextStartTime=0,t.scheduledBuffers=0,t.scheduledSources=new Set,t.pcmChunkQueue=[],t.preparedBuffer=[],t.isProcessingPcmQueue=!1,t.isSchedulingFrames=!1,t.MAX_LOOKAHEAD_SECONDS=.02,t.pendingSentenceText=null,t.sentenceTimings=[],t.isCheckingTranscripts=!1,t.codecs={pcm:new jt,pcmu:new Bt,pcma:new zt},t.SUPPORTED_CONTAINERS=["wav","raw"],t.SUPPORTED_ENCODINGS=["pcm","pcmu","pcma"],t.SUPPORTED_SAMPLE_RATES=[8e3,16e3,22050,24e3,44100,48e3],t.SUPPORTED_BIT_DEPTHS=[8,16,24],t.SUPPORTED_CHANNELS=[1],console.log("🎵 AudioPlayer v2 initialized"),t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Zt(t,e)}(e,t),n=e,o=[{key:"setOutputFormat",value:function(t){var e;this.validateFormat(t)||(console.warn("⚠️ AudioPlayer: Invalid format, using defaults:",t),t=this.getDefaultFormat());var n=null===(e=this.outputFormat)||void 0===e?void 0:e.sampleRate,o=t.sampleRate;this.outputFormat=t,console.log("✅ AudioPlayer v2: Format set:",t),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(function(){console.log("✅ AudioPlayer v2: AudioContext resumed and ready")}).catch(function(t){console.warn("⚠️ AudioPlayer v2: Could not resume AudioContext:",t)}))}},{key:"validateFormat",value:function(t){var e,n;if(!t)return!1;var o=null===(e=t.container)||void 0===e?void 0:e.toLowerCase(),r=null===(n=t.encoding)||void 0===n?void 0:n.toLowerCase();return o&&r&&this.SUPPORTED_CONTAINERS.includes(o)&&this.SUPPORTED_ENCODINGS.includes(r)&&this.SUPPORTED_SAMPLE_RATES.includes(t.sampleRate)&&this.SUPPORTED_BIT_DEPTHS.includes(t.bitDepth)&&(!t.channels||this.SUPPORTED_CHANNELS.includes(t.channels))}},{key:"getDefaultFormat",value:function(){return{container:"raw",encoding:"pcm",sampleRate:16e3,channels:1,bitDepth:16}}},{key:"playAudio",value:function(t){var e=this;try{var n=this.createAudioBlob(t);this.audioQueue.push(n),this.isPlaying||this.isProcessingQueue||this.currentSource||setTimeout(function(){return e.processQueue()},50)}catch(t){console.error("❌ AudioPlayer v2: Playback error:",t),this.emit("playbackError",t)}}},{key:"playChunk",value:(c=Qt(Wt().m(function t(e){var n,o,r=this;return Wt().w(function(t){for(;;)switch(t.n){case 0:(n=this.prepareChunk(e))?(this.preparedBuffer.push(n),(this.preparedBuffer.length<=3||this.preparedBuffer.length%10==0)&&console.log("📥 AudioPlayer: Frame received, queued: ".concat(this.preparedBuffer.length,", scheduled: ").concat(this.scheduledBuffers,", isScheduling: ").concat(this.isSchedulingFrames)),this.isSchedulingFrames?setTimeout(function(){r.preparedBuffer.length>0&&!r.isSchedulingFrames&&r.schedulePreparedFrames()},5):this.schedulePreparedFrames(),this.pcmChunkQueue.length>0&&!this.isProcessingPcmQueue&&this.processPcmQueue()):(console.error("❌ AudioPlayer: playChunk failed - prepareChunk returned null"),console.error(" pcmData length:",(null==e?void 0:e.byteLength)||"undefined"),console.error(" outputFormat:",this.outputFormat),console.error(" audioContext:",this.audioContext?"initialized":"not initialized"),console.error(" audioContext state:",(null===(o=this.audioContext)||void 0===o?void 0:o.state)||"N/A"),this.emit("playbackError",new Error("Failed to prepare PCM chunk for playback")));case 1:return t.a(2)}},t,this)})),function(t){return c.apply(this,arguments)})},{key:"prepareChunk",value:function(t){try{var e;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=t;if(t.byteLength%2!=0){console.warn("⚠️ Odd PCM chunk size, padding:",t.byteLength);var o=new Uint8Array(t.byteLength+1);o.set(new Uint8Array(t),0),o[t.byteLength]=0,n=o.buffer}for(var r=new Int16Array(n),i=new Float32Array(r.length),a=1/32768,s=r.length,c=0;c<s;c++)i[c]=r[c]*a;var l=(null===(e=this.outputFormat)||void 0===e?void 0:e.sampleRate)||this.audioContext.sampleRate,u=this.audioContext.sampleRate,d=this.audioContext.createBuffer(1,i.length,l);d.getChannelData(0).set(i);var p=d.duration,f=i.length,h=p;return u!==l&&(h=f/u),{buffer:d,duration:h,sampleRate:l,contextSampleRate:u}}catch(t){return console.error("❌ AudioPlayer: Error preparing chunk:",t),null}}},{key:"applyFadeOut",value:function(t){return t}},{key:"schedulePreparedFrames",value:(s=Qt(Wt().m(function t(){var e,n,o,r,i,a,s=this;return Wt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isSchedulingFrames){t.n=1;break}return t.a(2);case 1:if(this.isSchedulingFrames=!0,e=this.preparedBuffer.length,0===(n=Math.min(e,5))&&e>0&&(n=1),t.p=2,this.audioContext||this.initializeAudioContext(),o=0===this.scheduledBuffers&&!this.isPlaying,"suspended"!==this.audioContext.state){t.n=4;break}return t.n=3,this.audioContext.resume();case 3:if(!o){t.n=4;break}return t.n=4,new Promise(function(t){return setTimeout(t,50)});case 4:if("running"===this.audioContext.state){t.n=8;break}if(console.warn("AudioPlayer v2: AudioContext not in running state:",this.audioContext.state),"suspended"!==this.audioContext.state){t.n=8;break}return t.n=5,this.audioContext.resume();case 5:if(!o){t.n=7;break}return t.n=6,new Promise(function(t){return setTimeout(t,50)});case 6:t.n=8;break;case 7:return t.n=8,new Promise(function(t){return setTimeout(t,10)});case 8:r=0,i=Wt().m(function t(){var e,n,o,i,a;return Wt().w(function(t){for(;;)switch(t.n){case 0:if(e=s.preparedBuffer.shift()){t.n=1;break}return t.a(2,1);case 1:(n=s.audioContext.createBufferSource()).buffer=e.buffer,n.connect(s.audioContext.destination),s.scheduledSources.add(n),o=s.audioContext.currentTime,0===s.scheduledBuffers?(s.nextStartTime<o&&(s.nextStartTime=o+s.MAX_LOOKAHEAD_SECONDS),console.log("🎵 Starting playback with minimal delay:",s.nextStartTime)):(i=o+s.MAX_LOOKAHEAD_SECONDS,s.nextStartTime<i&&(s.nextStartTime=i,console.warn("⚠️ AudioPlayer: Fell behind schedule, adjusting nextStartTime to ".concat(s.nextStartTime.toFixed(4),"s")))),s.pendingSentenceText&&(s.sentenceTimings.push({startTime:s.nextStartTime,text:s.pendingSentenceText,displayed:!1}),console.log("📝 AudioPlayer: Sentence scheduled at ".concat(s.nextStartTime.toFixed(3),'s: "').concat(s.pendingSentenceText.substring(0,40),'..."')),s.pendingSentenceText=null,s.isCheckingTranscripts||s.startTranscriptChecker()),n.start(s.nextStartTime),s.nextStartTime+=e.duration,s.nextStartTime=Math.round(1e6*s.nextStartTime)/1e6,a=s.nextStartTime-e.duration,s.scheduledBuffers<5&&(console.log("🎵 AudioPlayer: Scheduled frame ".concat(s.scheduledBuffers+1," at ").concat(a.toFixed(4),"s, next at ").concat(s.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(e.duration.toFixed(4),"s (").concat((1e3*e.duration).toFixed(2),"ms), Queued: ").concat(s.preparedBuffer.length,", Scheduled: ").concat(s.scheduledBuffers))),s.scheduledBuffers++,r++,n.onended=function(){if(s.scheduledSources.delete(n),s.scheduledBuffers--,0===s.scheduledBuffers&&0===s.preparedBuffer.length&&0===s.pcmChunkQueue.length)s.isPlaying=!1,s.isSchedulingFrames=!1,console.log("🛑 AudioPlayer: Emitting playbackStopped event (all buffers finished)"),s.emit("playbackStopped");else if(s.preparedBuffer.length>0)setTimeout(function(){s.preparedBuffer.length>0&&!s.isSchedulingFrames&&s.schedulePreparedFrames()},0);else if(s.scheduledBuffers>0){var t=function(){s.preparedBuffer.length>0&&!s.isSchedulingFrames&&s.scheduledBuffers>0?s.schedulePreparedFrames():s.scheduledBuffers>0&&setTimeout(t,10)};setTimeout(t,10)}},s.isPlaying||(s.isPlaying=!0,console.log("🎵 AudioPlayer: Emitting playbackStarted event"),s.emit("playbackStarted"));case 2:return t.a(2)}},t)});case 9:if(!(this.preparedBuffer.length>0&&r<n)){t.n=12;break}return t.d(Kt(i()),10);case 10:if(!t.v){t.n=11;break}return t.a(3,12);case 11:t.n=9;break;case 12:this.isSchedulingFrames=!1,this.preparedBuffer.length>0&&requestAnimationFrame(function(){s.preparedBuffer.length>0&&!s.isSchedulingFrames&&s.schedulePreparedFrames()}),this.scheduledBuffers>0&&setTimeout(function(){s.preparedBuffer.length>0&&!s.isSchedulingFrames&&s.scheduledBuffers>0?s.schedulePreparedFrames():s.scheduledBuffers>0&&setTimeout(function(){s.preparedBuffer.length>0&&!s.isSchedulingFrames&&s.scheduledBuffers>0&&s.schedulePreparedFrames()},10)},10),t.n=14;break;case 13:t.p=13,a=t.v,console.error("❌ AudioPlayer v2: Error scheduling frames:",a),this.emit("playbackError",a),this.isSchedulingFrames=!1;case 14:return t.a(2)}},t,this,[[2,13]])})),function(){return s.apply(this,arguments)})},{key:"processPcmQueue",value:(a=Qt(Wt().m(function t(){var e,n,o,r,i,a,s,c,l,u,d,p,f,h,g,v,m,y,b,w,S,x=this;return Wt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isProcessingPcmQueue){t.n=1;break}return t.a(2);case 1:if(this.isProcessingPcmQueue=!0,t.p=2,this.audioContext||this.initializeAudioContext(),e=0===this.scheduledBuffers&&!this.isPlaying,"suspended"!==this.audioContext.state){t.n=4;break}return t.n=3,this.audioContext.resume();case 3:if(!e){t.n=4;break}return t.n=4,new Promise(function(t){return setTimeout(t,50)});case 4:if("running"===this.audioContext.state){t.n=8;break}if(console.warn("AudioPlayer v2: AudioContext not in running state:",this.audioContext.state),"suspended"!==this.audioContext.state){t.n=8;break}return t.n=5,this.audioContext.resume();case 5:if(!e){t.n=7;break}return t.n=6,new Promise(function(t){return setTimeout(t,50)});case 6:t.n=8;break;case 7:return t.n=8,new Promise(function(t){return setTimeout(t,10)});case 8:if(!(this.pcmChunkQueue.length>0)){t.n=10;break}if(r=this.pcmChunkQueue.shift()){t.n=9;break}return t.a(3,8);case 9:for(i=r,r.byteLength%2!=0&&(console.warn("⚠️ Odd PCM chunk size, padding:",r.byteLength),(a=new Uint8Array(r.byteLength+1)).set(new Uint8Array(r),0),a[r.byteLength]=0,i=a.buffer),s=new Int16Array(i),c=new Float32Array(s.length),l=1/32768,u=s.length,d=0;d<u;d++)c[d]=s[d]*l;p=(null===(n=this.outputFormat)||void 0===n?void 0:n.sampleRate)||this.audioContext.sampleRate,f=this.audioContext.sampleRate,null!==(o=this.outputFormat)&&void 0!==o&&o.sampleRate?this.scheduledBuffers<3&&console.log("🎵 AudioPlayer: Creating buffer at ".concat(p,"Hz (AudioContext: ").concat(f,"Hz)")):console.warn("⚠️ AudioPlayer: outputFormat.sampleRate not set! Using AudioContext sample rate:",f),(h=this.audioContext.createBuffer(1,c.length,p)).getChannelData(0).set(c),(g=this.audioContext.createBufferSource()).buffer=h,g.connect(this.audioContext.destination),v=this.audioContext.currentTime,this.nextStartTime<v&&(this.nextStartTime=v,0===this.scheduledBuffers&&console.log("🎵 Starting playback at current time:",v)),m=h.duration,y=c.length,b=m,f!==p&&(b=y/f,this.scheduledBuffers<3&&(console.log("🔄 Resampling detected: ".concat(p,"Hz → ").concat(f,"Hz")),console.log(" Buffer duration: ".concat(m.toFixed(4),"s, Calculated: ").concat(b.toFixed(4),"s")))),g.start(this.nextStartTime),this.nextStartTime+=b,this.nextStartTime=Math.round(1e6*this.nextStartTime)/1e6,this.scheduledBuffers<3&&(w=this.nextStartTime-b,console.log("🎵 AudioPlayer: Scheduled chunk ".concat(this.scheduledBuffers+1," at ").concat(w.toFixed(4),"s, next at ").concat(this.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(b.toFixed(4),"s (").concat((1e3*b).toFixed(2),"ms)"))),this.scheduledBuffers++,g.onended=function(){x.scheduledBuffers--,0===x.scheduledBuffers&&0===x.pcmChunkQueue.length&&(x.isPlaying=!1,x.isProcessingPcmQueue=!1,x.emit("playbackStopped"))},this.isPlaying||(this.isPlaying=!0,this.emit("playbackStarted")),t.n=8;break;case 10:this.isProcessingPcmQueue=!1,t.n=12;break;case 11:t.p=11,S=t.v,console.error("❌ AudioPlayer v2: Error playing chunk:",S),this.emit("playbackError",S),this.isProcessingPcmQueue=!1;case 12:return t.a(2)}},t,this,[[2,11]])})),function(){return a.apply(this,arguments)})},{key:"createAudioBlob",value:function(t){var e=new Uint8Array(t);console.log("🎵 AudioPlayer: Processing ".concat(e.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(),r=this.isWavFile(e);if(r&&console.log("🎵 AudioPlayer: Data has WAV header (RIFF)"),o&&r)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(e);if(o&&!r)console.log("🎵 AudioPlayer: Processing as RAW data (as negotiated)");else{if(n&&r)return console.log("✅ AudioPlayer: Processing as WAV file (matches negotiation)"),this.handleWavFile(e);if(n&&!r)return console.warn("⚠️ AudioPlayer: Negotiated WAV but data lacks WAV header. Attempting WAV processing anyway."),this.handleWavFile(e);if(!this.outputFormat&&r)return console.log("🎵 AudioPlayer: No format negotiated, auto-detecting WAV"),this.handleWavFile(e);this.outputFormat||r||(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(e)}},{key:"isWavFile",value:function(t){return t.length>=44&&82===t[0]&&73===t[1]&&70===t[2]&&70===t[3]}},{key:"handleWavFile",value:function(t){var e=this.parseWavHeader(t);if(console.log("🎵 WAV file detected:",{format:e.audioFormat,encoding:this.getEncodingName(e.audioFormat),sampleRate:e.sampleRate,channels:e.channels,bitDepth:e.bitsPerSample}),1===e.audioFormat)return console.log("✅ PCM WAV - using directly"),new Blob([t],{type:"audio/wav"});var n=this.getCodecForWavFormat(e.audioFormat);if(!n)throw new Error("Unsupported WAV format code: ".concat(e.audioFormat));console.log("🔄 Non-PCM WAV - converting to PCM WAV");var o=t.slice(44),r=n.decode(o),i=this.createWavHeader(r.byteLength,e.sampleRate,e.channels,16);return new Blob([i,r],{type:"audio/wav"})}},{key:"handleRawData",value:function(t){var e,n,o=this.outputFormat.encoding.toLowerCase(),r=this.getCodec(o);if(!r)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 i=this.outputFormat.bitDepth||16;t.length,24===i?(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."),e=this.convert24BitTo16Bit(t),n=16):8===i?(console.log("🔄 AudioPlayer: Converting 8-bit PCM to 16-bit PCM"),e=this.convert8BitTo16Bit(t),n=16):(e=t.buffer,n=i,console.log("✅ AudioPlayer: Using native ".concat(i,"-bit PCM (no conversion needed)")))}else e=r.decode(t),n=16,console.log("🔄 AudioPlayer: Decoded ".concat(o.toUpperCase()," to 16-bit PCM"));var a=this.createWavHeader(e.byteLength,this.outputFormat.sampleRate,this.outputFormat.channels,n);return new Blob([a,e],{type:"audio/wav"})}},{key:"convert24BitTo16Bit",value:function(t){for(var e=Math.floor(t.length/3),n=new Int16Array(e),o=0;o<e;o++){var r=t[3*o],i=t[3*o+1],a=t[3*o+2],s=r|i<<8|(255&a)<<16;128&a&&(s|=4278190080),n[o]=Math.max(-32768,Math.min(32767,Math.round(s/256)))}return n.buffer}},{key:"convert8BitTo16Bit",value:function(t){for(var e=t.length,n=new Int16Array(e),o=0;o<e;o++){var r=t[o];n[o]=256*(r-128)}return n.buffer}},{key:"getCodec",value:function(t){var e={pcm:"pcm",linear:"pcm",l16:"pcm",pcmu:"pcmu",ulaw:"pcmu",mulaw:"pcmu",g711u:"pcmu",pcma:"pcma",alaw:"pcma",g711a:"pcma"}[t.toLowerCase()];return this.codecs[e]}},{key:"getCodecForWavFormat",value:function(t){switch(t){case 1:return this.codecs.pcm;case 6:return this.codecs.pcma;case 7:return this.codecs.pcmu;default:return null}}},{key:"getEncodingName",value:function(t){switch(t){case 1:return"PCM";case 6:return"A-law";case 7:return"μ-law";default:return"Unknown (".concat(t,")")}}},{key:"parseWavHeader",value:function(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength);return{audioFormat:e.getUint16(20,!0),channels:e.getUint16(22,!0),sampleRate:e.getUint32(24,!0),byteRate:e.getUint32(28,!0),blockAlign:e.getUint16(32,!0),bitsPerSample:e.getUint16(34,!0)}}},{key:"createWavHeader",value:function(t,e,n,o){var r=new ArrayBuffer(44),i=new DataView(r);return i.setUint32(0,1380533830,!1),i.setUint32(4,36+t,!0),i.setUint32(8,1463899717,!1),i.setUint32(12,1718449184,!1),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,n,!0),i.setUint32(24,e,!0),i.setUint32(28,e*n*o/8,!0),i.setUint16(32,n*o/8,!0),i.setUint16(34,o,!0),i.setUint32(36,1684108385,!1),i.setUint32(40,t,!0),r}},{key:"initializeAudioContext",value:function(){var t,e,n=(null===(t=this.outputFormat)||void 0===t?void 0:t.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===(e=this.outputFormat)||void 0===e?void 0:e.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(t){console.error("❌ Failed to create AudioContext:",t),this.audioContext=new(window.AudioContext||window.webkitAudioContext),console.log("ℹ️ Using browser default: ".concat(this.audioContext.sampleRate,"Hz"))}}},{key:"processQueue",value:(i=Qt(Wt().m(function t(){var e,n,o,r,i,a,s,c,l=this;return Wt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isProcessingQueue&&0!==this.audioQueue.length){t.n=1;break}return t.a(2);case 1:if(this.isProcessingQueue=!0,e=this.audioQueue.shift()){t.n=2;break}return this.isProcessingQueue=!1,t.a(2);case 2:if(t.p=2,n=!this.isPlaying&&null===this.currentSource,this.audioContext||this.initializeAudioContext(),"suspended"!==(o=this.audioContext).state){t.n=4;break}return t.n=3,o.resume();case 3:if(!n){t.n=4;break}return t.n=4,new Promise(function(t){return setTimeout(t,50)});case 4:if("running"===o.state){t.n=8;break}if(console.warn("AudioPlayer v2: AudioContext not in running state:",o.state),"suspended"!==o.state){t.n=8;break}return t.n=5,o.resume();case 5:if(!n){t.n=7;break}return t.n=6,new Promise(function(t){return setTimeout(t,50)});case 6:t.n=8;break;case 7:return t.n=8,new Promise(function(t){return setTimeout(t,10)});case 8:return t.n=9,e.arrayBuffer();case 9:return r=t.v,t.n=10,o.decodeAudioData(r);case 10:i=t.v,a=n&&!this.isPlaying&&null===this.currentSource,(s=o.createBufferSource()).buffer=i,s.connect(o.destination),this.currentSource=s,this.isPlaying=!0,a&&this.emit("playbackStarted"),s.onended=function(){l.currentSource=null,l.isProcessingQueue=!1,l.audioQueue.length>0?setTimeout(function(){return l.processQueue()},50):setTimeout(function(){0!==l.audioQueue.length||l.currentSource||(l.isPlaying=!1,l.emit("playbackStopped"))},100)},s.start(),t.n=12;break;case 11:t.p=11,c=t.v,console.error("❌ AudioPlayer v2: Error processing queue:",c),this.currentSource=null,this.emit("playbackError",c),this.audioQueue.length>0?(this.isProcessingQueue=!1,setTimeout(function(){return l.processQueue()},100)):(this.isPlaying=!1,this.isProcessingQueue=!1,this.emit("playbackStopped"));case 12:return t.a(2)}},t,this,[[2,11]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:function(){this.stopImmediate()}},{key:"reset",value:function(){this.stop(),this.audioQueue=[],this.pcmChunkQueue=[]}},{key:"stopImmediate",value:function(){var t=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(t){console.log(" currentSource already stopped or error:",t.message)}this.currentSource=null}if(this.scheduledSources.size>0){console.log(" Stopping ".concat(this.scheduledSources.size," scheduled sources..."));var e,n=0,o=Lt(this.scheduledSources);try{for(o.s();!(e=o.n()).done;){var r=e.value;try{r.stop(),n++}catch(t){console.log(" Source already stopped or not started:",t.message)}}}catch(t){o.e(t)}finally{o.f()}console.log(" Stopped ".concat(n," 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(),t&&(console.log("🛑 AudioPlayer: Emitting playbackStopped event (stopImmediate called)"),this.emit("playbackStopped"))}},{key:"markNewSentence",value:function(t){this.pendingSentenceText=t,console.log('📝 AudioPlayer: New sentence marked: "'.concat(t.substring(0,40),'..."'))}},{key:"startTranscriptChecker",value:function(){var t=this;if(!this.isCheckingTranscripts){this.isCheckingTranscripts=!0,console.log("📝 AudioPlayer: Transcript checker started");var e=function(){if(t.isCheckingTranscripts&&t.audioContext){var n,o=t.audioContext.currentTime,r=Lt(t.sentenceTimings);try{for(r.s();!(n=r.n()).done;){var i=n.value;!i.displayed&&o>=i.startTime&&(i.displayed=!0,console.log("📝 AudioPlayer: Display transcript at ".concat(o.toFixed(3),'s: "').concat(i.text.substring(0,40),'..."')),t.emit("transcriptDisplay",{text:i.text}))}}catch(t){r.e(t)}finally{r.f()}t.isPlaying||t.scheduledBuffers>0?requestAnimationFrame(e):(t.isCheckingTranscripts=!1,console.log("📝 AudioPlayer: Transcript checker stopped"))}};requestAnimationFrame(e)}}},{key:"clearTranscriptState",value:function(){this.pendingSentenceText=null,this.sentenceTimings=[],this.isCheckingTranscripts=!1,console.log("📝 AudioPlayer: Transcript state cleared")}},{key:"resumeAudioContext",value:(r=Qt(Wt().m(function t(){var e;return Wt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.audioContext&&"closed"!==this.audioContext.state){t.n=2;break}return t.n=1,this.initializeAudioContext();case 1:return t.a(2);case 2:if("suspended"!==this.audioContext.state){t.n=6;break}return t.p=3,t.n=4,this.audioContext.resume();case 4:console.log("✅ AudioPlayer v2: AudioContext resumed after mic permission"),t.n=6;break;case 5:t.p=5,e=t.v,console.warn("⚠️ AudioPlayer v2: Failed to resume AudioContext:",e);case 6:return t.a(2)}},t,this,[[3,5]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){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}}},{key:"destroy",value:function(){this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.removeAllListeners()}}],o&&Yt(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,s,c}(Ot);const ee=te;function ne(t){return ne="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ne(t)}function oe(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return re(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(re(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,re(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,re(d,"constructor",l),re(l,"constructor",c),c.displayName="GeneratorFunction",re(l,r,"GeneratorFunction"),re(d),re(d,r,"Generator"),re(d,o,function(){return this}),re(d,"toString",function(){return"[object Generator]"}),(oe=function(){return{w:i,m:p}})()}function re(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}re=function(t,e,n,o){function i(e,n){re(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},re(t,e,n,o)}function ie(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function ae(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){ie(i,o,r,a,s,"next",t)}function s(t){ie(i,o,r,a,s,"throw",t)}a(void 0)})}}function se(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}function ce(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,le(o.key),o)}}function le(t){var e=function(t){if("object"!=ne(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=ne(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==ne(e)?e:e+""}function ue(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(ue=function(){return!!t})()}function de(t){return de=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},de(t)}function pe(t,e){return pe=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},pe(t,e)}var fe=function(t){function e(t){var n;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(n=function(t,e,n){return e=de(e),function(t,e){if(e&&("object"==ne(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,ue()?Reflect.construct(e,n||[],de(t).constructor):e.apply(t,n))}(this,e)).config=t,n.audioContext=null,n.audioWorkletNode=null,n.mediaStream=null,n.isRecording=!1,n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&pe(t,e)}(e,t),n=e,o=[{key:"getAudioProcessorPath",value:function(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var t,e=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return se(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?se(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}(document.getElementsByTagName("script"));try{for(e.s();!(t=e.n()).done;){var n=t.value.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(t){var r=n.substring(0,n.lastIndexOf("/"));return"".concat(r,"/audio-processor.js")}}}catch(t){e.e(t)}finally{e.f()}return"https://cdn.talktopc.com/audio-processor.js"}},{key:"start",value:(i=ae(oe().m(function t(){var e,n,o,r,i,a,s=this;return oe().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,"https:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname){t.n=1;break}throw e=new Error("Microphone access requires HTTPS. Please use https:// or test on localhost."),console.error("❌ AudioRecorder:",e.message),this.emit("error",e),e;case 1:if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){t.n=2;break}throw n=new Error("getUserMedia is not supported in this browser. Please use a modern browser."),console.error("❌ AudioRecorder:",n.message),this.emit("error",n),n;case 2:return console.log("🎤 AudioRecorder: Requesting microphone access..."),t.n=3,navigator.mediaDevices.getUserMedia({audio:{sampleRate:this.config.sampleRate,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 3:if(this.mediaStream=t.v,console.log("✅ AudioRecorder: Microphone access granted"),this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:this.config.sampleRate}),"suspended"!==this.audioContext.state){t.n=4;break}return t.n=4,this.audioContext.resume();case 4:return o=this.getAudioProcessorPath(),t.n=5,this.audioContext.audioWorklet.addModule(o);case 5:this.audioWorkletNode=new AudioWorkletNode(this.audioContext,"audio-processor"),this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.audioWorkletNode),this.audioWorkletNode.port.onmessage=function(t){var e=t.data,n=e.type,o=e.data;"pcm_audio_data"===n&&s.emit("audioData",o)},this.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),this.isRecording=!0,this.emit("recordingStarted"),t.n=7;break;case 6:throw t.p=6,a=t.v,r=a.message,"NotAllowedError"===a.name||"PermissionDeniedError"===a.name?(r="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"===a.name||"DevicesNotFoundError"===a.name?(r="No microphone found. Please connect a microphone and try again.",console.error("❌ AudioRecorder: No microphone device found.")):"NotReadableError"===a.name||"TrackStartError"===a.name?(r="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.")):a.message&&a.message.includes("not allowed by the user agent")&&(r="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.")),(i=new Error(r)).name=a.name,i.originalError=a,console.error("❌ AudioRecorder: Failed to start recording:",i),this.emit("error",i),i;case 7:return t.a(2)}},t,this,[[0,6]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:(r=ae(oe().m(function t(){var e;return oe().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.isRecording){t.n=1;break}return t.a(2);case 1:if(t.p=1,!this.audioWorkletNode){t.n=2;break}return this.audioWorkletNode.port.postMessage({type:"flush"}),t.n=2,new Promise(function(t){return setTimeout(t,100)});case 2:if(this.mediaStream&&(this.mediaStream.getTracks().forEach(function(t){return t.stop()}),this.mediaStream=null),!this.audioContext||"closed"===this.audioContext.state){t.n=4;break}return t.n=3,this.audioContext.close();case 3:this.audioContext=null;case 4:this.audioWorkletNode=null,this.isRecording=!1,this.emit("recordingStopped"),t.n=6;break;case 5:throw t.p=5,e=t.v,this.emit("error",e),e;case 6:return t.a(2)}},t,this,[[1,5]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop()}}],o&&ce(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(Ot);function he(t){return he="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},he(t)}function ge(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,ve(o.key),o)}}function ve(t){var e=function(t){if("object"!=he(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=he(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==he(e)?e:e+""}const me=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}return e=t,n=[{key:"extractPcmFromWav",value:function(t){var e=t instanceof Uint8Array?t:new Uint8Array(t);if(e.length<44)throw new Error("WAV data too short (< 44 bytes)");if("RIFF"!==String.fromCharCode(e[0],e[1],e[2],e[3]))throw new Error("Not a valid WAV file - missing RIFF header");if("WAVE"!==String.fromCharCode(e[8],e[9],e[10],e[11]))throw new Error("Not a valid WAV file - missing WAVE format");for(var n=e[22]|e[23]<<8,o=e[24]|e[25]<<8|e[26]<<16|e[27]<<24,r=e[34]|e[35]<<8,i=-1,a=12;a<e.length-8;a+=4){if("data"===String.fromCharCode(e[a],e[a+1],e[a+2],e[a+3])){i=a;break}a+=4+(e[a+4]|e[a+5]<<8|e[a+6]<<16|e[a+7]<<24)}if(-1===i)throw new Error("No data chunk found in WAV");var s=e[i+4]|e[i+5]<<8|e[i+6]<<16|e[i+7]<<24,c=i+8,l=Math.min(s,e.length-c);return{pcmData:e.slice(c,c+l).buffer,format:{sampleRate:o,channels:n,bitDepth:r}}}},{key:"isWavFile",value:function(t){return t.length>=44&&82===t[0]&&73===t[1]&&70===t[2]&&70===t[3]}},{key:"createWavHeader",value:function(t,e,n,o){var r=new ArrayBuffer(44),i=new DataView(r);return i.setUint32(0,1380533830,!1),i.setUint32(4,36+t,!0),i.setUint32(8,1463899717,!1),i.setUint32(12,1718449184,!1),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,n,!0),i.setUint32(24,e,!0),i.setUint32(28,e*n*o/8,!0),i.setUint16(32,n*o/8,!0),i.setUint16(34,o,!0),i.setUint32(36,1684108385,!1),i.setUint32(40,t,!0),r}},{key:"wrapPcmInWav",value:function(e,n){var o=t.createWavHeader(e.byteLength,n.sampleRate,n.channels||1,n.bitDepth||16),r=new Uint8Array(o.byteLength+e.byteLength);return r.set(new Uint8Array(o),0),r.set(new Uint8Array(e),o.byteLength),r.buffer}}],null&&ge(e.prototype,null),n&&ge(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,n}();function ye(t){return ye="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ye(t)}function be(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,we(o.key),o)}}function we(t){var e=function(t){if("object"!=ye(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=ye(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==ye(e)?e:e+""}const Se=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.codecs={pcm:new jt,pcmu:new Bt,pcma:new zt}},(e=[{key:"decodeToPcm",value:function(t,e){var n=null==e?void 0:e.toLowerCase();if(!n||"pcm"===n)return t instanceof ArrayBuffer?t:t instanceof Uint8Array?t.buffer:t;var o=this.codecs[n];if(!o)throw new Error("Unsupported encoding: ".concat(e));var r=t instanceof Uint8Array?t:new Uint8Array(t);return o.decode(r)}},{key:"encodeFromPcm",value:function(t,e){var n=null==e?void 0:e.toLowerCase();if(!n||"pcm"===n)return t;var o=this.codecs[n];if(!o)throw new Error("Unsupported target encoding: ".concat(e));var r=o.encode(t);return r instanceof Uint8Array?r.buffer:r}},{key:"getCodec",value:function(t){var e=null==t?void 0:t.toLowerCase();return this.codecs[e]||null}}])&&be(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function xe(t){return xe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xe(t)}function ke(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Ce(o.key),o)}}function Ce(t){var e=function(t){if("object"!=xe(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=xe(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==xe(e)?e:e+""}const Pe=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}return e=t,n=[{key:"convert",value:function(e,n,o){if(n===o)return e;if(8===n)throw new Error("Source bit depth cannot be 8-bit (only 16-bit or 24-bit supported)");var r=n/8,i=o/8,a=e.byteLength/r;if(new ArrayBuffer(a*i),16===n&&16===o)return e;if(24===n&&16===o)return t.convert24To16(e);if(16===n&&24===o)return t.convert16To24(e);if(16===n&&8===o)return t.convert16To8(e);if(24===n&&8===o)return t.convert24To8(e);throw new Error("Unsupported bit depth conversion: ".concat(n,"-bit → ").concat(o,"-bit"))}},{key:"convert24To16",value:function(t){for(var e=new Uint8Array(t),n=Math.floor(e.length/3),o=new Int16Array(n),r=0;r<n;r++){var i=e[3*r],a=e[3*r+1],s=e[3*r+2],c=i|a<<8|(255&s)<<16;128&s&&(c|=4278190080),o[r]=Math.max(-32768,Math.min(32767,Math.round(c/256)))}return o.buffer}},{key:"convert16To24",value:function(t){for(var e=new Int16Array(t),n=new Uint8Array(3*e.length),o=0;o<e.length;o++){var r=256*e[o];n[3*o]=255&r,n[3*o+1]=r>>8&255,n[3*o+2]=r>>16&255}return n.buffer}},{key:"convert16To8",value:function(t){for(var e=new Int16Array(t),n=new Uint8Array(e.length),o=0;o<e.length;o++){var r=e[o];n[o]=Math.max(0,Math.min(255,Math.round(r/256+128)))}return n.buffer}},{key:"convert24To8",value:function(e){var n=t.convert24To16(e);return t.convert16To8(n)}}],null&&ke(e.prototype,null),n&&ke(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,n}();function Te(t){return Te="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Te(t)}function Ee(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Oe(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Oe(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Oe(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Oe(d,"constructor",l),Oe(l,"constructor",c),c.displayName="GeneratorFunction",Oe(l,r,"GeneratorFunction"),Oe(d),Oe(d,r,"Generator"),Oe(d,o,function(){return this}),Oe(d,"toString",function(){return"[object Generator]"}),(Ee=function(){return{w:i,m:p}})()}function Oe(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Oe=function(t,e,n,o){function i(e,n){Oe(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Oe(t,e,n,o)}function Ae(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Ie(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Re(o.key),o)}}function Re(t){var e=function(t){if("object"!=Te(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Te(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Te(e)?e:e+""}const je=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)},e=[{key:"resample",value:(n=Ee().m(function t(e,n,o){var r,i,a,s,c,l,u,d,p,f,h,g,v;return Ee().w(function(t){for(;;)switch(t.n){case 0:if(n!==o){t.n=1;break}return t.a(2,e);case 1:for(r=new Int16Array(e),i=new Float32Array(r.length),a=1/32768,s=0;s<r.length;s++)i[s]=r[s]*a;return c=Math.ceil(i.length*o/n),l=new OfflineAudioContext(1,c,o),(u=l.createBuffer(1,i.length,n)).getChannelData(0).set(i),(d=l.createBufferSource()).buffer=u,d.connect(l.destination),d.start(),t.n=2,l.startRendering();case 2:for(p=t.v,f=p.getChannelData(0),h=new Int16Array(f.length),g=0;g<f.length;g++)v=Math.max(-1,Math.min(1,f[g])),h[g]=Math.round(32767*v);return t.a(2,h.buffer)}},t)}),o=function(){var t=this,e=arguments;return new Promise(function(o,r){var i=n.apply(t,e);function a(t){Ae(i,o,r,a,s,"next",t)}function s(t){Ae(i,o,r,a,s,"throw",t)}a(void 0)})},function(t,e,n){return o.apply(this,arguments)})}],e&&Ie(t,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();function De(t){return De="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},De(t)}function Fe(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,_e(o.key),o)}}function _e(t){var e=function(t){if("object"!=De(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=De(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==De(e)?e:e+""}const Be=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}return e=t,n=[{key:"convert",value:function(e,n,o){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:16;if(n===o)return e;if(1===n&&1===o)return e;if(1===n&&2===o)return t.monoToStereo(e,r);if(2===n&&1===o)return t.stereoToMono(e,r);throw new Error("Unsupported channel conversion: ".concat(n," → ").concat(o))}},{key:"monoToStereo",value:function(t,e){for(var n=e/8,o=t.byteLength/n,r=new ArrayBuffer(o*n*2),i=new Uint8Array(t),a=new Uint8Array(r),s=0;s<o;s++)for(var c=s*n,l=s*n*2,u=0;u<n;u++)a[l+u]=i[c+u],a[l+n+u]=i[c+u];return r}},{key:"stereoToMono",value:function(t,e){var n=e/8,o=t.byteLength/(2*n),r=new ArrayBuffer(o*n),i=new Uint8Array(t),a=new Uint8Array(r);if(16===e)for(var s=0;s<o;s++){var c=s*n*2,l=c+n,u=(i[c]|i[c+1]<<8)<<16>>16,d=(i[l]|i[l+1]<<8)<<16>>16,p=Math.round((u+d)/2),f=s*n;a[f]=255&p,a[f+1]=p>>8&255}else for(var h=0;h<o;h++)for(var g=h*n*2,v=h*n,m=0;m<n;m++)a[v+m]=i[g+m];return r}}],null&&Fe(e.prototype,null),n&&Fe(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,n}();function Me(t){return Me="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Me(t)}function Ue(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Ne(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Ne(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Ne(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Ne(d,"constructor",l),Ne(l,"constructor",c),c.displayName="GeneratorFunction",Ne(l,r,"GeneratorFunction"),Ne(d),Ne(d,r,"Generator"),Ne(d,o,function(){return this}),Ne(d,"toString",function(){return"[object Generator]"}),(Ue=function(){return{w:i,m:p}})()}function Ne(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Ne=function(t,e,n,o){function i(e,n){Ne(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Ne(t,e,n,o)}function ze(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function He(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?ze(Object(n),!0).forEach(function(e){Le(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ze(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function Le(t,e,n){return(e=We(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Ve(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Ke(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,We(o.key),o)}}function We(t){var e=function(t){if("object"!=Me(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Me(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Me(e)?e:e+""}const Ge=function(){return t=function t(e,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.requestedFormat=e,this.actualFormat=n,this.encodingConverter=new Se,this.conversionSteps=[],this._analyzeConversions()},e=[{key:"_analyzeConversions",value:function(){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")}},{key:"needsConversion",value:function(){return this.conversionSteps.length>0}},{key:"getConversionSteps",value:function(){var t=[];return this.conversionSteps.includes("extract_wav")&&t.push("Extract PCM from WAV (".concat(this.actualFormat.container," → raw)")),this.conversionSteps.includes("decode_encoding")&&t.push("Decode ".concat(this.actualFormat.encoding.toUpperCase()," → PCM")),this.conversionSteps.includes("resample")&&t.push("Resample ".concat(this.actualFormat.sampleRate,"Hz → ").concat(this.requestedFormat.sampleRate,"Hz")),this.conversionSteps.includes("convert_bitdepth")&&t.push("Convert bit depth ".concat(this.actualFormat.bitDepth,"-bit → ").concat(this.requestedFormat.bitDepth,"-bit")),this.conversionSteps.includes("convert_channels")&&t.push("Convert channels ".concat(this.actualFormat.channels," → ").concat(this.requestedFormat.channels)),this.conversionSteps.includes("encode_encoding")&&t.push("Encode PCM → ".concat(this.requestedFormat.encoding.toUpperCase())),this.conversionSteps.includes("wrap_wav")&&t.push("Wrap in WAV container (raw → ".concat(this.requestedFormat.container,")")),t}},{key:"convert",value:(n=Ue().m(function t(e){var n,o,r,i;return Ue().w(function(t){for(;;)switch(t.n){case 0:if(this.needsConversion()){t.n=1;break}return t.a(2,e instanceof ArrayBuffer?e:e.buffer);case 1:if(n=e instanceof ArrayBuffer?e:e.buffer,o=He({},this.actualFormat),this.conversionSteps.includes("extract_wav")&&(r=me.extractPcmFromWav(n),n=r.pcmData,o=He(He({},o),{},{container:"raw",sampleRate:r.format.sampleRate,channels:r.format.channels,bitDepth:r.format.bitDepth}),console.log("🔄 AudioFormatConverter: Extracted PCM from WAV",r.format)),this.conversionSteps.includes("decode_encoding")&&(n=this.encodingConverter.decodeToPcm(n,o.encoding),o.encoding="pcm",o.bitDepth=16,console.log("🔄 AudioFormatConverter: Decoded ".concat(this.actualFormat.encoding.toUpperCase()," → PCM"))),24===o.bitDepth&&o.bitDepth!==this.requestedFormat.bitDepth&&(this.conversionSteps.includes("resample")||this.conversionSteps.includes("convert_channels")||24!==this.requestedFormat.bitDepth)&&(n=Pe.convert(n,24,16),o.bitDepth=16,console.log("🔄 AudioFormatConverter: Normalized 24-bit → 16-bit PCM")),!this.conversionSteps.includes("resample")){t.n=3;break}return t.n=2,je.resample(n,o.sampleRate,this.requestedFormat.sampleRate);case 2:n=t.v,o.sampleRate=this.requestedFormat.sampleRate,console.log("🔄 AudioFormatConverter: Resampled ".concat(this.actualFormat.sampleRate,"Hz → ").concat(this.requestedFormat.sampleRate,"Hz"));case 3:return this.conversionSteps.includes("convert_channels")&&(n=Be.convert(n,o.channels,this.requestedFormat.channels,o.bitDepth),o.channels=this.requestedFormat.channels,console.log("🔄 AudioFormatConverter: Converted channels ".concat(this.actualFormat.channels," → ").concat(this.requestedFormat.channels))),this.conversionSteps.includes("convert_bitdepth")&&(n=Pe.convert(n,o.bitDepth,this.requestedFormat.bitDepth),o.bitDepth=this.requestedFormat.bitDepth,console.log("🔄 AudioFormatConverter: Converted bit depth ".concat(this.actualFormat.bitDepth,"-bit → ").concat(this.requestedFormat.bitDepth,"-bit"))),this.conversionSteps.includes("encode_encoding")&&(i=this.encodingConverter.encodeFromPcm(n,this.requestedFormat.encoding),n=i instanceof ArrayBuffer?i:i.buffer,o.encoding=this.requestedFormat.encoding,console.log("🔄 AudioFormatConverter: Encoded PCM → ".concat(this.requestedFormat.encoding.toUpperCase()))),this.conversionSteps.includes("wrap_wav")&&(n=me.wrapPcmInWav(n,o),o.container="wav",console.log("🔄 AudioFormatConverter: Wrapped in WAV container")),console.log("✅ AudioFormatConverter: Conversion complete"),t.a(2,n)}},t,this)}),o=function(){var t=this,e=arguments;return new Promise(function(o,r){var i=n.apply(t,e);function a(t){Ve(i,o,r,a,s,"next",t)}function s(t){Ve(i,o,r,a,s,"throw",t)}a(void 0)})},function(t){return o.apply(this,arguments)})}],e&&Ke(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();function qe(t){return qe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},qe(t)}function Qe(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function Ye(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?Qe(Object(n),!0).forEach(function(e){rn(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Qe(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function $e(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Je(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Je(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Je(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Je(d,"constructor",l),Je(l,"constructor",c),c.displayName="GeneratorFunction",Je(l,r,"GeneratorFunction"),Je(d),Je(d,r,"Generator"),Je(d,o,function(){return this}),Je(d,"toString",function(){return"[object Generator]"}),($e=function(){return{w:i,m:p}})()}function Je(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Je=function(t,e,n,o){function i(e,n){Je(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Je(t,e,n,o)}function Xe(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Ze(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){Xe(i,o,r,a,s,"next",t)}function s(t){Xe(i,o,r,a,s,"throw",t)}a(void 0)})}}function tn(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,an(o.key),o)}}function en(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(en=function(){return!!t})()}function nn(t){return nn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},nn(t)}function on(t,e){return on=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},on(t,e)}function rn(t,e,n){return(e=an(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function an(t){var e=function(t){if("object"!=qe(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=qe(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==qe(e)?e:e+""}var sn=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(t=function(t,e,n){return e=nn(e),function(t,e){if(e&&("object"==qe(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,en()?Reflect.construct(e,n||[],nn(t).constructor):e.apply(t,n))}(this,e)).version="2.0.0",t.config={signedUrl:n.signedUrl||n.websocketUrl||"wss://speech.talktopc.com/ws/conv",websocketUrl:n.signedUrl||n.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:n.agentId,appId:n.appId,sampleRate:n.sampleRate||16e3,channels:n.channels||1,bitDepth:n.bitDepth||16,audioProcessorPath:n.audioProcessorPath,outputContainer:n.outputContainer||t.getDefaultContainer(n),outputEncoding:n.outputEncoding||n.outputCodec||"pcm",outputSampleRate:n.outputSampleRate||16e3,outputChannels:n.outputChannels||1,outputBitDepth:n.outputBitDepth||16,outputFrameDurationMs:n.outputFrameDurationMs||600,outputCodec:n.outputCodec,agentSettingsOverride:n.agentSettingsOverride||null,variables:n.variables||null,autoReconnect:!1!==n.autoReconnect,protocolVersion:n.protocolVersion||2},t.isConnected=!1,t.hasEverConnected=!1,t.isRecording=!1,t.isPlaying=!1,t.isDestroyed=!1,t.outputAudioFormat=null,t.requestedOutputFormat=null,t.formatConverter=null,t.websocket=null,t.conversationId=null,t.transcriptQueue=[],t.currentPlayingSentenceId=null,t.audioFrameCount=0,t.audioPlayer=new ee(t.config),t.audioRecorder=new fe(t.config),t.setupAudioPlayerEvents(),t.setupAudioRecorderEvents(),t.clientToolsRegistry=new lt(function(e){return t.sendMessage(e)}),t.validateConfig(),console.log("🎵 VoiceSDK v2 initialized:",{version:t.version,outputContainer:t.config.outputContainer,outputEncoding:t.config.outputEncoding,outputSampleRate:t.config.outputSampleRate}),t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&on(t,e)}(e,t),n=e,o=[{key:"getDefaultContainer",value:function(t){return"wav"===t.outputCodec?"wav":"raw"}},{key:"validateInputFormat",value:function(t){var n;if(!t)return"Input format is required";var o=null===(n=t.encoding)||void 0===n?void 0:n.toLowerCase();return o&&e.SUPPORTED_INPUT_ENCODINGS.includes(o)?t.sampleRate&&e.SUPPORTED_INPUT_SAMPLE_RATES.includes(t.sampleRate)?t.bitDepth&&e.SUPPORTED_INPUT_BIT_DEPTHS.includes(t.bitDepth)?t.channels&&e.SUPPORTED_INPUT_CHANNELS.includes(t.channels)?null:"Unsupported input channels: ".concat(t.channels,". Supported: ").concat(e.SUPPORTED_INPUT_CHANNELS.join(", ")):"Unsupported input bit depth: ".concat(t.bitDepth,". Supported: ").concat(e.SUPPORTED_INPUT_BIT_DEPTHS.join(", ")):"Unsupported input sample rate: ".concat(t.sampleRate,". Supported: ").concat(e.SUPPORTED_INPUT_SAMPLE_RATES.join(", ")):"Unsupported input encoding: ".concat(t.encoding,". Supported: ").concat(e.SUPPORTED_INPUT_ENCODINGS.join(", "))}},{key:"validateOutputFormat",value:function(t){var n,o;if(!t)return"Output format is required";var r=null===(n=t.encoding)||void 0===n?void 0:n.toLowerCase();if(!r||!e.SUPPORTED_OUTPUT_ENCODINGS.includes(r))return"Unsupported output encoding: ".concat(t.encoding,". Supported: ").concat(e.SUPPORTED_OUTPUT_ENCODINGS.join(", "));if(!t.sampleRate||!e.SUPPORTED_OUTPUT_SAMPLE_RATES.includes(t.sampleRate))return"Unsupported output sample rate: ".concat(t.sampleRate,". Supported: ").concat(e.SUPPORTED_OUTPUT_SAMPLE_RATES.join(", "));if(!t.bitDepth||!e.SUPPORTED_OUTPUT_BIT_DEPTHS.includes(t.bitDepth))return"Unsupported output bit depth: ".concat(t.bitDepth,". Supported: ").concat(e.SUPPORTED_OUTPUT_BIT_DEPTHS.join(", "));if(!t.channels||!e.SUPPORTED_OUTPUT_CHANNELS.includes(t.channels))return"Unsupported output channels: ".concat(t.channels,". Supported: ").concat(e.SUPPORTED_OUTPUT_CHANNELS.join(", "));var i=null===(o=t.container)||void 0===o?void 0:o.toLowerCase();return i&&e.SUPPORTED_OUTPUT_CONTAINERS.includes(i)?null:"Unsupported output container: ".concat(t.container,". Supported: ").concat(e.SUPPORTED_OUTPUT_CONTAINERS.join(", "))}},{key:"validateConfig",value:function(){var t={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},e=this.validateInputFormat(t);if(e)return console.error("❌ VoiceSDK v2: Invalid input format:",e),void this.emit("error",new Error(e));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")}},{key:"setupAudioPlayerEvents",value:function(){var t=this;this.audioPlayer.on("playbackStarted",function(){t.isPlaying=!0,t.emit("playbackStarted"),t.isConnected?(console.log("📤 VoiceSDK v2: Sending audio_started_playing message to server"),t.sendMessage({t:"audio_started_playing"})):console.warn("⚠️ VoiceSDK v2: Cannot send audio_started_playing - not connected")}),this.audioPlayer.on("transcriptDisplay",function(e){var n=t.currentPlayingSentenceId?t.currentPlayingSentenceId+1:1;t.currentPlayingSentenceId=n;var o={text:e.text,role:"assistant",sentenceId:n,final:!0,timestamp:Date.now()};console.log("📝 VoiceSDK v2: Emitting synced transcriptDisplay from AudioPlayer:",o),t.emit("transcriptDisplay",o),t.emit("transcript",o)}),this.audioPlayer.on("playbackStopped",function(){t.isPlaying=!1,t.emit("playbackStopped"),t.isConnected?(console.log("📤 VoiceSDK v2: Sending audio_stopped_playing message to server"),t.sendMessage({t:"audio_stopped_playing"})):console.warn("⚠️ VoiceSDK v2: Cannot send audio_stopped_playing - not connected")}),this.audioPlayer.on("playbackError",function(e){t.emit("playbackError",e),t.emit("error",e)})}},{key:"setupAudioRecorderEvents",value:function(){var t=this;this.audioRecorder.on("recordingStarted",function(){t.isRecording=!0,t.emit("recordingStarted")}),this.audioRecorder.on("recordingStopped",function(){t.isRecording&&(t.isRecording=!1,t.emit("recordingStopped"),console.log("🛑 VoiceSDK v2: Recording stopped (from audioRecorder event)"))}),this.audioRecorder.on("audioData",function(e){t.isConnected&&t.sendBinary(e)}),this.audioRecorder.on("error",function(e){console.error("❌ AudioRecorder error:",e),t.emit("error",e)})}},{key:"buildWebSocketUrl",value:function(){var t=this.config.signedUrl||this.config.websocketUrl,e=new URLSearchParams;if(this.config.agentId&&e.append("agentId",this.config.agentId),this.config.appId&&e.append("appId",this.config.appId),e.toString()){var n=t.includes("?")?"&":"?";return"".concat(t).concat(n).concat(e.toString())}return t}},{key:"connect",value:(l=Ze($e().m(function t(){var e,n,o=this;return $e().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isDestroyed){t.n=1;break}return console.warn("VoiceSDK v2: Cannot connect - SDK is destroyed"),t.a(2,!1);case 1:if(!this.isConnected){t.n=2;break}return console.warn("VoiceSDK v2: Already connected"),t.a(2,!0);case 2:return t.p=2,e=this.buildWebSocketUrl(),console.log("🔌 VoiceSDK v2: Connecting to",e),t.n=3,new Promise(function(t,n){o.websocket=new WebSocket(e),o.websocket.onopen=function(){console.log("✅ VoiceSDK v2: WebSocket connected"),o.isConnected=!0,o.hasEverConnected=!0,o.clientToolsRegistry&&o.clientToolsRegistry.setSendMessage(function(t){return o.sendMessage(t)}),o.sendHelloMessage(),o.emit("connected"),t(!0)},o.websocket.onerror=function(t){console.error("❌ VoiceSDK v2: WebSocket error:",t),n(t)},o.websocket.onclose=function(t){console.log("🔌 VoiceSDK v2: WebSocket closed:",t.code,t.reason),o.isConnected=!1,o.isRecording&&o.stopRecording().catch(function(t){return console.error("Error stopping recording:",t)}),o.emit("disconnected",t),o.config.autoReconnect&&!o.isDestroyed&&o.hasEverConnected?(console.log("🔄 VoiceSDK v2: Auto-reconnecting in 3s..."),setTimeout(function(){o.isDestroyed||o.isConnected||o.connect()},3e3)):o.config.autoReconnect&&!o.hasEverConnected&&console.log("⚠️ VoiceSDK v2: Initial connection failed. Auto-reconnect disabled to prevent retry loop.")},o.websocket.onmessage=function(t){o.handleMessage(t)}});case 3:return t.a(2,t.v);case 4:return t.p=4,n=t.v,console.error("🔌 VoiceSDK v2: Connection failed:",n),this.emit("error",n),t.a(2,!1)}},t,this,[[2,4]])})),function(){return l.apply(this,arguments)})},{key:"sendHelloMessage",value:function(){if(this.isConnected){var t={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},e={encoding:this.config.outputEncoding,sampleRate:this.config.outputSampleRate,channels:this.config.outputChannels,bitDepth:this.config.outputBitDepth,container:this.config.outputContainer},n=this.validateInputFormat(t);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(e);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 r={t:"hello",v:this.config.protocolVersion,inputFormat:t,requestedOutputFormat:e,outputFrameDurationMs:this.config.outputFrameDurationMs};this.config.agentSettingsOverride&&(r.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?(r.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:r.v,requestedFormat:r.requestedOutputFormat,variables:r.variables?Object.keys(r.variables):void 0}),console.log("📤 VoiceSDK v2: Requested output format:",{container:r.requestedOutputFormat.container,encoding:r.requestedOutputFormat.encoding,sampleRate:r.requestedOutputFormat.sampleRate,bitDepth:r.requestedOutputFormat.bitDepth}),console.log("📤 VoiceSDK v2: Full hello message being sent:",JSON.stringify(r,null,2));try{this.sendMessage(r)}catch(t){console.error("VoiceSDK v2: Failed to send hello:",t),this.emit("error",t)}}else console.warn("VoiceSDK v2: Cannot send hello - not connected")}},{key:"handleMessage",value:function(t){if(t.data instanceof ArrayBuffer||t.data instanceof Blob)this.handleBinaryMessage(t.data);else try{var e=JSON.parse(t.data);switch("audio"!==e.t&&console.log("📥 VoiceSDK v2: Received message type:",e.t,"Full message:",JSON.stringify(e).substring(0,200)),!this.conversationId&&e.conversationId&&(this.conversationId=e.conversationId,console.log("🔍 VoiceSDK v2: Captured conversationId from message:",this.conversationId),this.emit("conversationIdChanged",this.conversationId)),"audio"!==e.t&&console.log("📨 VoiceSDK v2: Received message type:",e.t,e),e.t){case"hello_ack":this.handleHelloAck(e);break;case"transcript":console.log("📝 VoiceSDK v2: Processing transcript message:",e),this.handleTranscript(e);break;case"user_transcript":console.log("📝 VoiceSDK v2: Received user_transcript:",e),this.emit("message",e);break;case"agent_response":if(console.log("📝 VoiceSDK v2: Received agent_response:",e),(e.text||e.transcript)&&(console.log("📝 VoiceSDK v2: agent_response contains transcript data:",e.text||e.transcript),e.sentenceId&&(e.text||e.transcript))){var n={t:"transcript",sentenceId:e.sentenceId,text:e.text||e.transcript,role:e.role||"assistant",final:!1!==e.final,timestamp:e.timestamp||Date.now()};console.log("📝 VoiceSDK v2: Converting agent_response to transcript:",n),this.handleTranscript(n)}this.emit("message",e);break;case"error":this.emit("message",e);break;case"barge_in":this.emit("bargeIn",e),this.stopAudioPlayback();break;case"stop_playing":this.emit("stopPlaying",e),this.stopAudioPlayback();break;case"audio_start":console.log("📝 VoiceSDK v2: Received audio_start with text:",e.text),e.text&&this.audioPlayer&&this.audioPlayer.markNewSentence(e.text),this.emit("message",e);break;case"client_tool_call":this.clientToolsRegistry.handleToolCall(e);break;default:if(console.log("VoiceSDK v2: Unknown message type:",e.t,"Full message:",JSON.stringify(e).substring(0,300)),(e.text||e.transcript||e.transcription)&&(console.log("📝 VoiceSDK v2: Unknown message contains transcript-like data:",{text:e.text,transcript:e.transcript,transcription:e.transcription,sentenceId:e.sentenceId,role:e.role}),e.sentenceId&&(e.text||e.transcript||e.transcription))){var o={t:"transcript",sentenceId:e.sentenceId,text:e.text||e.transcript||e.transcription,role:e.role||"assistant",final:!1!==e.final,timestamp:e.timestamp||Date.now()};console.log("📝 VoiceSDK v2: Attempting to process unknown message as transcript:",o),this.handleTranscript(o)}this.emit("message",e)}}catch(t){console.error("VoiceSDK v2: Error parsing message:",t)}}},{key:"handleHelloAck",value:function(t){if(console.log("📥 VoiceSDK v2: Received hello_ack:",{hasOutputFormat:!!t.outputAudioFormat,outputFormat:t.outputAudioFormat,hasConversationId:!!t.conversationId,messageType:t.t}),t.conversationId&&(this.conversationId=t.conversationId,console.log("🔍 VoiceSDK v2: Received conversationId:",this.conversationId),this.emit("conversationIdChanged",this.conversationId)),t.outputAudioFormat){this.outputAudioFormat=t.outputAudioFormat,this.audioPlayer.setOutputFormat(t.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 e={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!==e.container&&n.push('container: "'.concat(this.requestedOutputFormat.container,'" → "').concat(e.container,'"')),this.requestedOutputFormat.encoding!==e.encoding&&n.push('encoding: "'.concat(this.requestedOutputFormat.encoding,'" → "').concat(e.encoding,'"')),this.requestedOutputFormat.sampleRate!==e.sampleRate&&n.push("sampleRate: ".concat(this.requestedOutputFormat.sampleRate,"Hz → ").concat(e.sampleRate,"Hz")),this.requestedOutputFormat.bitDepth!==e.bitDepth&&n.push("bitDepth: ".concat(this.requestedOutputFormat.bitDepth,"-bit → ").concat(e.bitDepth,"-bit")),this.requestedOutputFormat.channels!==e.channels&&n.push("channels: ".concat(this.requestedOutputFormat.channels," → ").concat(e.channels)),n.length>0){console.warn("⚠️ VoiceSDK v2: Format negotiation mismatch!"),console.warn(" Requested:",this.requestedOutputFormat),console.warn(" Negotiated:",e),console.warn(" Differences:",n.join(", "));try{if(this.formatConverter=new Ge(this.requestedOutputFormat,e),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(t){console.error("❌ VoiceSDK v2: Failed to create format converter:",t),console.warn(" Will use backend format without conversion"),this.formatConverter=null}}else console.log("✅ VoiceSDK v2: Format perfectly matched!",e),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 r={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=r,this.requestedOutputFormat=r,this.audioPlayer.setOutputFormat(r),this.formatConverter=null}}},{key:"handleTranscript",value:function(t){if(t.sentenceId&&t.text){var e=t.sentenceId,n={text:t.text,role:t.role||"assistant",sentenceId:e,final:!1!==t.final,timestamp:t.timestamp||Date.now()};this.transcriptQueue.push(n),console.log("📝 VoiceSDK v2: Received transcript for sentence",e,":",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",e),this.emit("transcriptDisplay",n),this.currentPlayingSentenceId=e,this.emit("transcript",n)}else console.warn("⚠️ VoiceSDK v2: Invalid transcript message:",t)}},{key:"handleBinaryMessage",value:(c=Ze($e().m(function t(e){var n,o,r,i,a,s,c,l,u,d;return $e().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!(e instanceof Blob)){t.n=2;break}return t.n=1,e.arrayBuffer();case 1:o=t.v,t.n=3;break;case 2:o=e;case 3:if(console.log("📥 VoiceSDK v2: Received audio:",o.byteLength,"bytes"),console.log(" Current outputFormat:",this.outputAudioFormat),console.log(" AudioPlayer outputFormat:",null===(n=this.audioPlayer)||void 0===n?void 0:n.outputFormat),console.log(" Format converter:",this.formatConverter?"active":"none"),r=o,!this.formatConverter||!this.formatConverter.needsConversion()){t.n=7;break}return t.p=4,t.n=5,this.formatConverter.convert(o);case 5:r=t.v,console.log("✅ VoiceSDK v2: Audio converted to requested format"),t.n=7;break;case 6:t.p=6,d=t.v,console.error("❌ VoiceSDK v2: Format conversion failed:",d),console.warn(" Using backend format without conversion"),r=o;case 7:i=this.formatConverter&&this.formatConverter.needsConversion()?this.requestedOutputFormat:this.outputAudioFormat||{container:this.config.outputContainer||"raw",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,bitDepth:this.config.outputBitDepth||16,channels:this.config.outputChannels||1},a=i.container||"raw",s=(i.encoding||"pcm").toLowerCase(),"raw"===a?(c=r,"pcm"!==s&&((l=this.audioPlayer.getCodec(s))?(u=l.decode(new Uint8Array(r)),c=u.buffer,console.log("🔄 VoiceSDK v2: Decoded ".concat(s.toUpperCase()," to PCM (").concat(u.byteLength," bytes)"))):console.warn("⚠️ VoiceSDK v2: No codec for ".concat(s,", treating as PCM"))),this.audioPlayer.outputFormat||(console.warn("⚠️ VoiceSDK v2: outputFormat not set on AudioPlayer, setting from playbackFormat"),this.audioPlayer.setOutputFormat(i)),this.audioFrameCount++,this.audioPlayer.playChunk(c)):(this.audioFrameCount++,this.audioPlayer.playAudio(r));case 8:return t.a(2)}},t,this,[[4,6]])})),function(t){return c.apply(this,arguments)})},{key:"sendMessage",value:function(t){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send message - not connected"),!1;try{return this.websocket.send(JSON.stringify(t)),!0}catch(t){return console.error("VoiceSDK v2: Error sending message:",t),this.emit("error",t),!1}}},{key:"sendBinary",value:function(t){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send audio - not connected"),!1;try{return this.websocket.send(t),!0}catch(t){return console.error("VoiceSDK v2: Error sending audio:",t),this.emit("error",t),!1}}},{key:"disconnect",value:function(){this.isDestroyed||(console.log("🔌 VoiceSDK v2: Disconnecting..."),this.stopRecording(),this.audioPlayer&&this.stopAudioPlayback(),this.websocket&&(this.websocket.close(),this.websocket=null),this.isConnected=!1)}},{key:"startRecording",value:(s=Ze($e().m(function t(){var e,n,o;return $e().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.isConnected){t.n=1;break}throw e=new Error("Not connected to voice server"),this.emit("error",e),e;case 1:if(!this.isRecording){t.n=2;break}return console.warn("VoiceSDK v2: Already recording"),t.a(2,!0);case 2:return console.log("🎤 VoiceSDK v2: Starting recording..."),t.p=3,console.log("🎤 VoiceSDK v2: Requesting microphone permission (mobile-friendly)..."),t.n=4,this.audioRecorder.start();case 4:return t.n=5,this.audioPlayer.resumeAudioContext();case 5:return this.sendMessage({t:"start_continuous_mode",ttpId:this.generateTtpId()}),t.a(2,!0);case 6:return t.p=6,o=t.v,console.error("❌ VoiceSDK v2: Failed to start recording:",o),"NotAllowedError"===o.name||"PermissionDeniedError"===o.name?((n=new Error("Microphone permission denied. Please allow microphone access in your browser settings and try again.")).name=o.name,n.originalError=o,this.emit("error",n)):this.emit("error",o),t.a(2,!1)}},t,this,[[3,6]])})),function(){return s.apply(this,arguments)})},{key:"stopRecording",value:(a=Ze($e().m(function t(){var e;return $e().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.isRecording){t.n=1;break}return console.warn("VoiceSDK v2: Not recording"),t.a(2,!0);case 1:return console.log("🛑 VoiceSDK v2: Stopping recording..."),t.p=2,this.sendMessage({t:"stop_continuous_mode",ttpId:this.generateTtpId()}),this.isRecording=!1,this.emit("recordingStopped"),console.log("🛑 VoiceSDK v2: Recording stopped (emitted before audioRecorder.stop())"),t.n=3,this.audioRecorder.stop();case 3:return this.stopAudioPlayback(),t.a(2,!0);case 4:return t.p=4,e=t.v,console.error("VoiceSDK v2: Error stopping recording:",e),this.emit("error",e),t.a(2,!1)}},t,this,[[2,4]])})),function(){return a.apply(this,arguments)})},{key:"toggleRecording",value:(i=Ze($e().m(function t(){return $e().w(function(t){for(;;)switch(t.n){case 0:if(!this.isRecording){t.n=2;break}return t.n=1,this.stopRecording();case 1:case 3:return t.a(2,t.v);case 2:return t.n=3,this.startRecording();case 4:return t.a(2)}},t,this)})),function(){return i.apply(this,arguments)})},{key:"clearTranscriptState",value:function(){this.currentPlayingSentenceId=null,console.log("📝 VoiceSDK v2: Cleared transcript state")}},{key:"stopAudioPlayback",value:function(){this.audioPlayer.stopImmediate(),this.clearTranscriptState()}},{key:"handleBargeIn",value:(r=Ze($e().m(function t(){return $e().w(function(t){for(;;)switch(t.n){case 0:if(this.stopAudioPlayback(),this.isRecording){t.n=1;break}return t.n=1,this.startRecording();case 1:return t.a(2)}},t,this)})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){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()}}},{key:"updateConfig",value:function(t){this.config=Ye(Ye({},this.config),t)}},{key:"generateTtpId",value:function(){return"sdk_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"registerToolHandler",value:function(t,e){return this.clientToolsRegistry.registerHandler(t,e)}},{key:"unregisterToolHandler",value:function(t){return this.clientToolsRegistry.unregisterHandler(t)}},{key:"hasToolHandler",value:function(t){return this.clientToolsRegistry.hasHandler(t)}},{key:"getRegisteredTools",value:function(){return this.clientToolsRegistry.getRegisteredTools()}},{key:"destroy",value:function(){var t=this;this.isDestroyed||(console.log("🗑️ VoiceSDK v2: Destroying..."),this.disconnect(),this.isDestroyed=!0,this.audioPlayer&&this.audioPlayer.destroy(),this.audioRecorder&&this.audioRecorder.destroy(),this.clientToolsRegistry&&this.clientToolsRegistry.getRegisteredTools().forEach(function(e){return t.clientToolsRegistry.unregisterHandler(e)}),this.removeAllListeners())}}],o&&tn(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,s,c,l}(Ot);rn(sn,"SUPPORTED_INPUT_ENCODINGS",["pcm","pcmu","pcma"]),rn(sn,"SUPPORTED_INPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),rn(sn,"SUPPORTED_INPUT_BIT_DEPTHS",[8,16,24]),rn(sn,"SUPPORTED_INPUT_CHANNELS",[1]),rn(sn,"SUPPORTED_OUTPUT_ENCODINGS",["pcm","pcmu","pcma"]),rn(sn,"SUPPORTED_OUTPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),rn(sn,"SUPPORTED_OUTPUT_BIT_DEPTHS",[8,16,24]),rn(sn,"SUPPORTED_OUTPUT_CHANNELS",[1]),rn(sn,"SUPPORTED_OUTPUT_CONTAINERS",["raw","wav"]);const cn=sn;function ln(t){return ln="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ln(t)}function un(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return dn(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(dn(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,dn(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,dn(d,"constructor",l),dn(l,"constructor",c),c.displayName="GeneratorFunction",dn(l,r,"GeneratorFunction"),dn(d),dn(d,r,"Generator"),dn(d,o,function(){return this}),dn(d,"toString",function(){return"[object Generator]"}),(un=function(){return{w:i,m:p}})()}function dn(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}dn=function(t,e,n,o){function i(e,n){dn(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},dn(t,e,n,o)}function pn(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function fn(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function hn(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?fn(Object(n),!0).forEach(function(e){gn(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):fn(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function gn(t,e,n){return(e=mn(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vn(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,mn(o.key),o)}}function mn(t){var e=function(t){if("object"!=ln(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=ln(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==ln(e)?e:e+""}function yn(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(yn=function(){return!!t})()}function bn(t){return bn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},bn(t)}function wn(t,e){return wn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},wn(t,e)}var Sn=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var o=(t=function(t,e,n){return e=bn(e),function(t,e){if(e&&("object"==ln(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,yn()?Reflect.construct(e,n||[],bn(t).constructor):e.apply(t,n))}(this,e)).readScriptTagConfig();return t.config=hn({baseWsUrl:"wss://backend.talktopc.com/chat/websocket",appId:n.appId||o.appId,agentId:n.agentId||o.agentId,conversationId:void 0!==n.conversationId?n.conversationId:t.getPersistedConversationId(),forceConversationId:n.forceConversationId,queue:[],inFlight:!1},n),t.fullResponseBuffer="",t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&wn(t,e)}(e,t),n=e,o=[{key:"readScriptTagConfig",value:function(){try{var t=Array.from(document.getElementsByTagName("script")).reverse().find(function(t){return t.dataset&&(t.dataset.appId||t.dataset.agentId)||t.src&&t.src.includes("agent-widget")});return t?{appId:t.dataset.appId,agentId:t.dataset.agentId}:{}}catch(t){return{}}}},{key:"buildWebSocketUrl",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.config.baseWsUrl,e=new URLSearchParams;return this.config.appId&&e.append("appId",this.config.appId),this.config.agentId&&e.append("agentId",this.config.agentId),this.config.conversationId&&e.append("conversationId",this.config.conversationId),"".concat(t,"?").concat(e.toString())}},{key:"sendMessage",value:(r=un().m(function t(e){var n=this;return un().w(function(t){for(;;)if(0===t.n)return t.a(2,new Promise(function(t,o){if(e&&e.trim())if(n.config.appId&&n.config.agentId){var r={text:e,resolve:t,reject:o};n.config.inFlight?n.config.queue.push(r):n.executeTask(r)}else o(new Error("Missing appId or agentId"));else o(new Error("Message is empty"))}))},t)}),i=function(){var t=this,e=arguments;return new Promise(function(n,o){var i=r.apply(t,e);function a(t){pn(i,n,o,a,s,"next",t)}function s(t){pn(i,n,o,a,s,"throw",t)}a(void 0)})},function(t){return i.apply(this,arguments)})},{key:"executeTask",value:function(t){var e=this;if(this.config.inFlight=!0,this.fullResponseBuffer="",!this.config.conversationId){var n=this.getPersistedConversationId();n&&(this.config.conversationId=n,console.log("🔍 TextChatSDK hydrated conversationId from storage:",n))}var o,r=this.buildWebSocketUrl(this.config.baseWsUrl),i=this.config.baseWsUrl.endsWith("/websocket")?this.config.baseWsUrl.replace(/\/websocket$/,""):"".concat(this.config.baseWsUrl,"/websocket"),a=this.buildWebSocketUrl(i),s=!1,c=!1,l=null,u=function(n){if(!c)try{var o={message:t.text},r=e.config.forceConversationId||e.config.conversationId;r&&(o.conversationId=r,e.config.forceConversationId&&!e.config.conversationId&&(e.config.conversationId=r,e.persistConversationId(r))),console.log("🔍 TextChatSDK sending payload:",o,"conversationId in config:",e.config.conversationId),n.send(JSON.stringify(o)),c=!0}catch(o){t.reject(o),e.emit("error",o);try{n.close()}catch(t){}}},d=function(t){return function(){e.config.conversationId?u(t):l=setTimeout(function(){return u(t)},200)}},p=function(n){return function(o){try{try{console.log("🔎 [TextChatSDK] WS <= raw:",o.data)}catch(t){}var r=JSON.parse(o.data);try{console.log("🔎 [TextChatSDK] WS <= parsed:",r)}catch(t){}if("hello"===r.type&&r.conversationId){if(console.log("🔍 TextChatSDK received conversationId:",r.conversationId),e.config.conversationId=r.conversationId,e.persistConversationId(r.conversationId),e.emit&&e.emit("conversationIdChanged",r.conversationId),!c&&n&&1===n.readyState){if(l)try{clearTimeout(l)}catch(t){}u(n)}return}if(!e.config.conversationId&&r.conversationId&&(console.log("🔍 TextChatSDK captured conversationId from message:",r.conversationId),e.config.conversationId=r.conversationId,e.persistConversationId(r.conversationId)),"chunk"===r.type&&"string"==typeof r.content)e.fullResponseBuffer+=r.content,e.emit("chunk",r.content);else if("done"===r.type){try{var i=r.text||r.content||r.answer||r.message||"";i&&!e.fullResponseBuffer&&(e.fullResponseBuffer=i)}catch(t){}!e.config.conversationId&&r.conversationId&&(console.log("🔍 TextChatSDK captured conversationId from done:",r.conversationId),e.config.conversationId=r.conversationId),e.persistConversationId(e.config.conversationId),e.emit("done",{text:e.fullResponseBuffer}),t.resolve({conversationId:e.config.conversationId,fullText:e.fullResponseBuffer});try{n.close()}catch(t){}}else if("error"===r.type){var a=new Error(r.message||"Server error");e.emit("error",a),t.reject(a);try{n.close()}catch(t){}}}catch(t){}}},f=function(n){if(1008===n.code&&n.reason&&(n.reason.includes("Domain not whitelisted")||n.reason.includes("domain")||n.reason.includes("whitelist"))){var o=new Error("DOMAIN_NOT_WHITELISTED");return o.reason=n.reason,o.code=n.code,e.emit("domainError",o),t.reject(o),e.config.inFlight=!1,void e.drainQueue()}e.config.inFlight=!1,e.drainQueue()},h=new WebSocket(r);h.onopen=d(h),h.onmessage=p(h),h.onerror=(o=h,function(n){if(!s){s=!0;try{o.close()}catch(t){}var r=new WebSocket(a);return r.onopen=d(r),r.onmessage=p(r),r.onerror=function(n){e.emit("error",n),t.reject(n)},void(r.onclose=f)}e.emit("error",n),t.reject(n)}),h.onclose=f}},{key:"drainQueue",value:function(){if(0!==this.config.queue.length&&!this.config.inFlight){var t=this.config.queue.shift();this.executeTask(t)}}},{key:"persistConversationId",value:function(t){try{t&&localStorage.setItem("ttp_text_chat_conversation_id",t)}catch(t){}}},{key:"getPersistedConversationId",value:function(){try{return localStorage.getItem("ttp_text_chat_conversation_id")||null}catch(t){return null}}},{key:"updateConfig",value:function(t){this.config=hn(hn({},this.config),t)}},{key:"destroy",value:function(){this.config.queue=[],this.config.inFlight=!1,this.removeAllListeners()}}],o&&vn(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(l),xn=n(540),kn=n(848);function Cn(t){return Cn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Cn(t)}function Pn(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function Tn(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?Pn(Object(n),!0).forEach(function(e){En(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Pn(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function En(t,e,n){return(e=function(t){var e=function(t){if("object"!=Cn(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Cn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Cn(e)?e:e+""}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function On(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return An(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(An(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,An(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,An(d,"constructor",l),An(l,"constructor",c),c.displayName="GeneratorFunction",An(l,r,"GeneratorFunction"),An(d),An(d,r,"Generator"),An(d,o,function(){return this}),An(d,"toString",function(){return"[object Generator]"}),(On=function(){return{w:i,m:p}})()}function An(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}An=function(t,e,n,o){function i(e,n){An(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},An(t,e,n,o)}function In(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Rn(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var o,r,i,a,s=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(o=i.call(n)).done)&&(s.push(o.value),s.length!==e);c=!0);}catch(t){l=!0,r=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw r}}return s}}(t,e)||function(t,e){if(t){if("string"==typeof t)return jn(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?jn(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function jn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}const Dn=function(t){var e=t.signedUrl,n=t.websocketUrl,o=t.agentId,r=t.appId,i=t.voice,a=void 0===i?"default":i,s=t.language,c=void 0===s?"en":s,l=t.autoReconnect,u=void 0===l||l,d=t.agentSettingsOverride,p=void 0===d?null:d,f=t.onConnected,h=t.onDisconnected,g=t.onRecordingStarted,v=t.onRecordingStopped,m=t.onPlaybackStarted,y=t.onPlaybackStopped,b=t.onError,w=t.onMessage,S=t.onBargeIn,x=t.onStopPlaying,k=t.onStartConversation,C=t.onEndConversation,P=t.className,T=void 0===P?"":P,E=t.style,O=void 0===E?{}:E,A=t.children,I=Rn((0,xn.useState)(!1),2),R=I[0],j=I[1],D=Rn((0,xn.useState)(!1),2),F=D[0],_=D[1],B=Rn((0,xn.useState)(!1),2),M=(B[0],B[1]),U=Rn((0,xn.useState)("Disconnected"),2),N=(U[0],U[1]),z=(0,xn.useRef)(null);(0,xn.useEffect)(function(){console.log("🎙️ VoiceButton: Creating VoiceSDK instance for ".concat(n)),z.current&&(console.log("🎙️ VoiceButton: Destroying existing VoiceSDK instance"),z.current.destroy(),z.current=null);var t=new kt({websocketUrl:n,agentId:o,appId:r,voice:a,language:c,autoReconnect:u,agentSettingsOverride:p,onStartConversation:k,onEndConversation:C});return t.on("connected",function(){j(!0),N("Connected"),null==f||f()}),t.on("disconnected",function(){j(!1),N("Disconnected"),null==h||h()}),t.on("recordingStarted",function(){_(!0),null==g||g()}),t.on("recordingStopped",function(){_(!1),null==v||v()}),t.on("playbackStarted",function(){M(!0),null==m||m()}),t.on("playbackStopped",function(){M(!1),null==y||y()}),t.on("error",function(t){null==b||b(t)}),t.on("message",function(t){null==w||w(t)}),t.on("bargeIn",function(t){null==S||S(t)}),t.on("stopPlaying",function(t){null==x||x(t)}),z.current=t,t.connect(),function(){var t=e||n;console.log("🎙️ VoiceButton: Cleaning up VoiceSDK instance for ".concat(t)),z.current&&(z.current.destroy(),z.current=null)}},[e,n,o,r,a,c,p]);var H=function(){var t,e=(t=On().m(function t(){var e;return On().w(function(t){for(;;)switch(t.p=t.n){case 0:if(z.current){t.n=1;break}return t.a(2);case 1:return t.p=1,t.n=2,z.current.toggleRecording();case 2:t.n=4;break;case 3:t.p=3,e=t.v,console.error("Error toggling recording:",e);case 4:return t.a(2)}},t,null,[[1,3]])}),function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){In(i,o,r,a,s,"next",t)}function s(t){In(i,o,r,a,s,"throw",t)}a(void 0)})});return function(){return e.apply(this,arguments)}}(),L=(0,kn.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,kn.jsx)("div",{style:{fontSize:"20px"},children:F?"🔴":"🎤"}),(0,kn.jsx)("div",{children:F?"Stop Listening":"Start Listening"})]});return(0,kn.jsx)("button",{className:"voice-button ".concat(F?"recording":""," ").concat(T),style:Tn({padding:"12px 24px",border:"none",borderRadius:"8px",backgroundColor:F?"#dc3545":"#007bff",color:"white",cursor:"pointer",fontSize:"16px",fontWeight:"500",transition:"all 0.2s ease"},O),onClick:H,disabled:!R,children:A||L})};function Fn(t){return Fn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fn(t)}function _n(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Bn(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Bn(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Bn(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Bn(d,"constructor",l),Bn(l,"constructor",c),c.displayName="GeneratorFunction",Bn(l,r,"GeneratorFunction"),Bn(d),Bn(d,r,"Generator"),Bn(d,o,function(){return this}),Bn(d,"toString",function(){return"[object Generator]"}),(_n=function(){return{w:i,m:p}})()}function Bn(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Bn=function(t,e,n,o){function i(e,n){Bn(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Bn(t,e,n,o)}function Mn(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Un(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){Mn(i,o,r,a,s,"next",t)}function s(t){Mn(i,o,r,a,s,"throw",t)}a(void 0)})}}function Nn(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function zn(t,e,n){return(e=Ln(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Hn(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Ln(o.key),o)}}function Ln(t){var e=function(t){if("object"!=Fn(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Fn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Fn(e)?e:e+""}var Vn=function(){return t=function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.options=function(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?Nn(Object(n),!0).forEach(function(e){zn(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Nn(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}({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 kt({websocketUrl:this.options.websocketUrl,agentId:this.options.agentId,voice:this.options.voice,language:this.options.language}),this.setupEventListeners(),this.createButton(),this.connect()},e=[{key:"setupEventListeners",value:function(){var t=this;this.voiceSDK.on("connected",function(){var e,n;t.isConnected=!0,t.updateButton(),null===(e=(n=t.options).onConnected)||void 0===e||e.call(n)}),this.voiceSDK.on("disconnected",function(){var e,n;t.isConnected=!1,t.updateButton(),null===(e=(n=t.options).onDisconnected)||void 0===e||e.call(n)}),this.voiceSDK.on("recordingStarted",function(){var e,n;t.isRecording=!0,t.updateButton(),null===(e=(n=t.options).onRecordingStarted)||void 0===e||e.call(n)}),this.voiceSDK.on("recordingStopped",function(){var e,n;t.isRecording=!1,t.updateButton(),null===(e=(n=t.options).onRecordingStopped)||void 0===e||e.call(n)}),this.voiceSDK.on("playbackStarted",function(){var e,n;t.isPlaying=!0,null===(e=(n=t.options).onPlaybackStarted)||void 0===e||e.call(n)}),this.voiceSDK.on("playbackStopped",function(){var e,n;t.isPlaying=!1,null===(e=(n=t.options).onPlaybackStopped)||void 0===e||e.call(n)}),this.voiceSDK.on("error",function(e){var n,o;null===(n=(o=t.options).onError)||void 0===n||n.call(o,e)}),this.voiceSDK.on("message",function(e){var n,o;null===(n=(o=t.options).onMessage)||void 0===n||n.call(o,e)}),this.voiceSDK.on("bargeIn",function(e){var n,o;null===(n=(o=t.options).onBargeIn)||void 0===n||n.call(o,e)}),this.voiceSDK.on("stopPlaying",function(e){var n,o;null===(n=(o=t.options).onStopPlaying)||void 0===n||n.call(o,e)})}},{key:"createButton",value:function(){var t=this;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",function(){return t.toggleRecording()}),this.options.container.appendChild(this.button),this.updateButton()}},{key:"updateButton",value:function(){if(this.button){var t=this.isRecording?"🔴":"🎤",e=this.isRecording?"Stop Listening":"Start Listening";this.button.innerHTML='\n <span style="font-size: 20px;">'.concat(t,"</span>\n <span>").concat(e,"</span>\n "),this.button.disabled=!this.isConnected,this.button.style.backgroundColor=this.isRecording?"#dc3545":this.isConnected?"#007bff":"#6c757d"}}},{key:"connect",value:(o=Un(_n().m(function t(){var e;return _n().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,t.n=1,this.voiceSDK.connect();case 1:t.n=3;break;case 2:t.p=2,e=t.v,console.error("Failed to connect:",e);case 3:return t.a(2)}},t,this,[[0,2]])})),function(){return o.apply(this,arguments)})},{key:"toggleRecording",value:(n=Un(_n().m(function t(){var e;return _n().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.voiceSDK){t.n=1;break}return t.a(2);case 1:return t.p=1,t.n=2,this.voiceSDK.toggleRecording();case 2:t.n=4;break;case 3:t.p=3,e=t.v,console.error("Error toggling recording:",e);case 4:return t.a(2)}},t,this,[[1,3]])})),function(){return n.apply(this,arguments)})},{key:"getStatus",value:function(){return{isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying}}},{key:"updateConfig",value:function(t){this.voiceSDK.updateConfig(t)}},{key:"destroy",value:function(){this.button&&this.button.parentNode&&this.button.parentNode.removeChild(this.button),this.voiceSDK&&this.voiceSDK.destroy()}}],e&&Hn(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();function Kn(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Wn(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Wn(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Wn(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Wn(d,"constructor",l),Wn(l,"constructor",c),c.displayName="GeneratorFunction",Wn(l,r,"GeneratorFunction"),Wn(d),Wn(d,r,"Generator"),Wn(d,o,function(){return this}),Wn(d,"toString",function(){return"[object Generator]"}),(Kn=function(){return{w:i,m:p}})()}function Wn(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Wn=function(t,e,n,o){function i(e,n){Wn(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Wn(t,e,n,o)}function Gn(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var o,r,i,a,s=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(o=i.call(n)).done)&&(s.push(o.value),s.length!==e);c=!0);}catch(t){l=!0,r=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw r}}return s}}(t,e)||Qn(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function qn(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=Qn(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}function Qn(t,e){if(t){if("string"==typeof t)return Yn(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Yn(t,e):void 0}}function Yn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}function $n(t){return $n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$n(t)}function Jn(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Xn(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){Jn(i,o,r,a,s,"next",t)}function s(t){Jn(i,o,r,a,s,"throw",t)}a(void 0)})}}function Zn(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,to(o.key),o)}}function to(t){var e=function(t){if("object"!=$n(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=$n(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==$n(e)?e:e+""}var eo=function(){return t=function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),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.onConnected=function(){},this.onDisconnected=function(){},this.onError=function(t){return console.error("SDK Error:",t)},this.onTranscript=function(t){},this.onAgentSpeaking=function(t){},this.onConversationStart=e.onConversationStart||function(){},this.onConversationEnd=e.onConversationEnd||function(){},this.onBargeIn=e.onBargeIn||function(){},this.onAudioStartPlaying=e.onAudioStartPlaying||function(){},this.onAudioStoppedPlaying=e.onAudioStoppedPlaying||function(){},this.onSubtitleDisplay=e.onSubtitleDisplay||function(){}},e=[{key:"connect",value:(o=Xn(Kn().m(function t(e){var n,o,r,i,a,s,c=this;return Kn().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,e){t.n=1;break}throw new Error("signedUrl is required");case 1:if(this.voiceSDK&&(console.log("🔌 AgentSDK: Cleaning up existing connection"),this.voiceSDK.destroy(),this.voiceSDK=null),this.voiceSDK=new cn({signedUrl:e,autoReconnect:!1,agentId:this.config.agentId,appId:this.config.appId,language:this.config.language||"en",agentSettingsOverride:this.config.agentSettingsOverride,protocolVersion:2,outputContainer:this.config.outputContainer||"raw",outputEncoding:this.config.outputEncoding||"pcm",outputSampleRate:this.config.outputSampleRate||44100,outputChannels:this.config.outputChannels||1,outputBitDepth:this.config.outputBitDepth||16}),this.voiceSDK.on("connected",function(){c.isConnected=!0,c.onConnected()}),setTimeout(function(){c.voiceSDK&&c.voiceSDK.isConnected&&!c.isConnected&&(c.isConnected=!0,c.onConnected())},10),this.voiceSDK.on("disconnected",function(t){if(c.isConnected=!1,t&&1008===t.code&&t.reason&&(t.reason.includes("Domain not whitelisted")||t.reason.includes("domain")||t.reason.includes("whitelist"))){var e=new Error("DOMAIN_NOT_WHITELISTED");e.reason=t.reason,e.code=t.code,c.onError(e)}if((c.isListening||c.wasListening)&&(console.log("🎤 [AGENT SDK] disconnected event - calling onConversationEnd hook (isListening:",c.isListening,", wasListening:",c.wasListening,")"),c.onConversationEnd&&"function"==typeof c.onConversationEnd))try{c.onConversationEnd(),console.log("🎤 [AGENT SDK] ✅ onConversationEnd hook called from disconnected event"),c.wasListening=!1}catch(t){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationEnd from disconnected:",t)}c.onDisconnected()}),this.voiceSDK.on("domainError",function(t){c.onError(t)}),this.voiceSDK.on("error",function(t){c.onError(t)}),this.voiceSDK.on("message",function(t){c.handleWebSocketMessage(t)}),this.voiceSDK.on("recordingStarted",function(){if(c.isListening=!0,c.wasListening=!0,c.onConversationStart&&"function"==typeof c.onConversationStart)try{c.onConversationStart()}catch(t){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationStart:",t)}}),this.voiceSDK.on("recordingStopped",function(){console.log("🎤 [AGENT SDK] recordingStopped event received");var t=c.isListening;if(c.isListening=!1,t&&c.onConversationEnd&&"function"==typeof c.onConversationEnd)try{console.log("🎤 [AGENT SDK] ✅ Calling onConversationEnd hook from recordingStopped"),c.onConversationEnd(),console.log("🎤 [AGENT SDK] ✅ onConversationEnd hook called successfully"),c.wasListening=!1}catch(t){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationEnd:",t)}}),this.voiceSDK.on("playbackStarted",function(){c.onAgentSpeaking(!0),c.onAudioStartPlaying()}),this.voiceSDK.on("playbackStopped",function(){c.onAgentSpeaking(!1),c.onAudioStoppedPlaying()}),this.voiceSDK.on("bargeIn",function(t){c.onBargeIn(t)}),this.voiceSDK.on("transcriptDisplay",function(t){console.log("📝 [AGENT SDK] transcriptDisplay event received:",t),t&&t.text&&(console.log("📝 [AGENT SDK] Calling onTranscript with text:",t.text),c.onTranscript&&"function"==typeof c.onTranscript?c.onTranscript(t.text):console.warn("📝 [AGENT SDK] ⚠️ onTranscript is not a function!",$n(c.onTranscript))),c.onSubtitleDisplay(t)}),this._pendingToolHandlers&&this._pendingToolHandlers.size>0){console.log("🔧 AgentSDK: Registering ".concat(this._pendingToolHandlers.size," pending tool handlers")),n=qn(this._pendingToolHandlers);try{for(n.s();!(o=n.n()).done;)r=Gn(o.value,2),i=r[0],a=r[1],this.voiceSDK.registerToolHandler(i,a)}catch(t){n.e(t)}finally{n.f()}}return t.n=2,this.voiceSDK.connect();case 2:t.n=4;break;case 3:throw t.p=3,s=t.v,this.onError(s),s;case 4:return t.a(2)}},t,this,[[0,3]])})),function(t){return o.apply(this,arguments)})},{key:"handleWebSocketMessage",value:function(t){switch(t.t||t.type){case"connected":case"hello_ack":console.log("Session started successfully");break;case"user_transcript":this.onTranscript(t.user_transcription||t.text||t.transcript);break;case"agent_response":case"barge_in":case"stop_playing":default:break;case"error":this.onError(new Error(t.message||t.error||"Unknown error"))}}},{key:"startListening",value:(n=Xn(Kn().m(function t(){var e;return Kn().w(function(t){for(;;)switch(t.p=t.n){case 0:if(console.log("🎤 AgentSDK: startListening() called"),!this.voiceSDK){t.n=5;break}return t.p=1,console.log("🎤 AgentSDK: Starting recording..."),t.n=2,this.voiceSDK.startRecording();case 2:console.log("✅ AgentSDK: Recording started successfully"),t.n=4;break;case 3:throw t.p=3,e=t.v,console.error("❌ AgentSDK: Failed to start recording:",e),e;case 4:t.n=6;break;case 5:throw console.error("❌ AgentSDK: No voiceSDK instance available"),new Error("No voiceSDK instance available");case 6:return t.a(2)}},t,this,[[1,3]])})),function(){return n.apply(this,arguments)})},{key:"stopListening",value:function(){this.voiceSDK&&this.voiceSDK.stopRecording()}},{key:"updateVariables",value:function(t){this.voiceSDK&&this.isConnected&&this.voiceSDK.sendMessage({t:"update_variables",variables:t})}},{key:"disconnect",value:function(){this.voiceSDK&&(this.voiceSDK.destroy(),this.voiceSDK=null),this.isConnected=!1,this.isListening=!1}},{key:"registerToolHandler",value:function(t,e){if(this.voiceSDK)return this.voiceSDK.registerToolHandler(t,e);this._pendingToolHandlers||(this._pendingToolHandlers=new Map),this._pendingToolHandlers.set(t,e),console.log("🔧 AgentSDK: Queued tool handler '".concat(t,"' for registration after connect"))}},{key:"unregisterToolHandler",value:function(t){if(this.voiceSDK)return this.voiceSDK.unregisterToolHandler(t);this._pendingToolHandlers&&this._pendingToolHandlers.delete(t)}},{key:"hasToolHandler",value:function(t){var e;return this.voiceSDK?this.voiceSDK.hasToolHandler(t):(null===(e=this._pendingToolHandlers)||void 0===e?void 0:e.has(t))||!1}},{key:"getRegisteredTools",value:function(){return this.voiceSDK?this.voiceSDK.getRegisteredTools():this._pendingToolHandlers?Array.from(this._pendingToolHandlers.keys()):[]}}],e&&Zn(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();function no(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return oo(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(oo(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,oo(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,oo(d,"constructor",l),oo(l,"constructor",c),c.displayName="GeneratorFunction",oo(l,r,"GeneratorFunction"),oo(d),oo(d,r,"Generator"),oo(d,o,function(){return this}),oo(d,"toString",function(){return"[object Generator]"}),(no=function(){return{w:i,m:p}})()}function oo(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}oo=function(t,e,n,o){function i(e,n){oo(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},oo(t,e,n,o)}function ro(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function io(){var t=navigator.userAgent,e=/iPad|iPhone|iPod/.test(t)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,n=/Android/.test(t),o=/Mac/.test(t)&&!e,r=/Win/.test(t),i=/Chrome/.test(t)&&!/Edg|OPR/.test(t),a=/Safari/.test(t)&&!/Chrome/.test(t),s=/Firefox/.test(t),c=/Edg/.test(t),l=/SamsungBrowser/.test(t),u="unknown";e?u="safari":l?u="samsung":i?u="chrome":a?u="safari":s?u="firefox":c&&(u="edge");var d="unknown";return e?d="ios":n?d="android":o?d="mac":r&&(d="windows"),{platform:d,browser:u,isIOS:e,isAndroid:n,isMac:o,isWindows:r,isMobile:e||n,isDesktop:!e&&!n}}function ao(){return so.apply(this,arguments)}function so(){var t;return t=no().m(function t(){var e;return no().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,!navigator.permissions||!navigator.permissions.query){t.n=2;break}return t.n=1,navigator.permissions.query({name:"microphone"});case 1:return e=t.v,t.a(2,e.state);case 2:t.n=4;break;case 3:t.p=3,t.v,console.log("⚠️ MicPermissionUtils: Permissions API not available or not supported for microphone");case 4:return t.a(2,"unknown")}},t,null,[[0,3]])}),so=function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){ro(i,o,r,a,s,"next",t)}function s(t){ro(i,o,r,a,s,"throw",t)}a(void 0)})},so.apply(this,arguments)}function co(t){var e=t.platform,n=t.browser,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"===e?o.ios:"android"===e?o["android_".concat(n)]||o.android_chrome:o["desktop_".concat(n)]||o.desktop_chrome}function lo(t){var e=t.isIOS,n=t.isAndroid,o=t.browser;if(e)try{return window.location.href="app-settings:",!0}catch(t){return console.warn("Could not open iOS settings:",t),!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(t){return console.warn("Could not open Android settings:",t),!1}return!1}function uo(t){return uo="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},uo(t)}function po(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,fo(o.key),o)}}function fo(t){var e=function(t){if("object"!=uo(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=uo(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==uo(e)?e:e+""}function ho(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return go(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?go(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}function go(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}var vo=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.overlay=null,this.modal=null},(e=[{key:"createOverlay",value:function(){var t=document.createElement("div");return t.className="mic-permission-overlay",t.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(),t}},{key:"injectStyles",value:function(){if(!document.getElementById("mic-permission-styles")){var t=document.createElement("style");t.id="mic-permission-styles",t.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(t)}}},{key:"close",value:function(){this.overlay&&this.overlay.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.modal=null}},{key:"show",value:function(){this.overlay&&this.modal&&document.body.appendChild(this.overlay)}}])&&po(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function mo(t,e){var n=new vo,o=n.createOverlay(),r=io(),i=document.createElement("div");return i.className="mic-permission-modal",i.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(r.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(i),n.overlay=o,n.modal=i,i.querySelector('[data-action="accept"]').addEventListener("click",function(){n.close(),t()}),i.querySelector('[data-action="cancel"]').addEventListener("click",function(){n.close(),e()}),o.addEventListener("click",function(t){t.target===o&&(n.close(),e())}),n.show(),n}function yo(t,e){var n,o,r,i=new vo,a=i.createOverlay(),s=io(),c=co(s),l=document.createElement("div");l.className="mic-permission-modal";var u="";c.altSteps&&c.altSteps.length>0&&(u='\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(function(t){return'<li style="padding: 8px 0; font-size: 14px; color: #6b7280;">'.concat(t,"</li>")}).join(""),"\n </ol>\n </div>\n "));var d=function(t){var e,n=t.platform,o=t.browser,r=document.getElementsByTagName("script"),i="",a=ho(r);try{for(a.s();!(e=a.n()).done;){var s=e.value.src;if(s&&(s.includes("agent-widget.js")||s.includes("ttp-agent-sdk")||s.includes("ttp-sdk-front")))try{new URL(s),i=s.substring(0,s.lastIndexOf("/"));break}catch(t){var c=s.match(/^(.*\/)[^\/]+$/);if(c){i=c[1];break}}}}catch(t){a.e(t)}finally{a.f()}var l;if(l="ios"===n?"ios-settings.svg":"android"===n?"android-chrome.svg":"chrome"===o?"desktop-chrome.svg":"safari"===o?"desktop-safari.svg":"firefox"===o?"desktop-firefox.svg":"edge"===o?"desktop-edge.svg":"desktop-chrome.svg",!i||""===i||i.startsWith("/")){var u,d=ho(r);try{for(d.s();!(u=d.n()).done;){var p=u.value.src;if(p&&(p.includes("cdn.talktopc.com")||p.includes("talktopc.com"))){if(p.includes("/ttp-agent-sdk/")||p.includes("/ttp-sdk-front/")){var f=p.match(/(https?:\/\/[^\/]+(?:\/[^\/]+)*)/);if(f){i=f[1].replace(/\/[^\/]+\.js$/,"");break}}if(!i&&(p.includes("cdn.talktopc.com")||p.includes("talktopc.com"))){i="https://cdn.talktopc.com/ttp-agent-sdk";break}}}}catch(t){d.e(t)}finally{d.f()}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 g="".concat(i,"/shared/mic-permission-assets/").concat(l);return"undefined"!=typeof console&&console.log&&console.log("[MicPermission] Visual guide path:",g,"Base path:",i,"Platform:",n,"Browser:",o),g}(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(d,'" 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(function(t){return"<li>".concat(t,"</li>")}).join(""),"\n </ol>\n </div>\n ").concat(u,'\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),i.overlay=a,i.modal=l,null===(n=l.querySelector('[data-action="close"]'))||void 0===n||n.addEventListener("click",function(){i.close(),t()}),null===(o=l.querySelector('[data-action="open-settings"]'))||void 0===o||o.addEventListener("click",function(){lo(s)}),null===(r=l.querySelector('[data-action="refresh"]'))||void 0===r||r.addEventListener("click",function(){window.location.reload()});var p=l.querySelector('[data-action="show-hint"]');p&&p.addEventListener("click",function(){i.close(),t(),function(){var t=document.getElementById("mic-address-bar-hint");t&&t.remove(),io();var e,n=document.getElementsByTagName("script"),o="",r=ho(n);try{for(r.s();!(e=r.n()).done;){var i=e.value.src;if(i&&(i.includes("agent-widget.js")||i.includes("ttp-agent-sdk")||i.includes("ttp-sdk-front")))try{new URL(i),o=i.substring(0,i.lastIndexOf("/"));break}catch(t){var a=i.match(/^(.*\/)[^\/]+$/);if(a){o=a[1];break}}}}catch(t){r.e(t)}finally{r.f()}if(!o||""===o||o.startsWith("/")){var s,c=ho(n);try{for(c.s();!(s=c.n()).done;){var l=s.value.src;if(l&&(l.includes("cdn.talktopc.com")||l.includes("talktopc.com"))){if(l.includes("/ttp-agent-sdk/")||l.includes("/ttp-sdk-front/")){var u=l.match(/(https?:\/\/[^\/]+(?:\/[^\/]+)*)/);if(u){o=u[1].replace(/\/[^\/]+\.js$/,"");break}}if(!o&&(l.includes("cdn.talktopc.com")||l.includes("talktopc.com"))){o="https://cdn.talktopc.com/ttp-agent-sdk";break}}}}catch(t){c.e(t)}finally{c.f()}if(!o||""===o)if(window.location.hostname.includes("cdn.talktopc.com")||window.location.hostname.includes("talktopc.com"))o="https://cdn.talktopc.com/ttp-agent-sdk";else{var d=window.location.pathname.split("/");d.pop(),(o=window.location.origin+d.join("/"))&&o!==window.location.origin||(o=window.location.origin)}}o=o.replace(/\/$/,"");var p="".concat(o,"/shared/mic-permission-assets/address-bar-hint.svg"),f=document.createElement("div");f.id="mic-address-bar-hint",f.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 g=document.createElement("div");g.style.cssText="\n flex-shrink: 0;\n ";var v=document.createElement("img");v.src=p,v.alt="Address bar hint",v.style.cssText="\n width: auto;\n height: 80px;\n display: block;\n ",v.onerror=function(){g.style.display="none"},g.appendChild(v);var m=document.createElement("div");m.style.cssText="\n display: flex;\n flex-direction: column;\n gap: 4px;\n flex: 1;\n ";var y=document.createElement("div");y.style.cssText="\n font-size: 15px;\n font-weight: 500;\n ",y.innerHTML="Click the <strong>lock icon 🔒</strong>, <strong>information icon ℹ️</strong>, or <strong>settings icon ⋮</strong> in the address bar to enable microphone";var b=document.createElement("button");if(b.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 ",b.textContent="✕",b.addEventListener("click",function(){f.remove()}),b.addEventListener("mouseenter",function(){b.style.background="rgba(255, 255, 255, 0.3)"}),b.addEventListener("mouseleave",function(){b.style.background="rgba(255, 255, 255, 0.2)"}),!document.getElementById("mic-address-bar-hint-styles")){var w=document.createElement("style");w.id="mic-address-bar-hint-styles",w.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(w)}m.appendChild(y),h.appendChild(g),h.appendChild(m),h.appendChild(b),f.appendChild(h),document.body.appendChild(f),setTimeout(function(){f.parentNode&&(f.style.opacity="0",f.style.transition="opacity 0.3s ease-out",setTimeout(function(){f.parentNode&&f.remove()},300))},1e4)}()});var f=l.querySelector(".mic-permission-modal__alt-toggle");if(f&&c.altSteps){var h=f.nextElementSibling;h&&(h.style.display="none",f.addEventListener("click",function(){"none"===h.style.display?(h.style.display="block",f.innerHTML="▼ ".concat(c.altTitle||"Alternative method")):(h.style.display="none",f.innerHTML="▶ ".concat(c.altTitle||"Alternative method"))}))}return a.addEventListener("click",function(e){e.target===a&&(i.close(),t())}),i.show(),i}function bo(t){var e=new vo,n=e.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),e.overlay=n,e.modal=o,o.querySelector('[data-action="retry"]').addEventListener("click",function(){window.location.reload()}),o.querySelector('[data-action="close"]').addEventListener("click",function(){e.close(),t()}),n.addEventListener("click",function(o){o.target===n&&(e.close(),t())}),e.show(),e}function wo(t){return wo="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},wo(t)}function So(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return xo(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(xo(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,xo(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,xo(d,"constructor",l),xo(l,"constructor",c),c.displayName="GeneratorFunction",xo(l,r,"GeneratorFunction"),xo(d),xo(d,r,"Generator"),xo(d,o,function(){return this}),xo(d,"toString",function(){return"[object Generator]"}),(So=function(){return{w:i,m:p}})()}function xo(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}xo=function(t,e,n,o){function i(e,n){xo(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},xo(t,e,n,o)}function ko(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Co(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){ko(i,o,r,a,s,"next",t)}function s(t){ko(i,o,r,a,s,"throw",t)}a(void 0)})}}function Po(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,To(o.key),o)}}function To(t){var e=function(t){if("object"!=wo(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=wo(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==wo(e)?e:e+""}var Eo=function(){return t=function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),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 eo({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()},e=[{key:"setupSDKEventHandlers",value:function(){var t=this;this.sdk.onTranscript=function(e){console.log("📝 [VOICE INTERFACE] onTranscript called with text:",e),t.updateTranscript(e)},this.sdk.onAgentSpeaking=function(e){var n=t.shadowRoot.getElementById("voiceAvatarActive");n&&(e?n.classList.add("speaking"):n.classList.remove("speaking"))},this.sdk.onDisconnected=function(){console.log("🔌 WebSocket disconnected, hanging up call..."),t.isActive&&(t.isActive=!1,t.endVoiceCall())},this.sdk.onError=function(e){console.error("❌ Voice SDK Error:",e),e&&("DOMAIN_NOT_WHITELISTED"===e.message||e.message&&e.message.includes("Domain not whitelisted"))?t.showDomainError():t.showError(e.message||e)}}},{key:"t",value:function(t){var e,n,o=this.config.language||"en";return((null===(e=this.config.translations)||void 0===e?void 0:e[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[t]||t}},{key:"getText",value:function(t,e){return void 0!==this.config[t]&&null!==this.config[t]?this.config[t]:this.t(e)}},{key:"getTooltip",value:function(t){var e,n=null===(e=this.config.tooltips)||void 0===e?void 0:e[t];return null!=n?n:{mute:this.t("mute"),speaker:this.t("speaker"),endCall:this.t("endCall")}[t]||""}},{key:"generateHTML",value:function(){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>')}},{key:"generateCSS",value:function(){var t=this.config.avatarBackgroundColor||"#667eea",e=this.config.avatarActiveBackgroundColor||this.config.avatarBackgroundColor||"#667eea",n=this.config.statusTitleColor||"#1e293b",o=this.config.statusSubtitleColor||"#64748b",r=this.config.startCallButtonColor||"#667eea",i=this.config.startCallButtonTextColor||"#FFFFFF",a=this.config.transcriptBackgroundColor||"#FFFFFF",s=this.config.transcriptTextColor||"#1e293b",c=this.config.transcriptLabelColor||"#94a3b8",l=this.config.controlButtonColor||"#FFFFFF",u=this.config.controlButtonSecondaryColor||"#64748b",d=(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(d,"; \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(d,'; }\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(t," 0%, ").concat(e," 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(r,";\n color: ").concat(i,";\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(u,";\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 ")}},{key:"setupEventHandlers",value:function(t){var e=this,n=this.shadowRoot.getElementById("startCallBtn"),o=this.shadowRoot.getElementById("endCallBtn"),r=this.shadowRoot.getElementById("muteBtn"),i=this.shadowRoot.getElementById("speakerBtn");n&&(n.onclick=function(){return e.startVoiceCall()}),o&&(o.onclick=function(){return e.endVoiceCall()}),r&&(r.onclick=function(){return e.toggleMute()}),i&&(i.onclick=function(){return e.toggleSpeaker()});var a=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=e.shadowRoot.getElementById("voiceInterface");n&&n.classList.contains("active")&&n.clientHeight>100?(console.log("✅ Interface is active and has proper dimensions, adjusting sizes (attempt",t+1,")"),e.adjustSizesForContainer(),0===t&&setTimeout(function(){return e.adjustSizesForContainer()},500)):t<15?(console.log("⏳ Interface not ready yet (height:",null==n?void 0:n.clientHeight,"), retrying... (attempt",t+1,")"),setTimeout(function(){return a(t+1)},250)):(console.warn("⚠️ Interface never became fully ready, adjusting sizes anyway"),e.adjustSizesForContainer())};setTimeout(function(){return a()},200),window.addEventListener("resize",function(){console.log("🔄 Window resized, re-adjusting sizes"),e.adjustSizesForContainer()})}},{key:"getSignedUrl",value:(r=Co(So().m(function t(){var e,n;return So().w(function(t){for(;;)switch(t.n){case 0:if(!this.config.signedUrl){t.n=1;break}return t.a(2,this.config.signedUrl);case 1:if(this.config.agentId){t.n=2;break}throw new Error("agentId is required when signedUrl is not provided");case 2:return e=this.config.websocketUrl||"wss://speech.talktopc.com/ws/conv",(n=new URLSearchParams).append("agentId",this.config.agentId),this.config.appId&&n.append("appId",this.config.appId),!1!==this.config.demo&&n.append("demo","true"),t.a(2,"".concat(e,"?").concat(n.toString()))}},t,this)})),function(){return r.apply(this,arguments)})},{key:"adjustSizesForContainer",value:function(){var t=this.shadowRoot.getElementById("voiceInterface");if(t){var e=t.clientHeight,n=t.clientWidth;console.log("📏 Container size:",e,"x",n);var o,r,i,a,s,c,l,u,d,p=this.shadowRoot.getElementById("voiceIdleState"),f=this.shadowRoot.getElementById("voiceActiveState"),h=p&&"none"!==p.style.display,g=f&&"none"!==f.style.display;console.log("👁️ Visible state - Idle:",h,"Active:",g),e<=350?(d=5,o=70,r=35,i=11,a=9,s=32,c=100,l=42,u=48):e<=450?(d=7,o=110,r=55,i=15,a=11,s=38,c=110,l=52,u=58):e<=550?(d=8,o=140,r=70,i=16,a=12,s=42,c=120,l=56,u=64):e<=700?(d=10,o=130,r=65,i=18,a=13,s=46,c=130,l=60,u=70):(d=12,o=150,r=75,i=20,a=14,s=50,c=140,l=66,u=76),this.shadowRoot.querySelectorAll("#voiceIdleState, #voiceActiveState").forEach(function(t){t.style.gap="".concat(d,"px")});var v=this.shadowRoot.querySelectorAll(".voice-avatar, .voice-avatar-active");console.log("🤖 Found",v.length,"avatars, setting size to",o,"px"),v.forEach(function(t){t.style.width="".concat(o,"px"),t.style.height="".concat(o,"px"),t.style.fontSize="".concat(r,"px")}),this.shadowRoot.querySelectorAll(".voice-status-title").forEach(function(t){return t.style.fontSize="".concat(i,"px")}),this.shadowRoot.querySelectorAll(".voice-status-subtitle").forEach(function(t){return t.style.fontSize="".concat(a,"px")});var m=this.shadowRoot.querySelector(".voice-transcript");m&&(m.style.minHeight="".concat(c,"px"),m.style.maxHeight="".concat(c,"px"),m.style.height="".concat(c,"px"),m.style.width="min(360px, ".concat(n-40,"px)"),m.style.boxSizing="border-box");var y=this.shadowRoot.querySelector(".transcript-label");y&&(y.style.fontSize="".concat(Math.max(8,i-4),"px"));var b=this.shadowRoot.querySelector(".transcript-text");b&&(b.style.fontSize="".concat(Math.max(10,i-2),"px")),this.shadowRoot.querySelectorAll(".voice-control-btn.secondary").forEach(function(t){t.style.width="".concat(l,"px"),t.style.height="".concat(l,"px");var e=t.querySelector("svg");if(e){var n=.65*l;e.style.setProperty("width","".concat(n,"px"),"important"),e.style.setProperty("height","".concat(n,"px"),"important"),e.style.setProperty("min-width","".concat(n,"px"),"important"),e.style.setProperty("min-height","".concat(n,"px"),"important")}});var w=this.shadowRoot.querySelector(".voice-control-btn.primary");if(w){w.style.width="".concat(u,"px"),w.style.height="".concat(u,"px");var S=w.querySelector("svg");if(S){var x=.7*u;S.style.setProperty("width","".concat(x,"px"),"important"),S.style.setProperty("height","".concat(x,"px"),"important"),S.style.setProperty("min-width","".concat(x,"px"),"important"),S.style.setProperty("min-height","".concat(x,"px"),"important")}}var k=this.shadowRoot.querySelector(".start-call-btn");if(k){var C,P;e<=350?(C=48,P=14):e<=450?(C=52,P=15):e<=550?(C=58,P=17):e<=700?(C=62,P=18):(C=64,P=18),k.style.height="".concat(C,"px"),k.style.fontSize="".concat(P,"px");var T=k.querySelector("svg");if(T){var E=Math.max(22,.5*C);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")}},{key:"startVoiceCall",value:(o=Co(So().m(function t(){var e,n=this;return So().w(function(t){for(;;)switch(t.n){case 0:if(!this.isActive){t.n=1;break}return console.log("⚠️ Voice call already active"),t.a(2);case 1:return console.log("🎤 Starting voice call..."),t.n=2,ao();case 2:if(e=t.v,console.log("📋 Current permission state: ".concat(e)),"denied"!==e){t.n=3;break}return console.log("🚫 Permission is denied, showing blocked modal..."),io(),yo(function(){console.log("Blocked modal closed")}),t.a(2);case 3:if("prompt"!==e&&"unknown"!==e){t.n=4;break}return console.log("📋 Permission is in prompt state, showing pre-prompt modal..."),t.a(2,new Promise(function(t){mo(Co(So().m(function e(){return So().w(function(e){for(;;)switch(e.n){case 0:return console.log("✅ Pre-prompt accepted, proceeding with voice call..."),e.n=1,n.proceedWithVoiceCall();case 1:t();case 2:return e.a(2)}},e)})),function(){console.log("❌ Pre-prompt cancelled"),t()})}));case 4:return t.n=5,this.proceedWithVoiceCall();case 5:return t.a(2)}},t,this)})),function(){return o.apply(this,arguments)})},{key:"proceedWithVoiceCall",value:(n=Co(So().m(function t(){var e,n,o,r,i,a,s,c,l,u,d,p=this;return So().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,e=this.shadowRoot.getElementById("voiceIdleState"),n=this.shadowRoot.getElementById("voiceActiveState"),o=this.shadowRoot.getElementById("voiceInterface"),e&&(e.style.display="none"),n&&(n.style.display="flex"),setTimeout(function(){return p.adjustSizesForContainer()},50),o&&(o.scrollTop=0),r=io(),t.n=1,ao();case 1:if(i=t.v,!r.isMobile||"granted"===i){t.n=5;break}return console.log("📱 Mobile device detected - requesting mic permission before connecting..."),console.log("📋 Current permission state: ".concat(i)),t.p=2,a=this.config.outputSampleRate||44100,t.n=3,navigator.mediaDevices.getUserMedia({audio:{sampleRate:a,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 3:t.v.getTracks().forEach(function(t){return t.stop()}),console.log("✅ Microphone permission granted on mobile - proceeding with connection"),t.n=5;break;case 4:return t.p=4,t.v,console.log("🚫 Permission denied on mobile, showing blocked modal..."),yo(function(){p.resetUIState()}),t.a(2);case 5:return t.n=6,this.getSignedUrl();case 6:if(s=t.v,console.log("🔗 Got signed URL:",s),!this.sdk||!this.sdk.isConnected){t.n=10;break}return console.log("🔄 SDK already connected, disconnecting for clean retry..."),t.p=7,this.sdk.disconnect(),t.n=8,new Promise(function(t){return setTimeout(t,100)});case 8:t.n=10;break;case 9:t.p=9,u=t.v,console.warn("Warning: Error disconnecting existing connection:",u);case 10:return t.n=11,this.sdk.connect(s);case 11:c=t.v,console.log("✅ Connected to WebSocket, connected:",c),l=0;case 12:if(!(l<50)){t.n=15;break}if(!this.sdk.isConnected){t.n=13;break}if(!(this.sdk.voiceSDK&&this.sdk.voiceSDK.isConnected&&this.sdk.voiceSDK.websocket&&this.sdk.voiceSDK.websocket.readyState===WebSocket.OPEN)){t.n=13;break}return t.a(3,15);case 13:return t.n=14,new Promise(function(t){return setTimeout(t,100)});case 14:l++,t.n=12;break;case 15:if(!(this.sdk.isConnected&&this.sdk.voiceSDK&&this.sdk.voiceSDK.websocket&&this.sdk.voiceSDK.websocket.readyState===WebSocket.OPEN)){t.n=17;break}return console.log("✅ WebSocket ready, starting listening..."),t.n=16,this.sdk.startListening();case 16:console.log("🎤 Started listening"),this.isActive=!0,this.callStartTime=Date.now(),this.callTimerInterval=setInterval(function(){var t=Date.now()-p.callStartTime,e=Math.floor(t/6e4),n=Math.floor(t%6e4/1e3),o=p.shadowRoot.getElementById("voiceTimer");o&&(o.textContent="".concat(e.toString().padStart(2,"0"),":").concat(n.toString().padStart(2,"0")))},1e3),t.n=19;break;case 17:return console.warn("⚠️ Connection not fully ready, but trying to start listening anyway..."),t.n=18,this.sdk.startListening();case 18:console.log("🎤 Started listening"),this.isActive=!0,this.callStartTime=Date.now(),this.callTimerInterval=setInterval(function(){var t=Date.now()-p.callStartTime,e=Math.floor(t/6e4),n=Math.floor(t%6e4/1e3),o=p.shadowRoot.getElementById("voiceTimer");o&&(o.textContent="".concat(e.toString().padStart(2,"0"),":").concat(n.toString().padStart(2,"0")))},1e3);case 19:console.log("✅ Voice call started successfully"),t.n=21;break;case 20:if(t.p=20,d=t.v,console.error("❌ Error starting voice call:",d),this.isActive=!1,this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null),this.sdk&&this.sdk.isConnected)try{this.sdk.disconnect()}catch(t){console.warn("Error disconnecting SDK on error:",t)}"NotAllowedError"===d.name||"PermissionDeniedError"===d.name?(io(),yo(function(){p.resetUIState()})):"NotFoundError"===d.name||"DevicesNotFoundError"===d.name?bo(function(){p.resetUIState()}):(this.showError(d.message||d),this.resetUIState());case 21:return t.a(2)}},t,this,[[7,9],[2,4],[0,20]])})),function(){return n.apply(this,arguments)})},{key:"resetUIState",value:function(){var t=this.shadowRoot.getElementById("voiceIdleState"),e=this.shadowRoot.getElementById("voiceActiveState");t&&(t.style.display="flex"),e&&(e.style.display="none")}},{key:"endVoiceCall",value:function(){var t=this;console.log("🔴 Ending voice call..."),this.sdk&&this.isActive&&(this.sdk.stopListening(),this.sdk.disconnect(),this.isActive=!1),this.audioStream&&(this.audioStream.getTracks().forEach(function(t){return t.stop()}),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null);var e=this.shadowRoot.getElementById("voiceIdleState"),n=this.shadowRoot.getElementById("voiceActiveState");e&&(e.style.display="flex"),n&&(n.style.display="none"),setTimeout(function(){return t.adjustSizesForContainer()},50);var o=this.shadowRoot.getElementById("transcriptText");o&&(o.textContent=this.t("transcriptWillAppear"),o.classList.add("empty"));var r=this.shadowRoot.getElementById("voiceAvatarActive");r&&r.classList.remove("speaking"),console.log("✅ Voice call ended")}},{key:"updateTranscript",value:function(t){console.log("📝 [VOICE INTERFACE] updateTranscript called with text:",t);var e=this.shadowRoot.getElementById("transcriptText");e?(console.log("📝 [VOICE INTERFACE] Found transcript element, updating text"),e.textContent=t,e.classList.remove("empty")):console.warn("📝 [VOICE INTERFACE] ⚠️ transcriptText element not found!")}},{key:"showError",value:function(t){var e=this.shadowRoot.getElementById("transcriptText");e&&(e.textContent="".concat(this.t("error"),": ").concat(t),e.classList.remove("empty"))}},{key:"showDomainError",value:function(){var t=this.shadowRoot.getElementById("transcriptText");if(t){var e=this.t("domainNotValidated"),n=this.t("domainErrorMessage");t.innerHTML='<div style="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;">'.concat(e,'</div><div style="font-size: 14px; color: #991B1B; line-height: 1.5;">').concat(n,"</div>"),t.classList.remove("empty")}}},{key:"toggleMute",value:function(){if(this.sdk&&this.isActive){var t=null;if(this.sdk.voiceSDK&&this.sdk.voiceSDK.audioRecorder&&this.sdk.voiceSDK.audioRecorder.mediaStream&&(t=this.sdk.voiceSDK.audioRecorder.mediaStream.getAudioTracks()[0]),!t&&this.audioStream&&(t=this.audioStream.getAudioTracks()[0]),t){t.enabled=!t.enabled;var e=this.shadowRoot.getElementById("muteBtn"),n=null==e?void 0:e.querySelector(".mute-icon"),o=null==e?void 0:e.querySelector(".mute-cross");e&&n&&o&&(t.enabled?(n.style.stroke="",o.style.display="none",e.classList.remove("muted")):(n.style.stroke="#9ca3af",o.style.display="block",e.classList.add("muted"))),console.log(t.enabled?"🔊 Unmuted":"🔇 Muted")}else console.warn("⚠️ No audio track available for mute toggle")}}},{key:"toggleSpeaker",value:function(){console.log("🔊 Speaker toggle")}},{key:"destroy",value:function(){this.isActive&&this.endVoiceCall(),this.audioStream&&(this.audioStream.getTracks().forEach(function(t){return t.stop()}),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null),this.sdk&&(this.sdk.disconnect(),this.sdk=null)}}],e&&Po(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o,r}();function Oo(t){return Oo="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Oo(t)}function Ao(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Io(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Io(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Io(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Io(d,"constructor",l),Io(l,"constructor",c),c.displayName="GeneratorFunction",Io(l,r,"GeneratorFunction"),Io(d),Io(d,r,"Generator"),Io(d,o,function(){return this}),Io(d,"toString",function(){return"[object Generator]"}),(Ao=function(){return{w:i,m:p}})()}function Io(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Io=function(t,e,n,o){function i(e,n){Io(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Io(t,e,n,o)}function Ro(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function jo(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){Ro(i,o,r,a,s,"next",t)}function s(t){Ro(i,o,r,a,s,"throw",t)}a(void 0)})}}function Do(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Fo(o.key),o)}}function Fo(t){var e=function(t){if("object"!=Oo(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Oo(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Oo(e)?e:e+""}var _o=function(){return t=function t(e,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.config=e,this.sdk=n,this.streamingEl=null,this.hasStartedStreaming=!1,this.isActive=!1,this.shadowRoot=e.shadowRoot||document,this.eventHandlers={autoResize:null,keydown:null},this.eventHandlersSetup=!1},e=[{key:"t",value:function(t){var e,n,o=this.config.language||"en";return((null===(e=this.config.translations)||void 0===e?void 0:e[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[t]||t}},{key:"generateHTML",value:function(){var t,e,n,o,r,i,a,s,c,l=this.config.inputPlaceholder||(null===(t=this.config.panel)||void 0===t?void 0:t.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!==(e=this.config.sendButtonHint)&&void 0!==e&&e.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===(r=this.config.panel)||void 0===r||null===(r=r.sendButtonHint)||void 0===r?void 0:r.color)||"#6B7280","; font-size: ").concat((null===(i=this.config.sendButtonHint)||void 0===i?void 0:i.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>")}},{key:"generateCSS",value:function(){var t,e,n,o,r,i,a,s,c,l,u,d,p,f=this.config.messages,h=(this.config.panel,this.config.animation,this.config.sendButtonColor||(null===(t=this.config.panel)||void 0===t?void 0:t.sendButtonColor)||"#7C3AED"),g=this.config.sendButtonHoverColor||(null===(e=this.config.panel)||void 0===e?void 0:e.sendButtonHoverColor)||"#6D28D9",v=this.config.sendButtonTextColor||(null===(n=this.config.panel)||void 0===n?void 0:n.sendButtonTextColor)||"#FFFFFF",m=(this.config.inputPlaceholder||null===(o=this.config.panel)||void 0===o||o.inputPlaceholder,this.config.inputBorderColor||(null===(r=this.config.panel)||void 0===r?void 0:r.inputBorderColor)||"#E5E7EB"),y=this.config.inputFocusColor||(null===(i=this.config.panel)||void 0===i?void 0:i.inputFocusColor)||"#7C3AED",b=this.config.inputBackgroundColor||(null===(a=this.config.panel)||void 0===a?void 0:a.inputBackgroundColor)||"#FFFFFF",w=this.config.inputTextColor||(null===(s=this.config.panel)||void 0===s?void 0:s.inputTextColor)||"#1F2937",S=this.config.inputFontSize||(null===(c=this.config.panel)||void 0===c?void 0:c.inputFontSize)||"14px",x=this.config.inputBorderRadius||(null===(l=this.config.panel)||void 0===l?void 0:l.inputBorderRadius)||20,k=this.config.inputPadding||(null===(u=this.config.panel)||void 0===u?void 0:u.inputPadding)||"6px 14px",C=!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(C,"; \n flex: 1; \n flex-direction: column; \n min-height: 0; \n overflow: hidden; \n }\n .text-interface.active { display: flex").concat(C,"; }\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(f.borderRadius,"px; \n max-width: 80%; \n font-size: ").concat(f.fontSize,"; \n color: ").concat(f.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(f.userBackgroundColor,"; \n align-self: ").concat("rtl"===this.config.direction?"flex-start":"flex-end","; \n }\n .message.agent { \n background: ").concat(f.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(f.systemBackgroundColor,";\n align-self: flex-start;\n }\n .message.error {\n background: ").concat(f.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(k,";\n border: 1px solid ").concat(m,";\n border-radius: ").concat(x,"px;\n font-size: ").concat(S,";\n font-family: inherit;\n line-height: 1.3;\n resize: none;\n overflow-y: auto;\n background: ").concat(b,";\n color: ").concat(w,";\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"===b?"#FFFFFF":b,";\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(h,";\n color: ").concat(v,";\n font-size: ").concat(this.config.sendButtonFontSize||(null===(d=this.config.panel)||void 0===d?void 0:d.sendButtonFontSize)||"18px",";\n font-weight: ").concat(this.config.sendButtonFontWeight||(null===(p=this.config.panel)||void 0===p?void 0:p.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(g,";\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(f.errorBackgroundColor,";\n border-radius: ").concat(f.borderRadius,"px;\n color: #991B1B;\n font-size: ").concat(f.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 ")}},{key:"setupEventHandlers",value:function(){var t=this,e=this.shadowRoot.getElementById("sendButton"),n=this.shadowRoot.getElementById("messageInput"),o=this.shadowRoot.getElementById("newChatBtn");if(e&&(e.onclick=function(){return t.sendMessage()}),o&&(o.onclick=function(){return t.startNewChat()}),this.updateInputAttributes(),n){n.style.height="32px",n.style.overflow="hidden";var r=function(){n.style.height="auto";var t=Math.min(n.scrollHeight,120);n.style.height=t+"px",n.style.overflowY=t>=120?"auto":"hidden",t>=120&&setTimeout(function(){n.scrollTop=n.scrollHeight},0)};n.addEventListener("input",r),n.addEventListener("keydown",function(e){"Enter"!==e.key||e.shiftKey?"Enter"===e.key&&e.shiftKey&&setTimeout(r,0):(e.preventDefault(),t.sendMessage())})}}},{key:"startNewChat",value:function(){try{localStorage.removeItem("ttp_text_chat_conversation_id")}catch(t){}this.sdk&&(this.sdk.config.conversationId=null);var t=this.shadowRoot.getElementById("messagesContainer");t&&(t.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 e=this.shadowRoot.getElementById("messageInput");e&&e.focus()}},{key:"updateInputAttributes",value:function(){var t=this.shadowRoot.getElementById("messageInput");if(t){var e,n=this.config.inputPlaceholder||(null===(e=this.config.panel)||void 0===e?void 0:e.inputPlaceholder)||this.t("typeMessage")||"Type your message...";t.placeholder=n,t.dir=this.config.direction||"ltr",t.style.textAlign="rtl"===this.config.direction?"right":"left"}}},{key:"show",value:function(){var t=this,e=this.shadowRoot.getElementById("textInterface");e&&e.classList.add("active"),setTimeout(function(){var e=t.shadowRoot.getElementById("messageInput");e&&e.focus()},50)}},{key:"hide",value:function(){var t=this.shadowRoot.getElementById("textInterface");t&&t.classList.remove("active")}},{key:"startChat",value:(o=jo(Ao().m(function t(){return Ao().w(function(t){for(;;)switch(t.n){case 0:this.isActive=!0,this.updateSendButtonState();case 1:return t.a(2)}},t,this)})),function(){return o.apply(this,arguments)})},{key:"sendMessage",value:(n=jo(Ao().m(function t(){var e,n,o;return Ao().w(function(t){for(;;)switch(t.p=t.n){case 0:if(e=this.shadowRoot.getElementById("messageInput"),n=e.value.trim()){t.n=1;break}return t.a(2);case 1:if(this.isActive){t.n=2;break}return t.n=2,this.startChat();case 2:return this.addMessage("user",n),e.value="",e.style.height="32px",e.style.overflow="hidden",t.p=3,this.beginStreaming(),t.n=4,this.sdk.sendMessage(n);case 4:t.n=6;break;case 5:t.p=5,o=t.v,console.error("❌ Failed to send message:",o),o&&("DOMAIN_NOT_WHITELISTED"===o.message||o.message&&o.message.includes("Domain not whitelisted"))||this.showError(o),this.stopStreamingState();case 6:return t.a(2)}},t,this,[[3,5]])})),function(){return n.apply(this,arguments)})},{key:"updateSendButtonState",value:function(){var t=this.shadowRoot.getElementById("sendButton");t&&(t.disabled=!this.isActive)}},{key:"addMessage",value:function(t,e){var n=this.shadowRoot.getElementById("messagesContainer");if(n){var o=n.querySelector(".empty-state");o&&o.remove();var r=document.createElement("div"),i="rtl"===this.config.direction?"user"===t?"edge-left":"edge-right":"user"===t?"edge-right":"edge-left";r.className="message ".concat(t," ").concat(i);var a=document.createElement("div");a.className="message-avatar ".concat(t),a.textContent="user"===t?"👤":"🤖";var s=document.createElement("div");s.className="message-bubble",s.textContent=e,r.appendChild(a),r.appendChild(s),n.appendChild(r),n.scrollTop=n.scrollHeight}}},{key:"beginStreaming",value:function(){var t=this.shadowRoot.getElementById("messagesContainer");if(t){this.stopStreamingState();var e=document.createElement("div"),n="rtl"===this.config.direction?"edge-right":"edge-left";e.className="message agent ".concat(n),e.id="agent-streaming";var o=document.createElement("div");o.className="message-avatar agent",o.textContent="🤖";var r=document.createElement("div");r.className="message-bubble",r.innerHTML='<span class="typing-indicator"><span class="typing-dot"></span><span class="typing-dot"></span><span class="typing-dot"></span></span>',e.appendChild(o),e.appendChild(r),t.appendChild(e),this.streamingEl=r,this.hasStartedStreaming=!1,t.scrollTop=t.scrollHeight}}},{key:"appendStreamingChunk",value:function(t){if(this.streamingEl){this.hasStartedStreaming||(this.streamingEl.textContent="",this.hasStartedStreaming=!0),this.streamingEl.textContent+=t;var e=this.shadowRoot.getElementById("messagesContainer");e&&(e.scrollTop=e.scrollHeight)}}},{key:"finalizeStreaming",value:function(t){if(this.streamingEl){this.streamingEl.textContent=t||this.streamingEl.textContent;var e=this.shadowRoot.getElementById("agent-streaming");e&&(e.id=""),this.streamingEl=null}this.updateSendButtonState()}},{key:"stopStreamingState",value:function(){var t=this.shadowRoot.getElementById("agent-streaming");t&&t.remove(),this.streamingEl=null,this.hasStartedStreaming=!1}},{key:"showError",value:function(t){var e=this.shadowRoot.getElementById("messagesContainer");if(e){if(t&&("DOMAIN_NOT_WHITELISTED"===t.message||"string"==typeof t&&t.includes("DOMAIN_NOT_WHITELISTED")||t.message&&t.message.includes("Domain not whitelisted")||"string"==typeof t&&t.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 r=document.createElement("div");r.style.cssText="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;",r.textContent=this.t("domainNotValidated");var i=document.createElement("div");i.style.cssText="font-size: 14px; color: #991B1B; line-height: 1.5;",i.textContent=this.t("domainErrorMessage"),o.appendChild(r),o.appendChild(i),e.appendChild(o)}else{var a=document.createElement("div");a.className="error-message",a.textContent="string"==typeof t?t:(null==t?void 0:t.message)||t,e.appendChild(a)}e.scrollTop=e.scrollHeight}}},{key:"setActive",value:function(t){this.isActive=t,this.updateSendButtonState()}}],e&&Do(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();const Bo={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 Mo(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Uo(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Uo(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Uo(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Uo(d,"constructor",l),Uo(l,"constructor",c),c.displayName="GeneratorFunction",Uo(l,r,"GeneratorFunction"),Uo(d),Uo(d,r,"Generator"),Uo(d,o,function(){return this}),Uo(d,"toString",function(){return"[object Generator]"}),(Mo=function(){return{w:i,m:p}})()}function Uo(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Uo=function(t,e,n,o){function i(e,n){Uo(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Uo(t,e,n,o)}function No(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function zo(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){No(i,o,r,a,s,"next",t)}function s(t){No(i,o,r,a,s,"throw",t)}a(void 0)})}}function Ho(t){return Ho="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ho(t)}function Lo(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function Vo(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?Lo(Object(n),!0).forEach(function(e){Ko(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Lo(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function Ko(t,e,n){return(e=Go(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Wo(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Go(o.key),o)}}function Go(t){var e=function(t){if("object"!=Ho(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Ho(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Ho(e)?e:e+""}var qo=function(){return t=function t(){var e,n,o,r,i,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.config=this.mergeWithDefaults(s),this.sdk=new Sn(this.config),this.isOpen=!1,this.isActive=!1,this.translations=Bo,this.currentView="landing",this.shadowRoot=null,this.container=null,this.config.useShadowDOM?(this.createShadowHost(),this.container=this.shadowRoot):(this.createRegularContainer(),this.container=this.regularContainer,this.shadowRoot=document);var c=Vo(Vo(Vo({},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===(n=this.config.voice)||void 0===n?void 0:n.outputContainer)||"raw",outputEncoding:(null===(o=this.config.voice)||void 0===o?void 0:o.outputEncoding)||"pcm",outputSampleRate:(null===(r=this.config.voice)||void 0===r?void 0:r.outputSampleRate)||44100,outputChannels:(null===(i=this.config.voice)||void 0===i?void 0:i.outputChannels)||1,outputBitDepth:(null===(a=this.config.voice)||void 0===a?void 0:a.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 Eo(c);var l=Vo(Vo(Vo({},this.config),this.config.text),{},{translations:this.translations,shadowRoot:this.shadowRoot});if(this.textInterface=new _o(l,this.sdk),this.createWidget(),this.setupEventHandlers(),this.config.behavior.startOpen||this.config.behavior.autoOpen){var u,d=null===(u=this.shadowRoot)||void 0===u?void 0:u.getElementById("text-chat-panel");d&&(this.isOpen=!0,d.classList.add("open"))}},e=[{key:"mergeWithDefaults",value:function(t){var e,n,o,r,i,a,s,c,l,u,d,p,f,h,g,v,m,y,b,w,S,x,k,C,P,T,E,O,A,I,R,j,D,F,_,B,M,U,N,z,H,L,V,K,W,G,q,Q,Y,$,J,X,Z,tt,et,nt,ot,rt,it,at,st,ct,lt,ut,dt,pt,ft,ht,gt,vt,mt,yt,bt,wt,St,xt,kt,Ct,Pt,Tt,Et,Ot,At,It,Rt,jt,Dt,Ft,_t,Bt,Mt,Ut,Nt,zt,Ht,Lt,Vt,Kt,Wt,Gt,qt,Qt,Yt,$t,Jt,Xt,Zt,te,ee,ne,oe,re,ie,ae,se,ce,le,ue,de,pe,fe,he,ge,ve,me,ye,be,we,Se,xe,ke,Ce,Pe,Te,Ee,Oe,Ae,Ie,Re,je,De=t.position||"bottom-right";if("string"==typeof De){var Fe=De.split("-");De={vertical:Fe[0]||"bottom",horizontal:Fe[1]||"right",offset:t.positionOffset||{x:20,y:20}}}var _e=t.primaryColor||(null===(e=t.button)||void 0===e?void 0:e.primaryColor)||(null===(n=t.button)||void 0===n?void 0:n.backgroundColor)||"#FFFFFF",Be=(null===(o=t.header)||void 0===o?void 0:o.backgroundColor)||"#7C3AED";return Vo({agentId:t.agentId,appId:t.appId,signedUrl:t.signedUrl,agentSettingsOverride:t.agentSettingsOverride,demo:!1!==t.demo,direction:t.direction||"ltr",language:t.language||"en",icon:Vo({type:(null===(r=t.icon)||void 0===r?void 0:r.type)||"custom",customImage:(null===(i=t.icon)||void 0===i?void 0:i.customImage)||"https://talktopc.com/logo192.png",emoji:(null===(a=t.icon)||void 0===a?void 0:a.emoji)||"🎤",text:(null===(s=t.icon)||void 0===s?void 0:s.text)||"AI",size:(null===(c=t.icon)||void 0===c?void 0:c.size)||"medium",backgroundColor:(null===(l=t.icon)||void 0===l?void 0:l.backgroundColor)||"#FFFFFF"},t.icon),position:Vo({vertical:De.vertical||"bottom",horizontal:De.horizontal||"right",offset:De.offset||{x:20,y:20}},"object"===Ho(t.position)?t.position:{}),button:Vo({size:(null===(u=t.button)||void 0===u?void 0:u.size)||"medium",shape:(null===(d=t.button)||void 0===d?void 0:d.shape)||"circle",backgroundColor:(null===(p=t.button)||void 0===p?void 0:p.backgroundColor)||(null===(f=t.icon)||void 0===f?void 0:f.backgroundColor)||"#FFFFFF",hoverColor:(null===(h=t.button)||void 0===h?void 0:h.hoverColor)||"#D3D3D3",shadow:!1!==(null===(g=t.button)||void 0===g?void 0:g.shadow),shadowColor:(null===(v=t.button)||void 0===v?void 0:v.shadowColor)||"rgba(0,0,0,0.15)",primaryColor:(null===(m=t.button)||void 0===m?void 0:m.backgroundColor)||(null===(y=t.icon)||void 0===y?void 0:y.backgroundColor)||"#FFFFFF"},t.button),panel:Vo({width:(null===(b=t.panel)||void 0===b?void 0:b.width)||350,height:(null===(w=t.panel)||void 0===w?void 0:w.height)||500,borderRadius:(null===(S=t.panel)||void 0===S?void 0:S.borderRadius)||12,backgroundColor:(null===(x=t.panel)||void 0===x?void 0:x.backgroundColor)||"#FFFFFF",backdropFilter:(null===(k=t.panel)||void 0===k?void 0:k.backdropFilter)||null,border:(null===(C=t.panel)||void 0===C?void 0:C.border)||"1px solid #E5E7EB"},t.panel),voice:Vo({micButtonColor:(null===(P=t.voice)||void 0===P?void 0:P.micButtonColor)||(null===(T=t.panel)||void 0===T?void 0:T.micButtonColor)||_e,micButtonActiveColor:(null===(E=t.voice)||void 0===E?void 0:E.micButtonActiveColor)||(null===(O=t.panel)||void 0===O?void 0:O.micButtonActiveColor)||"#EF4444",micButtonHint:Vo(Vo({text:(null===(A=t.voice)||void 0===A||null===(A=A.micButtonHint)||void 0===A?void 0:A.text)||(null===(I=t.panel)||void 0===I||null===(I=I.micButtonHint)||void 0===I?void 0:I.text)||"Click the button to start voice conversation",color:(null===(R=t.voice)||void 0===R||null===(R=R.micButtonHint)||void 0===R?void 0:R.color)||(null===(j=t.panel)||void 0===j||null===(j=j.micButtonHint)||void 0===j?void 0:j.color)||"#6B7280",fontSize:(null===(D=t.voice)||void 0===D||null===(D=D.micButtonHint)||void 0===D?void 0:D.fontSize)||(null===(F=t.panel)||void 0===F||null===(F=F.micButtonHint)||void 0===F?void 0:F.fontSize)||"12px"},null===(_=t.voice)||void 0===_?void 0:_.micButtonHint),null===(B=t.panel)||void 0===B?void 0:B.micButtonHint),avatarBackgroundColor:(null===(M=t.voice)||void 0===M?void 0:M.avatarBackgroundColor)||"#667eea",avatarActiveBackgroundColor:(null===(U=t.voice)||void 0===U?void 0:U.avatarActiveBackgroundColor)||"#667eea",statusTitleColor:(null===(N=t.voice)||void 0===N?void 0:N.statusTitleColor)||"#1e293b",statusSubtitleColor:(null===(z=t.voice)||void 0===z?void 0:z.statusSubtitleColor)||"#64748b",startCallButtonColor:(null===(H=t.voice)||void 0===H?void 0:H.startCallButtonColor)||"#667eea",startCallButtonTextColor:(null===(L=t.voice)||void 0===L?void 0:L.startCallButtonTextColor)||"#FFFFFF",startCallTitle:(null===(V=t.voice)||void 0===V?void 0:V.startCallTitle)||null,startCallSubtitle:(null===(K=t.voice)||void 0===K?void 0:K.startCallSubtitle)||null,startCallButtonText:(null===(W=t.voice)||void 0===W?void 0:W.startCallButtonText)||null,transcriptBackgroundColor:(null===(G=t.voice)||void 0===G?void 0:G.transcriptBackgroundColor)||"#FFFFFF",transcriptTextColor:(null===(q=t.voice)||void 0===q?void 0:q.transcriptTextColor)||"#1e293b",transcriptLabelColor:(null===(Q=t.voice)||void 0===Q?void 0:Q.transcriptLabelColor)||"#94a3b8",controlButtonColor:(null===(Y=t.voice)||void 0===Y?void 0:Y.controlButtonColor)||"#FFFFFF",controlButtonSecondaryColor:(null===($=t.voice)||void 0===$?void 0:$.controlButtonSecondaryColor)||"#64748b",endCallButtonColor:(null===(J=t.voice)||void 0===J?void 0:J.endCallButtonColor)||"#ef4444",language:(null===(X=t.voice)||void 0===X?void 0:X.language)||t.language||"en"},t.voice),text:Vo({sendButtonColor:(null===(Z=t.text)||void 0===Z?void 0:Z.sendButtonColor)||(null===(tt=t.panel)||void 0===tt?void 0:tt.sendButtonColor)||"#7C3AED",sendButtonHoverColor:(null===(et=t.text)||void 0===et?void 0:et.sendButtonHoverColor)||(null===(nt=t.panel)||void 0===nt?void 0:nt.sendButtonHoverColor)||"#6D28D9",sendButtonActiveColor:(null===(ot=t.text)||void 0===ot?void 0:ot.sendButtonActiveColor)||(null===(rt=t.panel)||void 0===rt?void 0:rt.sendButtonActiveColor)||"#6D28D9",sendButtonText:(null===(it=t.text)||void 0===it?void 0:it.sendButtonText)||(null===(at=t.panel)||void 0===at?void 0:at.sendButtonText)||"➤",sendButtonTextColor:(null===(st=t.text)||void 0===st?void 0:st.sendButtonTextColor)||(null===(ct=t.panel)||void 0===ct?void 0:ct.sendButtonTextColor)||"#FFFFFF",sendButtonFontSize:(null===(lt=t.text)||void 0===lt?void 0:lt.sendButtonFontSize)||(null===(ut=t.panel)||void 0===ut?void 0:ut.sendButtonFontSize)||"18px",sendButtonFontWeight:(null===(dt=t.text)||void 0===dt?void 0:dt.sendButtonFontWeight)||(null===(pt=t.panel)||void 0===pt?void 0:pt.sendButtonFontWeight)||"500",sendButtonHint:Vo(Vo({text:(null===(ft=t.text)||void 0===ft||null===(ft=ft.sendButtonHint)||void 0===ft?void 0:ft.text)||(null===(ht=t.panel)||void 0===ht||null===(ht=ht.sendButtonHint)||void 0===ht?void 0:ht.text)||"",color:(null===(gt=t.text)||void 0===gt||null===(gt=gt.sendButtonHint)||void 0===gt?void 0:gt.color)||(null===(vt=t.panel)||void 0===vt||null===(vt=vt.sendButtonHint)||void 0===vt?void 0:vt.color)||"#6B7280",fontSize:(null===(mt=t.text)||void 0===mt||null===(mt=mt.sendButtonHint)||void 0===mt?void 0:mt.fontSize)||(null===(yt=t.panel)||void 0===yt||null===(yt=yt.sendButtonHint)||void 0===yt?void 0:yt.fontSize)||"12px"},null===(bt=t.text)||void 0===bt?void 0:bt.sendButtonHint),null===(wt=t.panel)||void 0===wt?void 0:wt.sendButtonHint),inputPlaceholder:(null===(St=t.text)||void 0===St?void 0:St.inputPlaceholder)||(null===(xt=t.panel)||void 0===xt?void 0:xt.inputPlaceholder)||"Type your message...",inputBorderColor:(null===(kt=t.text)||void 0===kt?void 0:kt.inputBorderColor)||(null===(Ct=t.panel)||void 0===Ct?void 0:Ct.inputBorderColor)||"#E5E7EB",inputFocusColor:(null===(Pt=t.text)||void 0===Pt?void 0:Pt.inputFocusColor)||(null===(Tt=t.panel)||void 0===Tt?void 0:Tt.inputFocusColor)||"#7C3AED",inputBackgroundColor:(null===(Et=t.text)||void 0===Et?void 0:Et.inputBackgroundColor)||(null===(Ot=t.panel)||void 0===Ot?void 0:Ot.inputBackgroundColor)||"#FFFFFF",inputTextColor:(null===(At=t.text)||void 0===At?void 0:At.inputTextColor)||(null===(It=t.panel)||void 0===It?void 0:It.inputTextColor)||"#1F2937",inputFontSize:(null===(Rt=t.text)||void 0===Rt?void 0:Rt.inputFontSize)||(null===(jt=t.panel)||void 0===jt?void 0:jt.inputFontSize)||"14px",inputBorderRadius:(null===(Dt=t.text)||void 0===Dt?void 0:Dt.inputBorderRadius)||(null===(Ft=t.panel)||void 0===Ft?void 0:Ft.inputBorderRadius)||20,inputPadding:(null===(_t=t.text)||void 0===_t?void 0:_t.inputPadding)||(null===(Bt=t.panel)||void 0===Bt?void 0:Bt.inputPadding)||"6px 14px"},t.text),landing:Vo({backgroundColor:(null===(Mt=t.landing)||void 0===Mt?void 0:Mt.backgroundColor)||"linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%)",logo:(null===(Ut=t.landing)||void 0===Ut?void 0:Ut.logo)||"🤖",title:(null===(Nt=t.landing)||void 0===Nt?void 0:Nt.title)||null,titleColor:(null===(zt=t.landing)||void 0===zt?void 0:zt.titleColor)||"#1e293b",modeCardBackgroundColor:(null===(Ht=t.landing)||void 0===Ht?void 0:Ht.modeCardBackgroundColor)||"#FFFFFF",modeCardBorderColor:(null===(Lt=t.landing)||void 0===Lt?void 0:Lt.modeCardBorderColor)||"#E2E8F0",modeCardHoverBorderColor:(null===(Vt=t.landing)||void 0===Vt?void 0:Vt.modeCardHoverBorderColor)||Be,modeCardIconBackgroundColor:(null===(Kt=t.landing)||void 0===Kt?void 0:Kt.modeCardIconBackgroundColor)||Be,modeCardTitleColor:(null===(Wt=t.landing)||void 0===Wt?void 0:Wt.modeCardTitleColor)||"#111827",voiceCardIcon:(null===(Gt=t.landing)||void 0===Gt?void 0:Gt.voiceCardIcon)||"🎤",textCardIcon:(null===(qt=t.landing)||void 0===qt?void 0:qt.textCardIcon)||"💬",voiceCardTitle:(null===(Qt=t.landing)||void 0===Qt?void 0:Qt.voiceCardTitle)||null,textCardTitle:(null===(Yt=t.landing)||void 0===Yt?void 0:Yt.textCardTitle)||null},t.landing),header:Vo({title:(null===($t=t.header)||void 0===$t?void 0:$t.title)||"Chat Assistant",showTitle:!1!==(null===(Jt=t.header)||void 0===Jt?void 0:Jt.showTitle),backgroundColor:(null===(Xt=t.header)||void 0===Xt?void 0:Xt.backgroundColor)||"#7C3AED",textColor:(null===(Zt=t.header)||void 0===Zt?void 0:Zt.textColor)||"#FFFFFF",showCloseButton:!1!==(null===(te=t.header)||void 0===te?void 0:te.showCloseButton)},t.header),footer:Vo({show:!1!==(null===(ee=t.footer)||void 0===ee?void 0:ee.show),backgroundColor:(null===(ne=t.footer)||void 0===ne?void 0:ne.backgroundColor)||"#f9fafb",textColor:(null===(oe=t.footer)||void 0===oe?void 0:oe.textColor)||"#9ca3af",hoverColor:(null===(re=t.footer)||void 0===re?void 0:re.hoverColor)||"#7C3AED"},t.footer),tooltips:Vo({newChat:(null===(ie=t.tooltips)||void 0===ie?void 0:ie.newChat)||null,back:(null===(ae=t.tooltips)||void 0===ae?void 0:ae.back)||null,close:(null===(se=t.tooltips)||void 0===se?void 0:se.close)||null,mute:(null===(ce=t.tooltips)||void 0===ce?void 0:ce.mute)||null,speaker:(null===(le=t.tooltips)||void 0===le?void 0:le.speaker)||null,endCall:(null===(ue=t.tooltips)||void 0===ue?void 0:ue.endCall)||null},t.tooltips),messages:Vo({userBackgroundColor:(null===(de=t.messages)||void 0===de?void 0:de.userBackgroundColor)||"#E5E7EB",agentBackgroundColor:(null===(pe=t.messages)||void 0===pe?void 0:pe.agentBackgroundColor)||"#F3F4F6",systemBackgroundColor:(null===(fe=t.messages)||void 0===fe?void 0:fe.systemBackgroundColor)||"#DCFCE7",errorBackgroundColor:(null===(he=t.messages)||void 0===he?void 0:he.errorBackgroundColor)||"#FEE2E2",textColor:(null===(ge=t.messages)||void 0===ge?void 0:ge.textColor)||"#1F2937",fontSize:(null===(ve=t.messages)||void 0===ve?void 0:ve.fontSize)||"14px",borderRadius:(null===(me=t.messages)||void 0===me?void 0:me.borderRadius)||8},t.messages),animation:Vo({enableHover:!1!==(null===(ye=t.animation)||void 0===ye?void 0:ye.enableHover),enablePulse:!1!==(null===(be=t.animation)||void 0===be?void 0:be.enablePulse),enableSlide:!1!==(null===(we=t.animation)||void 0===we?void 0:we.enableSlide),duration:(null===(Se=t.animation)||void 0===Se?void 0:Se.duration)||.3},t.animation),behavior:Vo({autoOpen:(null===(xe=t.behavior)||void 0===xe?void 0:xe.autoOpen)||!1,startOpen:(null===(ke=t.behavior)||void 0===ke?void 0:ke.startOpen)||!1,hidden:(null===(Ce=t.behavior)||void 0===Ce?void 0:Ce.hidden)||!1,autoConnect:(null===(Pe=t.behavior)||void 0===Pe?void 0:Pe.autoConnect)||!1,showWelcomeMessage:!1!==(null===(Te=t.behavior)||void 0===Te?void 0:Te.showWelcomeMessage),welcomeMessage:(null===(Ee=t.behavior)||void 0===Ee?void 0:Ee.welcomeMessage)||"Hello! How can I help you today?",enableVoiceMode:void 0===(null===(Oe=t.behavior)||void 0===Oe?void 0:Oe.enableVoiceMode)||t.behavior.enableVoiceMode,mode:(null===(Ae=t.behavior)||void 0===Ae?void 0:Ae.mode)||"unified"},t.behavior),accessibility:Vo({ariaLabel:(null===(Ie=t.accessibility)||void 0===Ie?void 0:Ie.ariaLabel)||"Chat Assistant",ariaDescription:(null===(Re=t.accessibility)||void 0===Re?void 0:Re.ariaDescription)||"Click to open chat assistant",keyboardNavigation:!1!==(null===(je=t.accessibility)||void 0===je?void 0:je.keyboardNavigation)},t.accessibility),customStyles:t.customStyles||"",useShadowDOM:!1!==t.useShadowDOM,variables:t.variables||{},forceConversationId:t.forceConversationId,onConversationStart:t.onConversationStart,onConversationEnd:t.onConversationEnd,onBargeIn:t.onBargeIn,onAudioStartPlaying:t.onAudioStartPlaying,onAudioStoppedPlaying:t.onAudioStoppedPlaying,onSubtitleDisplay:t.onSubtitleDisplay,primaryColor:_e},"string"==typeof t.position?{positionString:t.position}:{})}},{key:"setupEventHandlers",value:function(){var t=this;this.sdk.on("domainError",function(e){t.textInterface.showError(e),t.textInterface.stopStreamingState()}),this.sdk.on("error",function(e){e&&("DOMAIN_NOT_WHITELISTED"===e.message||e.message&&e.message.includes("Domain not whitelisted"))||(t.textInterface.showError(e.message||e),t.textInterface.stopStreamingState())}),this.sdk.on("chunk",function(e){t.textInterface.appendStreamingChunk(e)}),this.sdk.on("done",function(e){var n=e.text;t.textInterface.finalizeStreaming(n)})}},{key:"createShadowHost",value:function(){var t=document.getElementById("ttp-widget-shadow-host");t&&t.remove();var e=document.createElement("div");e.id="ttp-widget-shadow-host",e.style.cssText="position: fixed; z-index: 10000; pointer-events: none; top: 0; left: 0; width: 100%; height: 100%; overflow: visible;",this.shadowRoot=e.attachShadow({mode:"open"}),document.body.appendChild(e)}},{key:"createRegularContainer",value:function(){var t=document.getElementById("ttp-widget-container");t&&t.remove();var e=document.createElement("div");e.id="ttp-widget-container",e.style.cssText="position: fixed; z-index: 10000; pointer-events: none; top: 0; left: 0; width: 100%; height: 100%; overflow: visible;",document.body.appendChild(e),this.regularContainer=e}},{key:"createWidget",value:function(){this.container||(this.config.useShadowDOM?(this.createShadowHost(),this.container=this.shadowRoot):(this.createRegularContainer(),this.container=this.regularContainer,this.shadowRoot=document));var t;t=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 e=this.generateWidgetHTML();if(this.config.useShadowDOM){var n="\n <style>".concat(t,"</style>\n ").concat(e,"\n ");this.shadowRoot.innerHTML=n}else this.injectStylesIntoHead(t),this.container.innerHTML=e;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"))}},{key:"injectStylesIntoHead",value:function(t){var e,n,o=document.getElementById("ttp-widget-styles");o&&o.remove();var r={small:50,medium:60,large:70,xl:80}[null===(e=this.config.button)||void 0===e?void 0:e.size]||60,i={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,r,i),c=document.createElement("style");c.id="ttp-widget-styles",c.textContent=t+"\n"+s,this.config.customStyles&&(c.textContent+="\n"+this.config.customStyles),document.head.appendChild(c)}},{key:"generateWidgetHTML",value:function(){var t,e,n,o,r=this,i=(this.config.position,this.config.button),a=this.config.icon,s=(this.config.panel,this.config.header),c=(this.config.animation,{small:50,medium:60,large:70,xl:80}[i.size]||60),l={small:20,medium:28,large:36,xl:44}[a.size]||28,u=this.generatePositionStyles(),d=this.generateIconHTML(l),p=this.config.behavior.mode||"unified",f="unified"===p,h="unified"===p||"voice-only"===p,g="unified"===p||"text-only"===p,v=function(t){var e=r.config.language||"en";return(r.translations[e]||r.translations.en)[t]||t},m=function(t){var e,n=null===(e=r.config.tooltips)||void 0===e?void 0:e[t];return null!=n?n:{newChat:v("newChat"),back:v("back"),close:v("close"),mute:v("mute"),speaker:v("speaker"),endCall:v("endCall")}[t]||""},y=this.config.useShadowDOM?"\n <style>\n ".concat(this.generateCSS(u,c,l),"\n ").concat(this.config.customStyles,"\n </style>\n "):"";return"\n ".concat(y,"\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(s.backgroundColor,"; color: ").concat(s.textColor,';">\n <div>\n ').concat(s.showTitle?'<div class="header-title">'.concat(s.title,"</div>"):"",'\n <div class="header-status">\n <span class="status-dot"></span>\n <span>').concat(v("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(m("newChat"),'" style="').concat(f?"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"===p?'<button class="header-icon back-btn" id="backBtn" title="'.concat(m("back"),'" style="display: none;">\n <span style="font-size: 16px;">‹</span>\n </button>'):"","\n \n \x3c!-- Close Button --\x3e\n ").concat(s.showCloseButton?'<button class="header-icon close-btn" id="closeBtn" title="'+m("close")+'"><span style="font-size: 18px; font-weight: bold;">×</span></button>':"","\n </div>\n </div>\n\n ").concat(f?'\n <div class="landing-screen" id="landingScreen">\n <div class="landing-logo">'.concat((null===(t=this.config.landing)||void 0===t?void 0:t.logo)||"🤖",'</div>\n <div class="landing-title">').concat((null===(e=this.config.landing)||void 0===e?void 0:e.title)||v("landingTitle"),'</div>\n <div class="mode-selection">\n ').concat(h?'<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)||v("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)||v("textChat"),"</div>\n </div>"):"","\n </div>\n </div>"):"","\n\n ").concat(h?this.voiceInterface.generateHTML():"","\n ").concat(g?this.textInterface.generateHTML():"","\n ").concat(this.generateFooterHTML(),"\n </div>\n </div>\n </div>\n ")}},{key:"generateFooterHTML",value:function(){var t=this.config.footer;if(!t.show)return"";var e=encodeURIComponent(window.location.hostname||"widget"),n="https://talktopc.com?ref=widget&source=".concat(e);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(t.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(t.textColor,';\n transition: color 0.2s ease;\n "\n onmouseover="this.style.color=\'').concat(t.hoverColor,"'\"\n onmouseout=\"this.style.color='").concat(t.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 ')}},{key:"generatePositionStyles",value:function(){var t=this.config.position,e=t.offset||{x:20,y:20},n="";return"top"===t.vertical?n+="top: ".concat(e.y,"px;"):"bottom"===t.vertical?n+="bottom: ".concat(e.y,"px;"):"center"===t.vertical&&(n+="top: 50%; transform: translateY(-50%);"),"left"===t.horizontal?n+="left: ".concat(e.x,"px;"):"right"===t.horizontal?n+="right: ".concat(e.x,"px;"):"center"===t.horizontal&&(n+="left: 50%; transform: translateX(-50%);"),n}},{key:"generateIconHTML",value:function(t){var e=this.config.icon;switch(e.type){case"custom":return'<img src="'.concat(e.customImage,'" alt="Chat Assistant" style="width: ').concat(t,"px; height: ").concat(t,'px; object-fit: contain;" />');case"emoji":return'<span style="font-size: '.concat(t,'px; line-height: 1;">').concat(e.emoji,"</span>");case"text":return'<span style="font-size: '.concat(Math.floor(.6*t),'px; font-weight: bold; color: white;">').concat(e.text,"</span>");case"microphone":default:return'<svg viewBox="0 0 24 24" style="width: '.concat(t,"px; height: ").concat(t,'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(t,"px; height: ").concat(t,'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>')}}},{key:"generateCSS",value:function(t,e,n){var o,r,i,a,s,c,l,u,d,p,f,h=this.config.button,g=this.config.icon,v=this.config.panel,m=this.config.header,y=(this.config.messages,this.config.animation),b=this.config.behavior.mode||"unified",w="unified"===b||"voice-only"===b,S="unified"===b||"text-only"===b,x=!1===this.config.useShadowDOM?" !important":"",k=m.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(t,"\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===(r=this.config.position.offset)||void 0===r?void 0:r.y)||20,"px;"),"\n ").concat("right"===this.config.position.horizontal?"right: ".concat((null===(i=this.config.position.offset)||void 0===i?void 0:i.x)||20,"px;"):"left: ".concat((null===(a=this.config.position.offset)||void 0===a?void 0:a.x)||20,"px;"),"\n width: ").concat(e,"px;\n height: ").concat(e,"px;\n border-radius: ").concat("circle"===h.shape?"50%":"square"===h.shape?"0":"12px",";\n background: ").concat(h.backgroundColor||g.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(h.hoverColor?"background: ".concat(h.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(x,";\n position: fixed;\n bottom: calc(").concat(e,"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(e,"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(x,";\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(x,"; \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(x,"; }\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===(u=this.config.landing)||void 0===u?void 0:u.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===(d=this.config.landing)||void 0===d?void 0:d.modeCardHoverBorderColor)||k,"; \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===(p=this.config.landing)||void 0===p?void 0:p.modeCardIconBackgroundColor)||k,"; \n color: #fff; \n font-size: 32px; \n }\n .mode-card-title { \n color: ").concat((null===(f=this.config.landing)||void 0===f?void 0:f.modeCardTitleColor)||"#111827","; \n font-weight: 600; \n text-align: center;\n width: 100%;\n }\n\n ").concat(w?this.voiceInterface.generateCSS():"","\n ").concat(S?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 ")}},{key:"setupWidgetEvents",value:function(){var t=this;if(this.shadowRoot){var e=this.shadowRoot.getElementById("text-chat-button");e&&(e.onclick=function(){return t.togglePanel()});var n=this.shadowRoot.getElementById("closeBtn");n&&(n.onclick=function(){return t.togglePanel()});var o=this.config.behavior.mode||"unified",r="unified"===o,i="unified"===o||"voice-only"===o,a="unified"===o||"text-only"===o,s=this.shadowRoot.getElementById("backBtn"),c=this.shadowRoot.getElementById("landingScreen"),l=this.shadowRoot.getElementById("mode-card-voice"),u=this.shadowRoot.getElementById("mode-card-text"),d=this.shadowRoot.getElementById("textInterface"),p=this.shadowRoot.getElementById("voiceInterface");s&&(s.onclick=function(){return t.showLanding()}),r?(l&&(l.onclick=function(){return t.showVoice()}),u&&(u.onclick=function(){return t.showText()}),"text"===this.currentView?(c&&c.classList.remove("active"),d&&d.classList.add("active"),p&&p.classList.remove("active"),s&&"unified"===o&&s.classList.add("visible"),f&&(f.style.display="")):"voice"===this.currentView?(c&&c.classList.remove("active"),d&&d.classList.remove("active"),p&&p.classList.add("active"),s&&"unified"===o&&s.classList.add("visible"),f&&(f.style.display="none")):(this.currentView="landing",c&&c.classList.add("active"),d&&d.classList.remove("active"),p&&p.classList.remove("active"),s&&"unified"===o&&s.classList.remove("visible"))):"voice-only"===o?(p&&p.classList.add("active"),d&&d.classList.remove("active"),c&&c.classList.remove("active")):"text-only"===o&&(d&&d.classList.add("active"),p&&p.classList.remove("active"),c&&c.classList.remove("active")),i&&(console.log("⚙️ Setting up voice interface event handlers"),this.voiceInterface.setupEventHandlers()),a&&(console.log("⚙️ Setting up text interface event handlers"),this.textInterface.setupEventHandlers());var f=this.shadowRoot.getElementById("newChatBtn");f&&(f.onclick=function(){return t.textInterface.startNewChat()},r&&(f.style.display="none")),this.config.accessibility.keyboardNavigation&&this.setupKeyboardNavigation()}}},{key:"startNewChat",value:function(){this.textInterface.startNewChat()}},{key:"showLanding",value:function(){if(this.shadowRoot&&"unified"===(this.config.behavior.mode||"unified")){this.currentView="landing";var t=this.shadowRoot.getElementById("landingScreen"),e=this.shadowRoot.getElementById("textInterface"),n=this.shadowRoot.getElementById("voiceInterface"),o=this.shadowRoot.getElementById("backBtn"),r=this.shadowRoot.getElementById("newChatBtn");t&&t.classList.add("active"),e&&e.classList.remove("active"),n&&n.classList.remove("active"),o&&o.classList.remove("visible"),r&&(r.style.display="none")}}},{key:"showText",value:function(){if(this.shadowRoot){this.currentView="text";var t=this.shadowRoot.getElementById("landingScreen"),e=this.shadowRoot.getElementById("voiceInterface"),n=this.shadowRoot.getElementById("backBtn"),o=this.shadowRoot.getElementById("newChatBtn");t&&t.classList.remove("active"),e&&e.classList.remove("active"),this.textInterface.show();var r=this.config.behavior.mode||"unified";n&&"unified"===r&&n.classList.add("visible"),o&&(o.style.display="")}}},{key:"showVoice",value:function(){if(this.shadowRoot){this.currentView="voice";var t=this.shadowRoot.getElementById("landingScreen"),e=this.shadowRoot.getElementById("textInterface"),n=this.shadowRoot.getElementById("voiceInterface"),o=this.shadowRoot.getElementById("backBtn"),r=this.shadowRoot.getElementById("newChatBtn");t&&t.classList.remove("active"),e&&e.classList.remove("active"),n&&n.classList.add("active");var i=this.config.behavior.mode||"unified";o&&"unified"===i&&o.classList.add("visible"),r&&(r.style.display="none")}}},{key:"setupKeyboardNavigation",value:function(){var t=this;document.addEventListener("keydown",function(e){"Escape"===e.key&&t.isOpen&&t.togglePanel()})}},{key:"togglePanel",value:function(){var t=this;if(this.shadowRoot){this.isOpen=!this.isOpen;var e=this.shadowRoot.getElementById("text-chat-panel");e&&e.classList.toggle("open"),this.isOpen&&setTimeout(function(){var e=t.shadowRoot.getElementById("messageInput");e&&e.focus()},100),this.isOpen&&!this.isActive&&this.config.behavior.autoConnect&&this.startChat()}}},{key:"startChat",value:(i=zo(Mo().m(function t(){return Mo().w(function(t){for(;;)switch(t.n){case 0:this.isActive=!0,this.textInterface.setActive(!0);case 1:return t.a(2)}},t,this)})),function(){return i.apply(this,arguments)})},{key:"sendMessage",value:(r=zo(Mo().m(function t(){return Mo().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,this.textInterface.sendMessage();case 1:return t.a(2)}},t,this)})),function(){return r.apply(this,arguments)})},{key:"updateSendButtonState",value:function(){this.textInterface.updateSendButtonState()}},{key:"getSignedUrl",value:(o=zo(Mo().m(function t(){var e,n;return Mo().w(function(t){for(;;)switch(t.n){case 0:if(!this.config.signedUrl){t.n=1;break}return t.a(2,this.config.signedUrl);case 1:if(this.config.agentId){t.n=2;break}throw new Error("agentId is required when signedUrl is not provided");case 2:return e=this.config.websocketUrl||"wss://backend.talktopc.com/ws/conv",(n=new URLSearchParams).append("agentId",this.config.agentId),this.config.appId&&n.append("appId",this.config.appId),!1!==this.config.demo&&n.append("demo","true"),t.a(2,"".concat(e,"?").concat(n.toString()))}},t,this)})),function(){return o.apply(this,arguments)})},{key:"addMessage",value:function(t,e){this.textInterface.addMessage(t,e)}},{key:"beginStreaming",value:function(){this.textInterface.beginStreaming()}},{key:"appendStreamingChunk",value:function(t){this.textInterface.appendStreamingChunk(t)}},{key:"finalizeStreaming",value:function(t){this.textInterface.finalizeStreaming(t)}},{key:"stopStreamingState",value:function(){this.textInterface.stopStreamingState()}},{key:"showError",value:function(t){this.textInterface.showError(t)}},{key:"updateStatus",value:function(t){}},{key:"updateConfig",value:function(t){var e,n,o,r,i,a,s,c,l,u=Vo({},this.config);t.panel&&(u.panel=Vo(Vo({},this.config.panel),t.panel)),t.voice&&(u.voice=Vo(Vo({},this.config.voice),t.voice),t.voice.micButtonHint&&(u.voice.micButtonHint=Vo(Vo({},null===(c=this.config.voice)||void 0===c?void 0:c.micButtonHint),t.voice.micButtonHint))),t.text&&(u.text=Vo(Vo({},this.config.text),t.text),t.text.sendButtonHint&&(u.text.sendButtonHint=Vo(Vo({},null===(l=this.config.text)||void 0===l?void 0:l.sendButtonHint),t.text.sendButtonHint))),void 0!==t.language&&(u.language=t.language),void 0!==t.language&&(["he","ar"].includes(t.language)?u.direction="rtl":void 0===t.direction&&(u.direction="ltr")),t.translations&&(u.translations=t.translations,this.translations=t.translations),t.button&&(u.button=Vo(Vo({},this.config.button),t.button)),t.header&&(u.header=Vo(Vo({},this.config.header),t.header)),t.icon&&(u.icon=Vo(Vo({},this.config.icon),t.icon)),t.messages&&(u.messages=Vo(Vo({},this.config.messages),t.messages)),t.animation&&(u.animation=Vo(Vo({},this.config.animation),t.animation)),t.behavior&&(u.behavior=Vo(Vo({},this.config.behavior),t.behavior)),t.accessibility&&(u.accessibility=Vo(Vo({},this.config.accessibility),t.accessibility)),t.tooltips&&(u.tooltips=Vo(Vo({},this.config.tooltips),t.tooltips)),t.landing&&(u.landing=Vo(Vo({},this.config.landing),t.landing)),t.footer&&(u.footer=Vo(Vo({},this.config.footer),t.footer)),void 0!==t.direction&&void 0===u.direction&&(u.direction=t.direction),void 0!==t.primaryColor&&(u.primaryColor=t.primaryColor),u.onConversationStart=void 0!==t.onConversationStart?t.onConversationStart:this.config.onConversationStart,u.onConversationEnd=void 0!==t.onConversationEnd?t.onConversationEnd:this.config.onConversationEnd,u.onBargeIn=void 0!==t.onBargeIn?t.onBargeIn:this.config.onBargeIn,u.onAudioStartPlaying=void 0!==t.onAudioStartPlaying?t.onAudioStartPlaying:this.config.onAudioStartPlaying,u.onAudioStoppedPlaying=void 0!==t.onAudioStoppedPlaying?t.onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,u.onSubtitleDisplay=void 0!==t.onSubtitleDisplay?t.onSubtitleDisplay:this.config.onSubtitleDisplay,void 0!==t.useShadowDOM&&(u.useShadowDOM=t.useShadowDOM),Object.keys(t).forEach(function(e){["panel","button","header","footer","icon","messages","direction","voice","text","animation","behavior","accessibility","language","tooltips","landing","primaryColor","useShadowDOM","onConversationStart","onConversationEnd","onBargeIn","onAudioStartPlaying","onAudioStoppedPlaying","onSubtitleDisplay"].includes(e)||(u[e]=t[e])}),null===(e=this.config)||void 0===e||e.language;var d=!1!==(null===(n=this.config)||void 0===n?void 0:n.useShadowDOM);if(this.config=this.mergeWithDefaults(u),!1!==this.config.useShadowDOM===d&&this.container){var p=document.getElementById("ttp-widget-shadow-host");p&&!this.config.useShadowDOM&&p.remove();var f=document.getElementById("ttp-widget-container");if(f&&this.config.useShadowDOM&&f.remove(),this.config.useShadowDOM)if(this.shadowRoot)this.container=this.shadowRoot;else{var h=document.getElementById("ttp-widget-shadow-host");h?(this.shadowRoot=h.shadowRoot,this.container=this.shadowRoot):(this.createShadowHost(),this.container=this.shadowRoot)}else{if(this.regularContainer)this.container=this.regularContainer;else{var g=document.getElementById("ttp-widget-container");g?(this.regularContainer=g,this.container=g):(this.createRegularContainer(),this.container=this.regularContainer)}this.shadowRoot=document}}else{var v=document.getElementById("ttp-widget-shadow-host");v&&v.remove();var m=document.getElementById("ttp-widget-container");if(m&&m.remove(),!1===d){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 b=this.config.language||"en",w=Vo(Vo(Vo({},this.config),this.config.voice),{},{language:b,translations:this.translations,shadowRoot:this.shadowRoot,outputContainer:(null===(o=this.config.voice)||void 0===o?void 0:o.outputContainer)||"raw",outputEncoding:(null===(r=this.config.voice)||void 0===r?void 0:r.outputEncoding)||"pcm",outputSampleRate:(null===(i=this.config.voice)||void 0===i?void 0:i.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 Eo(w);var S=Vo(Vo(Vo({},this.config),this.config.text),{},{language:b,translations:this.translations,shadowRoot:this.shadowRoot});this.textInterface=new _o(S,this.sdk),this.createWidget(),this.textInterface&&this.textInterface.updateInputAttributes&&this.textInterface.updateInputAttributes()}},{key:"destroy",value:function(){var t=document.getElementById("ttp-widget-shadow-host");t&&t.remove();var e=document.getElementById("ttp-widget-container");e&&e.remove();var n=document.getElementById("ttp-widget-styles");n&&n.remove(),this.sdk&&this.sdk.destroy(),this.voiceInterface&&this.voiceInterface.destroy()}},{key:"startVoiceCall",value:(n=zo(Mo().m(function t(){return Mo().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,this.voiceInterface.startVoiceCall();case 1:return t.a(2)}},t,this)})),function(){return n.apply(this,arguments)})},{key:"endVoiceCall",value:function(){this.voiceInterface.endVoiceCall()}},{key:"toggleMute",value:function(){this.voiceInterface.toggleMute()}},{key:"toggleSpeaker",value:function(){this.voiceInterface.toggleSpeaker()}},{key:"registerToolHandler",value:function(t,e){var n;if(null!==(n=this.voiceInterface)&&void 0!==n&&n.sdk)return this.voiceInterface.sdk.registerToolHandler(t,e);console.warn("TTPChatWidget: Cannot register tool handler - voice interface not initialized")}},{key:"unregisterToolHandler",value:function(t){var e;if(null!==(e=this.voiceInterface)&&void 0!==e&&e.sdk)return this.voiceInterface.sdk.unregisterToolHandler(t)}},{key:"hasToolHandler",value:function(t){var e;return!(null===(e=this.voiceInterface)||void 0===e||!e.sdk)&&this.voiceInterface.sdk.hasToolHandler(t)}},{key:"getRegisteredTools",value:function(){var t;return null!==(t=this.voiceInterface)&&void 0!==t&&t.sdk?this.voiceInterface.sdk.getRegisteredTools():[]}}],e&&Wo(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o,r,i}(),Qo="2.18.0";const Yo={VoiceSDK:kt,VoiceSDK_v2:cn,TextChatSDK:Sn,WebSocketManager:D,AudioRecorder:W,AudioPlayer:nt,EventEmitter:l,VoiceButton:Dn,VanillaVoiceButton:Vn,AgentSDK:eo,TTPChatWidget:qo,VERSION:Qo};return o})());
|
|
2
|
+
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.TTPAgentSDK=e():t.TTPAgentSDK=e()}(window,()=>(()=>{"use strict";var t={540:(t,e,n)=>{t.exports=n(869)},698:(t,e)=>{var n=Symbol.for("react.transitional.element");function o(t,e,o){var r=null;if(void 0!==o&&(r=""+o),void 0!==e.key&&(r=""+e.key),"key"in e)for(var i in o={},e)"key"!==i&&(o[i]=e[i]);else o=e;return e=o.ref,{$$typeof:n,type:t,key:r,ref:void 0!==e?e:null,props:o}}Symbol.for("react.fragment"),e.jsx=o,e.jsxs=o},848:(t,e,n)=>{t.exports=n(698)},869:(t,e)=>{Symbol.for("react.transitional.element"),Symbol.for("react.portal"),Symbol.for("react.fragment"),Symbol.for("react.strict_mode"),Symbol.for("react.profiler"),Symbol.for("react.consumer"),Symbol.for("react.context"),Symbol.for("react.forward_ref"),Symbol.for("react.suspense"),Symbol.for("react.memo"),Symbol.for("react.lazy"),Symbol.for("react.activity"),Symbol.iterator;var n={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},o=Object.assign,r={};function i(t,e,o){this.props=t,this.context=e,this.refs=r,this.updater=o||n}function a(){}function s(t,e,o){this.props=t,this.context=e,this.refs=r,this.updater=o||n}i.prototype.isReactComponent={},i.prototype.setState=function(t,e){if("object"!=typeof t&&"function"!=typeof t&&null!=t)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")},i.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")},a.prototype=i.prototype;var c=s.prototype=new a;c.constructor=s,o(c,i.prototype),c.isPureReactComponent=!0;Array.isArray;var l={H:null,A:null,T:null,S:null};Object.prototype.hasOwnProperty;"function"==typeof reportError&&reportError;e.useEffect=function(t,e){return l.H.useEffect(t,e)},e.useRef=function(t){return l.H.useRef(t)},e.useState=function(t){return l.H.useState(t)}}},e={};function n(o){var r=e[o];if(void 0!==r)return r.exports;var i=e[o]={exports:{}};return t[o](i,i.exports,n),i.exports}n.d=(t,e)=>{for(var o in e)n.o(e,o)&&!n.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:e[o]})},n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var o={};n.r(o),n.d(o,{AgentSDK:()=>Nn,AudioPlayer:()=>rn,AudioRecorder:()=>qe,EventEmitter:()=>Xt,MicPermissionModals:()=>i,MicPermissionUtils:()=>r,TTPChatWidget:()=>Ro,TextChatSDK:()=>de,VERSION:()=>Fo,VanillaVoiceButton:()=>En,VoiceButton:()=>mn,VoiceSDK_v2:()=>Qt,WebSocketManager:()=>_e,default:()=>jo});var r={};n.r(r),n.d(r,{checkPermissionState:()=>Vn,getDeviceInfo:()=>Kn,getPermissionInstructions:()=>Gn,openSettings:()=>qn});var i={};function a(t){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a(t)}function s(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,c(o.key),o)}}function c(t){var e=function(t){if("object"!=a(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=a(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==a(e)?e:e+""}n.r(i),n.d(i,{showBlockedModal:()=>eo,showNoMicrophoneModal:()=>no,showPrePromptModal:()=>to});const l=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.events={}},e=[{key:"on",value:function(t,e){return this.events[t]||(this.events[t]=[]),this.events[t].push(e),this}},{key:"off",value:function(t,e){return this.events[t]?(this.events[t]=this.events[t].filter(function(t){return t!==e}),this):this}},{key:"emit",value:function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),o=1;o<e;o++)n[o-1]=arguments[o];return!!this.events[t]&&(this.events[t].forEach(function(t){t.apply(void 0,n)}),!0)}},{key:"once",value:function(t,e){var n=this,o=function(){e.apply(void 0,arguments),n.off(t,o)};return this.on(t,o)}},{key:"removeAllListeners",value:function(t){return t?delete this.events[t]:this.events={},this}}],e&&s(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function u(t){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u(t)}function d(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,p(o.key),o)}}function p(t){var e=function(t){if("object"!=u(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=u(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==u(e)?e:e+""}const f=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.name="PCM"},(e=[{key:"decode",value:function(t){if(t instanceof ArrayBuffer)return t;if(t instanceof Uint8Array)return t.buffer;throw new Error("Invalid PCM data type")}},{key:"encode",value:function(t){return t}}])&&d(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function h(t){return h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},h(t)}function g(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,v(o.key),o)}}function v(t){var e=function(t){if("object"!=h(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=h(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==h(e)?e:e+""}const m=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.name="PCMU"},(e=[{key:"decode",value:function(t){for(var e=t instanceof Uint8Array?t:new Uint8Array(t),n=new Int16Array(e.length),o=0;o<e.length;o++)n[o]=this.mulawToLinear(e[o]);return n.buffer}},{key:"encode",value:function(t){for(var e=t instanceof Int16Array?t:new Int16Array(t),n=new Uint8Array(e.length),o=0;o<e.length;o++)n[o]=this.linearToMulaw(e[o]);return n}},{key:"mulawToLinear",value:function(t){var e=1<<3+(t>>4&7);return(128&t?-1:1)*(132+(15&t)*e+(e>>1)-4)}},{key:"linearToMulaw",value:function(t){var e=t>>8&128;e&&(t=-t),t>32635&&(t=32635),t+=132;for(var n=7,o=16384;0===(t&o)&&n>0;n--,o>>=1);return 255&~(e|n<<4|t>>n+3&15)}}])&&g(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function y(t){return y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},y(t)}function b(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,w(o.key),o)}}function w(t){var e=function(t){if("object"!=y(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=y(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==y(e)?e:e+""}const S=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.name="PCMA"},(e=[{key:"decode",value:function(t){for(var e=t instanceof Uint8Array?t:new Uint8Array(t),n=new Int16Array(e.length),o=0;o<e.length;o++)n[o]=this.alawToLinear(e[o]);return n.buffer}},{key:"encode",value:function(t){for(var e=t instanceof Int16Array?t:new Int16Array(t),n=new Uint8Array(e.length),o=0;o<e.length;o++)n[o]=this.linearToAlaw(e[o]);return n}},{key:"alawToLinear",value:function(t){var e=(t^=85)>>4&7,n=15&t;return(128&t?-1:1)*(0===e?8+(n<<4):264+(n<<4)<<e-1)}},{key:"linearToAlaw",value:function(t){var e,n,o=t>>8&128;if(o&&(t=-t),t>32635&&(t=32635),t<256)e=0,n=t>>4;else{e=7;for(var r=16384;0===(t&r)&&e>0;e--,r>>=1);n=t>>e+3&15}return 85^(o|e<<4|n)}}])&&b(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function x(t){return x="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},x(t)}function k(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return C(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?C(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}function C(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}function P(t){if(null!=t){var e=t["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],n=0;if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length))return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}}}throw new TypeError(x(t)+" is not iterable")}function T(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return E(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(E(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,E(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,E(d,"constructor",l),E(l,"constructor",c),c.displayName="GeneratorFunction",E(l,r,"GeneratorFunction"),E(d),E(d,r,"Generator"),E(d,o,function(){return this}),E(d,"toString",function(){return"[object Generator]"}),(T=function(){return{w:i,m:p}})()}function E(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}E=function(t,e,n,o){function i(e,n){E(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},E(t,e,n,o)}function O(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function A(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){O(i,o,r,a,s,"next",t)}function s(t){O(i,o,r,a,s,"throw",t)}a(void 0)})}}function I(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,R(o.key),o)}}function R(t){var e=function(t){if("object"!=x(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=x(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==x(e)?e:e+""}function F(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(F=function(){return!!t})()}function j(t){return j=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},j(t)}function D(t,e){return D=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},D(t,e)}const _=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(t=function(t,e,n){return e=j(e),function(t,e){if(e&&("object"==x(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,F()?Reflect.construct(e,n||[],j(t).constructor):e.apply(t,n))}(this,e)).config=n,t.audioContext=null,t.audioQueue=[],t.isPlaying=!1,t.isProcessingQueue=!1,t.currentSource=null,t.outputFormat=null,t.nextStartTime=0,t.scheduledBuffers=0,t.scheduledSources=new Set,t.pcmChunkQueue=[],t.preparedBuffer=[],t.isProcessingPcmQueue=!1,t.isSchedulingFrames=!1,t.MAX_LOOKAHEAD_SECONDS=.02,t.pendingSentenceText=null,t.sentenceTimings=[],t.isCheckingTranscripts=!1,t.codecs={pcm:new f,pcmu:new m,pcma:new S},t.SUPPORTED_CONTAINERS=["wav","raw"],t.SUPPORTED_ENCODINGS=["pcm","pcmu","pcma"],t.SUPPORTED_SAMPLE_RATES=[8e3,16e3,22050,24e3,44100,48e3],t.SUPPORTED_BIT_DEPTHS=[8,16,24],t.SUPPORTED_CHANNELS=[1],console.log("🎵 AudioPlayer v2 initialized"),t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&D(t,e)}(e,t),n=e,o=[{key:"setOutputFormat",value:function(t){var e;this.validateFormat(t)||(console.warn("⚠️ AudioPlayer: Invalid format, using defaults:",t),t=this.getDefaultFormat());var n=null===(e=this.outputFormat)||void 0===e?void 0:e.sampleRate,o=t.sampleRate;this.outputFormat=t,console.log("✅ AudioPlayer v2: Format set:",t),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(function(){console.log("✅ AudioPlayer v2: AudioContext resumed and ready")}).catch(function(t){console.warn("⚠️ AudioPlayer v2: Could not resume AudioContext:",t)}))}},{key:"validateFormat",value:function(t){var e,n;if(!t)return!1;var o=null===(e=t.container)||void 0===e?void 0:e.toLowerCase(),r=null===(n=t.encoding)||void 0===n?void 0:n.toLowerCase();return o&&r&&this.SUPPORTED_CONTAINERS.includes(o)&&this.SUPPORTED_ENCODINGS.includes(r)&&this.SUPPORTED_SAMPLE_RATES.includes(t.sampleRate)&&this.SUPPORTED_BIT_DEPTHS.includes(t.bitDepth)&&(!t.channels||this.SUPPORTED_CHANNELS.includes(t.channels))}},{key:"getDefaultFormat",value:function(){return{container:"raw",encoding:"pcm",sampleRate:16e3,channels:1,bitDepth:16}}},{key:"playAudio",value:function(t){var e=this;try{var n=this.createAudioBlob(t);this.audioQueue.push(n),this.isPlaying||this.isProcessingQueue||this.currentSource||setTimeout(function(){return e.processQueue()},50)}catch(t){console.error("❌ AudioPlayer v2: Playback error:",t),this.emit("playbackError",t)}}},{key:"playChunk",value:(c=A(T().m(function t(e){var n,o,r=this;return T().w(function(t){for(;;)switch(t.n){case 0:(n=this.prepareChunk(e))?(this.preparedBuffer.push(n),this.isSchedulingFrames?setTimeout(function(){r.preparedBuffer.length>0&&!r.isSchedulingFrames&&r.schedulePreparedFrames()},5):this.schedulePreparedFrames(),this.pcmChunkQueue.length>0&&!this.isProcessingPcmQueue&&this.processPcmQueue()):(console.error("❌ AudioPlayer: playChunk failed - prepareChunk returned null"),console.error(" pcmData length:",(null==e?void 0:e.byteLength)||"undefined"),console.error(" outputFormat:",this.outputFormat),console.error(" audioContext:",this.audioContext?"initialized":"not initialized"),console.error(" audioContext state:",(null===(o=this.audioContext)||void 0===o?void 0:o.state)||"N/A"),this.emit("playbackError",new Error("Failed to prepare PCM chunk for playback")));case 1:return t.a(2)}},t,this)})),function(t){return c.apply(this,arguments)})},{key:"prepareChunk",value:function(t){try{var e;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=t;if(t.byteLength%2!=0){console.warn("⚠️ Odd PCM chunk size, padding:",t.byteLength);var o=new Uint8Array(t.byteLength+1);o.set(new Uint8Array(t),0),o[t.byteLength]=0,n=o.buffer}for(var r=new Int16Array(n),i=new Float32Array(r.length),a=1/32768,s=r.length,c=0;c<s;c++)i[c]=r[c]*a;var l=(null===(e=this.outputFormat)||void 0===e?void 0:e.sampleRate)||this.audioContext.sampleRate,u=this.audioContext.sampleRate,d=this.audioContext.createBuffer(1,i.length,l);d.getChannelData(0).set(i);var p=d.duration,f=i.length,h=p;return u!==l&&(h=f/u),{buffer:d,duration:h,sampleRate:l,contextSampleRate:u}}catch(t){return console.error("❌ AudioPlayer: Error preparing chunk:",t),null}}},{key:"applyFadeOut",value:function(t){return t}},{key:"schedulePreparedFrames",value:(s=A(T().m(function t(){var e,n,o,r,i,a,s=this;return T().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isSchedulingFrames){t.n=1;break}return t.a(2);case 1:if(this.isSchedulingFrames=!0,e=this.preparedBuffer.length,0===(n=Math.min(e,5))&&e>0&&(n=1),t.p=2,this.audioContext||this.initializeAudioContext(),o=0===this.scheduledBuffers&&!this.isPlaying,"suspended"!==this.audioContext.state){t.n=4;break}return t.n=3,this.audioContext.resume();case 3:if(!o){t.n=4;break}return t.n=4,new Promise(function(t){return setTimeout(t,50)});case 4:if("running"===this.audioContext.state){t.n=8;break}if(console.warn("AudioPlayer v2: AudioContext not in running state:",this.audioContext.state),"suspended"!==this.audioContext.state){t.n=8;break}return t.n=5,this.audioContext.resume();case 5:if(!o){t.n=7;break}return t.n=6,new Promise(function(t){return setTimeout(t,50)});case 6:t.n=8;break;case 7:return t.n=8,new Promise(function(t){return setTimeout(t,10)});case 8:r=0,i=T().m(function t(){var e,n,o,i,a;return T().w(function(t){for(;;)switch(t.n){case 0:if(e=s.preparedBuffer.shift()){t.n=1;break}return t.a(2,1);case 1:(n=s.audioContext.createBufferSource()).buffer=e.buffer,n.connect(s.audioContext.destination),s.scheduledSources.add(n),o=s.audioContext.currentTime,0===s.scheduledBuffers?(s.nextStartTime<o&&(s.nextStartTime=o+s.MAX_LOOKAHEAD_SECONDS),console.log("🎵 Starting playback with minimal delay:",s.nextStartTime)):(i=o+s.MAX_LOOKAHEAD_SECONDS,s.nextStartTime<i&&(s.nextStartTime=i,console.warn("⚠️ AudioPlayer: Fell behind schedule, adjusting nextStartTime to ".concat(s.nextStartTime.toFixed(4),"s")))),s.pendingSentenceText&&(s.sentenceTimings.push({startTime:s.nextStartTime,text:s.pendingSentenceText,displayed:!1}),console.log("📝 AudioPlayer: Sentence scheduled at ".concat(s.nextStartTime.toFixed(3),'s: "').concat(s.pendingSentenceText.substring(0,40),'..."')),s.pendingSentenceText=null,s.isCheckingTranscripts||s.startTranscriptChecker()),n.start(s.nextStartTime),s.nextStartTime+=e.duration,s.nextStartTime=Math.round(1e6*s.nextStartTime)/1e6,a=s.nextStartTime-e.duration,s.scheduledBuffers<5&&(console.log("🎵 AudioPlayer: Scheduled frame ".concat(s.scheduledBuffers+1," at ").concat(a.toFixed(4),"s, next at ").concat(s.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(e.duration.toFixed(4),"s (").concat((1e3*e.duration).toFixed(2),"ms), Queued: ").concat(s.preparedBuffer.length,", Scheduled: ").concat(s.scheduledBuffers))),s.scheduledBuffers++,r++,n.onended=function(){if(s.scheduledSources.delete(n),s.scheduledBuffers--,0===s.scheduledBuffers&&0===s.preparedBuffer.length&&0===s.pcmChunkQueue.length)s.isPlaying=!1,s.isSchedulingFrames=!1,console.log("🛑 AudioPlayer: Emitting playbackStopped event (all buffers finished)"),s.emit("playbackStopped");else if(s.preparedBuffer.length>0)setTimeout(function(){s.preparedBuffer.length>0&&!s.isSchedulingFrames&&s.schedulePreparedFrames()},0);else if(s.scheduledBuffers>0){var t=function(){s.preparedBuffer.length>0&&!s.isSchedulingFrames&&s.scheduledBuffers>0?s.schedulePreparedFrames():s.scheduledBuffers>0&&setTimeout(t,10)};setTimeout(t,10)}},s.isPlaying||(s.isPlaying=!0,console.log("🎵 AudioPlayer: Emitting playbackStarted event"),s.emit("playbackStarted"));case 2:return t.a(2)}},t)});case 9:if(!(this.preparedBuffer.length>0&&r<n)){t.n=12;break}return t.d(P(i()),10);case 10:if(!t.v){t.n=11;break}return t.a(3,12);case 11:t.n=9;break;case 12:this.isSchedulingFrames=!1,this.preparedBuffer.length>0&&requestAnimationFrame(function(){s.preparedBuffer.length>0&&!s.isSchedulingFrames&&s.schedulePreparedFrames()}),this.scheduledBuffers>0&&setTimeout(function(){s.preparedBuffer.length>0&&!s.isSchedulingFrames&&s.scheduledBuffers>0?s.schedulePreparedFrames():s.scheduledBuffers>0&&setTimeout(function(){s.preparedBuffer.length>0&&!s.isSchedulingFrames&&s.scheduledBuffers>0&&s.schedulePreparedFrames()},10)},10),t.n=14;break;case 13:t.p=13,a=t.v,console.error("❌ AudioPlayer v2: Error scheduling frames:",a),this.emit("playbackError",a),this.isSchedulingFrames=!1;case 14:return t.a(2)}},t,this,[[2,13]])})),function(){return s.apply(this,arguments)})},{key:"processPcmQueue",value:(a=A(T().m(function t(){var e,n,o,r,i,a,s,c,l,u,d,p,f,h,g,v,m,y,b,w,S,x=this;return T().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isProcessingPcmQueue){t.n=1;break}return t.a(2);case 1:if(this.isProcessingPcmQueue=!0,t.p=2,this.audioContext||this.initializeAudioContext(),e=0===this.scheduledBuffers&&!this.isPlaying,"suspended"!==this.audioContext.state){t.n=4;break}return t.n=3,this.audioContext.resume();case 3:if(!e){t.n=4;break}return t.n=4,new Promise(function(t){return setTimeout(t,50)});case 4:if("running"===this.audioContext.state){t.n=8;break}if(console.warn("AudioPlayer v2: AudioContext not in running state:",this.audioContext.state),"suspended"!==this.audioContext.state){t.n=8;break}return t.n=5,this.audioContext.resume();case 5:if(!e){t.n=7;break}return t.n=6,new Promise(function(t){return setTimeout(t,50)});case 6:t.n=8;break;case 7:return t.n=8,new Promise(function(t){return setTimeout(t,10)});case 8:if(!(this.pcmChunkQueue.length>0)){t.n=10;break}if(r=this.pcmChunkQueue.shift()){t.n=9;break}return t.a(3,8);case 9:for(i=r,r.byteLength%2!=0&&(console.warn("⚠️ Odd PCM chunk size, padding:",r.byteLength),(a=new Uint8Array(r.byteLength+1)).set(new Uint8Array(r),0),a[r.byteLength]=0,i=a.buffer),s=new Int16Array(i),c=new Float32Array(s.length),l=1/32768,u=s.length,d=0;d<u;d++)c[d]=s[d]*l;p=(null===(n=this.outputFormat)||void 0===n?void 0:n.sampleRate)||this.audioContext.sampleRate,f=this.audioContext.sampleRate,null!==(o=this.outputFormat)&&void 0!==o&&o.sampleRate?this.scheduledBuffers<3&&console.log("🎵 AudioPlayer: Creating buffer at ".concat(p,"Hz (AudioContext: ").concat(f,"Hz)")):console.warn("⚠️ AudioPlayer: outputFormat.sampleRate not set! Using AudioContext sample rate:",f),(h=this.audioContext.createBuffer(1,c.length,p)).getChannelData(0).set(c),(g=this.audioContext.createBufferSource()).buffer=h,g.connect(this.audioContext.destination),v=this.audioContext.currentTime,this.nextStartTime<v&&(this.nextStartTime=v,0===this.scheduledBuffers&&console.log("🎵 Starting playback at current time:",v)),m=h.duration,y=c.length,b=m,f!==p&&(b=y/f,this.scheduledBuffers<3&&(console.log("🔄 Resampling detected: ".concat(p,"Hz → ").concat(f,"Hz")),console.log(" Buffer duration: ".concat(m.toFixed(4),"s, Calculated: ").concat(b.toFixed(4),"s")))),g.start(this.nextStartTime),this.nextStartTime+=b,this.nextStartTime=Math.round(1e6*this.nextStartTime)/1e6,this.scheduledBuffers<3&&(w=this.nextStartTime-b,console.log("🎵 AudioPlayer: Scheduled chunk ".concat(this.scheduledBuffers+1," at ").concat(w.toFixed(4),"s, next at ").concat(this.nextStartTime.toFixed(4),"s")),console.log(" Duration: ".concat(b.toFixed(4),"s (").concat((1e3*b).toFixed(2),"ms)"))),this.scheduledBuffers++,g.onended=function(){x.scheduledBuffers--,0===x.scheduledBuffers&&0===x.pcmChunkQueue.length&&(x.isPlaying=!1,x.isProcessingPcmQueue=!1,x.emit("playbackStopped"))},this.isPlaying||(this.isPlaying=!0,this.emit("playbackStarted")),t.n=8;break;case 10:this.isProcessingPcmQueue=!1,t.n=12;break;case 11:t.p=11,S=t.v,console.error("❌ AudioPlayer v2: Error playing chunk:",S),this.emit("playbackError",S),this.isProcessingPcmQueue=!1;case 12:return t.a(2)}},t,this,[[2,11]])})),function(){return a.apply(this,arguments)})},{key:"createAudioBlob",value:function(t){var e=new Uint8Array(t);console.log("🎵 AudioPlayer: Processing ".concat(e.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(),r=this.isWavFile(e);if(r&&console.log("🎵 AudioPlayer: Data has WAV header (RIFF)"),o&&r)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(e);if(o&&!r)console.log("🎵 AudioPlayer: Processing as RAW data (as negotiated)");else{if(n&&r)return console.log("✅ AudioPlayer: Processing as WAV file (matches negotiation)"),this.handleWavFile(e);if(n&&!r)return console.warn("⚠️ AudioPlayer: Negotiated WAV but data lacks WAV header. Attempting WAV processing anyway."),this.handleWavFile(e);if(!this.outputFormat&&r)return console.log("🎵 AudioPlayer: No format negotiated, auto-detecting WAV"),this.handleWavFile(e);this.outputFormat||r||(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(e)}},{key:"isWavFile",value:function(t){return t.length>=44&&82===t[0]&&73===t[1]&&70===t[2]&&70===t[3]}},{key:"handleWavFile",value:function(t){var e=this.parseWavHeader(t);if(console.log("🎵 WAV file detected:",{format:e.audioFormat,encoding:this.getEncodingName(e.audioFormat),sampleRate:e.sampleRate,channels:e.channels,bitDepth:e.bitsPerSample}),1===e.audioFormat)return console.log("✅ PCM WAV - using directly"),new Blob([t],{type:"audio/wav"});var n=this.getCodecForWavFormat(e.audioFormat);if(!n)throw new Error("Unsupported WAV format code: ".concat(e.audioFormat));console.log("🔄 Non-PCM WAV - converting to PCM WAV");var o=t.slice(44),r=n.decode(o),i=this.createWavHeader(r.byteLength,e.sampleRate,e.channels,16);return new Blob([i,r],{type:"audio/wav"})}},{key:"handleRawData",value:function(t){var e,n,o=this.outputFormat.encoding.toLowerCase(),r=this.getCodec(o);if(!r)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 i=this.outputFormat.bitDepth||16;t.length,24===i?(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."),e=this.convert24BitTo16Bit(t),n=16):8===i?(console.log("🔄 AudioPlayer: Converting 8-bit PCM to 16-bit PCM"),e=this.convert8BitTo16Bit(t),n=16):(e=t.buffer,n=i,console.log("✅ AudioPlayer: Using native ".concat(i,"-bit PCM (no conversion needed)")))}else e=r.decode(t),n=16,console.log("🔄 AudioPlayer: Decoded ".concat(o.toUpperCase()," to 16-bit PCM"));var a=this.createWavHeader(e.byteLength,this.outputFormat.sampleRate,this.outputFormat.channels,n);return new Blob([a,e],{type:"audio/wav"})}},{key:"convert24BitTo16Bit",value:function(t){for(var e=Math.floor(t.length/3),n=new Int16Array(e),o=0;o<e;o++){var r=t[3*o],i=t[3*o+1],a=t[3*o+2],s=r|i<<8|(255&a)<<16;128&a&&(s|=4278190080),n[o]=Math.max(-32768,Math.min(32767,Math.round(s/256)))}return n.buffer}},{key:"convert8BitTo16Bit",value:function(t){for(var e=t.length,n=new Int16Array(e),o=0;o<e;o++){var r=t[o];n[o]=256*(r-128)}return n.buffer}},{key:"getCodec",value:function(t){var e={pcm:"pcm",linear:"pcm",l16:"pcm",pcmu:"pcmu",ulaw:"pcmu",mulaw:"pcmu",g711u:"pcmu",pcma:"pcma",alaw:"pcma",g711a:"pcma"}[t.toLowerCase()];return this.codecs[e]}},{key:"getCodecForWavFormat",value:function(t){switch(t){case 1:return this.codecs.pcm;case 6:return this.codecs.pcma;case 7:return this.codecs.pcmu;default:return null}}},{key:"getEncodingName",value:function(t){switch(t){case 1:return"PCM";case 6:return"A-law";case 7:return"μ-law";default:return"Unknown (".concat(t,")")}}},{key:"parseWavHeader",value:function(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength);return{audioFormat:e.getUint16(20,!0),channels:e.getUint16(22,!0),sampleRate:e.getUint32(24,!0),byteRate:e.getUint32(28,!0),blockAlign:e.getUint16(32,!0),bitsPerSample:e.getUint16(34,!0)}}},{key:"createWavHeader",value:function(t,e,n,o){var r=new ArrayBuffer(44),i=new DataView(r);return i.setUint32(0,1380533830,!1),i.setUint32(4,36+t,!0),i.setUint32(8,1463899717,!1),i.setUint32(12,1718449184,!1),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,n,!0),i.setUint32(24,e,!0),i.setUint32(28,e*n*o/8,!0),i.setUint16(32,n*o/8,!0),i.setUint16(34,o,!0),i.setUint32(36,1684108385,!1),i.setUint32(40,t,!0),r}},{key:"initializeAudioContext",value:function(){var t,e,n=(null===(t=this.outputFormat)||void 0===t?void 0:t.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===(e=this.outputFormat)||void 0===e?void 0:e.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(t){console.error("❌ Failed to create AudioContext:",t),this.audioContext=new(window.AudioContext||window.webkitAudioContext),console.log("ℹ️ Using browser default: ".concat(this.audioContext.sampleRate,"Hz"))}}},{key:"processQueue",value:(i=A(T().m(function t(){var e,n,o,r,i,a,s,c,l=this;return T().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isProcessingQueue&&0!==this.audioQueue.length){t.n=1;break}return t.a(2);case 1:if(this.isProcessingQueue=!0,e=this.audioQueue.shift()){t.n=2;break}return this.isProcessingQueue=!1,t.a(2);case 2:if(t.p=2,n=!this.isPlaying&&null===this.currentSource,this.audioContext||this.initializeAudioContext(),"suspended"!==(o=this.audioContext).state){t.n=4;break}return t.n=3,o.resume();case 3:if(!n){t.n=4;break}return t.n=4,new Promise(function(t){return setTimeout(t,50)});case 4:if("running"===o.state){t.n=8;break}if(console.warn("AudioPlayer v2: AudioContext not in running state:",o.state),"suspended"!==o.state){t.n=8;break}return t.n=5,o.resume();case 5:if(!n){t.n=7;break}return t.n=6,new Promise(function(t){return setTimeout(t,50)});case 6:t.n=8;break;case 7:return t.n=8,new Promise(function(t){return setTimeout(t,10)});case 8:return t.n=9,e.arrayBuffer();case 9:return r=t.v,t.n=10,o.decodeAudioData(r);case 10:i=t.v,a=n&&!this.isPlaying&&null===this.currentSource,(s=o.createBufferSource()).buffer=i,s.connect(o.destination),this.currentSource=s,this.isPlaying=!0,a&&this.emit("playbackStarted"),s.onended=function(){l.currentSource=null,l.isProcessingQueue=!1,l.audioQueue.length>0?setTimeout(function(){return l.processQueue()},50):setTimeout(function(){0!==l.audioQueue.length||l.currentSource||(l.isPlaying=!1,l.emit("playbackStopped"))},100)},s.start(),t.n=12;break;case 11:t.p=11,c=t.v,console.error("❌ AudioPlayer v2: Error processing queue:",c),this.currentSource=null,this.emit("playbackError",c),this.audioQueue.length>0?(this.isProcessingQueue=!1,setTimeout(function(){return l.processQueue()},100)):(this.isPlaying=!1,this.isProcessingQueue=!1,this.emit("playbackStopped"));case 12:return t.a(2)}},t,this,[[2,11]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:function(){this.stopImmediate()}},{key:"reset",value:function(){this.stop(),this.audioQueue=[],this.pcmChunkQueue=[]}},{key:"stopImmediate",value:function(){var t=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(t){console.log(" currentSource already stopped or error:",t.message)}this.currentSource=null}if(this.scheduledSources.size>0){console.log(" Stopping ".concat(this.scheduledSources.size," scheduled sources..."));var e,n=0,o=k(this.scheduledSources);try{for(o.s();!(e=o.n()).done;){var r=e.value;try{r.stop(),n++}catch(t){console.log(" Source already stopped or not started:",t.message)}}}catch(t){o.e(t)}finally{o.f()}console.log(" Stopped ".concat(n," 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(),t&&(console.log("🛑 AudioPlayer: Emitting playbackStopped event (stopImmediate called)"),this.emit("playbackStopped"))}},{key:"markNewSentence",value:function(t){this.pendingSentenceText=t,console.log('📝 AudioPlayer: New sentence marked: "'.concat(t.substring(0,40),'..."'))}},{key:"startTranscriptChecker",value:function(){var t=this;if(!this.isCheckingTranscripts){this.isCheckingTranscripts=!0,console.log("📝 AudioPlayer: Transcript checker started");var e=function(){if(t.isCheckingTranscripts&&t.audioContext){var n,o=t.audioContext.currentTime,r=k(t.sentenceTimings);try{for(r.s();!(n=r.n()).done;){var i=n.value;!i.displayed&&o>=i.startTime&&(i.displayed=!0,console.log("📝 AudioPlayer: Display transcript at ".concat(o.toFixed(3),'s: "').concat(i.text.substring(0,40),'..."')),t.emit("transcriptDisplay",{text:i.text}))}}catch(t){r.e(t)}finally{r.f()}t.isPlaying||t.scheduledBuffers>0?requestAnimationFrame(e):(t.isCheckingTranscripts=!1,console.log("📝 AudioPlayer: Transcript checker stopped"))}};requestAnimationFrame(e)}}},{key:"clearTranscriptState",value:function(){this.pendingSentenceText=null,this.sentenceTimings=[],this.isCheckingTranscripts=!1,console.log("📝 AudioPlayer: Transcript state cleared")}},{key:"resumeAudioContext",value:(r=A(T().m(function t(){var e;return T().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.audioContext&&"closed"!==this.audioContext.state){t.n=2;break}return t.n=1,this.initializeAudioContext();case 1:return t.a(2);case 2:if("suspended"!==this.audioContext.state){t.n=6;break}return t.p=3,t.n=4,this.audioContext.resume();case 4:console.log("✅ AudioPlayer v2: AudioContext resumed after mic permission"),t.n=6;break;case 5:t.p=5,e=t.v,console.warn("⚠️ AudioPlayer v2: Failed to resume AudioContext:",e);case 6:return t.a(2)}},t,this,[[3,5]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){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}}},{key:"destroy",value:function(){this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.removeAllListeners()}}],o&&I(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,s,c}(l);function B(t){return B="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},B(t)}function M(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return U(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(U(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,U(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,U(d,"constructor",l),U(l,"constructor",c),c.displayName="GeneratorFunction",U(l,r,"GeneratorFunction"),U(d),U(d,r,"Generator"),U(d,o,function(){return this}),U(d,"toString",function(){return"[object Generator]"}),(M=function(){return{w:i,m:p}})()}function U(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}U=function(t,e,n,o){function i(e,n){U(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},U(t,e,n,o)}function N(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function z(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){N(i,o,r,a,s,"next",t)}function s(t){N(i,o,r,a,s,"throw",t)}a(void 0)})}}function H(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}function L(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,K(o.key),o)}}function K(t){var e=function(t){if("object"!=B(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=B(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==B(e)?e:e+""}function V(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(V=function(){return!!t})()}function W(t){return W=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},W(t)}function G(t,e){return G=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},G(t,e)}var q=function(t){function e(t){var n;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(n=function(t,e,n){return e=W(e),function(t,e){if(e&&("object"==B(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,V()?Reflect.construct(e,n||[],W(t).constructor):e.apply(t,n))}(this,e)).config=t,n.audioContext=null,n.audioWorkletNode=null,n.mediaStream=null,n.isRecording=!1,n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&G(t,e)}(e,t),n=e,o=[{key:"getAudioProcessorPath",value:function(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var t,e=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return H(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}(document.getElementsByTagName("script"));try{for(e.s();!(t=e.n()).done;){var n=t.value.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(t){var r=n.substring(0,n.lastIndexOf("/"));return"".concat(r,"/audio-processor.js")}}}catch(t){e.e(t)}finally{e.f()}return"https://cdn.talktopc.com/audio-processor.js"}},{key:"start",value:(i=z(M().m(function t(){var e,n,o,r,i,a,s=this;return M().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,"https:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname){t.n=1;break}throw e=new Error("Microphone access requires HTTPS. Please use https:// or test on localhost."),console.error("❌ AudioRecorder:",e.message),this.emit("error",e),e;case 1:if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){t.n=2;break}throw n=new Error("getUserMedia is not supported in this browser. Please use a modern browser."),console.error("❌ AudioRecorder:",n.message),this.emit("error",n),n;case 2:return console.log("🎤 AudioRecorder: Requesting microphone access..."),t.n=3,navigator.mediaDevices.getUserMedia({audio:{sampleRate:this.config.sampleRate,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 3:if(this.mediaStream=t.v,console.log("✅ AudioRecorder: Microphone access granted"),this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:this.config.sampleRate}),"suspended"!==this.audioContext.state){t.n=4;break}return t.n=4,this.audioContext.resume();case 4:return o=this.getAudioProcessorPath(),t.n=5,this.audioContext.audioWorklet.addModule(o);case 5:this.audioWorkletNode=new AudioWorkletNode(this.audioContext,"audio-processor"),this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.audioWorkletNode),this.audioWorkletNode.port.onmessage=function(t){var e=t.data,n=e.type,o=e.data;"pcm_audio_data"===n&&s.emit("audioData",o)},this.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),this.isRecording=!0,this.emit("recordingStarted"),t.n=7;break;case 6:throw t.p=6,a=t.v,r=a.message,"NotAllowedError"===a.name||"PermissionDeniedError"===a.name?(r="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"===a.name||"DevicesNotFoundError"===a.name?(r="No microphone found. Please connect a microphone and try again.",console.error("❌ AudioRecorder: No microphone device found.")):"NotReadableError"===a.name||"TrackStartError"===a.name?(r="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.")):a.message&&a.message.includes("not allowed by the user agent")&&(r="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.")),(i=new Error(r)).name=a.name,i.originalError=a,console.error("❌ AudioRecorder: Failed to start recording:",i),this.emit("error",i),i;case 7:return t.a(2)}},t,this,[[0,6]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:(r=z(M().m(function t(){var e;return M().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.isRecording){t.n=1;break}return t.a(2);case 1:if(t.p=1,!this.audioWorkletNode){t.n=2;break}return this.audioWorkletNode.port.postMessage({type:"flush"}),t.n=2,new Promise(function(t){return setTimeout(t,100)});case 2:if(this.mediaStream&&(this.mediaStream.getTracks().forEach(function(t){return t.stop()}),this.mediaStream=null),!this.audioContext||"closed"===this.audioContext.state){t.n=4;break}return t.n=3,this.audioContext.close();case 3:this.audioContext=null;case 4:this.audioWorkletNode=null,this.isRecording=!1,this.emit("recordingStopped"),t.n=6;break;case 5:throw t.p=5,e=t.v,this.emit("error",e),e;case 6:return t.a(2)}},t,this,[[1,5]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop()}}],o&&L(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(l);function Q(t){return Q="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Q(t)}function Y(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,$(o.key),o)}}function $(t){var e=function(t){if("object"!=Q(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Q(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Q(e)?e:e+""}const J=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}return e=t,n=[{key:"extractPcmFromWav",value:function(t){var e=t instanceof Uint8Array?t:new Uint8Array(t);if(e.length<44)throw new Error("WAV data too short (< 44 bytes)");if("RIFF"!==String.fromCharCode(e[0],e[1],e[2],e[3]))throw new Error("Not a valid WAV file - missing RIFF header");if("WAVE"!==String.fromCharCode(e[8],e[9],e[10],e[11]))throw new Error("Not a valid WAV file - missing WAVE format");for(var n=e[22]|e[23]<<8,o=e[24]|e[25]<<8|e[26]<<16|e[27]<<24,r=e[34]|e[35]<<8,i=-1,a=12;a<e.length-8;a+=4){if("data"===String.fromCharCode(e[a],e[a+1],e[a+2],e[a+3])){i=a;break}a+=4+(e[a+4]|e[a+5]<<8|e[a+6]<<16|e[a+7]<<24)}if(-1===i)throw new Error("No data chunk found in WAV");var s=e[i+4]|e[i+5]<<8|e[i+6]<<16|e[i+7]<<24,c=i+8,l=Math.min(s,e.length-c);return{pcmData:e.slice(c,c+l).buffer,format:{sampleRate:o,channels:n,bitDepth:r}}}},{key:"isWavFile",value:function(t){return t.length>=44&&82===t[0]&&73===t[1]&&70===t[2]&&70===t[3]}},{key:"createWavHeader",value:function(t,e,n,o){var r=new ArrayBuffer(44),i=new DataView(r);return i.setUint32(0,1380533830,!1),i.setUint32(4,36+t,!0),i.setUint32(8,1463899717,!1),i.setUint32(12,1718449184,!1),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,n,!0),i.setUint32(24,e,!0),i.setUint32(28,e*n*o/8,!0),i.setUint16(32,n*o/8,!0),i.setUint16(34,o,!0),i.setUint32(36,1684108385,!1),i.setUint32(40,t,!0),r}},{key:"wrapPcmInWav",value:function(e,n){var o=t.createWavHeader(e.byteLength,n.sampleRate,n.channels||1,n.bitDepth||16),r=new Uint8Array(o.byteLength+e.byteLength);return r.set(new Uint8Array(o),0),r.set(new Uint8Array(e),o.byteLength),r.buffer}}],null&&Y(e.prototype,null),n&&Y(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,n}();function X(t){return X="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},X(t)}function Z(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,tt(o.key),o)}}function tt(t){var e=function(t){if("object"!=X(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=X(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==X(e)?e:e+""}const et=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.codecs={pcm:new f,pcmu:new m,pcma:new S}},(e=[{key:"decodeToPcm",value:function(t,e){var n=null==e?void 0:e.toLowerCase();if(!n||"pcm"===n)return t instanceof ArrayBuffer?t:t instanceof Uint8Array?t.buffer:t;var o=this.codecs[n];if(!o)throw new Error("Unsupported encoding: ".concat(e));var r=t instanceof Uint8Array?t:new Uint8Array(t);return o.decode(r)}},{key:"encodeFromPcm",value:function(t,e){var n=null==e?void 0:e.toLowerCase();if(!n||"pcm"===n)return t;var o=this.codecs[n];if(!o)throw new Error("Unsupported target encoding: ".concat(e));var r=o.encode(t);return r instanceof Uint8Array?r.buffer:r}},{key:"getCodec",value:function(t){var e=null==t?void 0:t.toLowerCase();return this.codecs[e]||null}}])&&Z(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function nt(t){return nt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nt(t)}function ot(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,rt(o.key),o)}}function rt(t){var e=function(t){if("object"!=nt(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=nt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==nt(e)?e:e+""}const it=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}return e=t,n=[{key:"convert",value:function(e,n,o){if(n===o)return e;if(8===n)throw new Error("Source bit depth cannot be 8-bit (only 16-bit or 24-bit supported)");var r=n/8,i=o/8,a=e.byteLength/r;if(new ArrayBuffer(a*i),16===n&&16===o)return e;if(24===n&&16===o)return t.convert24To16(e);if(16===n&&24===o)return t.convert16To24(e);if(16===n&&8===o)return t.convert16To8(e);if(24===n&&8===o)return t.convert24To8(e);throw new Error("Unsupported bit depth conversion: ".concat(n,"-bit → ").concat(o,"-bit"))}},{key:"convert24To16",value:function(t){for(var e=new Uint8Array(t),n=Math.floor(e.length/3),o=new Int16Array(n),r=0;r<n;r++){var i=e[3*r],a=e[3*r+1],s=e[3*r+2],c=i|a<<8|(255&s)<<16;128&s&&(c|=4278190080),o[r]=Math.max(-32768,Math.min(32767,Math.round(c/256)))}return o.buffer}},{key:"convert16To24",value:function(t){for(var e=new Int16Array(t),n=new Uint8Array(3*e.length),o=0;o<e.length;o++){var r=256*e[o];n[3*o]=255&r,n[3*o+1]=r>>8&255,n[3*o+2]=r>>16&255}return n.buffer}},{key:"convert16To8",value:function(t){for(var e=new Int16Array(t),n=new Uint8Array(e.length),o=0;o<e.length;o++){var r=e[o];n[o]=Math.max(0,Math.min(255,Math.round(r/256+128)))}return n.buffer}},{key:"convert24To8",value:function(e){var n=t.convert24To16(e);return t.convert16To8(n)}}],null&&ot(e.prototype,null),n&&ot(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,n}();function at(t){return at="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},at(t)}function st(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return ct(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(ct(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,ct(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,ct(d,"constructor",l),ct(l,"constructor",c),c.displayName="GeneratorFunction",ct(l,r,"GeneratorFunction"),ct(d),ct(d,r,"Generator"),ct(d,o,function(){return this}),ct(d,"toString",function(){return"[object Generator]"}),(st=function(){return{w:i,m:p}})()}function ct(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}ct=function(t,e,n,o){function i(e,n){ct(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},ct(t,e,n,o)}function lt(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function ut(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,dt(o.key),o)}}function dt(t){var e=function(t){if("object"!=at(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=at(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==at(e)?e:e+""}const pt=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)},e=[{key:"resample",value:(n=st().m(function t(e,n,o){var r,i,a,s,c,l,u,d,p,f,h,g,v;return st().w(function(t){for(;;)switch(t.n){case 0:if(n!==o){t.n=1;break}return t.a(2,e);case 1:for(r=new Int16Array(e),i=new Float32Array(r.length),a=1/32768,s=0;s<r.length;s++)i[s]=r[s]*a;return c=Math.ceil(i.length*o/n),l=new OfflineAudioContext(1,c,o),(u=l.createBuffer(1,i.length,n)).getChannelData(0).set(i),(d=l.createBufferSource()).buffer=u,d.connect(l.destination),d.start(),t.n=2,l.startRendering();case 2:for(p=t.v,f=p.getChannelData(0),h=new Int16Array(f.length),g=0;g<f.length;g++)v=Math.max(-1,Math.min(1,f[g])),h[g]=Math.round(32767*v);return t.a(2,h.buffer)}},t)}),o=function(){var t=this,e=arguments;return new Promise(function(o,r){var i=n.apply(t,e);function a(t){lt(i,o,r,a,s,"next",t)}function s(t){lt(i,o,r,a,s,"throw",t)}a(void 0)})},function(t,e,n){return o.apply(this,arguments)})}],e&&ut(t,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();function ft(t){return ft="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ft(t)}function ht(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,gt(o.key),o)}}function gt(t){var e=function(t){if("object"!=ft(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=ft(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==ft(e)?e:e+""}const vt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t)}return e=t,n=[{key:"convert",value:function(e,n,o){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:16;if(n===o)return e;if(1===n&&1===o)return e;if(1===n&&2===o)return t.monoToStereo(e,r);if(2===n&&1===o)return t.stereoToMono(e,r);throw new Error("Unsupported channel conversion: ".concat(n," → ").concat(o))}},{key:"monoToStereo",value:function(t,e){for(var n=e/8,o=t.byteLength/n,r=new ArrayBuffer(o*n*2),i=new Uint8Array(t),a=new Uint8Array(r),s=0;s<o;s++)for(var c=s*n,l=s*n*2,u=0;u<n;u++)a[l+u]=i[c+u],a[l+n+u]=i[c+u];return r}},{key:"stereoToMono",value:function(t,e){var n=e/8,o=t.byteLength/(2*n),r=new ArrayBuffer(o*n),i=new Uint8Array(t),a=new Uint8Array(r);if(16===e)for(var s=0;s<o;s++){var c=s*n*2,l=c+n,u=(i[c]|i[c+1]<<8)<<16>>16,d=(i[l]|i[l+1]<<8)<<16>>16,p=Math.round((u+d)/2),f=s*n;a[f]=255&p,a[f+1]=p>>8&255}else for(var h=0;h<o;h++)for(var g=h*n*2,v=h*n,m=0;m<n;m++)a[v+m]=i[g+m];return r}}],null&&ht(e.prototype,null),n&&ht(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,n}();function mt(t){return mt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},mt(t)}function yt(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return bt(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(bt(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,bt(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,bt(d,"constructor",l),bt(l,"constructor",c),c.displayName="GeneratorFunction",bt(l,r,"GeneratorFunction"),bt(d),bt(d,r,"Generator"),bt(d,o,function(){return this}),bt(d,"toString",function(){return"[object Generator]"}),(yt=function(){return{w:i,m:p}})()}function bt(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}bt=function(t,e,n,o){function i(e,n){bt(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},bt(t,e,n,o)}function wt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function St(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?wt(Object(n),!0).forEach(function(e){xt(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):wt(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function xt(t,e,n){return(e=Pt(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function kt(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Ct(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Pt(o.key),o)}}function Pt(t){var e=function(t){if("object"!=mt(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=mt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==mt(e)?e:e+""}const Tt=function(){return t=function t(e,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.requestedFormat=e,this.actualFormat=n,this.encodingConverter=new et,this.conversionSteps=[],this._analyzeConversions()},e=[{key:"_analyzeConversions",value:function(){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")}},{key:"needsConversion",value:function(){return this.conversionSteps.length>0}},{key:"getConversionSteps",value:function(){var t=[];return this.conversionSteps.includes("extract_wav")&&t.push("Extract PCM from WAV (".concat(this.actualFormat.container," → raw)")),this.conversionSteps.includes("decode_encoding")&&t.push("Decode ".concat(this.actualFormat.encoding.toUpperCase()," → PCM")),this.conversionSteps.includes("resample")&&t.push("Resample ".concat(this.actualFormat.sampleRate,"Hz → ").concat(this.requestedFormat.sampleRate,"Hz")),this.conversionSteps.includes("convert_bitdepth")&&t.push("Convert bit depth ".concat(this.actualFormat.bitDepth,"-bit → ").concat(this.requestedFormat.bitDepth,"-bit")),this.conversionSteps.includes("convert_channels")&&t.push("Convert channels ".concat(this.actualFormat.channels," → ").concat(this.requestedFormat.channels)),this.conversionSteps.includes("encode_encoding")&&t.push("Encode PCM → ".concat(this.requestedFormat.encoding.toUpperCase())),this.conversionSteps.includes("wrap_wav")&&t.push("Wrap in WAV container (raw → ".concat(this.requestedFormat.container,")")),t}},{key:"convert",value:(n=yt().m(function t(e){var n,o,r,i;return yt().w(function(t){for(;;)switch(t.n){case 0:if(this.needsConversion()){t.n=1;break}return t.a(2,e instanceof ArrayBuffer?e:e.buffer);case 1:if(n=e instanceof ArrayBuffer?e:e.buffer,o=St({},this.actualFormat),this.conversionSteps.includes("extract_wav")&&(r=J.extractPcmFromWav(n),n=r.pcmData,o=St(St({},o),{},{container:"raw",sampleRate:r.format.sampleRate,channels:r.format.channels,bitDepth:r.format.bitDepth}),console.log("🔄 AudioFormatConverter: Extracted PCM from WAV",r.format)),this.conversionSteps.includes("decode_encoding")&&(n=this.encodingConverter.decodeToPcm(n,o.encoding),o.encoding="pcm",o.bitDepth=16,console.log("🔄 AudioFormatConverter: Decoded ".concat(this.actualFormat.encoding.toUpperCase()," → PCM"))),24===o.bitDepth&&o.bitDepth!==this.requestedFormat.bitDepth&&(this.conversionSteps.includes("resample")||this.conversionSteps.includes("convert_channels")||24!==this.requestedFormat.bitDepth)&&(n=it.convert(n,24,16),o.bitDepth=16,console.log("🔄 AudioFormatConverter: Normalized 24-bit → 16-bit PCM")),!this.conversionSteps.includes("resample")){t.n=3;break}return t.n=2,pt.resample(n,o.sampleRate,this.requestedFormat.sampleRate);case 2:n=t.v,o.sampleRate=this.requestedFormat.sampleRate,console.log("🔄 AudioFormatConverter: Resampled ".concat(this.actualFormat.sampleRate,"Hz → ").concat(this.requestedFormat.sampleRate,"Hz"));case 3:return this.conversionSteps.includes("convert_channels")&&(n=vt.convert(n,o.channels,this.requestedFormat.channels,o.bitDepth),o.channels=this.requestedFormat.channels,console.log("🔄 AudioFormatConverter: Converted channels ".concat(this.actualFormat.channels," → ").concat(this.requestedFormat.channels))),this.conversionSteps.includes("convert_bitdepth")&&(n=it.convert(n,o.bitDepth,this.requestedFormat.bitDepth),o.bitDepth=this.requestedFormat.bitDepth,console.log("🔄 AudioFormatConverter: Converted bit depth ".concat(this.actualFormat.bitDepth,"-bit → ").concat(this.requestedFormat.bitDepth,"-bit"))),this.conversionSteps.includes("encode_encoding")&&(i=this.encodingConverter.encodeFromPcm(n,this.requestedFormat.encoding),n=i instanceof ArrayBuffer?i:i.buffer,o.encoding=this.requestedFormat.encoding,console.log("🔄 AudioFormatConverter: Encoded PCM → ".concat(this.requestedFormat.encoding.toUpperCase()))),this.conversionSteps.includes("wrap_wav")&&(n=J.wrapPcmInWav(n,o),o.container="wav",console.log("🔄 AudioFormatConverter: Wrapped in WAV container")),console.log("✅ AudioFormatConverter: Conversion complete"),t.a(2,n)}},t,this)}),o=function(){var t=this,e=arguments;return new Promise(function(o,r){var i=n.apply(t,e);function a(t){kt(i,o,r,a,s,"next",t)}function s(t){kt(i,o,r,a,s,"throw",t)}a(void 0)})},function(t){return o.apply(this,arguments)})}],e&&Ct(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();function Et(t){return Et="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Et(t)}function Ot(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return At(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(At(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,At(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,At(d,"constructor",l),At(l,"constructor",c),c.displayName="GeneratorFunction",At(l,r,"GeneratorFunction"),At(d),At(d,r,"Generator"),At(d,o,function(){return this}),At(d,"toString",function(){return"[object Generator]"}),(Ot=function(){return{w:i,m:p}})()}function At(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}At=function(t,e,n,o){function i(e,n){At(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},At(t,e,n,o)}function It(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Rt(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Ft(o.key),o)}}function Ft(t){var e=function(t){if("object"!=Et(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Et(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Et(e)?e:e+""}const jt=function(){return t=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return null};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.handlers=new Map,this.sendMessage=e,this.getConversationId=n},e=[{key:"registerHandler",value:function(t,e){if("function"!=typeof e)throw new Error("Handler for tool '".concat(t,"' must be a function"));this.handlers.set(t,e),console.log("🔧 ClientTools: Registered handler for '".concat(t,"'"))}},{key:"unregisterHandler",value:function(t){this.handlers.delete(t),console.log("🔧 ClientTools: Unregistered handler for '".concat(t,"'"))}},{key:"hasHandler",value:function(t){return this.handlers.has(t)}},{key:"getRegisteredTools",value:function(){return Array.from(this.handlers.keys())}},{key:"handleToolCall",value:(n=Ot().m(function t(e){var n,o,r,i,a,s,c,l,u,d,p,f,h;return Ot().w(function(t){for(;;)switch(t.p=t.n){case 0:if(n=e.toolCallId,o=e.toolName,r=e.parameters,i=Date.now(),a=(new Date).toISOString(),console.log("🔧 ClientTools: [".concat(a,"] Received tool call '").concat(o,"' (id: ").concat(n,")")),console.log(" 📋 Full message received:",JSON.stringify(e,null,2)),console.log(" ⏱️ Start time: ".concat(i,"ms (").concat(new Date(i).toISOString(),")")),s=this.handlers.get(o)){t.n=1;break}return console.warn("🔧 ClientTools: No handler registered for '".concat(o,"'")),this.sendError(n,o,"No handler registered for tool '".concat(o,"'"),"NO_HANDLER",i),t.a(2);case 1:return t.p=1,t.n=2,s(r);case 2:c=t.v,l=Date.now()-i,console.log("🔧 ClientTools: Tool '".concat(o,"' completed in ").concat(l,"ms")),this.sendResult(n,o,c,l),t.n=4;break;case 3:t.p=3,h=t.v,p=Date.now()-i,console.error("🔧 ClientTools: Tool '".concat(o,"' failed:"),h),f="EXECUTION_ERROR","NotAllowedError"===h.name||null!==(u=h.message)&&void 0!==u&&u.includes("permission")?f="PERMISSION_DENIED":("NotSupportedError"===h.name||null!==(d=h.message)&&void 0!==d&&d.includes("not supported"))&&(f="API_UNAVAILABLE"),this.sendError(n,o,h.message||"Unknown error",f,p);case 4:return t.a(2)}},t,this,[[1,3]])}),o=function(){var t=this,e=arguments;return new Promise(function(o,r){var i=n.apply(t,e);function a(t){It(i,o,r,a,s,"next",t)}function s(t){It(i,o,r,a,s,"throw",t)}a(void 0)})},function(t){return o.apply(this,arguments)})},{key:"sendResult",value:function(t,e,n,o){var r=this.getConversationId(),i=(new Date).toISOString(),a={t:"client_tool_result",toolCallId:t,toolName:e,conversationId:r,result:n,executionTimeMs:o};console.log("🔧 ClientTools: [".concat(i,"] Sending result for tool '").concat(e,"'")),console.log(" 📋 toolCallId: ".concat(t)),console.log(" 📋 conversationId: ".concat(r||"null")),console.log(" 📋 toolName: ".concat(e)),console.log(" 📋 result:",n),console.log(" 📋 Full message:",JSON.stringify(a,null,2)),this.sendMessage(a),console.log("✅ ClientTools: Result message sent at ".concat(i))}},{key:"sendError",value:function(t,e,n,o,r){var i="number"==typeof r?Date.now()-r:r,a=(new Date).toISOString(),s=this.getConversationId(),c={t:"client_tool_error",toolCallId:t,toolName:e,conversationId:s,error:n,errorCode:o,executionTimeMs:i};console.log("🔧 ClientTools: [".concat(a,"] Sending error for tool '").concat(e,"'")),console.log(" 📋 toolCallId: ".concat(t)),console.log(" 📋 conversationId: ".concat(s||"null")),console.log(" 📋 toolName: ".concat(e)),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))}},{key:"setSendMessage",value:function(t){this.sendMessage=t}}],e&&Rt(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();function Dt(t){return Dt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Dt(t)}function _t(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function Bt(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?_t(Object(n),!0).forEach(function(e){Wt(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):_t(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function Mt(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Ut(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Ut(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Ut(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Ut(d,"constructor",l),Ut(l,"constructor",c),c.displayName="GeneratorFunction",Ut(l,r,"GeneratorFunction"),Ut(d),Ut(d,r,"Generator"),Ut(d,o,function(){return this}),Ut(d,"toString",function(){return"[object Generator]"}),(Mt=function(){return{w:i,m:p}})()}function Ut(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Ut=function(t,e,n,o){function i(e,n){Ut(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Ut(t,e,n,o)}function Nt(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function zt(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){Nt(i,o,r,a,s,"next",t)}function s(t){Nt(i,o,r,a,s,"throw",t)}a(void 0)})}}function Ht(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Gt(o.key),o)}}function Lt(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(Lt=function(){return!!t})()}function Kt(t){return Kt=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Kt(t)}function Vt(t,e){return Vt=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},Vt(t,e)}function Wt(t,e,n){return(e=Gt(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Gt(t){var e=function(t){if("object"!=Dt(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Dt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Dt(e)?e:e+""}var qt=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(t=function(t,e,n){return e=Kt(e),function(t,e){if(e&&("object"==Dt(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,Lt()?Reflect.construct(e,n||[],Kt(t).constructor):e.apply(t,n))}(this,e)).version="2.0.0",t.config={signedUrl:n.signedUrl||n.websocketUrl||"wss://speech.talktopc.com/ws/conv",websocketUrl:n.signedUrl||n.websocketUrl||"wss://speech.talktopc.com/ws/conv",agentId:n.agentId,appId:n.appId,sampleRate:n.sampleRate||16e3,channels:n.channels||1,bitDepth:n.bitDepth||16,audioProcessorPath:n.audioProcessorPath,outputContainer:n.outputContainer||t.getDefaultContainer(n),outputEncoding:n.outputEncoding||n.outputCodec||"pcm",outputSampleRate:n.outputSampleRate||16e3,outputChannels:n.outputChannels||1,outputBitDepth:n.outputBitDepth||16,outputFrameDurationMs:n.outputFrameDurationMs||600,outputCodec:n.outputCodec,agentSettingsOverride:n.agentSettingsOverride||null,variables:n.variables||null,autoReconnect:!1!==n.autoReconnect,protocolVersion:n.protocolVersion||2},t.isConnected=!1,t.hasEverConnected=!1,t.isRecording=!1,t.isPlaying=!1,t.isDestroyed=!1,t.outputAudioFormat=null,t.requestedOutputFormat=null,t.formatConverter=null,t.websocket=null,t.conversationId=null,t.transcriptQueue=[],t.currentPlayingSentenceId=null,t.audioFrameCount=0,t.audioPlayer=new _(t.config),t.audioRecorder=new q(t.config),t.setupAudioPlayerEvents(),t.setupAudioRecorderEvents(),t.clientToolsRegistry=new jt(function(e){return t.sendMessage(e)},function(){return t.conversationId}),t.validateConfig(),console.log("🎵 VoiceSDK v2 initialized:",{version:t.version,outputContainer:t.config.outputContainer,outputEncoding:t.config.outputEncoding,outputSampleRate:t.config.outputSampleRate}),t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Vt(t,e)}(e,t),n=e,o=[{key:"getDefaultContainer",value:function(t){return"wav"===t.outputCodec?"wav":"raw"}},{key:"validateInputFormat",value:function(t){var n;if(!t)return"Input format is required";var o=null===(n=t.encoding)||void 0===n?void 0:n.toLowerCase();return o&&e.SUPPORTED_INPUT_ENCODINGS.includes(o)?t.sampleRate&&e.SUPPORTED_INPUT_SAMPLE_RATES.includes(t.sampleRate)?t.bitDepth&&e.SUPPORTED_INPUT_BIT_DEPTHS.includes(t.bitDepth)?t.channels&&e.SUPPORTED_INPUT_CHANNELS.includes(t.channels)?null:"Unsupported input channels: ".concat(t.channels,". Supported: ").concat(e.SUPPORTED_INPUT_CHANNELS.join(", ")):"Unsupported input bit depth: ".concat(t.bitDepth,". Supported: ").concat(e.SUPPORTED_INPUT_BIT_DEPTHS.join(", ")):"Unsupported input sample rate: ".concat(t.sampleRate,". Supported: ").concat(e.SUPPORTED_INPUT_SAMPLE_RATES.join(", ")):"Unsupported input encoding: ".concat(t.encoding,". Supported: ").concat(e.SUPPORTED_INPUT_ENCODINGS.join(", "))}},{key:"validateOutputFormat",value:function(t){var n,o;if(!t)return"Output format is required";var r=null===(n=t.encoding)||void 0===n?void 0:n.toLowerCase();if(!r||!e.SUPPORTED_OUTPUT_ENCODINGS.includes(r))return"Unsupported output encoding: ".concat(t.encoding,". Supported: ").concat(e.SUPPORTED_OUTPUT_ENCODINGS.join(", "));if(!t.sampleRate||!e.SUPPORTED_OUTPUT_SAMPLE_RATES.includes(t.sampleRate))return"Unsupported output sample rate: ".concat(t.sampleRate,". Supported: ").concat(e.SUPPORTED_OUTPUT_SAMPLE_RATES.join(", "));if(!t.bitDepth||!e.SUPPORTED_OUTPUT_BIT_DEPTHS.includes(t.bitDepth))return"Unsupported output bit depth: ".concat(t.bitDepth,". Supported: ").concat(e.SUPPORTED_OUTPUT_BIT_DEPTHS.join(", "));if(!t.channels||!e.SUPPORTED_OUTPUT_CHANNELS.includes(t.channels))return"Unsupported output channels: ".concat(t.channels,". Supported: ").concat(e.SUPPORTED_OUTPUT_CHANNELS.join(", "));var i=null===(o=t.container)||void 0===o?void 0:o.toLowerCase();return i&&e.SUPPORTED_OUTPUT_CONTAINERS.includes(i)?null:"Unsupported output container: ".concat(t.container,". Supported: ").concat(e.SUPPORTED_OUTPUT_CONTAINERS.join(", "))}},{key:"validateConfig",value:function(){var t={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},e=this.validateInputFormat(t);if(e)return console.error("❌ VoiceSDK v2: Invalid input format:",e),void this.emit("error",new Error(e));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")}},{key:"setupAudioPlayerEvents",value:function(){var t=this;this.audioPlayer.on("playbackStarted",function(){t.isPlaying=!0,t.emit("playbackStarted"),t.isConnected?(console.log("📤 VoiceSDK v2: Sending audio_started_playing message to server"),t.sendMessage({t:"audio_started_playing"})):console.warn("⚠️ VoiceSDK v2: Cannot send audio_started_playing - not connected")}),this.audioPlayer.on("transcriptDisplay",function(e){var n=t.currentPlayingSentenceId?t.currentPlayingSentenceId+1:1;t.currentPlayingSentenceId=n;var o={text:e.text,role:"assistant",sentenceId:n,final:!0,timestamp:Date.now()};console.log("📝 VoiceSDK v2: Emitting synced transcriptDisplay from AudioPlayer:",o),t.emit("transcriptDisplay",o),t.emit("transcript",o)}),this.audioPlayer.on("playbackStopped",function(){t.isPlaying=!1,t.emit("playbackStopped"),t.isConnected?(console.log("📤 VoiceSDK v2: Sending audio_stopped_playing message to server"),t.sendMessage({t:"audio_stopped_playing"})):console.warn("⚠️ VoiceSDK v2: Cannot send audio_stopped_playing - not connected")}),this.audioPlayer.on("playbackError",function(e){t.emit("playbackError",e),t.emit("error",e)})}},{key:"setupAudioRecorderEvents",value:function(){var t=this;this.audioRecorder.on("recordingStarted",function(){t.isRecording=!0,t.emit("recordingStarted")}),this.audioRecorder.on("recordingStopped",function(){t.isRecording&&(t.isRecording=!1,t.emit("recordingStopped"),console.log("🛑 VoiceSDK v2: Recording stopped (from audioRecorder event)"))}),this.audioRecorder.on("audioData",function(e){t.isConnected&&t.sendBinary(e)}),this.audioRecorder.on("error",function(e){console.error("❌ AudioRecorder error:",e),t.emit("error",e)})}},{key:"buildWebSocketUrl",value:function(){var t=this.config.signedUrl||this.config.websocketUrl,e=new URLSearchParams;if(this.config.agentId&&e.append("agentId",this.config.agentId),this.config.appId&&e.append("appId",this.config.appId),e.toString()){var n=t.includes("?")?"&":"?";return"".concat(t).concat(n).concat(e.toString())}return t}},{key:"connect",value:(l=zt(Mt().m(function t(){var e,n,o=this;return Mt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isDestroyed){t.n=1;break}return console.warn("VoiceSDK v2: Cannot connect - SDK is destroyed"),t.a(2,!1);case 1:if(!this.isConnected){t.n=2;break}return console.warn("VoiceSDK v2: Already connected"),t.a(2,!0);case 2:return t.p=2,e=this.buildWebSocketUrl(),console.log("🔌 VoiceSDK v2: Connecting to",e),t.n=3,new Promise(function(t,n){o.websocket=new WebSocket(e),o.websocket.onopen=function(){console.log("✅ VoiceSDK v2: WebSocket connected"),o.isConnected=!0,o.hasEverConnected=!0,o.clientToolsRegistry&&o.clientToolsRegistry.setSendMessage(function(t){return o.sendMessage(t)}),o.sendHelloMessage(),o.emit("connected"),t(!0)},o.websocket.onerror=function(t){console.error("❌ VoiceSDK v2: WebSocket error:",t),n(t)},o.websocket.onclose=function(t){console.log("🔌 VoiceSDK v2: WebSocket closed:",t.code,t.reason),o.isConnected=!1,o.isRecording&&o.stopRecording().catch(function(t){return console.error("Error stopping recording:",t)}),o.emit("disconnected",t),o.config.autoReconnect&&!o.isDestroyed&&o.hasEverConnected?(console.log("🔄 VoiceSDK v2: Auto-reconnecting in 3s..."),setTimeout(function(){o.isDestroyed||o.isConnected||o.connect()},3e3)):o.config.autoReconnect&&!o.hasEverConnected&&console.log("⚠️ VoiceSDK v2: Initial connection failed. Auto-reconnect disabled to prevent retry loop.")},o.websocket.onmessage=function(t){o.handleMessage(t)}});case 3:return t.a(2,t.v);case 4:return t.p=4,n=t.v,console.error("🔌 VoiceSDK v2: Connection failed:",n),this.emit("error",n),t.a(2,!1)}},t,this,[[2,4]])})),function(){return l.apply(this,arguments)})},{key:"sendHelloMessage",value:function(){if(this.isConnected){var t={encoding:"pcm",sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth},e={encoding:this.config.outputEncoding,sampleRate:this.config.outputSampleRate,channels:this.config.outputChannels,bitDepth:this.config.outputBitDepth,container:this.config.outputContainer},n=this.validateInputFormat(t);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(e);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 r={t:"hello",v:this.config.protocolVersion,inputFormat:t,requestedOutputFormat:e,outputFrameDurationMs:this.config.outputFrameDurationMs};this.config.agentSettingsOverride&&(r.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?(r.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:r.v,requestedFormat:r.requestedOutputFormat,variables:r.variables?Object.keys(r.variables):void 0}),console.log("📤 VoiceSDK v2: Requested output format:",{container:r.requestedOutputFormat.container,encoding:r.requestedOutputFormat.encoding,sampleRate:r.requestedOutputFormat.sampleRate,bitDepth:r.requestedOutputFormat.bitDepth}),console.log("📤 VoiceSDK v2: Full hello message being sent:",JSON.stringify(r,null,2));try{this.sendMessage(r)}catch(t){console.error("VoiceSDK v2: Failed to send hello:",t),this.emit("error",t)}}else console.warn("VoiceSDK v2: Cannot send hello - not connected")}},{key:"handleMessage",value:function(t){if(t.data instanceof ArrayBuffer||t.data instanceof Blob)this.handleBinaryMessage(t.data);else try{var e=JSON.parse(t.data);switch("audio"!==e.t&&console.log("📥 VoiceSDK v2: Received message type:",e.t,"Full message:",JSON.stringify(e).substring(0,200)),!this.conversationId&&e.conversationId&&(this.conversationId=e.conversationId,console.log("🔍 VoiceSDK v2: Captured conversationId from message:",this.conversationId),this.emit("conversationIdChanged",this.conversationId)),"audio"!==e.t&&console.log("📨 VoiceSDK v2: Received message type:",e.t,e),e.t){case"hello_ack":this.handleHelloAck(e);break;case"transcript":console.log("📝 VoiceSDK v2: Processing transcript message:",e),this.handleTranscript(e);break;case"user_transcript":console.log("📝 VoiceSDK v2: Received user_transcript:",e),this.emit("message",e);break;case"agent_response":if(console.log("📝 VoiceSDK v2: Received agent_response:",e),(e.text||e.transcript)&&(console.log("📝 VoiceSDK v2: agent_response contains transcript data:",e.text||e.transcript),e.sentenceId&&(e.text||e.transcript))){var n={t:"transcript",sentenceId:e.sentenceId,text:e.text||e.transcript,role:e.role||"assistant",final:!1!==e.final,timestamp:e.timestamp||Date.now()};console.log("📝 VoiceSDK v2: Converting agent_response to transcript:",n),this.handleTranscript(n)}this.emit("message",e);break;case"error":this.emit("message",e);break;case"barge_in":this.emit("bargeIn",e),this.stopAudioPlayback();break;case"stop_playing":this.emit("stopPlaying",e),this.stopAudioPlayback();break;case"audio_start":console.log("📝 VoiceSDK v2: Received audio_start with text:",e.text),e.text&&this.audioPlayer&&this.audioPlayer.markNewSentence(e.text),this.emit("message",e);break;case"client_tool_call":this.clientToolsRegistry.handleToolCall(e);break;default:if(console.log("VoiceSDK v2: Unknown message type:",e.t,"Full message:",JSON.stringify(e).substring(0,300)),(e.text||e.transcript||e.transcription)&&(console.log("📝 VoiceSDK v2: Unknown message contains transcript-like data:",{text:e.text,transcript:e.transcript,transcription:e.transcription,sentenceId:e.sentenceId,role:e.role}),e.sentenceId&&(e.text||e.transcript||e.transcription))){var o={t:"transcript",sentenceId:e.sentenceId,text:e.text||e.transcript||e.transcription,role:e.role||"assistant",final:!1!==e.final,timestamp:e.timestamp||Date.now()};console.log("📝 VoiceSDK v2: Attempting to process unknown message as transcript:",o),this.handleTranscript(o)}this.emit("message",e)}}catch(t){console.error("VoiceSDK v2: Error parsing message:",t)}}},{key:"handleHelloAck",value:function(t){if(console.log("📥 VoiceSDK v2: Received hello_ack:",{hasOutputFormat:!!t.outputAudioFormat,outputFormat:t.outputAudioFormat,hasConversationId:!!t.conversationId,messageType:t.t}),t.conversationId&&(this.conversationId=t.conversationId,console.log("🔍 VoiceSDK v2: Received conversationId:",this.conversationId),this.emit("conversationIdChanged",this.conversationId)),t.outputAudioFormat){this.outputAudioFormat=t.outputAudioFormat,this.audioPlayer.setOutputFormat(t.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 e={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!==e.container&&n.push('container: "'.concat(this.requestedOutputFormat.container,'" → "').concat(e.container,'"')),this.requestedOutputFormat.encoding!==e.encoding&&n.push('encoding: "'.concat(this.requestedOutputFormat.encoding,'" → "').concat(e.encoding,'"')),this.requestedOutputFormat.sampleRate!==e.sampleRate&&n.push("sampleRate: ".concat(this.requestedOutputFormat.sampleRate,"Hz → ").concat(e.sampleRate,"Hz")),this.requestedOutputFormat.bitDepth!==e.bitDepth&&n.push("bitDepth: ".concat(this.requestedOutputFormat.bitDepth,"-bit → ").concat(e.bitDepth,"-bit")),this.requestedOutputFormat.channels!==e.channels&&n.push("channels: ".concat(this.requestedOutputFormat.channels," → ").concat(e.channels)),n.length>0){console.warn("⚠️ VoiceSDK v2: Format negotiation mismatch!"),console.warn(" Requested:",this.requestedOutputFormat),console.warn(" Negotiated:",e),console.warn(" Differences:",n.join(", "));try{if(this.formatConverter=new Tt(this.requestedOutputFormat,e),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(t){console.error("❌ VoiceSDK v2: Failed to create format converter:",t),console.warn(" Will use backend format without conversion"),this.formatConverter=null}}else console.log("✅ VoiceSDK v2: Format perfectly matched!",e),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 r={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=r,this.requestedOutputFormat=r,this.audioPlayer.setOutputFormat(r),this.formatConverter=null}}},{key:"handleTranscript",value:function(t){if(t.sentenceId&&t.text){var e=t.sentenceId,n={text:t.text,role:t.role||"assistant",sentenceId:e,final:!1!==t.final,timestamp:t.timestamp||Date.now()};this.transcriptQueue.push(n),console.log("📝 VoiceSDK v2: Received transcript for sentence",e,":",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",e),this.emit("transcriptDisplay",n),this.currentPlayingSentenceId=e,this.emit("transcript",n)}else console.warn("⚠️ VoiceSDK v2: Invalid transcript message:",t)}},{key:"handleBinaryMessage",value:(c=zt(Mt().m(function t(e){var n,o,r,i,a,s,c,l,u;return Mt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!(e instanceof Blob)){t.n=2;break}return t.n=1,e.arrayBuffer();case 1:n=t.v,t.n=3;break;case 2:n=e;case 3:if(o=n,!this.formatConverter||!this.formatConverter.needsConversion()){t.n=7;break}return t.p=4,t.n=5,this.formatConverter.convert(n);case 5:o=t.v,console.log("✅ VoiceSDK v2: Audio converted to requested format"),t.n=7;break;case 6:t.p=6,u=t.v,console.error("❌ VoiceSDK v2: Format conversion failed:",u),console.warn(" Using backend format without conversion"),o=n;case 7:r=this.formatConverter&&this.formatConverter.needsConversion()?this.requestedOutputFormat:this.outputAudioFormat||{container:this.config.outputContainer||"raw",encoding:this.config.outputEncoding||"pcm",sampleRate:this.config.outputSampleRate||16e3,bitDepth:this.config.outputBitDepth||16,channels:this.config.outputChannels||1},i=r.container||"raw",a=(r.encoding||"pcm").toLowerCase(),"raw"===i?(s=o,"pcm"!==a&&((c=this.audioPlayer.getCodec(a))?(l=c.decode(new Uint8Array(o)),s=l.buffer,console.log("🔄 VoiceSDK v2: Decoded ".concat(a.toUpperCase()," to PCM (").concat(l.byteLength," bytes)"))):console.warn("⚠️ VoiceSDK v2: No codec for ".concat(a,", treating as PCM"))),this.audioPlayer.outputFormat||(console.warn("⚠️ VoiceSDK v2: outputFormat not set on AudioPlayer, setting from playbackFormat"),this.audioPlayer.setOutputFormat(r)),this.audioFrameCount++,this.audioPlayer.playChunk(s)):(this.audioFrameCount++,this.audioPlayer.playAudio(o));case 8:return t.a(2)}},t,this,[[4,6]])})),function(t){return c.apply(this,arguments)})},{key:"sendMessage",value:function(t){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send message - not connected"),!1;try{var e=(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"!==t.t&&"client_tool_error"!==t.t||(console.log("📤 VoiceSDK v2: [".concat(e,"] Sending tool ").concat(t.t)),console.log(" 🔌 WebSocket state: ".concat(o," (").concat(n,")")),console.log(" 📋 toolCallId: ".concat(t.toolCallId)),console.log(" 📋 conversationId: ".concat(t.conversationId||"null")),console.log(" 📋 toolName: ".concat(t.toolName)),"client_tool_result"===t.t?console.log(" 📋 result:",t.result):console.log(" 📋 error: ".concat(t.error,", errorCode: ").concat(t.errorCode)),console.log(" 📋 Full message:",JSON.stringify(t,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 r=JSON.stringify(t);return this.websocket.send(r),"client_tool_result"!==t.t&&"client_tool_error"!==t.t||console.log("✅ VoiceSDK v2: [".concat(e,"] Tool ").concat(t.t," message sent successfully (").concat(r.length," bytes)")),!0}catch(t){return console.error("VoiceSDK v2: Error sending message:",t),this.emit("error",t),!1}}},{key:"sendBinary",value:function(t){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return console.warn("VoiceSDK v2: Cannot send audio - not connected"),!1;try{return this.websocket.send(t),!0}catch(t){return console.error("VoiceSDK v2: Error sending audio:",t),this.emit("error",t),!1}}},{key:"disconnect",value:function(){var t=this;if(!this.isDestroyed){var e;if(console.log("🔌 VoiceSDK v2: Disconnecting..."),this.isRecording&&(this.isRecording=!1,null===(e=this.audioRecorder)||void 0===e||e.stop().catch(function(t){return console.error("Error stopping recorder on disconnect:",t)}),this.emit("recordingStopped")),this.audioPlayer&&this.stopAudioPlayback(),this.websocket)if(this.websocket.readyState===WebSocket.OPEN)try{this.sendMessage({t:"hangup"}),setTimeout(function(){t.websocket&&(t.websocket.close(),t.websocket=null)},100)}catch(t){console.error("VoiceSDK v2: Error sending hangup message:",t),this.websocket.close(),this.websocket=null}else this.websocket.close(),this.websocket=null;this.isConnected=!1}}},{key:"startRecording",value:(s=zt(Mt().m(function t(){var e,n,o;return Mt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.isConnected){t.n=1;break}throw e=new Error("Not connected to voice server"),this.emit("error",e),e;case 1:if(!this.isRecording){t.n=2;break}return console.warn("VoiceSDK v2: Already recording"),t.a(2,!0);case 2:return console.log("🎤 VoiceSDK v2: Starting recording..."),t.p=3,console.log("🎤 VoiceSDK v2: Requesting microphone permission (mobile-friendly)..."),t.n=4,this.audioRecorder.start();case 4:return t.n=5,this.audioPlayer.resumeAudioContext();case 5:return this.sendMessage({t:"start_continuous_mode",ttpId:this.generateTtpId()}),t.a(2,!0);case 6:return t.p=6,o=t.v,console.error("❌ VoiceSDK v2: Failed to start recording:",o),"NotAllowedError"===o.name||"PermissionDeniedError"===o.name?((n=new Error("Microphone permission denied. Please allow microphone access in your browser settings and try again.")).name=o.name,n.originalError=o,this.emit("error",n)):this.emit("error",o),t.a(2,!1)}},t,this,[[3,6]])})),function(){return s.apply(this,arguments)})},{key:"stopRecording",value:(a=zt(Mt().m(function t(){var e;return Mt().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.isRecording){t.n=1;break}return console.warn("VoiceSDK v2: Not recording"),t.a(2,!0);case 1:return console.log("🛑 VoiceSDK v2: Stopping recording..."),t.p=2,this.sendMessage({t:"stop_continuous_mode",ttpId:this.generateTtpId()}),this.isRecording=!1,this.emit("recordingStopped"),console.log("🛑 VoiceSDK v2: Recording stopped (emitted before audioRecorder.stop())"),t.n=3,this.audioRecorder.stop();case 3:return this.stopAudioPlayback(),t.a(2,!0);case 4:return t.p=4,e=t.v,console.error("VoiceSDK v2: Error stopping recording:",e),this.emit("error",e),t.a(2,!1)}},t,this,[[2,4]])})),function(){return a.apply(this,arguments)})},{key:"toggleRecording",value:(i=zt(Mt().m(function t(){return Mt().w(function(t){for(;;)switch(t.n){case 0:if(!this.isRecording){t.n=2;break}return t.n=1,this.stopRecording();case 1:case 3:return t.a(2,t.v);case 2:return t.n=3,this.startRecording();case 4:return t.a(2)}},t,this)})),function(){return i.apply(this,arguments)})},{key:"clearTranscriptState",value:function(){this.currentPlayingSentenceId=null,console.log("📝 VoiceSDK v2: Cleared transcript state")}},{key:"stopAudioPlayback",value:function(){this.audioPlayer.stopImmediate(),this.clearTranscriptState()}},{key:"handleBargeIn",value:(r=zt(Mt().m(function t(){return Mt().w(function(t){for(;;)switch(t.n){case 0:if(this.stopAudioPlayback(),this.isRecording){t.n=1;break}return t.n=1,this.startRecording();case 1:return t.a(2)}},t,this)})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){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()}}},{key:"updateConfig",value:function(t){this.config=Bt(Bt({},this.config),t)}},{key:"generateTtpId",value:function(){return"sdk_"+Math.random().toString(36).substr(2,9)+"_"+Date.now()}},{key:"registerToolHandler",value:function(t,e){return this.clientToolsRegistry.registerHandler(t,e)}},{key:"unregisterToolHandler",value:function(t){return this.clientToolsRegistry.unregisterHandler(t)}},{key:"hasToolHandler",value:function(t){return this.clientToolsRegistry.hasHandler(t)}},{key:"getRegisteredTools",value:function(){return this.clientToolsRegistry.getRegisteredTools()}},{key:"destroy",value:function(){var t=this;this.isDestroyed||(console.log("🗑️ VoiceSDK v2: Destroying..."),this.disconnect(),this.isDestroyed=!0,this.audioPlayer&&this.audioPlayer.destroy(),this.audioRecorder&&this.audioRecorder.destroy(),this.clientToolsRegistry&&this.clientToolsRegistry.getRegisteredTools().forEach(function(e){return t.clientToolsRegistry.unregisterHandler(e)}),this.removeAllListeners())}}],o&&Ht(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a,s,c,l}(l);Wt(qt,"SUPPORTED_INPUT_ENCODINGS",["pcm","pcmu","pcma"]),Wt(qt,"SUPPORTED_INPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),Wt(qt,"SUPPORTED_INPUT_BIT_DEPTHS",[8,16,24]),Wt(qt,"SUPPORTED_INPUT_CHANNELS",[1]),Wt(qt,"SUPPORTED_OUTPUT_ENCODINGS",["pcm","pcmu","pcma"]),Wt(qt,"SUPPORTED_OUTPUT_SAMPLE_RATES",[8e3,16e3,22050,24e3,44100,48e3]),Wt(qt,"SUPPORTED_OUTPUT_BIT_DEPTHS",[8,16,24]),Wt(qt,"SUPPORTED_OUTPUT_CHANNELS",[1]),Wt(qt,"SUPPORTED_OUTPUT_CONTAINERS",["raw","wav"]);const Qt=qt;function Yt(t){return Yt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Yt(t)}function $t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Jt(o.key),o)}}function Jt(t){var e=function(t){if("object"!=Yt(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Yt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Yt(e)?e:e+""}var Xt=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.events={}},e=[{key:"on",value:function(t,e){this.events[t]||(this.events[t]=[]),this.events[t].push(e)}},{key:"off",value:function(t,e){this.events[t]&&(this.events[t]=this.events[t].filter(function(t){return t!==e}))}},{key:"emit",value:function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),o=1;o<e;o++)n[o-1]=arguments[o];this.events[t]&&this.events[t].forEach(function(e){try{e.apply(void 0,n)}catch(e){console.error("Error in event listener for ".concat(t,":"),e)}})}},{key:"removeAllListeners",value:function(t){t?delete this.events[t]:this.events={}}}],e&&$t(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function Zt(t){return Zt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Zt(t)}function te(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return ee(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(ee(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,ee(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,ee(d,"constructor",l),ee(l,"constructor",c),c.displayName="GeneratorFunction",ee(l,r,"GeneratorFunction"),ee(d),ee(d,r,"Generator"),ee(d,o,function(){return this}),ee(d,"toString",function(){return"[object Generator]"}),(te=function(){return{w:i,m:p}})()}function ee(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}ee=function(t,e,n,o){function i(e,n){ee(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},ee(t,e,n,o)}function ne(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function oe(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function re(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?oe(Object(n),!0).forEach(function(e){ie(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):oe(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function ie(t,e,n){return(e=se(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function ae(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,se(o.key),o)}}function se(t){var e=function(t){if("object"!=Zt(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Zt(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Zt(e)?e:e+""}function ce(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(ce=function(){return!!t})()}function le(t){return le=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},le(t)}function ue(t,e){return ue=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},ue(t,e)}var de=function(t){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var o=(t=function(t,e,n){return e=le(e),function(t,e){if(e&&("object"==Zt(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,ce()?Reflect.construct(e,n||[],le(t).constructor):e.apply(t,n))}(this,e)).readScriptTagConfig();return t.config=re({baseWsUrl:"wss://backend.talktopc.com/chat/websocket",appId:n.appId||o.appId,agentId:n.agentId||o.agentId,conversationId:void 0!==n.conversationId?n.conversationId:t.getPersistedConversationId(),forceConversationId:n.forceConversationId,queue:[],inFlight:!1},n),t.fullResponseBuffer="",t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&ue(t,e)}(e,t),n=e,o=[{key:"readScriptTagConfig",value:function(){try{var t=Array.from(document.getElementsByTagName("script")).reverse().find(function(t){return t.dataset&&(t.dataset.appId||t.dataset.agentId)||t.src&&t.src.includes("agent-widget")});return t?{appId:t.dataset.appId,agentId:t.dataset.agentId}:{}}catch(t){return{}}}},{key:"buildWebSocketUrl",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.config.baseWsUrl,e=new URLSearchParams;return this.config.appId&&e.append("appId",this.config.appId),this.config.agentId&&e.append("agentId",this.config.agentId),this.config.conversationId&&e.append("conversationId",this.config.conversationId),"".concat(t,"?").concat(e.toString())}},{key:"sendMessage",value:(r=te().m(function t(e){var n=this;return te().w(function(t){for(;;)if(0===t.n)return t.a(2,new Promise(function(t,o){if(e&&e.trim())if(n.config.appId&&n.config.agentId){var r={text:e,resolve:t,reject:o};n.config.inFlight?n.config.queue.push(r):n.executeTask(r)}else o(new Error("Missing appId or agentId"));else o(new Error("Message is empty"))}))},t)}),i=function(){var t=this,e=arguments;return new Promise(function(n,o){var i=r.apply(t,e);function a(t){ne(i,n,o,a,s,"next",t)}function s(t){ne(i,n,o,a,s,"throw",t)}a(void 0)})},function(t){return i.apply(this,arguments)})},{key:"executeTask",value:function(t){var e=this;if(this.config.inFlight=!0,this.fullResponseBuffer="",!this.config.conversationId){var n=this.getPersistedConversationId();n&&(this.config.conversationId=n,console.log("🔍 TextChatSDK hydrated conversationId from storage:",n))}var o,r=this.buildWebSocketUrl(this.config.baseWsUrl),i=this.config.baseWsUrl.endsWith("/websocket")?this.config.baseWsUrl.replace(/\/websocket$/,""):"".concat(this.config.baseWsUrl,"/websocket"),a=this.buildWebSocketUrl(i),s=!1,c=!1,l=null,u=function(n){if(!c)try{var o={message:t.text},r=e.config.forceConversationId||e.config.conversationId;r&&(o.conversationId=r,e.config.forceConversationId&&!e.config.conversationId&&(e.config.conversationId=r,e.persistConversationId(r))),console.log("🔍 TextChatSDK sending payload:",o,"conversationId in config:",e.config.conversationId),n.send(JSON.stringify(o)),c=!0}catch(o){t.reject(o),e.emit("error",o);try{n.close()}catch(t){}}},d=function(t){return function(){e.config.conversationId?u(t):l=setTimeout(function(){return u(t)},200)}},p=function(n){return function(o){try{try{console.log("🔎 [TextChatSDK] WS <= raw:",o.data)}catch(t){}var r=JSON.parse(o.data);try{console.log("🔎 [TextChatSDK] WS <= parsed:",r)}catch(t){}if("hello"===r.type&&r.conversationId){if(console.log("🔍 TextChatSDK received conversationId:",r.conversationId),e.config.conversationId=r.conversationId,e.persistConversationId(r.conversationId),e.emit&&e.emit("conversationIdChanged",r.conversationId),!c&&n&&1===n.readyState){if(l)try{clearTimeout(l)}catch(t){}u(n)}return}if(!e.config.conversationId&&r.conversationId&&(console.log("🔍 TextChatSDK captured conversationId from message:",r.conversationId),e.config.conversationId=r.conversationId,e.persistConversationId(r.conversationId)),"chunk"===r.type&&"string"==typeof r.content)e.fullResponseBuffer+=r.content,e.emit("chunk",r.content);else if("done"===r.type){try{var i=r.text||r.content||r.answer||r.message||"";i&&!e.fullResponseBuffer&&(e.fullResponseBuffer=i)}catch(t){}!e.config.conversationId&&r.conversationId&&(console.log("🔍 TextChatSDK captured conversationId from done:",r.conversationId),e.config.conversationId=r.conversationId),e.persistConversationId(e.config.conversationId),e.emit("done",{text:e.fullResponseBuffer}),t.resolve({conversationId:e.config.conversationId,fullText:e.fullResponseBuffer});try{n.close()}catch(t){}}else if("error"===r.type){var a=new Error(r.message||"Server error");e.emit("error",a),t.reject(a);try{n.close()}catch(t){}}}catch(t){}}},f=function(n){if(1008===n.code&&n.reason&&(n.reason.includes("Domain not whitelisted")||n.reason.includes("domain")||n.reason.includes("whitelist"))){var o=new Error("DOMAIN_NOT_WHITELISTED");return o.reason=n.reason,o.code=n.code,e.emit("domainError",o),t.reject(o),e.config.inFlight=!1,void e.drainQueue()}e.config.inFlight=!1,e.drainQueue()},h=new WebSocket(r);h.onopen=d(h),h.onmessage=p(h),h.onerror=(o=h,function(n){if(!s){s=!0;try{o.close()}catch(t){}var r=new WebSocket(a);return r.onopen=d(r),r.onmessage=p(r),r.onerror=function(n){e.emit("error",n),t.reject(n)},void(r.onclose=f)}e.emit("error",n),t.reject(n)}),h.onclose=f}},{key:"drainQueue",value:function(){if(0!==this.config.queue.length&&!this.config.inFlight){var t=this.config.queue.shift();this.executeTask(t)}}},{key:"persistConversationId",value:function(t){try{t&&localStorage.setItem("ttp_text_chat_conversation_id",t)}catch(t){}}},{key:"getPersistedConversationId",value:function(){try{return localStorage.getItem("ttp_text_chat_conversation_id")||null}catch(t){return null}}},{key:"updateConfig",value:function(t){this.config=re(re({},this.config),t)}},{key:"destroy",value:function(){this.config.queue=[],this.config.inFlight=!1,this.removeAllListeners()}}],o&&ae(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(Xt);function pe(t){return pe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},pe(t)}function fe(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var o,r,i,a,s=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(o=i.call(n)).done)&&(s.push(o.value),s.length!==e);c=!0);}catch(t){l=!0,r=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw r}}return s}}(t,e)||ge(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function he(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=ge(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}function ge(t,e){if(t){if("string"==typeof t)return ve(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ve(t,e):void 0}}function ve(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}function me(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return ye(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(ye(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,ye(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,ye(d,"constructor",l),ye(l,"constructor",c),c.displayName="GeneratorFunction",ye(l,r,"GeneratorFunction"),ye(d),ye(d,r,"Generator"),ye(d,o,function(){return this}),ye(d,"toString",function(){return"[object Generator]"}),(me=function(){return{w:i,m:p}})()}function ye(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}ye=function(t,e,n,o){function i(e,n){ye(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},ye(t,e,n,o)}function be(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function we(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Se(o.key),o)}}function Se(t){var e=function(t){if("object"!=pe(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=pe(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==pe(e)?e:e+""}function xe(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(xe=function(){return!!t})()}function ke(t){return ke=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},ke(t)}function Ce(t,e){return Ce=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},Ce(t,e)}const Pe=new(function(t){function e(){var t;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(t=function(t,e,n){return e=ke(e),function(t,e){if(e&&("object"==pe(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,xe()?Reflect.construct(e,n||[],ke(t).constructor):e.apply(t,n))}(this,e)).connections=new Map,t.connectionCounts=new Map,t.creatingConnections=new Set,t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Ce(t,e)}(e,t),n=e,o=[{key:"getConnection",value:(r=me().m(function t(e){var n,o,r=this;return me().w(function(t){for(;;)switch(t.n){case 0:if(!this.connections.has(e)){t.n=1;break}return n=this.connections.get(e),this.connectionCounts.set(e,(this.connectionCounts.get(e)||0)+1),t.a(2,n);case 1:if(!this.creatingConnections||!this.creatingConnections.has(e)){t.n=2;break}return t.a(2,new Promise(function(t){var n=function(){if(r.connections.has(e)){var o=r.connections.get(e);r.connectionCounts.set(e,(r.connectionCounts.get(e)||0)+1),t(o)}else setTimeout(n,50)};n()}));case 2:return this.creatingConnections.add(e),o=new WebSocket(e),this.connections.set(e,o),this.connectionCounts.set(e,1),o.addEventListener("open",function(t){r.creatingConnections.delete(e),r.emit("open",t,e)}),o.addEventListener("close",function(t){r.creatingConnections.delete(e),r.connections.delete(e),r.connectionCounts.delete(e),r.emit("close",t,e)}),o.addEventListener("error",function(t){r.creatingConnections.delete(e),r.emit("error",t,e)}),o.addEventListener("message",function(t){r.emit("message",t,e)}),t.a(2,o)}},t,this)}),i=function(){var t=this,e=arguments;return new Promise(function(n,o){var i=r.apply(t,e);function a(t){be(i,n,o,a,s,"next",t)}function s(t){be(i,n,o,a,s,"throw",t)}a(void 0)})},function(t){return i.apply(this,arguments)})},{key:"releaseConnection",value:function(t){if(this.connections.has(t)){var e=this.connectionCounts.get(t)||0,n=Math.max(0,e-1);if(this.connectionCounts.set(t,n),0===n){var o=this.connections.get(t);o&&o.readyState===WebSocket.OPEN&&o.close(1e3,"No more subscribers"),this.connections.delete(t),this.connectionCounts.delete(t)}}}},{key:"forceClose",value:function(t){if(this.connections.has(t)){var e=this.connections.get(t);e&&e.readyState===WebSocket.OPEN&&e.close(1e3,"Force close"),this.connections.delete(t),this.connectionCounts.delete(t)}}},{key:"getConnectionStatus",value:function(t){return this.connections.has(t)?{exists:!0,readyState:this.connections.get(t).readyState,subscribers:this.connectionCounts.get(t)||0}:{exists:!1,readyState:null,subscribers:0}}},{key:"getAllConnections",value:function(){var t,e={},n=he(this.connections.entries());try{for(n.s();!(t=n.n()).done;){var o=fe(t.value,2),r=o[0],i=o[1];e[r]={readyState:i.readyState,subscribers:this.connectionCounts.get(r)||0}}}catch(t){n.e(t)}finally{n.f()}return e}},{key:"clearAll",value:function(){var t,e=he(this.connections.entries());try{for(e.s();!(t=e.n()).done;){var n=fe(t.value,2),o=(n[0],n[1]);o&&o.readyState===WebSocket.OPEN&&o.close(1e3,"Clear all")}}catch(t){e.e(t)}finally{e.f()}this.connections.clear(),this.connectionCounts.clear(),this.creatingConnections.clear()}}],o&&we(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i}(Xt));function Te(t){return Te="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Te(t)}function Ee(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Oe(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Oe(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Oe(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Oe(d,"constructor",l),Oe(l,"constructor",c),c.displayName="GeneratorFunction",Oe(l,r,"GeneratorFunction"),Oe(d),Oe(d,r,"Generator"),Oe(d,o,function(){return this}),Oe(d,"toString",function(){return"[object Generator]"}),(Ee=function(){return{w:i,m:p}})()}function Oe(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Oe=function(t,e,n,o){function i(e,n){Oe(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Oe(t,e,n,o)}function Ae(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Ie(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Re(o.key),o)}}function Re(t){var e=function(t){if("object"!=Te(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Te(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Te(e)?e:e+""}function Fe(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(Fe=function(){return!!t})()}function je(t){return je=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},je(t)}function De(t,e){return De=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},De(t,e)}var _e=function(t){function e(t){var n;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(n=function(t,e,n){return e=je(e),function(t,e){if(e&&("object"==Te(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,Fe()?Reflect.construct(e,n||[],je(t).constructor):e.apply(t,n))}(this,e)).config=t,n.ws=null,n.isConnected=!1,n.connectionId=null,n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&De(t,e)}(e,t),n=e,o=[{key:"connect",value:(i=Ee().m(function t(){var e=this;return Ee().w(function(t){for(;;)if(0===t.n)return t.a(2,new Promise(function(t,n){try{e.connectionId=Date.now()+"_"+Math.random().toString(36).substr(2,9),e.connectResolve=t,e.connectReject=n;var o=e.config.signedUrl||e.config.websocketUrl;Pe.getConnection(o,e.config).then(function(n){e.ws=n,e.setupEventListeners(),n.readyState===WebSocket.OPEN&&(e.isConnected=!0,e.emit("connected"),t(),e.connectResolve=null,e.connectReject=null)}).catch(function(t){console.error("🔌 WebSocketManager: Connection failed ".concat(e.connectionId),t),n(t),e.connectResolve=null,e.connectReject=null})}catch(t){console.error("🔌 WebSocketManager: Connection error ".concat(e.connectionId),t),n(t),e.connectResolve=null,e.connectReject=null}}))},t)}),a=function(){var t=this,e=arguments;return new Promise(function(n,o){var r=i.apply(t,e);function a(t){Ae(r,n,o,a,s,"next",t)}function s(t){Ae(r,n,o,a,s,"throw",t)}a(void 0)})},function(){return a.apply(this,arguments)})},{key:"setupEventListeners",value:function(){var t=this;if(this.ws){var e=function(e,n){n===(t.config.signedUrl||t.config.websocketUrl)&&(t.isConnected=!0,t.emit("connected"),t.connectResolve&&(t.connectResolve(),t.connectResolve=null,t.connectReject=null))},n=function(e,n){n===(t.config.signedUrl||t.config.websocketUrl)&&(t.isConnected=!1,t.emit("disconnected",e))},o=function(e,n){n===(t.config.signedUrl||t.config.websocketUrl)&&(t.emit("error",e),t.connectReject&&(t.connectReject(e),t.connectResolve=null,t.connectReject=null))},r=function(e,n){n===(t.config.signedUrl||t.config.websocketUrl)&&t.handleMessage(e)};Pe.on("open",e),Pe.on("close",n),Pe.on("error",o),Pe.on("message",r),this.eventHandlers={open:e,close:n,error:o,message:r}}}},{key:"disconnect",value:function(){this.eventHandlers&&(Pe.off("open",this.eventHandlers.open),Pe.off("close",this.eventHandlers.close),Pe.off("error",this.eventHandlers.error),Pe.off("message",this.eventHandlers.message));var t=this.config.signedUrl||this.config.websocketUrl;t&&Pe.releaseConnection(t),this.ws=null,this.isConnected=!1}},{key:"sendMessage",value:function(t){if(this.isConnected&&this.ws)try{this.ws.send(JSON.stringify(t))}catch(t){console.warn("🔌 WebSocketManager: Failed to send message:",t.message)}}},{key:"sendBinary",value:function(t){if(this.isConnected&&this.ws)try{this.ws.send(t)}catch(t){console.warn("🔌 WebSocketManager: Failed to send binary data:",t.message)}}},{key:"handleMessage",value:function(t){var e=this;if(t.data instanceof ArrayBuffer)this.emit("binaryAudio",t.data);else if(t.data instanceof Blob)t.data.arrayBuffer().then(function(t){e.emit("binaryAudio",t)}).catch(function(t){console.error("🔌 WebSocketManager: Error converting Blob to ArrayBuffer:",t)});else try{var n=JSON.parse(t.data);"barge_in_ack"!==n.t&&"stop_sending"!==n.t||this.emit("bargeIn",n),"stop_playing"===n.t&&this.emit("stopPlaying",n),this.emit("message",n)}catch(t){this.emit("error",t)}}},{key:"getStatus",value:function(){return{isConnected:this.isConnected,readyState:this.ws?this.ws.readyState:null,connectionId:this.connectionId}}}],r=[{key:"getSingletonStatus",value:function(){return Pe.getAllConnections()}},{key:"clearAllConnections",value:function(){Pe.clearAll()}}],o&&Ie(n.prototype,o),r&&Ie(n,r),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a}(Xt);function Be(t){return Be="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Be(t)}function Me(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Ue(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Ue(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Ue(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Ue(d,"constructor",l),Ue(l,"constructor",c),c.displayName="GeneratorFunction",Ue(l,r,"GeneratorFunction"),Ue(d),Ue(d,r,"Generator"),Ue(d,o,function(){return this}),Ue(d,"toString",function(){return"[object Generator]"}),(Me=function(){return{w:i,m:p}})()}function Ue(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Ue=function(t,e,n,o){function i(e,n){Ue(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Ue(t,e,n,o)}function Ne(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function ze(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){Ne(i,o,r,a,s,"next",t)}function s(t){Ne(i,o,r,a,s,"throw",t)}a(void 0)})}}function He(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}function Le(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Ke(o.key),o)}}function Ke(t){var e=function(t){if("object"!=Be(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Be(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Be(e)?e:e+""}function Ve(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(Ve=function(){return!!t})()}function We(t){return We=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},We(t)}function Ge(t,e){return Ge=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},Ge(t,e)}var qe=function(t){function e(t){var n;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(n=function(t,e,n){return e=We(e),function(t,e){if(e&&("object"==Be(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,Ve()?Reflect.construct(e,n||[],We(t).constructor):e.apply(t,n))}(this,e)).config=t,n.audioContext=null,n.audioWorkletNode=null,n.mediaStream=null,n.isRecording=!1,n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Ge(t,e)}(e,t),n=e,o=[{key:"getAudioProcessorPath",value:function(){if(this.config.audioProcessorPath)return this.config.audioProcessorPath;var t,e=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return He(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?He(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}(document.getElementsByTagName("script"));try{for(e.s();!(t=e.n()).done;){var n=t.value.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(t){var r=n.substring(0,n.lastIndexOf("/"));return"".concat(r,"/audio-processor.js")}}}catch(t){e.e(t)}finally{e.f()}return"https://cdn.talktopc.com/audio-processor.js"}},{key:"checkPermissionState",value:function(){var t=ze(Me().m(function t(){var e;return Me().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,!navigator.permissions||!navigator.permissions.query){t.n=2;break}return t.n=1,navigator.permissions.query({name:"microphone"});case 1:return e=t.v,t.a(2,e.state);case 2:t.n=4;break;case 3:t.p=3,t.v,console.log("⚠️ AudioRecorder: Permissions API not available or not supported for microphone");case 4:return t.a(2,null)}},t,null,[[0,3]])}));return function(){return t.apply(this,arguments)}}()},{key:"requestPermission",value:(a=ze(Me().m(function t(){var e,n;return Me().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,t.n=1,this.checkPermissionState();case 1:if("granted"!==t.v){t.n=2;break}return console.log("✅ AudioRecorder: Microphone permission already granted"),t.a(2,!0);case 2:return console.log("🎤 AudioRecorder: Requesting microphone permission..."),e=this.config.sampleRate||this.config.outputSampleRate||44100,t.n=3,navigator.mediaDevices.getUserMedia({audio:{sampleRate:e,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 3:return t.v.getTracks().forEach(function(t){return t.stop()}),console.log("✅ AudioRecorder: Microphone permission granted"),t.a(2,!0);case 4:return t.p=4,n=t.v,console.error("❌ AudioRecorder: Failed to get microphone permission:",n),t.a(2,!1)}},t,this,[[0,4]])})),function(){return a.apply(this,arguments)})},{key:"start",value:(i=ze(Me().m(function t(){var e,n,o,r,i,a,s,c=this;return Me().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,console.log("🎤 AudioRecorder: Requesting microphone access..."),t.n=1,this.checkPermissionState();case 1:return(e=t.v)&&(console.log("📋 AudioRecorder: Current permission state: ".concat(e)),"denied"===e&&console.warn('⚠️ AudioRecorder: Permission state is "denied" - browser may not show prompt. User may need to change in browser settings.')),n=this.config.sampleRate||this.config.outputSampleRate||44100,t.n=2,navigator.mediaDevices.getUserMedia({audio:{sampleRate:n,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 2:if(this.mediaStream=t.v,this.audioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:n}),"suspended"!==this.audioContext.state){t.n=3;break}return t.n=3,this.audioContext.resume();case 3:return o=this.getAudioProcessorPath(),t.n=4,this.audioContext.audioWorklet.addModule(o);case 4:this.audioWorkletNode=new AudioWorkletNode(this.audioContext,"audio-processor",{processorOptions:{sampleRate:n,outputSampleRate:this.config.outputSampleRate}}),this.audioContext.createMediaStreamSource(this.mediaStream).connect(this.audioWorkletNode),this.audioWorkletNode.port.onmessage=function(t){var e=t.data,n=e.type,o=e.data;"pcm_audio_data"===n&&c.emit("audioData",o)},this.audioWorkletNode.port.postMessage({type:"setForceContinuous",data:{enabled:!0}}),console.log("✅ AudioRecorder: Microphone access granted"),this.isRecording=!0,this.emit("recordingStarted"),t.n=9;break;case 5:if(t.p=5,s=t.v,r=s.message,"NotAllowedError"!==s.name&&"PermissionDeniedError"!==s.name){t.n=7;break}return t.n=6,this.checkPermissionState();case 6:"denied"===(i=t.v)?(r='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"===i?(r='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.')):(r="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.")),t.n=8;break;case 7:"NotFoundError"===s.name||"DevicesNotFoundError"===s.name?(r="No microphone found. Please connect a microphone and try again.",console.error("❌ AudioRecorder: No microphone device found.")):"NotReadableError"===s.name||"TrackStartError"===s.name?(r="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"!==s.name&&"PermissionDeniedError"!==s.name||(r="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."));case 8:throw(a=new Error(r)).name=s.name,a.originalError=s,this.emit("error",a),a;case 9:return t.a(2)}},t,this,[[0,5]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:(r=ze(Me().m(function t(){var e;return Me().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.isRecording){t.n=1;break}return t.a(2);case 1:if(t.p=1,!this.audioWorkletNode){t.n=2;break}return this.audioWorkletNode.port.postMessage({type:"flush"}),t.n=2,new Promise(function(t){return setTimeout(t,100)});case 2:if(this.mediaStream&&(this.mediaStream.getTracks().forEach(function(t){return t.stop()}),this.mediaStream=null),!this.audioContext||"closed"===this.audioContext.state){t.n=4;break}return t.n=3,this.audioContext.close();case 3:this.audioContext=null;case 4:this.audioWorkletNode=null,this.isRecording=!1,this.emit("recordingStopped"),t.n=6;break;case 5:throw t.p=5,e=t.v,this.emit("error",e),e;case 6:return t.a(2)}},t,this,[[1,5]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isRecording:this.isRecording,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop()}}],o&&Le(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a}(Xt);function Qe(t){return Qe="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qe(t)}function Ye(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return $e(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):($e(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,$e(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,$e(d,"constructor",l),$e(l,"constructor",c),c.displayName="GeneratorFunction",$e(l,r,"GeneratorFunction"),$e(d),$e(d,r,"Generator"),$e(d,o,function(){return this}),$e(d,"toString",function(){return"[object Generator]"}),(Ye=function(){return{w:i,m:p}})()}function $e(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}$e=function(t,e,n,o){function i(e,n){$e(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},$e(t,e,n,o)}function Je(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Xe(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){Je(i,o,r,a,s,"next",t)}function s(t){Je(i,o,r,a,s,"throw",t)}a(void 0)})}}function Ze(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,tn(o.key),o)}}function tn(t){var e=function(t){if("object"!=Qe(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Qe(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Qe(e)?e:e+""}function en(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(en=function(){return!!t})()}function nn(t){return nn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},nn(t)}function on(t,e){return on=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},on(t,e)}var rn=function(t){function e(t){var n;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(n=function(t,e,n){return e=nn(e),function(t,e){if(e&&("object"==Qe(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,en()?Reflect.construct(e,n||[],nn(t).constructor):e.apply(t,n))}(this,e)).config=t,n.audioContext=null,n.audioQueue=[],n.isPlaying=!1,n.isProcessingQueue=!1,n.currentSource=null,n.audioContextReady=!1,n.initializeAudioContext().catch(function(){}),n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&on(t,e)}(e,t),n=e,o=[{key:"initializeAudioContext",value:(a=Xe(Ye().m(function t(){var e,n,o,r,i,a;return Ye().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.audioContext||"closed"===this.audioContext.state){t.n=1;break}return t.a(2);case 1:if(t.p=1,e=this.config.sampleRate||this.config.outputSampleRate||44100,n={sampleRate:e},this.audioContext=new(window.AudioContext||window.webkitAudioContext)(n),"suspended"!==this.audioContext.state){t.n=2;break}return t.n=2,this.audioContext.resume();case 2:if("running"===this.audioContext.state)try{o=this.audioContext.sampleRate,r=this.audioContext.createBuffer(1,.01*o,o),(i=this.audioContext.createBufferSource()).buffer=r,i.connect(this.audioContext.destination),i.start(0),i.stop(this.audioContext.currentTime+.01)}catch(t){console.debug("AudioPlayer: AudioContext warmup skipped:",t)}this.audioContextReady=!0,t.n=4;break;case 3:t.p=3,a=t.v,console.warn("AudioPlayer: Failed to pre-initialize AudioContext:",a),this.audioContextReady=!1;case 4:return t.a(2)}},t,this,[[1,3]])})),function(){return a.apply(this,arguments)})},{key:"playAudio",value:function(t){var e=this;try{var n=this.createAudioBlob(t);if(this.audioQueue.push(n),!this.isPlaying&&!this.isProcessingQueue&&!this.currentSource){var o=this.audioContextReady?0:50;setTimeout(function(){return e.processQueue()},o)}}catch(t){this.emit("playbackError",t)}}},{key:"createAudioBlob",value:function(t){var e=new Uint8Array(t);if(e.length>=4){if(82===e[0]&&73===e[1]&&70===e[2]&&70===e[3])return new Blob([t],{type:"audio/wav"});if(255===e[0]&&!(224&~e[1]))return new Blob([t],{type:"audio/mpeg"});if(79===e[0]&&103===e[1]&&103===e[2]&&83===e[3])return new Blob([t],{type:"audio/ogg"})}return new Blob([t],{type:"audio/wav"})}},{key:"processQueue",value:(i=Xe(Ye().m(function t(){var e,n,o,r,i,a,s,c,l=this;return Ye().w(function(t){for(;;)switch(t.p=t.n){case 0:if(!this.isProcessingQueue&&0!==this.audioQueue.length){t.n=1;break}return t.a(2);case 1:if(this.isProcessingQueue=!0,e=this.audioQueue.shift()){t.n=2;break}return this.isProcessingQueue=!1,t.a(2);case 2:if(t.p=2,n=!this.isPlaying&&null===this.currentSource,this.audioContext&&"closed"!==this.audioContext.state){t.n=3;break}return t.n=3,this.initializeAudioContext();case 3:if("suspended"!==(o=this.audioContext).state){t.n=5;break}return t.n=4,o.resume();case 4:if(!n){t.n=5;break}return t.n=5,new Promise(function(t){return setTimeout(t,10)});case 5:if("running"===o.state){t.n=7;break}if(console.warn("AudioPlayer: AudioContext not in running state:",o.state),"suspended"!==o.state){t.n=7;break}return t.n=6,o.resume();case 6:return t.n=7,new Promise(function(t){return setTimeout(t,10)});case 7:return t.n=8,e.arrayBuffer();case 8:return r=t.v,t.n=9,o.decodeAudioData(r);case 9:i=t.v,a=n&&!this.isPlaying&&null===this.currentSource,(s=o.createBufferSource()).buffer=i,s.connect(o.destination),this.currentSource=s,this.isPlaying=!0,a&&this.emit("playbackStarted"),s.onended=function(){l.currentSource=null,l.isProcessingQueue=!1,l.audioQueue.length>0?setTimeout(function(){return l.processQueue()},0):setTimeout(function(){0!==l.audioQueue.length||l.currentSource||(l.isPlaying=!1,l.emit("playbackStopped"))},100)},s.start(),t.n=11;break;case 10:t.p=10,c=t.v,this.currentSource=null,this.emit("playbackError",c),this.audioQueue.length>0?(this.isProcessingQueue=!1,setTimeout(function(){return l.processQueue()},100)):(this.isPlaying=!1,this.isProcessingQueue=!1,this.emit("playbackStopped"));case 11:return t.a(2)}},t,this,[[2,10]])})),function(){return i.apply(this,arguments)})},{key:"stop",value:function(){this.stopImmediate()}},{key:"stopImmediate",value:function(){var t=this.isPlaying||null!==this.currentSource;if(this.currentSource){try{this.currentSource.stop()}catch(t){}this.currentSource=null}this.isPlaying=!1,this.isProcessingQueue=!1,this.audioQueue=[],t&&this.emit("playbackStopped")}},{key:"resumeAudioContext",value:(r=Xe(Ye().m(function t(){var e;return Ye().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.audioContext&&"closed"!==this.audioContext.state){t.n=2;break}return t.n=1,this.initializeAudioContext();case 1:return t.a(2);case 2:if("suspended"!==this.audioContext.state){t.n=6;break}return t.p=3,t.n=4,this.audioContext.resume();case 4:console.log("✅ AudioPlayer: AudioContext resumed after mic permission"),t.n=6;break;case 5:t.p=5,e=t.v,console.warn("⚠️ AudioPlayer: Failed to resume AudioContext:",e);case 6:return t.a(2)}},t,this,[[3,5]])})),function(){return r.apply(this,arguments)})},{key:"getStatus",value:function(){return{isPlaying:this.isPlaying,isProcessingQueue:this.isProcessingQueue,queueLength:this.audioQueue.length,audioContextState:this.audioContext?this.audioContext.state:"closed"}}},{key:"destroy",value:function(){this.stop(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close(),this.audioContext=null),this.audioContextReady=!1}}],o&&Ze(n.prototype,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,o,r,i,a}(Xt),an=n(540),sn=n(848);function cn(t){return cn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},cn(t)}function ln(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function un(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?ln(Object(n),!0).forEach(function(e){dn(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ln(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function dn(t,e,n){return(e=function(t){var e=function(t){if("object"!=cn(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=cn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==cn(e)?e:e+""}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function pn(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return fn(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(fn(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,fn(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,fn(d,"constructor",l),fn(l,"constructor",c),c.displayName="GeneratorFunction",fn(l,r,"GeneratorFunction"),fn(d),fn(d,r,"Generator"),fn(d,o,function(){return this}),fn(d,"toString",function(){return"[object Generator]"}),(pn=function(){return{w:i,m:p}})()}function fn(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}fn=function(t,e,n,o){function i(e,n){fn(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},fn(t,e,n,o)}function hn(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function gn(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var o,r,i,a,s=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(o=i.call(n)).done)&&(s.push(o.value),s.length!==e);c=!0);}catch(t){l=!0,r=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw r}}return s}}(t,e)||function(t,e){if(t){if("string"==typeof t)return vn(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?vn(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function vn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}const mn=function(t){var e=t.signedUrl,n=t.websocketUrl,o=t.agentId,r=t.appId,i=t.voice,a=void 0===i?"default":i,s=t.language,c=void 0===s?"en":s,l=t.autoReconnect,u=void 0===l||l,d=t.agentSettingsOverride,p=void 0===d?null:d,f=t.onConnected,h=t.onDisconnected,g=t.onRecordingStarted,v=t.onRecordingStopped,m=t.onPlaybackStarted,y=t.onPlaybackStopped,b=t.onError,w=t.onMessage,S=t.onBargeIn,x=t.onStopPlaying,k=t.onStartConversation,C=t.onEndConversation,P=t.className,T=void 0===P?"":P,E=t.style,O=void 0===E?{}:E,A=t.children,I=gn((0,an.useState)(!1),2),R=I[0],F=I[1],j=gn((0,an.useState)(!1),2),D=j[0],_=j[1],B=gn((0,an.useState)(!1),2),M=(B[0],B[1]),U=gn((0,an.useState)("Disconnected"),2),N=(U[0],U[1]),z=(0,an.useRef)(null);(0,an.useEffect)(function(){console.log("🎙️ VoiceButton: Creating VoiceSDK_v2 instance for ".concat(n||e)),z.current&&(console.log("🎙️ VoiceButton: Destroying existing VoiceSDK_v2 instance"),z.current.destroy(),z.current=null);var t=new Qt({signedUrl:n||e,websocketUrl:n||e,agentId:o,appId:r,voice:a,language:c,autoReconnect:u,agentSettingsOverride:p,onStartConversation:k,onEndConversation:C});return t.on("connected",function(){F(!0),N("Connected"),null==f||f()}),t.on("disconnected",function(){F(!1),N("Disconnected"),null==h||h()}),t.on("recordingStarted",function(){_(!0),null==g||g()}),t.on("recordingStopped",function(){_(!1),null==v||v()}),t.on("playbackStarted",function(){M(!0),null==m||m()}),t.on("playbackStopped",function(){M(!1),null==y||y()}),t.on("error",function(t){null==b||b(t)}),t.on("message",function(t){null==w||w(t)}),t.on("bargeIn",function(t){null==S||S(t)}),t.on("stopPlaying",function(t){null==x||x(t)}),z.current=t,t.connect(),function(){var t=e||n;console.log("🎙️ VoiceButton: Cleaning up VoiceSDK instance for ".concat(t)),z.current&&(z.current.destroy(),z.current=null)}},[e,n,o,r,a,c,p]);var H=function(){var t,e=(t=pn().m(function t(){var e;return pn().w(function(t){for(;;)switch(t.p=t.n){case 0:if(z.current){t.n=1;break}return t.a(2);case 1:return t.p=1,t.n=2,z.current.toggleRecording();case 2:t.n=4;break;case 3:t.p=3,e=t.v,console.error("Error toggling recording:",e);case 4:return t.a(2)}},t,null,[[1,3]])}),function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){hn(i,o,r,a,s,"next",t)}function s(t){hn(i,o,r,a,s,"throw",t)}a(void 0)})});return function(){return e.apply(this,arguments)}}(),L=(0,sn.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[(0,sn.jsx)("div",{style:{fontSize:"20px"},children:D?"🔴":"🎤"}),(0,sn.jsx)("div",{children:D?"Stop Listening":"Start Listening"})]});return(0,sn.jsx)("button",{className:"voice-button ".concat(D?"recording":""," ").concat(T),style:un({padding:"12px 24px",border:"none",borderRadius:"8px",backgroundColor:D?"#dc3545":"#007bff",color:"white",cursor:"pointer",fontSize:"16px",fontWeight:"500",transition:"all 0.2s ease"},O),onClick:H,disabled:!R,children:A||L})};function yn(t){return yn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},yn(t)}function bn(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return wn(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(wn(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,wn(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,wn(d,"constructor",l),wn(l,"constructor",c),c.displayName="GeneratorFunction",wn(l,r,"GeneratorFunction"),wn(d),wn(d,r,"Generator"),wn(d,o,function(){return this}),wn(d,"toString",function(){return"[object Generator]"}),(bn=function(){return{w:i,m:p}})()}function wn(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}wn=function(t,e,n,o){function i(e,n){wn(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},wn(t,e,n,o)}function Sn(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function xn(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){Sn(i,o,r,a,s,"next",t)}function s(t){Sn(i,o,r,a,s,"throw",t)}a(void 0)})}}function kn(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function Cn(t,e,n){return(e=Tn(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Pn(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Tn(o.key),o)}}function Tn(t){var e=function(t){if("object"!=yn(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=yn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==yn(e)?e:e+""}var En=function(){return t=function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.options=function(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?kn(Object(n),!0).forEach(function(e){Cn(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):kn(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}({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 Qt({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()},e=[{key:"setupEventListeners",value:function(){var t=this;this.voiceSDK.on("connected",function(){var e,n;t.isConnected=!0,t.updateButton(),null===(e=(n=t.options).onConnected)||void 0===e||e.call(n)}),this.voiceSDK.on("disconnected",function(){var e,n;t.isConnected=!1,t.updateButton(),null===(e=(n=t.options).onDisconnected)||void 0===e||e.call(n)}),this.voiceSDK.on("recordingStarted",function(){var e,n;t.isRecording=!0,t.updateButton(),null===(e=(n=t.options).onRecordingStarted)||void 0===e||e.call(n)}),this.voiceSDK.on("recordingStopped",function(){var e,n;t.isRecording=!1,t.updateButton(),null===(e=(n=t.options).onRecordingStopped)||void 0===e||e.call(n)}),this.voiceSDK.on("playbackStarted",function(){var e,n;t.isPlaying=!0,null===(e=(n=t.options).onPlaybackStarted)||void 0===e||e.call(n)}),this.voiceSDK.on("playbackStopped",function(){var e,n;t.isPlaying=!1,null===(e=(n=t.options).onPlaybackStopped)||void 0===e||e.call(n)}),this.voiceSDK.on("error",function(e){var n,o;null===(n=(o=t.options).onError)||void 0===n||n.call(o,e)}),this.voiceSDK.on("message",function(e){var n,o;null===(n=(o=t.options).onMessage)||void 0===n||n.call(o,e)}),this.voiceSDK.on("bargeIn",function(e){var n,o;null===(n=(o=t.options).onBargeIn)||void 0===n||n.call(o,e)}),this.voiceSDK.on("stopPlaying",function(e){var n,o;null===(n=(o=t.options).onStopPlaying)||void 0===n||n.call(o,e)})}},{key:"createButton",value:function(){var t=this;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",function(){return t.toggleRecording()}),this.options.container.appendChild(this.button),this.updateButton()}},{key:"updateButton",value:function(){if(this.button){var t=this.isRecording?"🔴":"🎤",e=this.isRecording?"Stop Listening":"Start Listening";this.button.innerHTML='\n <span style="font-size: 20px;">'.concat(t,"</span>\n <span>").concat(e,"</span>\n "),this.button.disabled=!this.isConnected,this.button.style.backgroundColor=this.isRecording?"#dc3545":this.isConnected?"#007bff":"#6c757d"}}},{key:"connect",value:(o=xn(bn().m(function t(){var e;return bn().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,t.n=1,this.voiceSDK.connect();case 1:t.n=3;break;case 2:t.p=2,e=t.v,console.error("Failed to connect:",e);case 3:return t.a(2)}},t,this,[[0,2]])})),function(){return o.apply(this,arguments)})},{key:"toggleRecording",value:(n=xn(bn().m(function t(){var e;return bn().w(function(t){for(;;)switch(t.p=t.n){case 0:if(this.voiceSDK){t.n=1;break}return t.a(2);case 1:return t.p=1,t.n=2,this.voiceSDK.toggleRecording();case 2:t.n=4;break;case 3:t.p=3,e=t.v,console.error("Error toggling recording:",e);case 4:return t.a(2)}},t,this,[[1,3]])})),function(){return n.apply(this,arguments)})},{key:"getStatus",value:function(){return{isConnected:this.isConnected,isRecording:this.isRecording,isPlaying:this.isPlaying}}},{key:"updateConfig",value:function(t){this.voiceSDK.updateConfig(t)}},{key:"destroy",value:function(){this.button&&this.button.parentNode&&this.button.parentNode.removeChild(this.button),this.voiceSDK&&this.voiceSDK.destroy()}}],e&&Pn(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();function On(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return An(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(An(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,An(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,An(d,"constructor",l),An(l,"constructor",c),c.displayName="GeneratorFunction",An(l,r,"GeneratorFunction"),An(d),An(d,r,"Generator"),An(d,o,function(){return this}),An(d,"toString",function(){return"[object Generator]"}),(On=function(){return{w:i,m:p}})()}function An(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}An=function(t,e,n,o){function i(e,n){An(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},An(t,e,n,o)}function In(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var o,r,i,a,s=[],c=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;c=!1}else for(;!(c=(o=i.call(n)).done)&&(s.push(o.value),s.length!==e);c=!0);}catch(t){l=!0,r=t}finally{try{if(!c&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw r}}return s}}(t,e)||Fn(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Rn(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=Fn(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}function Fn(t,e){if(t){if("string"==typeof t)return jn(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?jn(t,e):void 0}}function jn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}function Dn(t){return Dn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Dn(t)}function _n(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Bn(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){_n(i,o,r,a,s,"next",t)}function s(t){_n(i,o,r,a,s,"throw",t)}a(void 0)})}}function Mn(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Un(o.key),o)}}function Un(t){var e=function(t){if("object"!=Dn(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Dn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Dn(e)?e:e+""}var Nn=function(){return t=function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),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.onConnected=function(){},this.onDisconnected=function(){},this.onError=function(t){return console.error("SDK Error:",t)},this.onTranscript=function(t){},this.onAgentSpeaking=function(t){},this.onConversationStart=e.onConversationStart||function(){},this.onConversationEnd=e.onConversationEnd||function(){},this.onBargeIn=e.onBargeIn||function(){},this.onAudioStartPlaying=e.onAudioStartPlaying||function(){},this.onAudioStoppedPlaying=e.onAudioStoppedPlaying||function(){},this.onSubtitleDisplay=e.onSubtitleDisplay||function(){}},e=[{key:"connect",value:(o=Bn(On().m(function t(e){var n,o,r,i,a,s,c=this;return On().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,e){t.n=1;break}throw new Error("signedUrl is required");case 1:if(this.voiceSDK&&(console.log("🔌 AgentSDK: Cleaning up existing connection"),this.voiceSDK.destroy(),this.voiceSDK=null),this.voiceSDK=new Qt({signedUrl:e,autoReconnect:!1,agentId:this.config.agentId,appId:this.config.appId,language:this.config.language||"en",agentSettingsOverride:this.config.agentSettingsOverride,protocolVersion:2,outputContainer:this.config.outputContainer||"raw",outputEncoding:this.config.outputEncoding||"pcm",outputSampleRate:this.config.outputSampleRate||44100,outputChannels:this.config.outputChannels||1,outputBitDepth:this.config.outputBitDepth||16}),this.voiceSDK.on("connected",function(){c.isConnected=!0,c.onConnected()}),setTimeout(function(){c.voiceSDK&&c.voiceSDK.isConnected&&!c.isConnected&&(c.isConnected=!0,c.onConnected())},10),this.voiceSDK.on("disconnected",function(t){if(c.isConnected=!1,t&&1008===t.code&&t.reason&&(t.reason.includes("Domain not whitelisted")||t.reason.includes("domain")||t.reason.includes("whitelist"))){var e=new Error("DOMAIN_NOT_WHITELISTED");e.reason=t.reason,e.code=t.code,c.onError(e)}if((c.isListening||c.wasListening)&&(console.log("🎤 [AGENT SDK] disconnected event - calling onConversationEnd hook (isListening:",c.isListening,", wasListening:",c.wasListening,")"),c.onConversationEnd&&"function"==typeof c.onConversationEnd))try{c.onConversationEnd(),console.log("🎤 [AGENT SDK] ✅ onConversationEnd hook called from disconnected event"),c.wasListening=!1}catch(t){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationEnd from disconnected:",t)}c.onDisconnected()}),this.voiceSDK.on("domainError",function(t){c.onError(t)}),this.voiceSDK.on("error",function(t){c.onError(t)}),this.voiceSDK.on("message",function(t){c.handleWebSocketMessage(t)}),this.voiceSDK.on("recordingStarted",function(){if(c.isListening=!0,c.wasListening=!0,c.onConversationStart&&"function"==typeof c.onConversationStart)try{c.onConversationStart()}catch(t){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationStart:",t)}}),this.voiceSDK.on("recordingStopped",function(){console.log("🎤 [AGENT SDK] recordingStopped event received");var t=c.isListening;if(c.isListening=!1,t&&c.onConversationEnd&&"function"==typeof c.onConversationEnd)try{console.log("🎤 [AGENT SDK] ✅ Calling onConversationEnd hook from recordingStopped"),c.onConversationEnd(),console.log("🎤 [AGENT SDK] ✅ onConversationEnd hook called successfully"),c.wasListening=!1}catch(t){console.error("🎤 [AGENT SDK] ❌ Error calling onConversationEnd:",t)}}),this.voiceSDK.on("playbackStarted",function(){c.onAgentSpeaking(!0),c.onAudioStartPlaying()}),this.voiceSDK.on("playbackStopped",function(){c.onAgentSpeaking(!1),c.onAudioStoppedPlaying()}),this.voiceSDK.on("bargeIn",function(t){c.onBargeIn(t)}),this.voiceSDK.on("transcriptDisplay",function(t){console.log("📝 [AGENT SDK] transcriptDisplay event received:",t),t&&t.text&&(console.log("📝 [AGENT SDK] Calling onTranscript with text:",t.text),c.onTranscript&&"function"==typeof c.onTranscript?c.onTranscript(t.text):console.warn("📝 [AGENT SDK] ⚠️ onTranscript is not a function!",Dn(c.onTranscript))),c.onSubtitleDisplay(t)}),this._pendingToolHandlers&&this._pendingToolHandlers.size>0){console.log("🔧 AgentSDK: Registering ".concat(this._pendingToolHandlers.size," pending tool handlers")),n=Rn(this._pendingToolHandlers);try{for(n.s();!(o=n.n()).done;)r=In(o.value,2),i=r[0],a=r[1],this.voiceSDK.registerToolHandler(i,a)}catch(t){n.e(t)}finally{n.f()}}return t.n=2,this.voiceSDK.connect();case 2:t.n=4;break;case 3:throw t.p=3,s=t.v,this.onError(s),s;case 4:return t.a(2)}},t,this,[[0,3]])})),function(t){return o.apply(this,arguments)})},{key:"handleWebSocketMessage",value:function(t){switch(t.t||t.type){case"connected":case"hello_ack":console.log("Session started successfully");break;case"user_transcript":this.onTranscript(t.user_transcription||t.text||t.transcript);break;case"agent_response":case"barge_in":case"stop_playing":default:break;case"error":this.onError(new Error(t.message||t.error||"Unknown error"))}}},{key:"startListening",value:(n=Bn(On().m(function t(){var e;return On().w(function(t){for(;;)switch(t.p=t.n){case 0:if(console.log("🎤 AgentSDK: startListening() called"),!this.voiceSDK){t.n=5;break}return t.p=1,console.log("🎤 AgentSDK: Starting recording..."),t.n=2,this.voiceSDK.startRecording();case 2:console.log("✅ AgentSDK: Recording started successfully"),t.n=4;break;case 3:throw t.p=3,e=t.v,console.error("❌ AgentSDK: Failed to start recording:",e),e;case 4:t.n=6;break;case 5:throw console.error("❌ AgentSDK: No voiceSDK instance available"),new Error("No voiceSDK instance available");case 6:return t.a(2)}},t,this,[[1,3]])})),function(){return n.apply(this,arguments)})},{key:"stopListening",value:function(){this.voiceSDK&&this.voiceSDK.stopRecording()}},{key:"updateVariables",value:function(t){this.voiceSDK&&this.isConnected&&this.voiceSDK.sendMessage({t:"update_variables",variables:t})}},{key:"disconnect",value:function(){this.voiceSDK&&(this.voiceSDK.destroy(),this.voiceSDK=null),this.isConnected=!1,this.isListening=!1}},{key:"registerToolHandler",value:function(t,e){if(this.voiceSDK)return this.voiceSDK.registerToolHandler(t,e);this._pendingToolHandlers||(this._pendingToolHandlers=new Map),this._pendingToolHandlers.set(t,e),console.log("🔧 AgentSDK: Queued tool handler '".concat(t,"' for registration after connect"))}},{key:"unregisterToolHandler",value:function(t){if(this.voiceSDK)return this.voiceSDK.unregisterToolHandler(t);this._pendingToolHandlers&&this._pendingToolHandlers.delete(t)}},{key:"hasToolHandler",value:function(t){var e;return this.voiceSDK?this.voiceSDK.hasToolHandler(t):(null===(e=this._pendingToolHandlers)||void 0===e?void 0:e.has(t))||!1}},{key:"getRegisteredTools",value:function(){return this.voiceSDK?this.voiceSDK.getRegisteredTools():this._pendingToolHandlers?Array.from(this._pendingToolHandlers.keys()):[]}}],e&&Mn(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();function zn(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return Hn(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(Hn(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,Hn(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,Hn(d,"constructor",l),Hn(l,"constructor",c),c.displayName="GeneratorFunction",Hn(l,r,"GeneratorFunction"),Hn(d),Hn(d,r,"Generator"),Hn(d,o,function(){return this}),Hn(d,"toString",function(){return"[object Generator]"}),(zn=function(){return{w:i,m:p}})()}function Hn(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}Hn=function(t,e,n,o){function i(e,n){Hn(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},Hn(t,e,n,o)}function Ln(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Kn(){var t=navigator.userAgent,e=/iPad|iPhone|iPod/.test(t)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,n=/Android/.test(t),o=/Mac/.test(t)&&!e,r=/Win/.test(t),i=/Chrome/.test(t)&&!/Edg|OPR/.test(t),a=/Safari/.test(t)&&!/Chrome/.test(t),s=/Firefox/.test(t),c=/Edg/.test(t),l=/SamsungBrowser/.test(t),u="unknown";e?u="safari":l?u="samsung":i?u="chrome":a?u="safari":s?u="firefox":c&&(u="edge");var d="unknown";return e?d="ios":n?d="android":o?d="mac":r&&(d="windows"),{platform:d,browser:u,isIOS:e,isAndroid:n,isMac:o,isWindows:r,isMobile:e||n,isDesktop:!e&&!n}}function Vn(){return Wn.apply(this,arguments)}function Wn(){var t;return t=zn().m(function t(){var e;return zn().w(function(t){for(;;)switch(t.p=t.n){case 0:if(t.p=0,!navigator.permissions||!navigator.permissions.query){t.n=2;break}return t.n=1,navigator.permissions.query({name:"microphone"});case 1:return e=t.v,t.a(2,e.state);case 2:t.n=4;break;case 3:t.p=3,t.v,console.log("⚠️ MicPermissionUtils: Permissions API not available or not supported for microphone");case 4:return t.a(2,"unknown")}},t,null,[[0,3]])}),Wn=function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){Ln(i,o,r,a,s,"next",t)}function s(t){Ln(i,o,r,a,s,"throw",t)}a(void 0)})},Wn.apply(this,arguments)}function Gn(t){var e=t.platform,n=t.browser,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"===e?o.ios:"android"===e?o["android_".concat(n)]||o.android_chrome:o["desktop_".concat(n)]||o.desktop_chrome}function qn(t){var e=t.isIOS,n=t.isAndroid,o=t.browser;if(e)try{return window.location.href="app-settings:",!0}catch(t){return console.warn("Could not open iOS settings:",t),!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(t){return console.warn("Could not open Android settings:",t),!1}return!1}function Qn(t){return Qn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Qn(t)}function Yn(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,$n(o.key),o)}}function $n(t){var e=function(t){if("object"!=Qn(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Qn(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Qn(e)?e:e+""}function Jn(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Xn(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Xn(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var o=0,r=function(){};return{s:r,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,s=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){s=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(s)throw i}}}}function Xn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n<e;n++)o[n]=t[n];return o}var Zn=function(){return t=function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.overlay=null,this.modal=null},(e=[{key:"createOverlay",value:function(){var t=document.createElement("div");return t.className="mic-permission-overlay",t.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(),t}},{key:"injectStyles",value:function(){if(!document.getElementById("mic-permission-styles")){var t=document.createElement("style");t.id="mic-permission-styles",t.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(t)}}},{key:"close",value:function(){this.overlay&&this.overlay.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.modal=null}},{key:"show",value:function(){this.overlay&&this.modal&&document.body.appendChild(this.overlay)}}])&&Yn(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e}();function to(t,e){var n=new Zn,o=n.createOverlay(),r=Kn(),i=document.createElement("div");return i.className="mic-permission-modal",i.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(r.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(i),n.overlay=o,n.modal=i,i.querySelector('[data-action="accept"]').addEventListener("click",function(){n.close(),t()}),i.querySelector('[data-action="cancel"]').addEventListener("click",function(){n.close(),e()}),o.addEventListener("click",function(t){t.target===o&&(n.close(),e())}),n.show(),n}function eo(t,e){var n,o,r,i=new Zn,a=i.createOverlay(),s=Kn(),c=Gn(s),l=document.createElement("div");l.className="mic-permission-modal";var u="";c.altSteps&&c.altSteps.length>0&&(u='\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(function(t){return'<li style="padding: 8px 0; font-size: 14px; color: #6b7280;">'.concat(t,"</li>")}).join(""),"\n </ol>\n </div>\n "));var d=function(t){var e,n=t.platform,o=t.browser,r=document.getElementsByTagName("script"),i="",a=Jn(r);try{for(a.s();!(e=a.n()).done;){var s=e.value.src;if(s&&(s.includes("agent-widget.js")||s.includes("ttp-agent-sdk")||s.includes("ttp-sdk-front")))try{new URL(s),i=s.substring(0,s.lastIndexOf("/"));break}catch(t){var c=s.match(/^(.*\/)[^\/]+$/);if(c){i=c[1];break}}}}catch(t){a.e(t)}finally{a.f()}var l;if(l="ios"===n?"ios-settings.svg":"android"===n?"android-chrome.svg":"chrome"===o?"desktop-chrome.svg":"safari"===o?"desktop-safari.svg":"firefox"===o?"desktop-firefox.svg":"edge"===o?"desktop-edge.svg":"desktop-chrome.svg",!i||""===i||i.startsWith("/")){var u,d=Jn(r);try{for(d.s();!(u=d.n()).done;){var p=u.value.src;if(p&&(p.includes("cdn.talktopc.com")||p.includes("talktopc.com"))){if(p.includes("/ttp-agent-sdk/")||p.includes("/ttp-sdk-front/")){var f=p.match(/(https?:\/\/[^\/]+(?:\/[^\/]+)*)/);if(f){i=f[1].replace(/\/[^\/]+\.js$/,"");break}}if(!i&&(p.includes("cdn.talktopc.com")||p.includes("talktopc.com"))){i="https://cdn.talktopc.com/ttp-agent-sdk";break}}}}catch(t){d.e(t)}finally{d.f()}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 g="".concat(i,"/shared/mic-permission-assets/").concat(l);return"undefined"!=typeof console&&console.log&&console.log("[MicPermission] Visual guide path:",g,"Base path:",i,"Platform:",n,"Browser:",o),g}(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(d,'" 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(function(t){return"<li>".concat(t,"</li>")}).join(""),"\n </ol>\n </div>\n ").concat(u,'\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),i.overlay=a,i.modal=l,null===(n=l.querySelector('[data-action="close"]'))||void 0===n||n.addEventListener("click",function(){i.close(),t()}),null===(o=l.querySelector('[data-action="open-settings"]'))||void 0===o||o.addEventListener("click",function(){qn(s)}),null===(r=l.querySelector('[data-action="refresh"]'))||void 0===r||r.addEventListener("click",function(){window.location.reload()});var p=l.querySelector('[data-action="show-hint"]');p&&p.addEventListener("click",function(){i.close(),t(),function(){var t=document.getElementById("mic-address-bar-hint");t&&t.remove(),Kn();var e,n=document.getElementsByTagName("script"),o="",r=Jn(n);try{for(r.s();!(e=r.n()).done;){var i=e.value.src;if(i&&(i.includes("agent-widget.js")||i.includes("ttp-agent-sdk")||i.includes("ttp-sdk-front")))try{new URL(i),o=i.substring(0,i.lastIndexOf("/"));break}catch(t){var a=i.match(/^(.*\/)[^\/]+$/);if(a){o=a[1];break}}}}catch(t){r.e(t)}finally{r.f()}if(!o||""===o||o.startsWith("/")){var s,c=Jn(n);try{for(c.s();!(s=c.n()).done;){var l=s.value.src;if(l&&(l.includes("cdn.talktopc.com")||l.includes("talktopc.com"))){if(l.includes("/ttp-agent-sdk/")||l.includes("/ttp-sdk-front/")){var u=l.match(/(https?:\/\/[^\/]+(?:\/[^\/]+)*)/);if(u){o=u[1].replace(/\/[^\/]+\.js$/,"");break}}if(!o&&(l.includes("cdn.talktopc.com")||l.includes("talktopc.com"))){o="https://cdn.talktopc.com/ttp-agent-sdk";break}}}}catch(t){c.e(t)}finally{c.f()}if(!o||""===o)if(window.location.hostname.includes("cdn.talktopc.com")||window.location.hostname.includes("talktopc.com"))o="https://cdn.talktopc.com/ttp-agent-sdk";else{var d=window.location.pathname.split("/");d.pop(),(o=window.location.origin+d.join("/"))&&o!==window.location.origin||(o=window.location.origin)}}o=o.replace(/\/$/,"");var p="".concat(o,"/shared/mic-permission-assets/address-bar-hint.svg"),f=document.createElement("div");f.id="mic-address-bar-hint",f.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 g=document.createElement("div");g.style.cssText="\n flex-shrink: 0;\n ";var v=document.createElement("img");v.src=p,v.alt="Address bar hint",v.style.cssText="\n width: auto;\n height: 80px;\n display: block;\n ",v.onerror=function(){g.style.display="none"},g.appendChild(v);var m=document.createElement("div");m.style.cssText="\n display: flex;\n flex-direction: column;\n gap: 4px;\n flex: 1;\n ";var y=document.createElement("div");y.style.cssText="\n font-size: 15px;\n font-weight: 500;\n ",y.innerHTML="Click the <strong>lock icon 🔒</strong>, <strong>information icon ℹ️</strong>, or <strong>settings icon ⋮</strong> in the address bar to enable microphone";var b=document.createElement("button");if(b.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 ",b.textContent="✕",b.addEventListener("click",function(){f.remove()}),b.addEventListener("mouseenter",function(){b.style.background="rgba(255, 255, 255, 0.3)"}),b.addEventListener("mouseleave",function(){b.style.background="rgba(255, 255, 255, 0.2)"}),!document.getElementById("mic-address-bar-hint-styles")){var w=document.createElement("style");w.id="mic-address-bar-hint-styles",w.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(w)}m.appendChild(y),h.appendChild(g),h.appendChild(m),h.appendChild(b),f.appendChild(h),document.body.appendChild(f),setTimeout(function(){f.parentNode&&(f.style.opacity="0",f.style.transition="opacity 0.3s ease-out",setTimeout(function(){f.parentNode&&f.remove()},300))},1e4)}()});var f=l.querySelector(".mic-permission-modal__alt-toggle");if(f&&c.altSteps){var h=f.nextElementSibling;h&&(h.style.display="none",f.addEventListener("click",function(){"none"===h.style.display?(h.style.display="block",f.innerHTML="▼ ".concat(c.altTitle||"Alternative method")):(h.style.display="none",f.innerHTML="▶ ".concat(c.altTitle||"Alternative method"))}))}return a.addEventListener("click",function(e){e.target===a&&(i.close(),t())}),i.show(),i}function no(t){var e=new Zn,n=e.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),e.overlay=n,e.modal=o,o.querySelector('[data-action="retry"]').addEventListener("click",function(){window.location.reload()}),o.querySelector('[data-action="close"]').addEventListener("click",function(){e.close(),t()}),n.addEventListener("click",function(o){o.target===n&&(e.close(),t())}),e.show(),e}function oo(t){return oo="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},oo(t)}function ro(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return io(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(io(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,io(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,io(d,"constructor",l),io(l,"constructor",c),c.displayName="GeneratorFunction",io(l,r,"GeneratorFunction"),io(d),io(d,r,"Generator"),io(d,o,function(){return this}),io(d,"toString",function(){return"[object Generator]"}),(ro=function(){return{w:i,m:p}})()}function io(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}io=function(t,e,n,o){function i(e,n){io(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},io(t,e,n,o)}function ao(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function so(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){ao(i,o,r,a,s,"next",t)}function s(t){ao(i,o,r,a,s,"throw",t)}a(void 0)})}}function co(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,lo(o.key),o)}}function lo(t){var e=function(t){if("object"!=oo(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=oo(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==oo(e)?e:e+""}var uo=function(){return t=function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),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 Nn({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()},e=[{key:"setupSDKEventHandlers",value:function(){var t=this;this.sdk.onTranscript=function(e){console.log("📝 [VOICE INTERFACE] onTranscript called with text:",e),t.updateTranscript(e)},this.sdk.onAgentSpeaking=function(e){var n=t.shadowRoot.getElementById("voiceAvatarActive");n&&(e?n.classList.add("speaking"):n.classList.remove("speaking"))},this.sdk.onDisconnected=function(){console.log("🔌 WebSocket disconnected, hanging up call..."),t.isActive&&(t.isActive=!1,t.endVoiceCall())},this.sdk.onError=function(e){console.error("❌ Voice SDK Error:",e),e&&("DOMAIN_NOT_WHITELISTED"===e.message||e.message&&e.message.includes("Domain not whitelisted"))?t.showDomainError():t.showError(e.message||e)}}},{key:"t",value:function(t){var e,n,o=this.config.language||"en";return((null===(e=this.config.translations)||void 0===e?void 0:e[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[t]||t}},{key:"getText",value:function(t,e){return void 0!==this.config[t]&&null!==this.config[t]?this.config[t]:this.t(e)}},{key:"getTooltip",value:function(t){var e,n=null===(e=this.config.tooltips)||void 0===e?void 0:e[t];return null!=n?n:{mute:this.t("mute"),speaker:this.t("speaker"),endCall:this.t("endCall")}[t]||""}},{key:"generateHTML",value:function(){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>')}},{key:"generateCSS",value:function(){var t=this.config.avatarBackgroundColor||"#667eea",e=this.config.avatarActiveBackgroundColor||this.config.avatarBackgroundColor||"#667eea",n=this.config.statusTitleColor||"#1e293b",o=this.config.statusSubtitleColor||"#64748b",r=this.config.startCallButtonColor||"#667eea",i=this.config.startCallButtonTextColor||"#FFFFFF",a=this.config.transcriptBackgroundColor||"#FFFFFF",s=this.config.transcriptTextColor||"#1e293b",c=this.config.transcriptLabelColor||"#94a3b8",l=this.config.controlButtonColor||"#FFFFFF",u=this.config.controlButtonSecondaryColor||"#64748b",d=(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(d,"; \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(d,'; }\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(t," 0%, ").concat(e," 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(r,";\n color: ").concat(i,";\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(u,";\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 ")}},{key:"setupEventHandlers",value:function(t){var e=this,n=this.shadowRoot.getElementById("startCallBtn"),o=this.shadowRoot.getElementById("endCallBtn"),r=this.shadowRoot.getElementById("muteBtn"),i=this.shadowRoot.getElementById("speakerBtn");n&&(n.onclick=function(){return e.startVoiceCall()}),o&&(o.onclick=function(){return e.endVoiceCall()}),r&&(r.onclick=function(){return e.toggleMute()}),i&&(i.onclick=function(){return e.toggleSpeaker()});var a=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=e.shadowRoot.getElementById("voiceInterface");n&&n.classList.contains("active")&&n.clientHeight>100?(console.log("✅ Interface is active and has proper dimensions, adjusting sizes (attempt",t+1,")"),e.adjustSizesForContainer(),0===t&&setTimeout(function(){return e.adjustSizesForContainer()},500)):t<15?(console.log("⏳ Interface not ready yet (height:",null==n?void 0:n.clientHeight,"), retrying... (attempt",t+1,")"),setTimeout(function(){return a(t+1)},250)):(console.warn("⚠️ Interface never became fully ready, adjusting sizes anyway"),e.adjustSizesForContainer())};setTimeout(function(){return a()},200),window.addEventListener("resize",function(){console.log("🔄 Window resized, re-adjusting sizes"),e.adjustSizesForContainer()})}},{key:"getSignedUrl",value:(r=so(ro().m(function t(){var e,n;return ro().w(function(t){for(;;)switch(t.n){case 0:if(!this.config.signedUrl){t.n=1;break}return t.a(2,this.config.signedUrl);case 1:if(this.config.agentId){t.n=2;break}throw new Error("agentId is required when signedUrl is not provided");case 2:return e=this.config.websocketUrl||"wss://speech.talktopc.com/ws/conv",(n=new URLSearchParams).append("agentId",this.config.agentId),this.config.appId&&n.append("appId",this.config.appId),!1!==this.config.demo&&n.append("demo","true"),t.a(2,"".concat(e,"?").concat(n.toString()))}},t,this)})),function(){return r.apply(this,arguments)})},{key:"adjustSizesForContainer",value:function(){var t=this.shadowRoot.getElementById("voiceInterface");if(t){var e=t.clientHeight,n=t.clientWidth;console.log("📏 Container size:",e,"x",n);var o,r,i,a,s,c,l,u,d,p=this.shadowRoot.getElementById("voiceIdleState"),f=this.shadowRoot.getElementById("voiceActiveState"),h=p&&"none"!==p.style.display,g=f&&"none"!==f.style.display;console.log("👁️ Visible state - Idle:",h,"Active:",g),e<=350?(d=5,o=70,r=35,i=11,a=9,s=32,c=100,l=42,u=48):e<=450?(d=7,o=110,r=55,i=15,a=11,s=38,c=110,l=52,u=58):e<=550?(d=8,o=140,r=70,i=16,a=12,s=42,c=120,l=56,u=64):e<=700?(d=10,o=130,r=65,i=18,a=13,s=46,c=130,l=60,u=70):(d=12,o=150,r=75,i=20,a=14,s=50,c=140,l=66,u=76),this.shadowRoot.querySelectorAll("#voiceIdleState, #voiceActiveState").forEach(function(t){t.style.gap="".concat(d,"px")});var v=this.shadowRoot.querySelectorAll(".voice-avatar, .voice-avatar-active");console.log("🤖 Found",v.length,"avatars, setting size to",o,"px"),v.forEach(function(t){t.style.width="".concat(o,"px"),t.style.height="".concat(o,"px"),t.style.fontSize="".concat(r,"px")}),this.shadowRoot.querySelectorAll(".voice-status-title").forEach(function(t){return t.style.fontSize="".concat(i,"px")}),this.shadowRoot.querySelectorAll(".voice-status-subtitle").forEach(function(t){return t.style.fontSize="".concat(a,"px")});var m=this.shadowRoot.querySelector(".voice-transcript");m&&(m.style.minHeight="".concat(c,"px"),m.style.maxHeight="".concat(c,"px"),m.style.height="".concat(c,"px"),m.style.width="min(360px, ".concat(n-40,"px)"),m.style.boxSizing="border-box");var y=this.shadowRoot.querySelector(".transcript-label");y&&(y.style.fontSize="".concat(Math.max(8,i-4),"px"));var b=this.shadowRoot.querySelector(".transcript-text");b&&(b.style.fontSize="".concat(Math.max(10,i-2),"px")),this.shadowRoot.querySelectorAll(".voice-control-btn.secondary").forEach(function(t){t.style.width="".concat(l,"px"),t.style.height="".concat(l,"px");var e=t.querySelector("svg");if(e){var n=.65*l;e.style.setProperty("width","".concat(n,"px"),"important"),e.style.setProperty("height","".concat(n,"px"),"important"),e.style.setProperty("min-width","".concat(n,"px"),"important"),e.style.setProperty("min-height","".concat(n,"px"),"important")}});var w=this.shadowRoot.querySelector(".voice-control-btn.primary");if(w){w.style.width="".concat(u,"px"),w.style.height="".concat(u,"px");var S=w.querySelector("svg");if(S){var x=.7*u;S.style.setProperty("width","".concat(x,"px"),"important"),S.style.setProperty("height","".concat(x,"px"),"important"),S.style.setProperty("min-width","".concat(x,"px"),"important"),S.style.setProperty("min-height","".concat(x,"px"),"important")}}var k=this.shadowRoot.querySelector(".start-call-btn");if(k){var C,P;e<=350?(C=48,P=14):e<=450?(C=52,P=15):e<=550?(C=58,P=17):e<=700?(C=62,P=18):(C=64,P=18),k.style.height="".concat(C,"px"),k.style.fontSize="".concat(P,"px");var T=k.querySelector("svg");if(T){var E=Math.max(22,.5*C);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")}},{key:"startVoiceCall",value:(o=so(ro().m(function t(){var e,n=this;return ro().w(function(t){for(;;)switch(t.n){case 0:if(!this.isActive){t.n=1;break}return console.log("⚠️ Voice call already active"),t.a(2);case 1:return console.log("🎤 Starting voice call..."),t.n=2,Vn();case 2:if(e=t.v,console.log("📋 Current permission state: ".concat(e)),"denied"!==e){t.n=3;break}return console.log("🚫 Permission is denied, showing blocked modal..."),Kn(),eo(function(){console.log("Blocked modal closed")}),t.a(2);case 3:if("prompt"!==e&&"unknown"!==e){t.n=4;break}return console.log("📋 Permission is in prompt state, showing pre-prompt modal..."),t.a(2,new Promise(function(t){to(so(ro().m(function e(){return ro().w(function(e){for(;;)switch(e.n){case 0:return console.log("✅ Pre-prompt accepted, proceeding with voice call..."),e.n=1,n.proceedWithVoiceCall();case 1:t();case 2:return e.a(2)}},e)})),function(){console.log("❌ Pre-prompt cancelled"),t()})}));case 4:return t.n=5,this.proceedWithVoiceCall();case 5:return t.a(2)}},t,this)})),function(){return o.apply(this,arguments)})},{key:"proceedWithVoiceCall",value:(n=so(ro().m(function t(){var e,n,o,r,i,a,s,c,l,u,d,p=this;return ro().w(function(t){for(;;)switch(t.p=t.n){case 0:return t.p=0,e=this.shadowRoot.getElementById("voiceIdleState"),n=this.shadowRoot.getElementById("voiceActiveState"),o=this.shadowRoot.getElementById("voiceInterface"),e&&(e.style.display="none"),n&&(n.style.display="flex"),setTimeout(function(){return p.adjustSizesForContainer()},50),o&&(o.scrollTop=0),r=Kn(),t.n=1,Vn();case 1:if(i=t.v,!r.isMobile||"granted"===i){t.n=5;break}return console.log("📱 Mobile device detected - requesting mic permission before connecting..."),console.log("📋 Current permission state: ".concat(i)),t.p=2,a=this.config.outputSampleRate||44100,t.n=3,navigator.mediaDevices.getUserMedia({audio:{sampleRate:a,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});case 3:t.v.getTracks().forEach(function(t){return t.stop()}),console.log("✅ Microphone permission granted on mobile - proceeding with connection"),t.n=5;break;case 4:return t.p=4,t.v,console.log("🚫 Permission denied on mobile, showing blocked modal..."),eo(function(){p.resetUIState()}),t.a(2);case 5:return t.n=6,this.getSignedUrl();case 6:if(s=t.v,console.log("🔗 Got signed URL:",s),!this.sdk||!this.sdk.isConnected){t.n=10;break}return console.log("🔄 SDK already connected, disconnecting for clean retry..."),t.p=7,this.sdk.disconnect(),t.n=8,new Promise(function(t){return setTimeout(t,100)});case 8:t.n=10;break;case 9:t.p=9,u=t.v,console.warn("Warning: Error disconnecting existing connection:",u);case 10:return t.n=11,this.sdk.connect(s);case 11:c=t.v,console.log("✅ Connected to WebSocket, connected:",c),l=0;case 12:if(!(l<50)){t.n=15;break}if(!this.sdk.isConnected){t.n=13;break}if(!(this.sdk.voiceSDK&&this.sdk.voiceSDK.isConnected&&this.sdk.voiceSDK.websocket&&this.sdk.voiceSDK.websocket.readyState===WebSocket.OPEN)){t.n=13;break}return t.a(3,15);case 13:return t.n=14,new Promise(function(t){return setTimeout(t,100)});case 14:l++,t.n=12;break;case 15:if(!(this.sdk.isConnected&&this.sdk.voiceSDK&&this.sdk.voiceSDK.websocket&&this.sdk.voiceSDK.websocket.readyState===WebSocket.OPEN)){t.n=17;break}return console.log("✅ WebSocket ready, starting listening..."),t.n=16,this.sdk.startListening();case 16:console.log("🎤 Started listening"),this.isActive=!0,this.callStartTime=Date.now(),this.callTimerInterval=setInterval(function(){var t=Date.now()-p.callStartTime,e=Math.floor(t/6e4),n=Math.floor(t%6e4/1e3),o=p.shadowRoot.getElementById("voiceTimer");o&&(o.textContent="".concat(e.toString().padStart(2,"0"),":").concat(n.toString().padStart(2,"0")))},1e3),t.n=19;break;case 17:return console.warn("⚠️ Connection not fully ready, but trying to start listening anyway..."),t.n=18,this.sdk.startListening();case 18:console.log("🎤 Started listening"),this.isActive=!0,this.callStartTime=Date.now(),this.callTimerInterval=setInterval(function(){var t=Date.now()-p.callStartTime,e=Math.floor(t/6e4),n=Math.floor(t%6e4/1e3),o=p.shadowRoot.getElementById("voiceTimer");o&&(o.textContent="".concat(e.toString().padStart(2,"0"),":").concat(n.toString().padStart(2,"0")))},1e3);case 19:console.log("✅ Voice call started successfully"),t.n=21;break;case 20:if(t.p=20,d=t.v,console.error("❌ Error starting voice call:",d),this.isActive=!1,this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null),this.sdk&&this.sdk.isConnected)try{this.sdk.disconnect()}catch(t){console.warn("Error disconnecting SDK on error:",t)}"NotAllowedError"===d.name||"PermissionDeniedError"===d.name?(Kn(),eo(function(){p.resetUIState()})):"NotFoundError"===d.name||"DevicesNotFoundError"===d.name?no(function(){p.resetUIState()}):(this.showError(d.message||d),this.resetUIState());case 21:return t.a(2)}},t,this,[[7,9],[2,4],[0,20]])})),function(){return n.apply(this,arguments)})},{key:"resetUIState",value:function(){var t=this.shadowRoot.getElementById("voiceIdleState"),e=this.shadowRoot.getElementById("voiceActiveState");t&&(t.style.display="flex"),e&&(e.style.display="none")}},{key:"endVoiceCall",value:function(){var t=this;console.log("🔴 Ending voice call..."),this.sdk&&this.isActive&&(this.sdk.stopListening(),this.sdk.disconnect(),this.isActive=!1),this.audioStream&&(this.audioStream.getTracks().forEach(function(t){return t.stop()}),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null);var e=this.shadowRoot.getElementById("voiceIdleState"),n=this.shadowRoot.getElementById("voiceActiveState");e&&(e.style.display="flex"),n&&(n.style.display="none"),setTimeout(function(){return t.adjustSizesForContainer()},50);var o=this.shadowRoot.getElementById("transcriptText");o&&(o.textContent=this.t("transcriptWillAppear"),o.classList.add("empty"));var r=this.shadowRoot.getElementById("voiceAvatarActive");r&&r.classList.remove("speaking"),console.log("✅ Voice call ended")}},{key:"updateTranscript",value:function(t){console.log("📝 [VOICE INTERFACE] updateTranscript called with text:",t);var e=this.shadowRoot.getElementById("transcriptText");e?(console.log("📝 [VOICE INTERFACE] Found transcript element, updating text"),e.textContent=t,e.classList.remove("empty")):console.warn("📝 [VOICE INTERFACE] ⚠️ transcriptText element not found!")}},{key:"showError",value:function(t){var e=this.shadowRoot.getElementById("transcriptText");e&&(e.textContent="".concat(this.t("error"),": ").concat(t),e.classList.remove("empty"))}},{key:"showDomainError",value:function(){var t=this.shadowRoot.getElementById("transcriptText");if(t){var e=this.t("domainNotValidated"),n=this.t("domainErrorMessage");t.innerHTML='<div style="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;">'.concat(e,'</div><div style="font-size: 14px; color: #991B1B; line-height: 1.5;">').concat(n,"</div>"),t.classList.remove("empty")}}},{key:"toggleMute",value:function(){if(this.sdk&&this.isActive){var t=null;if(this.sdk.voiceSDK&&this.sdk.voiceSDK.audioRecorder&&this.sdk.voiceSDK.audioRecorder.mediaStream&&(t=this.sdk.voiceSDK.audioRecorder.mediaStream.getAudioTracks()[0]),!t&&this.audioStream&&(t=this.audioStream.getAudioTracks()[0]),t){t.enabled=!t.enabled;var e=this.shadowRoot.getElementById("muteBtn"),n=null==e?void 0:e.querySelector(".mute-icon"),o=null==e?void 0:e.querySelector(".mute-cross");e&&n&&o&&(t.enabled?(n.style.stroke="",o.style.display="none",e.classList.remove("muted")):(n.style.stroke="#9ca3af",o.style.display="block",e.classList.add("muted"))),console.log(t.enabled?"🔊 Unmuted":"🔇 Muted")}else console.warn("⚠️ No audio track available for mute toggle")}}},{key:"toggleSpeaker",value:function(){console.log("🔊 Speaker toggle")}},{key:"destroy",value:function(){this.isActive&&this.endVoiceCall(),this.audioStream&&(this.audioStream.getTracks().forEach(function(t){return t.stop()}),this.audioStream=null),this.callTimerInterval&&(clearInterval(this.callTimerInterval),this.callTimerInterval=null),this.sdk&&(this.sdk.disconnect(),this.sdk=null)}}],e&&co(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o,r}();function po(t){return po="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},po(t)}function fo(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return ho(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(ho(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,ho(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,ho(d,"constructor",l),ho(l,"constructor",c),c.displayName="GeneratorFunction",ho(l,r,"GeneratorFunction"),ho(d),ho(d,r,"Generator"),ho(d,o,function(){return this}),ho(d,"toString",function(){return"[object Generator]"}),(fo=function(){return{w:i,m:p}})()}function ho(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}ho=function(t,e,n,o){function i(e,n){ho(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},ho(t,e,n,o)}function go(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function vo(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){go(i,o,r,a,s,"next",t)}function s(t){go(i,o,r,a,s,"throw",t)}a(void 0)})}}function mo(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,yo(o.key),o)}}function yo(t){var e=function(t){if("object"!=po(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=po(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==po(e)?e:e+""}var bo=function(){return t=function t(e,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.config=e,this.sdk=n,this.streamingEl=null,this.hasStartedStreaming=!1,this.isActive=!1,this.shadowRoot=e.shadowRoot||document,this.eventHandlers={autoResize:null,keydown:null},this.eventHandlersSetup=!1},e=[{key:"t",value:function(t){var e,n,o=this.config.language||"en";return((null===(e=this.config.translations)||void 0===e?void 0:e[o])||(null===(n=this.config.translations)||void 0===n?void 0:n.en)||{})[t]||t}},{key:"generateHTML",value:function(){var t,e,n,o,r,i,a,s,c,l=this.config.inputPlaceholder||(null===(t=this.config.panel)||void 0===t?void 0:t.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!==(e=this.config.sendButtonHint)&&void 0!==e&&e.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===(r=this.config.panel)||void 0===r||null===(r=r.sendButtonHint)||void 0===r?void 0:r.color)||"#6B7280","; font-size: ").concat((null===(i=this.config.sendButtonHint)||void 0===i?void 0:i.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>")}},{key:"generateCSS",value:function(){var t,e,n,o,r,i,a,s,c,l,u,d,p,f=this.config.messages,h=(this.config.panel,this.config.animation,this.config.sendButtonColor||(null===(t=this.config.panel)||void 0===t?void 0:t.sendButtonColor)||"#7C3AED"),g=this.config.sendButtonHoverColor||(null===(e=this.config.panel)||void 0===e?void 0:e.sendButtonHoverColor)||"#6D28D9",v=this.config.sendButtonTextColor||(null===(n=this.config.panel)||void 0===n?void 0:n.sendButtonTextColor)||"#FFFFFF",m=(this.config.inputPlaceholder||null===(o=this.config.panel)||void 0===o||o.inputPlaceholder,this.config.inputBorderColor||(null===(r=this.config.panel)||void 0===r?void 0:r.inputBorderColor)||"#E5E7EB"),y=this.config.inputFocusColor||(null===(i=this.config.panel)||void 0===i?void 0:i.inputFocusColor)||"#7C3AED",b=this.config.inputBackgroundColor||(null===(a=this.config.panel)||void 0===a?void 0:a.inputBackgroundColor)||"#FFFFFF",w=this.config.inputTextColor||(null===(s=this.config.panel)||void 0===s?void 0:s.inputTextColor)||"#1F2937",S=this.config.inputFontSize||(null===(c=this.config.panel)||void 0===c?void 0:c.inputFontSize)||"14px",x=this.config.inputBorderRadius||(null===(l=this.config.panel)||void 0===l?void 0:l.inputBorderRadius)||20,k=this.config.inputPadding||(null===(u=this.config.panel)||void 0===u?void 0:u.inputPadding)||"6px 14px",C=!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(C,"; \n flex: 1; \n flex-direction: column; \n min-height: 0; \n overflow: hidden; \n }\n .text-interface.active { display: flex").concat(C,"; }\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(f.borderRadius,"px; \n max-width: 80%; \n font-size: ").concat(f.fontSize,"; \n color: ").concat(f.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(f.userBackgroundColor,"; \n align-self: ").concat("rtl"===this.config.direction?"flex-start":"flex-end","; \n }\n .message.agent { \n background: ").concat(f.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(f.systemBackgroundColor,";\n align-self: flex-start;\n }\n .message.error {\n background: ").concat(f.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(k,";\n border: 1px solid ").concat(m,";\n border-radius: ").concat(x,"px;\n font-size: ").concat(S,";\n font-family: inherit;\n line-height: 1.3;\n resize: none;\n overflow-y: auto;\n background: ").concat(b,";\n color: ").concat(w,";\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"===b?"#FFFFFF":b,";\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(h,";\n color: ").concat(v,";\n font-size: ").concat(this.config.sendButtonFontSize||(null===(d=this.config.panel)||void 0===d?void 0:d.sendButtonFontSize)||"18px",";\n font-weight: ").concat(this.config.sendButtonFontWeight||(null===(p=this.config.panel)||void 0===p?void 0:p.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(g,";\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(f.errorBackgroundColor,";\n border-radius: ").concat(f.borderRadius,"px;\n color: #991B1B;\n font-size: ").concat(f.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 ")}},{key:"setupEventHandlers",value:function(){var t=this,e=this.shadowRoot.getElementById("sendButton"),n=this.shadowRoot.getElementById("messageInput"),o=this.shadowRoot.getElementById("newChatBtn");if(e&&(e.onclick=function(){return t.sendMessage()}),o&&(o.onclick=function(){return t.startNewChat()}),this.updateInputAttributes(),n){n.style.height="32px",n.style.overflow="hidden";var r=function(){n.style.height="auto";var t=Math.min(n.scrollHeight,120);n.style.height=t+"px",n.style.overflowY=t>=120?"auto":"hidden",t>=120&&setTimeout(function(){n.scrollTop=n.scrollHeight},0)};n.addEventListener("input",r),n.addEventListener("keydown",function(e){"Enter"!==e.key||e.shiftKey?"Enter"===e.key&&e.shiftKey&&setTimeout(r,0):(e.preventDefault(),t.sendMessage())})}}},{key:"startNewChat",value:function(){try{localStorage.removeItem("ttp_text_chat_conversation_id")}catch(t){}this.sdk&&(this.sdk.config.conversationId=null);var t=this.shadowRoot.getElementById("messagesContainer");t&&(t.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 e=this.shadowRoot.getElementById("messageInput");e&&e.focus()}},{key:"updateInputAttributes",value:function(){var t=this.shadowRoot.getElementById("messageInput");if(t){var e,n=this.config.inputPlaceholder||(null===(e=this.config.panel)||void 0===e?void 0:e.inputPlaceholder)||this.t("typeMessage")||"Type your message...";t.placeholder=n,t.dir=this.config.direction||"ltr",t.style.textAlign="rtl"===this.config.direction?"right":"left"}}},{key:"show",value:function(){var t=this,e=this.shadowRoot.getElementById("textInterface");e&&e.classList.add("active"),setTimeout(function(){var e=t.shadowRoot.getElementById("messageInput");e&&e.focus()},50)}},{key:"hide",value:function(){var t=this.shadowRoot.getElementById("textInterface");t&&t.classList.remove("active")}},{key:"startChat",value:(o=vo(fo().m(function t(){return fo().w(function(t){for(;;)switch(t.n){case 0:this.isActive=!0,this.updateSendButtonState();case 1:return t.a(2)}},t,this)})),function(){return o.apply(this,arguments)})},{key:"sendMessage",value:(n=vo(fo().m(function t(){var e,n,o;return fo().w(function(t){for(;;)switch(t.p=t.n){case 0:if(e=this.shadowRoot.getElementById("messageInput"),n=e.value.trim()){t.n=1;break}return t.a(2);case 1:if(this.isActive){t.n=2;break}return t.n=2,this.startChat();case 2:return this.addMessage("user",n),e.value="",e.style.height="32px",e.style.overflow="hidden",t.p=3,this.beginStreaming(),t.n=4,this.sdk.sendMessage(n);case 4:t.n=6;break;case 5:t.p=5,o=t.v,console.error("❌ Failed to send message:",o),o&&("DOMAIN_NOT_WHITELISTED"===o.message||o.message&&o.message.includes("Domain not whitelisted"))||this.showError(o),this.stopStreamingState();case 6:return t.a(2)}},t,this,[[3,5]])})),function(){return n.apply(this,arguments)})},{key:"updateSendButtonState",value:function(){var t=this.shadowRoot.getElementById("sendButton");t&&(t.disabled=!this.isActive)}},{key:"addMessage",value:function(t,e){var n=this.shadowRoot.getElementById("messagesContainer");if(n){var o=n.querySelector(".empty-state");o&&o.remove();var r=document.createElement("div"),i="rtl"===this.config.direction?"user"===t?"edge-left":"edge-right":"user"===t?"edge-right":"edge-left";r.className="message ".concat(t," ").concat(i);var a=document.createElement("div");a.className="message-avatar ".concat(t),a.textContent="user"===t?"👤":"🤖";var s=document.createElement("div");s.className="message-bubble",s.textContent=e,r.appendChild(a),r.appendChild(s),n.appendChild(r),n.scrollTop=n.scrollHeight}}},{key:"beginStreaming",value:function(){var t=this.shadowRoot.getElementById("messagesContainer");if(t){this.stopStreamingState();var e=document.createElement("div"),n="rtl"===this.config.direction?"edge-right":"edge-left";e.className="message agent ".concat(n),e.id="agent-streaming";var o=document.createElement("div");o.className="message-avatar agent",o.textContent="🤖";var r=document.createElement("div");r.className="message-bubble",r.innerHTML='<span class="typing-indicator"><span class="typing-dot"></span><span class="typing-dot"></span><span class="typing-dot"></span></span>',e.appendChild(o),e.appendChild(r),t.appendChild(e),this.streamingEl=r,this.hasStartedStreaming=!1,t.scrollTop=t.scrollHeight}}},{key:"appendStreamingChunk",value:function(t){if(this.streamingEl){this.hasStartedStreaming||(this.streamingEl.textContent="",this.hasStartedStreaming=!0),this.streamingEl.textContent+=t;var e=this.shadowRoot.getElementById("messagesContainer");e&&(e.scrollTop=e.scrollHeight)}}},{key:"finalizeStreaming",value:function(t){if(this.streamingEl){this.streamingEl.textContent=t||this.streamingEl.textContent;var e=this.shadowRoot.getElementById("agent-streaming");e&&(e.id=""),this.streamingEl=null}this.updateSendButtonState()}},{key:"stopStreamingState",value:function(){var t=this.shadowRoot.getElementById("agent-streaming");t&&t.remove(),this.streamingEl=null,this.hasStartedStreaming=!1}},{key:"showError",value:function(t){var e=this.shadowRoot.getElementById("messagesContainer");if(e){if(t&&("DOMAIN_NOT_WHITELISTED"===t.message||"string"==typeof t&&t.includes("DOMAIN_NOT_WHITELISTED")||t.message&&t.message.includes("Domain not whitelisted")||"string"==typeof t&&t.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 r=document.createElement("div");r.style.cssText="font-weight: 600; font-size: 16px; margin-bottom: 8px; color: #991B1B;",r.textContent=this.t("domainNotValidated");var i=document.createElement("div");i.style.cssText="font-size: 14px; color: #991B1B; line-height: 1.5;",i.textContent=this.t("domainErrorMessage"),o.appendChild(r),o.appendChild(i),e.appendChild(o)}else{var a=document.createElement("div");a.className="error-message",a.textContent="string"==typeof t?t:(null==t?void 0:t.message)||t,e.appendChild(a)}e.scrollTop=e.scrollHeight}}},{key:"setActive",value:function(t){this.isActive=t,this.updateSendButtonState()}}],e&&mo(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o}();const wo={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 So(){var t,e,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",r=n.toStringTag||"@@toStringTag";function i(n,o,r,i){var c=o&&o.prototype instanceof s?o:s,l=Object.create(c.prototype);return xo(l,"_invoke",function(n,o,r){var i,s,c,l=0,u=r||[],d=!1,p={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,n){return i=e,s=0,c=t,p.n=n,a}};function f(n,o){for(s=n,c=o,e=0;!d&&l&&!r&&e<u.length;e++){var r,i=u[e],f=p.p,h=i[2];n>3?(r=h===o)&&(c=i[(s=i[4])?5:(s=3,3)],i[4]=i[5]=t):i[0]<=f&&((r=n<2&&f<i[1])?(s=0,p.v=o,p.n=i[1]):f<h&&(r=n<3||i[0]>o||o>h)&&(i[4]=n,i[5]=o,p.n=h,s=0))}if(r||n>1)return a;throw d=!0,o}return function(r,u,h){if(l>1)throw TypeError("Generator is already running");for(d&&1===u&&f(u,h),s=u,c=h;(e=s<2?t:c)||!d;){i||(s?s<3?(s>1&&(p.n=-1),f(s,c)):p.n=c:p.v=c);try{if(l=2,i){if(s||(r="next"),e=i[r]){if(!(e=e.call(i,c)))throw TypeError("iterator result is not an object");if(!e.done)return e;c=e.value,s<2&&(s=0)}else 1===s&&(e=i.return)&&e.call(i),s<2&&(c=TypeError("The iterator does not provide a '"+r+"' method"),s=1);i=t}else if((e=(d=p.n<0)?c:n.call(o,p))!==a)break}catch(e){i=t,s=1,c=e}finally{l=1}}return{value:e,done:d}}}(n,r,i),!0),l}var a={};function s(){}function c(){}function l(){}e=Object.getPrototypeOf;var u=[][o]?e(e([][o]())):(xo(e={},o,function(){return this}),e),d=l.prototype=s.prototype=Object.create(u);function p(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,l):(t.__proto__=l,xo(t,r,"GeneratorFunction")),t.prototype=Object.create(d),t}return c.prototype=l,xo(d,"constructor",l),xo(l,"constructor",c),c.displayName="GeneratorFunction",xo(l,r,"GeneratorFunction"),xo(d),xo(d,r,"Generator"),xo(d,o,function(){return this}),xo(d,"toString",function(){return"[object Generator]"}),(So=function(){return{w:i,m:p}})()}function xo(t,e,n,o){var r=Object.defineProperty;try{r({},"",{})}catch(t){r=0}xo=function(t,e,n,o){function i(e,n){xo(t,e,function(t){return this._invoke(e,n,t)})}e?r?r(t,e,{value:n,enumerable:!o,configurable:!o,writable:!o}):t[e]=n:(i("next",0),i("throw",1),i("return",2))},xo(t,e,n,o)}function ko(t,e,n,o,r,i,a){try{var s=t[i](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(o,r)}function Co(t){return function(){var e=this,n=arguments;return new Promise(function(o,r){var i=t.apply(e,n);function a(t){ko(i,o,r,a,s,"next",t)}function s(t){ko(i,o,r,a,s,"throw",t)}a(void 0)})}}function Po(t){return Po="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Po(t)}function To(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function Eo(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?To(Object(n),!0).forEach(function(e){Oo(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):To(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function Oo(t,e,n){return(e=Io(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Ao(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,Io(o.key),o)}}function Io(t){var e=function(t){if("object"!=Po(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=Po(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==Po(e)?e:e+""}var Ro=function(){return t=function t(){var e,n,o,r,i,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.config=this.mergeWithDefaults(s),this.sdk=new de(this.config),this.isOpen=!1,this.isActive=!1,this.translations=wo,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 c=Eo(Eo(Eo({},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===(n=this.config.voice)||void 0===n?void 0:n.outputContainer)||"raw",outputEncoding:(null===(o=this.config.voice)||void 0===o?void 0:o.outputEncoding)||"pcm",outputSampleRate:(null===(r=this.config.voice)||void 0===r?void 0:r.outputSampleRate)||44100,outputChannels:(null===(i=this.config.voice)||void 0===i?void 0:i.outputChannels)||1,outputBitDepth:(null===(a=this.config.voice)||void 0===a?void 0:a.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 uo(c);var l=Eo(Eo(Eo({},this.config),this.config.text),{},{translations:this.translations,shadowRoot:this.shadowRoot});if(this.textInterface=new bo(l,this.sdk),this.createWidget(),this.setupEventHandlers(),this.config.behavior.startOpen||this.config.behavior.autoOpen){var u,d=null===(u=this.shadowRoot)||void 0===u?void 0:u.getElementById("text-chat-panel");d&&(this.isOpen=!0,d.classList.add("open"))}},e=[{key:"mergeWithDefaults",value:function(t){var e,n,o,r,i,a,s,c,l,u,d,p,f,h,g,v,m,y,b,w,S,x,k,C,P,T,E,O,A,I,R,F,j,D,_,B,M,U,N,z,H,L,K,V,W,G,q,Q,Y,$,J,X,Z,tt,et,nt,ot,rt,it,at,st,ct,lt,ut,dt,pt,ft,ht,gt,vt,mt,yt,bt,wt,St,xt,kt,Ct,Pt,Tt,Et,Ot,At,It,Rt,Ft,jt,Dt,_t,Bt,Mt,Ut,Nt,zt,Ht,Lt,Kt,Vt,Wt,Gt,qt,Qt,Yt,$t,Jt,Xt,Zt,te,ee,ne,oe,re,ie,ae,se,ce,le,ue,de,pe,fe,he,ge,ve,me,ye,be,we,Se,xe,ke,Ce,Pe,Te,Ee,Oe,Ae,Ie,Re,Fe,je=t.position||"bottom-right";if("string"==typeof je){var De=je.split("-");je={vertical:De[0]||"bottom",horizontal:De[1]||"right",offset:t.positionOffset||{x:20,y:20}}}var _e=t.primaryColor||(null===(e=t.button)||void 0===e?void 0:e.primaryColor)||(null===(n=t.button)||void 0===n?void 0:n.backgroundColor)||"#FFFFFF",Be=(null===(o=t.header)||void 0===o?void 0:o.backgroundColor)||"#7C3AED";return Eo({agentId:t.agentId,appId:t.appId,signedUrl:t.signedUrl,agentSettingsOverride:t.agentSettingsOverride,demo:!1!==t.demo,direction:t.direction||"ltr",language:t.language||"en",icon:Eo({type:(null===(r=t.icon)||void 0===r?void 0:r.type)||"custom",customImage:(null===(i=t.icon)||void 0===i?void 0:i.customImage)||"https://talktopc.com/logo192.png",emoji:(null===(a=t.icon)||void 0===a?void 0:a.emoji)||"🎤",text:(null===(s=t.icon)||void 0===s?void 0:s.text)||"AI",size:(null===(c=t.icon)||void 0===c?void 0:c.size)||"medium",backgroundColor:(null===(l=t.icon)||void 0===l?void 0:l.backgroundColor)||"#FFFFFF"},t.icon),position:Eo({vertical:je.vertical||"bottom",horizontal:je.horizontal||"right",offset:je.offset||{x:20,y:20}},"object"===Po(t.position)?t.position:{}),button:Eo({size:(null===(u=t.button)||void 0===u?void 0:u.size)||"medium",shape:(null===(d=t.button)||void 0===d?void 0:d.shape)||"circle",backgroundColor:(null===(p=t.button)||void 0===p?void 0:p.backgroundColor)||(null===(f=t.icon)||void 0===f?void 0:f.backgroundColor)||"#FFFFFF",hoverColor:(null===(h=t.button)||void 0===h?void 0:h.hoverColor)||"#D3D3D3",shadow:!1!==(null===(g=t.button)||void 0===g?void 0:g.shadow),shadowColor:(null===(v=t.button)||void 0===v?void 0:v.shadowColor)||"rgba(0,0,0,0.15)",primaryColor:(null===(m=t.button)||void 0===m?void 0:m.backgroundColor)||(null===(y=t.icon)||void 0===y?void 0:y.backgroundColor)||"#FFFFFF"},t.button),panel:Eo({width:(null===(b=t.panel)||void 0===b?void 0:b.width)||350,height:(null===(w=t.panel)||void 0===w?void 0:w.height)||500,borderRadius:(null===(S=t.panel)||void 0===S?void 0:S.borderRadius)||12,backgroundColor:(null===(x=t.panel)||void 0===x?void 0:x.backgroundColor)||"#FFFFFF",backdropFilter:(null===(k=t.panel)||void 0===k?void 0:k.backdropFilter)||null,border:(null===(C=t.panel)||void 0===C?void 0:C.border)||"1px solid #E5E7EB"},t.panel),voice:Eo({micButtonColor:(null===(P=t.voice)||void 0===P?void 0:P.micButtonColor)||(null===(T=t.panel)||void 0===T?void 0:T.micButtonColor)||_e,micButtonActiveColor:(null===(E=t.voice)||void 0===E?void 0:E.micButtonActiveColor)||(null===(O=t.panel)||void 0===O?void 0:O.micButtonActiveColor)||"#EF4444",micButtonHint:Eo(Eo({text:(null===(A=t.voice)||void 0===A||null===(A=A.micButtonHint)||void 0===A?void 0:A.text)||(null===(I=t.panel)||void 0===I||null===(I=I.micButtonHint)||void 0===I?void 0:I.text)||"Click the button to start voice conversation",color:(null===(R=t.voice)||void 0===R||null===(R=R.micButtonHint)||void 0===R?void 0:R.color)||(null===(F=t.panel)||void 0===F||null===(F=F.micButtonHint)||void 0===F?void 0:F.color)||"#6B7280",fontSize:(null===(j=t.voice)||void 0===j||null===(j=j.micButtonHint)||void 0===j?void 0:j.fontSize)||(null===(D=t.panel)||void 0===D||null===(D=D.micButtonHint)||void 0===D?void 0:D.fontSize)||"12px"},null===(_=t.voice)||void 0===_?void 0:_.micButtonHint),null===(B=t.panel)||void 0===B?void 0:B.micButtonHint),avatarBackgroundColor:(null===(M=t.voice)||void 0===M?void 0:M.avatarBackgroundColor)||"#667eea",avatarActiveBackgroundColor:(null===(U=t.voice)||void 0===U?void 0:U.avatarActiveBackgroundColor)||"#667eea",statusTitleColor:(null===(N=t.voice)||void 0===N?void 0:N.statusTitleColor)||"#1e293b",statusSubtitleColor:(null===(z=t.voice)||void 0===z?void 0:z.statusSubtitleColor)||"#64748b",startCallButtonColor:(null===(H=t.voice)||void 0===H?void 0:H.startCallButtonColor)||"#667eea",startCallButtonTextColor:(null===(L=t.voice)||void 0===L?void 0:L.startCallButtonTextColor)||"#FFFFFF",startCallTitle:(null===(K=t.voice)||void 0===K?void 0:K.startCallTitle)||null,startCallSubtitle:(null===(V=t.voice)||void 0===V?void 0:V.startCallSubtitle)||null,startCallButtonText:(null===(W=t.voice)||void 0===W?void 0:W.startCallButtonText)||null,transcriptBackgroundColor:(null===(G=t.voice)||void 0===G?void 0:G.transcriptBackgroundColor)||"#FFFFFF",transcriptTextColor:(null===(q=t.voice)||void 0===q?void 0:q.transcriptTextColor)||"#1e293b",transcriptLabelColor:(null===(Q=t.voice)||void 0===Q?void 0:Q.transcriptLabelColor)||"#94a3b8",controlButtonColor:(null===(Y=t.voice)||void 0===Y?void 0:Y.controlButtonColor)||"#FFFFFF",controlButtonSecondaryColor:(null===($=t.voice)||void 0===$?void 0:$.controlButtonSecondaryColor)||"#64748b",endCallButtonColor:(null===(J=t.voice)||void 0===J?void 0:J.endCallButtonColor)||"#ef4444",language:(null===(X=t.voice)||void 0===X?void 0:X.language)||t.language||"en"},t.voice),text:Eo({sendButtonColor:(null===(Z=t.text)||void 0===Z?void 0:Z.sendButtonColor)||(null===(tt=t.panel)||void 0===tt?void 0:tt.sendButtonColor)||"#7C3AED",sendButtonHoverColor:(null===(et=t.text)||void 0===et?void 0:et.sendButtonHoverColor)||(null===(nt=t.panel)||void 0===nt?void 0:nt.sendButtonHoverColor)||"#6D28D9",sendButtonActiveColor:(null===(ot=t.text)||void 0===ot?void 0:ot.sendButtonActiveColor)||(null===(rt=t.panel)||void 0===rt?void 0:rt.sendButtonActiveColor)||"#6D28D9",sendButtonText:(null===(it=t.text)||void 0===it?void 0:it.sendButtonText)||(null===(at=t.panel)||void 0===at?void 0:at.sendButtonText)||"➤",sendButtonTextColor:(null===(st=t.text)||void 0===st?void 0:st.sendButtonTextColor)||(null===(ct=t.panel)||void 0===ct?void 0:ct.sendButtonTextColor)||"#FFFFFF",sendButtonFontSize:(null===(lt=t.text)||void 0===lt?void 0:lt.sendButtonFontSize)||(null===(ut=t.panel)||void 0===ut?void 0:ut.sendButtonFontSize)||"18px",sendButtonFontWeight:(null===(dt=t.text)||void 0===dt?void 0:dt.sendButtonFontWeight)||(null===(pt=t.panel)||void 0===pt?void 0:pt.sendButtonFontWeight)||"500",sendButtonHint:Eo(Eo({text:(null===(ft=t.text)||void 0===ft||null===(ft=ft.sendButtonHint)||void 0===ft?void 0:ft.text)||(null===(ht=t.panel)||void 0===ht||null===(ht=ht.sendButtonHint)||void 0===ht?void 0:ht.text)||"",color:(null===(gt=t.text)||void 0===gt||null===(gt=gt.sendButtonHint)||void 0===gt?void 0:gt.color)||(null===(vt=t.panel)||void 0===vt||null===(vt=vt.sendButtonHint)||void 0===vt?void 0:vt.color)||"#6B7280",fontSize:(null===(mt=t.text)||void 0===mt||null===(mt=mt.sendButtonHint)||void 0===mt?void 0:mt.fontSize)||(null===(yt=t.panel)||void 0===yt||null===(yt=yt.sendButtonHint)||void 0===yt?void 0:yt.fontSize)||"12px"},null===(bt=t.text)||void 0===bt?void 0:bt.sendButtonHint),null===(wt=t.panel)||void 0===wt?void 0:wt.sendButtonHint),inputPlaceholder:(null===(St=t.text)||void 0===St?void 0:St.inputPlaceholder)||(null===(xt=t.panel)||void 0===xt?void 0:xt.inputPlaceholder)||"Type your message...",inputBorderColor:(null===(kt=t.text)||void 0===kt?void 0:kt.inputBorderColor)||(null===(Ct=t.panel)||void 0===Ct?void 0:Ct.inputBorderColor)||"#E5E7EB",inputFocusColor:(null===(Pt=t.text)||void 0===Pt?void 0:Pt.inputFocusColor)||(null===(Tt=t.panel)||void 0===Tt?void 0:Tt.inputFocusColor)||"#7C3AED",inputBackgroundColor:(null===(Et=t.text)||void 0===Et?void 0:Et.inputBackgroundColor)||(null===(Ot=t.panel)||void 0===Ot?void 0:Ot.inputBackgroundColor)||"#FFFFFF",inputTextColor:(null===(At=t.text)||void 0===At?void 0:At.inputTextColor)||(null===(It=t.panel)||void 0===It?void 0:It.inputTextColor)||"#1F2937",inputFontSize:(null===(Rt=t.text)||void 0===Rt?void 0:Rt.inputFontSize)||(null===(Ft=t.panel)||void 0===Ft?void 0:Ft.inputFontSize)||"14px",inputBorderRadius:(null===(jt=t.text)||void 0===jt?void 0:jt.inputBorderRadius)||(null===(Dt=t.panel)||void 0===Dt?void 0:Dt.inputBorderRadius)||20,inputPadding:(null===(_t=t.text)||void 0===_t?void 0:_t.inputPadding)||(null===(Bt=t.panel)||void 0===Bt?void 0:Bt.inputPadding)||"6px 14px"},t.text),landing:Eo({backgroundColor:(null===(Mt=t.landing)||void 0===Mt?void 0:Mt.backgroundColor)||"linear-gradient(180deg, #f8fafc 0%, #e0e7ff 100%)",logo:(null===(Ut=t.landing)||void 0===Ut?void 0:Ut.logo)||"🤖",title:(null===(Nt=t.landing)||void 0===Nt?void 0:Nt.title)||null,titleColor:(null===(zt=t.landing)||void 0===zt?void 0:zt.titleColor)||"#1e293b",modeCardBackgroundColor:(null===(Ht=t.landing)||void 0===Ht?void 0:Ht.modeCardBackgroundColor)||"#FFFFFF",modeCardBorderColor:(null===(Lt=t.landing)||void 0===Lt?void 0:Lt.modeCardBorderColor)||"#E2E8F0",modeCardHoverBorderColor:(null===(Kt=t.landing)||void 0===Kt?void 0:Kt.modeCardHoverBorderColor)||Be,modeCardIconBackgroundColor:(null===(Vt=t.landing)||void 0===Vt?void 0:Vt.modeCardIconBackgroundColor)||Be,modeCardTitleColor:(null===(Wt=t.landing)||void 0===Wt?void 0:Wt.modeCardTitleColor)||"#111827",voiceCardIcon:(null===(Gt=t.landing)||void 0===Gt?void 0:Gt.voiceCardIcon)||"🎤",textCardIcon:(null===(qt=t.landing)||void 0===qt?void 0:qt.textCardIcon)||"💬",voiceCardTitle:(null===(Qt=t.landing)||void 0===Qt?void 0:Qt.voiceCardTitle)||null,textCardTitle:(null===(Yt=t.landing)||void 0===Yt?void 0:Yt.textCardTitle)||null},t.landing),header:Eo({title:(null===($t=t.header)||void 0===$t?void 0:$t.title)||"Chat Assistant",showTitle:!1!==(null===(Jt=t.header)||void 0===Jt?void 0:Jt.showTitle),backgroundColor:(null===(Xt=t.header)||void 0===Xt?void 0:Xt.backgroundColor)||"#7C3AED",textColor:(null===(Zt=t.header)||void 0===Zt?void 0:Zt.textColor)||"#FFFFFF",showCloseButton:!1!==(null===(te=t.header)||void 0===te?void 0:te.showCloseButton)},t.header),footer:Eo({show:!1!==(null===(ee=t.footer)||void 0===ee?void 0:ee.show),backgroundColor:(null===(ne=t.footer)||void 0===ne?void 0:ne.backgroundColor)||"#f9fafb",textColor:(null===(oe=t.footer)||void 0===oe?void 0:oe.textColor)||"#9ca3af",hoverColor:(null===(re=t.footer)||void 0===re?void 0:re.hoverColor)||"#7C3AED"},t.footer),tooltips:Eo({newChat:(null===(ie=t.tooltips)||void 0===ie?void 0:ie.newChat)||null,back:(null===(ae=t.tooltips)||void 0===ae?void 0:ae.back)||null,close:(null===(se=t.tooltips)||void 0===se?void 0:se.close)||null,mute:(null===(ce=t.tooltips)||void 0===ce?void 0:ce.mute)||null,speaker:(null===(le=t.tooltips)||void 0===le?void 0:le.speaker)||null,endCall:(null===(ue=t.tooltips)||void 0===ue?void 0:ue.endCall)||null},t.tooltips),messages:Eo({userBackgroundColor:(null===(de=t.messages)||void 0===de?void 0:de.userBackgroundColor)||"#E5E7EB",agentBackgroundColor:(null===(pe=t.messages)||void 0===pe?void 0:pe.agentBackgroundColor)||"#F3F4F6",systemBackgroundColor:(null===(fe=t.messages)||void 0===fe?void 0:fe.systemBackgroundColor)||"#DCFCE7",errorBackgroundColor:(null===(he=t.messages)||void 0===he?void 0:he.errorBackgroundColor)||"#FEE2E2",textColor:(null===(ge=t.messages)||void 0===ge?void 0:ge.textColor)||"#1F2937",fontSize:(null===(ve=t.messages)||void 0===ve?void 0:ve.fontSize)||"14px",borderRadius:(null===(me=t.messages)||void 0===me?void 0:me.borderRadius)||8},t.messages),animation:Eo({enableHover:!1!==(null===(ye=t.animation)||void 0===ye?void 0:ye.enableHover),enablePulse:!1!==(null===(be=t.animation)||void 0===be?void 0:be.enablePulse),enableSlide:!1!==(null===(we=t.animation)||void 0===we?void 0:we.enableSlide),duration:(null===(Se=t.animation)||void 0===Se?void 0:Se.duration)||.3},t.animation),behavior:Eo({autoOpen:(null===(xe=t.behavior)||void 0===xe?void 0:xe.autoOpen)||!1,startOpen:(null===(ke=t.behavior)||void 0===ke?void 0:ke.startOpen)||!1,hidden:(null===(Ce=t.behavior)||void 0===Ce?void 0:Ce.hidden)||!1,autoConnect:(null===(Pe=t.behavior)||void 0===Pe?void 0:Pe.autoConnect)||!1,showWelcomeMessage:!1!==(null===(Te=t.behavior)||void 0===Te?void 0:Te.showWelcomeMessage),welcomeMessage:(null===(Ee=t.behavior)||void 0===Ee?void 0:Ee.welcomeMessage)||"Hello! How can I help you today?",enableVoiceMode:void 0===(null===(Oe=t.behavior)||void 0===Oe?void 0:Oe.enableVoiceMode)||t.behavior.enableVoiceMode,mode:(null===(Ae=t.behavior)||void 0===Ae?void 0:Ae.mode)||"unified"},t.behavior),accessibility:Eo({ariaLabel:(null===(Ie=t.accessibility)||void 0===Ie?void 0:Ie.ariaLabel)||"Chat Assistant",ariaDescription:(null===(Re=t.accessibility)||void 0===Re?void 0:Re.ariaDescription)||"Click to open chat assistant",keyboardNavigation:!1!==(null===(Fe=t.accessibility)||void 0===Fe?void 0:Fe.keyboardNavigation)},t.accessibility),customStyles:t.customStyles||"",useShadowDOM:!1!==t.useShadowDOM,variables:t.variables||{},forceConversationId:t.forceConversationId,onConversationStart:t.onConversationStart,onConversationEnd:t.onConversationEnd,onBargeIn:t.onBargeIn,onAudioStartPlaying:t.onAudioStartPlaying,onAudioStoppedPlaying:t.onAudioStoppedPlaying,onSubtitleDisplay:t.onSubtitleDisplay,primaryColor:_e},"string"==typeof t.position?{positionString:t.position}:{})}},{key:"setupEventHandlers",value:function(){var t=this;this.sdk.on("domainError",function(e){t.textInterface.showError(e),t.textInterface.stopStreamingState()}),this.sdk.on("error",function(e){e&&("DOMAIN_NOT_WHITELISTED"===e.message||e.message&&e.message.includes("Domain not whitelisted"))||(t.textInterface.showError(e.message||e),t.textInterface.stopStreamingState())}),this.sdk.on("chunk",function(e){t.textInterface.appendStreamingChunk(e)}),this.sdk.on("done",function(e){var n=e.text;t.textInterface.finalizeStreaming(n)})}},{key:"createShadowHost",value:function(){var t=document.getElementById("ttp-widget-shadow-host");t&&t.remove();var e=document.createElement("div");e.id="ttp-widget-shadow-host",e.style.cssText="position: fixed; z-index: 10000; pointer-events: none; top: 0; left: 0; width: 100%; height: 100%; overflow: visible;",this.shadowRoot=e.attachShadow({mode:"open"}),document.body.appendChild(e)}},{key:"createRegularContainer",value:function(){var t=document.getElementById("ttp-widget-container");t&&t.remove();var e=document.createElement("div");e.id="ttp-widget-container",e.style.cssText="position: fixed; z-index: 10000; pointer-events: none; top: 0; left: 0; width: 100%; height: 100%; overflow: visible;",document.body.appendChild(e),this.regularContainer=e}},{key:"createWidget",value:function(){this.container||(this.config.useShadowDOM?(this.createShadowHost(),this.container=this.shadowRoot):(this.createRegularContainer(),this.container=this.regularContainer,this.shadowRoot=document));var t;t=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 e=this.generateWidgetHTML();if(this.config.useShadowDOM){var n="\n <style>".concat(t,"</style>\n ").concat(e,"\n ");this.shadowRoot.innerHTML=n}else this.injectStylesIntoHead(t),this.container.innerHTML=e;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"))}},{key:"injectStylesIntoHead",value:function(t){var e,n,o=document.getElementById("ttp-widget-styles");o&&o.remove();var r={small:50,medium:60,large:70,xl:80}[null===(e=this.config.button)||void 0===e?void 0:e.size]||60,i={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,r,i),c=document.createElement("style");c.id="ttp-widget-styles",c.textContent=t+"\n"+s,this.config.customStyles&&(c.textContent+="\n"+this.config.customStyles),document.head.appendChild(c)}},{key:"generateWidgetHTML",value:function(){var t,e,n,o,r=this,i=(this.config.position,this.config.button),a=this.config.icon,s=(this.config.panel,this.config.header),c=(this.config.animation,{small:50,medium:60,large:70,xl:80}[i.size]||60),l={small:20,medium:28,large:36,xl:44}[a.size]||28,u=this.generatePositionStyles(),d=this.generateIconHTML(l),p=this.config.behavior.mode||"unified",f="unified"===p,h="unified"===p||"voice-only"===p,g="unified"===p||"text-only"===p,v=function(t){var e=r.config.language||"en";return(r.translations[e]||r.translations.en)[t]||t},m=function(t){var e,n=null===(e=r.config.tooltips)||void 0===e?void 0:e[t];return null!=n?n:{newChat:v("newChat"),back:v("back"),close:v("close"),mute:v("mute"),speaker:v("speaker"),endCall:v("endCall")}[t]||""},y=this.config.useShadowDOM?"\n <style>\n ".concat(this.generateCSS(u,c,l),"\n ").concat(this.config.customStyles,"\n </style>\n "):"";return"\n ".concat(y,"\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(s.backgroundColor,"; color: ").concat(s.textColor,';">\n <div>\n ').concat(s.showTitle?'<div class="header-title">'.concat(s.title,"</div>"):"",'\n <div class="header-status">\n <span class="status-dot"></span>\n <span>').concat(v("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(m("newChat"),'" style="').concat(f?"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"===p?'<button class="header-icon back-btn" id="backBtn" title="'.concat(m("back"),'" style="display: none;">\n <span style="font-size: 16px;">‹</span>\n </button>'):"","\n \n \x3c!-- Close Button --\x3e\n ").concat(s.showCloseButton?'<button class="header-icon close-btn" id="closeBtn" title="'+m("close")+'"><span style="font-size: 18px; font-weight: bold;">×</span></button>':"","\n </div>\n </div>\n\n ").concat(f?'\n <div class="landing-screen" id="landingScreen">\n <div class="landing-logo">'.concat((null===(t=this.config.landing)||void 0===t?void 0:t.logo)||"🤖",'</div>\n <div class="landing-title">').concat((null===(e=this.config.landing)||void 0===e?void 0:e.title)||v("landingTitle"),'</div>\n <div class="mode-selection">\n ').concat(h?'<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)||v("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)||v("textChat"),"</div>\n </div>"):"","\n </div>\n </div>"):"","\n\n ").concat(h?this.voiceInterface.generateHTML():"","\n ").concat(g?this.textInterface.generateHTML():"","\n ").concat(this.generateFooterHTML(),"\n </div>\n </div>\n </div>\n ")}},{key:"generateFooterHTML",value:function(){var t=this.config.footer;if(!t.show)return"";var e=encodeURIComponent(window.location.hostname||"widget"),n="https://talktopc.com?ref=widget&source=".concat(e);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(t.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(t.textColor,';\n transition: color 0.2s ease;\n "\n onmouseover="this.style.color=\'').concat(t.hoverColor,"'\"\n onmouseout=\"this.style.color='").concat(t.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 ')}},{key:"generatePositionStyles",value:function(){var t=this.config.position,e=t.offset||{x:20,y:20},n="";return"top"===t.vertical?n+="top: ".concat(e.y,"px;"):"bottom"===t.vertical?n+="bottom: ".concat(e.y,"px;"):"center"===t.vertical&&(n+="top: 50%; transform: translateY(-50%);"),"left"===t.horizontal?n+="left: ".concat(e.x,"px;"):"right"===t.horizontal?n+="right: ".concat(e.x,"px;"):"center"===t.horizontal&&(n+="left: 50%; transform: translateX(-50%);"),n}},{key:"generateIconHTML",value:function(t){var e=this.config.icon;switch(e.type){case"custom":return'<img src="'.concat(e.customImage,'" alt="Chat Assistant" style="width: ').concat(t,"px; height: ").concat(t,'px; object-fit: contain;" />');case"emoji":return'<span style="font-size: '.concat(t,'px; line-height: 1;">').concat(e.emoji,"</span>");case"text":return'<span style="font-size: '.concat(Math.floor(.6*t),'px; font-weight: bold; color: white;">').concat(e.text,"</span>");case"microphone":default:return'<svg viewBox="0 0 24 24" style="width: '.concat(t,"px; height: ").concat(t,'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(t,"px; height: ").concat(t,'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>')}}},{key:"generateCSS",value:function(t,e,n){var o,r,i,a,s,c,l,u,d,p,f,h=this.config.button,g=this.config.icon,v=this.config.panel,m=this.config.header,y=(this.config.messages,this.config.animation),b=this.config.behavior.mode||"unified",w="unified"===b||"voice-only"===b,S="unified"===b||"text-only"===b,x=!1===this.config.useShadowDOM?" !important":"",k=m.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(t,"\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===(r=this.config.position.offset)||void 0===r?void 0:r.y)||20,"px;"),"\n ").concat("right"===this.config.position.horizontal?"right: ".concat((null===(i=this.config.position.offset)||void 0===i?void 0:i.x)||20,"px;"):"left: ".concat((null===(a=this.config.position.offset)||void 0===a?void 0:a.x)||20,"px;"),"\n width: ").concat(e,"px;\n height: ").concat(e,"px;\n border-radius: ").concat("circle"===h.shape?"50%":"square"===h.shape?"0":"12px",";\n background: ").concat(h.backgroundColor||g.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(h.hoverColor?"background: ".concat(h.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(x,";\n position: fixed;\n bottom: calc(").concat(e,"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(e,"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(x,";\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(x,"; \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(x,"; }\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===(u=this.config.landing)||void 0===u?void 0:u.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===(d=this.config.landing)||void 0===d?void 0:d.modeCardHoverBorderColor)||k,"; \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===(p=this.config.landing)||void 0===p?void 0:p.modeCardIconBackgroundColor)||k,"; \n color: #fff; \n font-size: 32px; \n }\n .mode-card-title { \n color: ").concat((null===(f=this.config.landing)||void 0===f?void 0:f.modeCardTitleColor)||"#111827","; \n font-weight: 600; \n text-align: center;\n width: 100%;\n }\n\n ").concat(w?this.voiceInterface.generateCSS():"","\n ").concat(S?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 ")}},{key:"setupWidgetEvents",value:function(){var t=this;if(this.shadowRoot){var e=this.shadowRoot.getElementById("text-chat-button");e&&(e.onclick=function(){return t.togglePanel()});var n=this.shadowRoot.getElementById("closeBtn");n&&(n.onclick=function(){return t.togglePanel()});var o=this.config.behavior.mode||"unified",r="unified"===o,i="unified"===o||"voice-only"===o,a="unified"===o||"text-only"===o,s=this.shadowRoot.getElementById("backBtn"),c=this.shadowRoot.getElementById("landingScreen"),l=this.shadowRoot.getElementById("mode-card-voice"),u=this.shadowRoot.getElementById("mode-card-text"),d=this.shadowRoot.getElementById("textInterface"),p=this.shadowRoot.getElementById("voiceInterface");s&&(s.onclick=function(){return t.showLanding()}),r?(l&&(l.onclick=function(){return t.showVoice()}),u&&(u.onclick=function(){return t.showText()}),"text"===this.currentView?(c&&c.classList.remove("active"),d&&d.classList.add("active"),p&&p.classList.remove("active"),s&&"unified"===o&&s.classList.add("visible"),f&&(f.style.display="")):"voice"===this.currentView?(c&&c.classList.remove("active"),d&&d.classList.remove("active"),p&&p.classList.add("active"),s&&"unified"===o&&s.classList.add("visible"),f&&(f.style.display="none")):(this.currentView="landing",c&&c.classList.add("active"),d&&d.classList.remove("active"),p&&p.classList.remove("active"),s&&"unified"===o&&s.classList.remove("visible"))):"voice-only"===o?(p&&p.classList.add("active"),d&&d.classList.remove("active"),c&&c.classList.remove("active")):"text-only"===o&&(d&&d.classList.add("active"),p&&p.classList.remove("active"),c&&c.classList.remove("active")),i&&(console.log("⚙️ Setting up voice interface event handlers"),this.voiceInterface.setupEventHandlers()),a&&(console.log("⚙️ Setting up text interface event handlers"),this.textInterface.setupEventHandlers());var f=this.shadowRoot.getElementById("newChatBtn");f&&(f.onclick=function(){return t.textInterface.startNewChat()},r&&(f.style.display="none")),this.config.accessibility.keyboardNavigation&&this.setupKeyboardNavigation()}}},{key:"startNewChat",value:function(){this.textInterface.startNewChat()}},{key:"showLanding",value:function(){if(this.shadowRoot&&"unified"===(this.config.behavior.mode||"unified")){this.currentView="landing";var t=this.shadowRoot.getElementById("landingScreen"),e=this.shadowRoot.getElementById("textInterface"),n=this.shadowRoot.getElementById("voiceInterface"),o=this.shadowRoot.getElementById("backBtn"),r=this.shadowRoot.getElementById("newChatBtn");t&&t.classList.add("active"),e&&e.classList.remove("active"),n&&n.classList.remove("active"),o&&o.classList.remove("visible"),r&&(r.style.display="none")}}},{key:"showText",value:function(){if(this.shadowRoot){this.currentView="text";var t=this.shadowRoot.getElementById("landingScreen"),e=this.shadowRoot.getElementById("voiceInterface"),n=this.shadowRoot.getElementById("backBtn"),o=this.shadowRoot.getElementById("newChatBtn");t&&t.classList.remove("active"),e&&e.classList.remove("active"),this.textInterface.show();var r=this.config.behavior.mode||"unified";n&&"unified"===r&&n.classList.add("visible"),o&&(o.style.display="")}}},{key:"showVoice",value:function(){if(this.shadowRoot){this.currentView="voice";var t=this.shadowRoot.getElementById("landingScreen"),e=this.shadowRoot.getElementById("textInterface"),n=this.shadowRoot.getElementById("voiceInterface"),o=this.shadowRoot.getElementById("backBtn"),r=this.shadowRoot.getElementById("newChatBtn");t&&t.classList.remove("active"),e&&e.classList.remove("active"),n&&n.classList.add("active");var i=this.config.behavior.mode||"unified";o&&"unified"===i&&o.classList.add("visible"),r&&(r.style.display="none")}}},{key:"setupKeyboardNavigation",value:function(){var t=this;document.addEventListener("keydown",function(e){"Escape"===e.key&&t.isOpen&&t.togglePanel()})}},{key:"togglePanel",value:function(){var t=this;if(this.shadowRoot){this.isOpen=!this.isOpen;var e=this.shadowRoot.getElementById("text-chat-panel");e&&e.classList.toggle("open"),this.isOpen&&setTimeout(function(){var e=t.shadowRoot.getElementById("messageInput");e&&e.focus()},100),this.isOpen&&!this.isActive&&this.config.behavior.autoConnect&&this.startChat()}}},{key:"startChat",value:(i=Co(So().m(function t(){return So().w(function(t){for(;;)switch(t.n){case 0:this.isActive=!0,this.textInterface.setActive(!0);case 1:return t.a(2)}},t,this)})),function(){return i.apply(this,arguments)})},{key:"sendMessage",value:(r=Co(So().m(function t(){return So().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,this.textInterface.sendMessage();case 1:return t.a(2)}},t,this)})),function(){return r.apply(this,arguments)})},{key:"updateSendButtonState",value:function(){this.textInterface.updateSendButtonState()}},{key:"getSignedUrl",value:(o=Co(So().m(function t(){var e,n;return So().w(function(t){for(;;)switch(t.n){case 0:if(!this.config.signedUrl){t.n=1;break}return t.a(2,this.config.signedUrl);case 1:if(this.config.agentId){t.n=2;break}throw new Error("agentId is required when signedUrl is not provided");case 2:return e=this.config.websocketUrl||"wss://backend.talktopc.com/ws/conv",(n=new URLSearchParams).append("agentId",this.config.agentId),this.config.appId&&n.append("appId",this.config.appId),!1!==this.config.demo&&n.append("demo","true"),t.a(2,"".concat(e,"?").concat(n.toString()))}},t,this)})),function(){return o.apply(this,arguments)})},{key:"addMessage",value:function(t,e){this.textInterface.addMessage(t,e)}},{key:"beginStreaming",value:function(){this.textInterface.beginStreaming()}},{key:"appendStreamingChunk",value:function(t){this.textInterface.appendStreamingChunk(t)}},{key:"finalizeStreaming",value:function(t){this.textInterface.finalizeStreaming(t)}},{key:"stopStreamingState",value:function(){this.textInterface.stopStreamingState()}},{key:"showError",value:function(t){this.textInterface.showError(t)}},{key:"updateStatus",value:function(t){}},{key:"updateConfig",value:function(t){var e,n,o,r,i,a,s,c,l,u=Eo({},this.config);t.panel&&(u.panel=Eo(Eo({},this.config.panel),t.panel)),t.voice&&(u.voice=Eo(Eo({},this.config.voice),t.voice),t.voice.micButtonHint&&(u.voice.micButtonHint=Eo(Eo({},null===(c=this.config.voice)||void 0===c?void 0:c.micButtonHint),t.voice.micButtonHint))),t.text&&(u.text=Eo(Eo({},this.config.text),t.text),t.text.sendButtonHint&&(u.text.sendButtonHint=Eo(Eo({},null===(l=this.config.text)||void 0===l?void 0:l.sendButtonHint),t.text.sendButtonHint))),void 0!==t.language&&(u.language=t.language),void 0!==t.language&&(["he","ar"].includes(t.language)?u.direction="rtl":void 0===t.direction&&(u.direction="ltr")),t.translations&&(u.translations=t.translations,this.translations=t.translations),t.button&&(u.button=Eo(Eo({},this.config.button),t.button)),t.header&&(u.header=Eo(Eo({},this.config.header),t.header)),t.icon&&(u.icon=Eo(Eo({},this.config.icon),t.icon)),t.messages&&(u.messages=Eo(Eo({},this.config.messages),t.messages)),t.animation&&(u.animation=Eo(Eo({},this.config.animation),t.animation)),t.behavior&&(u.behavior=Eo(Eo({},this.config.behavior),t.behavior)),t.accessibility&&(u.accessibility=Eo(Eo({},this.config.accessibility),t.accessibility)),t.tooltips&&(u.tooltips=Eo(Eo({},this.config.tooltips),t.tooltips)),t.landing&&(u.landing=Eo(Eo({},this.config.landing),t.landing)),t.footer&&(u.footer=Eo(Eo({},this.config.footer),t.footer)),void 0!==t.direction&&void 0===u.direction&&(u.direction=t.direction),void 0!==t.primaryColor&&(u.primaryColor=t.primaryColor),u.onConversationStart=void 0!==t.onConversationStart?t.onConversationStart:this.config.onConversationStart,u.onConversationEnd=void 0!==t.onConversationEnd?t.onConversationEnd:this.config.onConversationEnd,u.onBargeIn=void 0!==t.onBargeIn?t.onBargeIn:this.config.onBargeIn,u.onAudioStartPlaying=void 0!==t.onAudioStartPlaying?t.onAudioStartPlaying:this.config.onAudioStartPlaying,u.onAudioStoppedPlaying=void 0!==t.onAudioStoppedPlaying?t.onAudioStoppedPlaying:this.config.onAudioStoppedPlaying,u.onSubtitleDisplay=void 0!==t.onSubtitleDisplay?t.onSubtitleDisplay:this.config.onSubtitleDisplay,void 0!==t.useShadowDOM&&(u.useShadowDOM=t.useShadowDOM),Object.keys(t).forEach(function(e){["panel","button","header","footer","icon","messages","direction","voice","text","animation","behavior","accessibility","language","tooltips","landing","primaryColor","useShadowDOM","onConversationStart","onConversationEnd","onBargeIn","onAudioStartPlaying","onAudioStoppedPlaying","onSubtitleDisplay"].includes(e)||(u[e]=t[e])}),null===(e=this.config)||void 0===e||e.language;var d=!1!==(null===(n=this.config)||void 0===n?void 0:n.useShadowDOM);if(this.config=this.mergeWithDefaults(u),!1!==this.config.useShadowDOM===d&&this.container){var p=document.getElementById("ttp-widget-shadow-host");p&&!this.config.useShadowDOM&&p.remove();var f=document.getElementById("ttp-widget-container");if(f&&this.config.useShadowDOM&&f.remove(),this.config.useShadowDOM)if(this.shadowRoot)this.container=this.shadowRoot;else{var h=document.getElementById("ttp-widget-shadow-host");h?(this.shadowRoot=h.shadowRoot,this.container=this.shadowRoot):(this.createShadowHost(),this.container=this.shadowRoot)}else{if(this.regularContainer)this.container=this.regularContainer;else{var g=document.getElementById("ttp-widget-container");g?(this.regularContainer=g,this.container=g):(this.createRegularContainer(),this.container=this.regularContainer)}this.shadowRoot=document}}else{var v=document.getElementById("ttp-widget-shadow-host");v&&v.remove();var m=document.getElementById("ttp-widget-container");if(m&&m.remove(),!1===d){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 b=this.config.language||"en",w=Eo(Eo(Eo({},this.config),this.config.voice),{},{language:b,translations:this.translations,shadowRoot:this.shadowRoot,outputContainer:(null===(o=this.config.voice)||void 0===o?void 0:o.outputContainer)||"raw",outputEncoding:(null===(r=this.config.voice)||void 0===r?void 0:r.outputEncoding)||"pcm",outputSampleRate:(null===(i=this.config.voice)||void 0===i?void 0:i.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 uo(w);var S=Eo(Eo(Eo({},this.config),this.config.text),{},{language:b,translations:this.translations,shadowRoot:this.shadowRoot});this.textInterface=new bo(S,this.sdk),this.createWidget(),this.textInterface&&this.textInterface.updateInputAttributes&&this.textInterface.updateInputAttributes()}},{key:"destroy",value:function(){var t=document.getElementById("ttp-widget-shadow-host");t&&t.remove();var e=document.getElementById("ttp-widget-container");e&&e.remove();var n=document.getElementById("ttp-widget-styles");n&&n.remove(),this.sdk&&this.sdk.destroy(),this.voiceInterface&&this.voiceInterface.destroy()}},{key:"startVoiceCall",value:(n=Co(So().m(function t(){return So().w(function(t){for(;;)switch(t.n){case 0:return t.n=1,this.voiceInterface.startVoiceCall();case 1:this._flushPendingClientTools();case 2:return t.a(2)}},t,this)})),function(){return n.apply(this,arguments)})},{key:"endVoiceCall",value:function(){this.voiceInterface.endVoiceCall()}},{key:"toggleMute",value:function(){this.voiceInterface.toggleMute()}},{key:"toggleSpeaker",value:function(){this.voiceInterface.toggleSpeaker()}},{key:"registerToolHandler",value:function(t,e){var n;return null!==(n=this.voiceInterface)&&void 0!==n&&n.sdk?this.voiceInterface.sdk.registerToolHandler(t,e):(this._pendingClientTools=this._pendingClientTools||[],this._pendingClientTools.push({name:t,handler:e}),console.warn("TTPChatWidget: Tool handler queued - voice interface SDK not ready yet"),this._flushPendingClientTools(),this)}},{key:"unregisterToolHandler",value:function(t){var e;return null!==(e=this.voiceInterface)&&void 0!==e&&e.sdk?this.voiceInterface.sdk.unregisterToolHandler(t):(this._pendingClientTools&&(this._pendingClientTools=this._pendingClientTools.filter(function(e){return e.name!==t})),this)}},{key:"hasToolHandler",value:function(t){var e;return!(null===(e=this.voiceInterface)||void 0===e||!e.sdk)&&this.voiceInterface.sdk.hasToolHandler(t)}},{key:"getRegisteredTools",value:function(){var t;return null!==(t=this.voiceInterface)&&void 0!==t&&t.sdk?this.voiceInterface.sdk.getRegisteredTools():this._pendingClientTools?this._pendingClientTools.map(function(t){return t.name}):[]}},{key:"_flushPendingClientTools",value:function(){var t,e=this;this._pendingClientTools&&null!==(t=this.voiceInterface)&&void 0!==t&&t.sdk&&(this._pendingClientTools.forEach(function(t){var n=t.name,o=t.handler;e.voiceInterface.sdk.registerToolHandler(n,o)}),this._pendingClientTools=null,console.log("TTPChatWidget: Flushed pending client tools"))}},{key:"registerClientTool",value:function(t,e){return this.registerToolHandler(t,e)}},{key:"unregisterClientTool",value:function(t){return this.unregisterToolHandler(t)}},{key:"hasClientTool",value:function(t){return this.hasToolHandler(t)}},{key:"getRegisteredClientTools",value:function(){return this.getRegisteredTools()}}],e&&Ao(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,n,o,r,i}(),Fo="2.18.0";const jo={VoiceSDK_v2:Qt,TextChatSDK:de,WebSocketManager:_e,AudioRecorder:qe,AudioPlayer:rn,EventEmitter:Xt,VoiceButton:mn,VanillaVoiceButton:En,AgentSDK:Nn,TTPChatWidget:Ro,VERSION:Fo};return o})());
|
|
3
3
|
//# sourceMappingURL=agent-widget.js.map
|