@botuyo/chat-widget-standalone 1.8.8 → 1.8.9

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.
@@ -26,7 +26,7 @@ return y("div",{className:"w-full my-2 rounded-2xl border shadow-sm overflow-hid
26
26
  /* @__PURE__ */y("button",{type:"button",onClick:()=>{d||(c("cancelled"),o?.(e.proposalId))},"data-testid":"tool-proposal-cancel",className:"flex-1 flex items-center justify-center gap-1.5 py-3 text-xs font-bold transition-colors hover:bg-muted/50 active:scale-[0.98]",style:{color:"hsl(var(--muted-foreground))"},children:[
27
27
  /* @__PURE__ */b(fe,{size:14,strokeWidth:2.5}),a("cancel")]}),
28
28
  /* @__PURE__ */y("button",{type:"button",onClick:()=>{p||(c("confirmed"),r?.(e.proposalId))},disabled:p,"data-testid":"tool-proposal-confirm",className:"flex-1 flex items-center justify-center gap-1.5 py-3 text-xs font-black text-white transition-all active:scale-[0.98] disabled:opacity-40 disabled:cursor-not-allowed disabled:active:scale-100",style:{backgroundColor:s},children:[
29
- /* @__PURE__ */b(Z,{size:14,strokeWidth:3}),a("confirm")]})]})]})}const Ul=p(()=>import("./AudioPlayer-BdU6dFck.js").then(e=>({default:e.AudioPlayer}))),ql=p(()=>import("./Gallery-CoKglJTc.js").then(e=>({default:e.Gallery})));function Vl({message:e,brandColor:t,onButtonClick:n}){const[r,o]=i(e.selectedId||null);/* @__PURE__ */
29
+ /* @__PURE__ */b(Z,{size:14,strokeWidth:3}),a("confirm")]})]})]})}const Ul=p(()=>import("./AudioPlayer-CLKsDc0I.js").then(e=>({default:e.AudioPlayer}))),ql=p(()=>import("./Gallery-YA_Vmft5.js").then(e=>({default:e.Gallery})));function Vl({message:e,brandColor:t,onButtonClick:n}){const[r,o]=i(e.selectedId||null);/* @__PURE__ */
30
30
  return y("div",{className:"space-y-3",children:[
31
31
  /* @__PURE__ */b("div",{className:Mt("prose prose-sm max-w-none break-words leading-relaxed dark:prose-invert text-foreground"),children:/* @__PURE__ */b(Da,{remarkPlugins:[Al],rehypePlugins:[[Fl,{tagNames:["p","strong","em","br","span"],attributes:{}}]],components:{p:({children:e})=>/* @__PURE__ */b("p",{className:"mb-0 last:mb-0",children:e})},children:e.content})}),
32
32
  /* @__PURE__ */b("div",{className:"flex flex-col gap-2",children:e.buttons.map((i,a)=>{const s=r===i.id;/* @__PURE__ */
@@ -37,7 +37,7 @@ return b("button",{type:"button",onClick:()=>(t=>{r||(o(t.id),n?.(t.label,e))})(
37
37
  /* @__PURE__ */b("span",{className:"flex flex-col min-w-0 flex-1 text-[11px] font-bold text-foreground leading-tight uppercase tracking-tight",children:f("ver_ubicacion")}),
38
38
  /* @__PURE__ */b(K,{size:12,className:"text-muted-foreground/40 group-hover:text-primary"})]})}):i?/* @__PURE__ */y("a",{href:e,target:c,rel:u,onClick:l,className:"inline-flex items-center justify-center gap-2 px-4 py-2.5 mt-2 mx-1 text-[11px] font-black w-[calc(100%-0.5rem)] sm:w-auto rounded-xl shadow-md uppercase tracking-widest transition-transform active:scale-95 text-white",style:{backgroundColor:x},children:[t," ",
39
39
  /* @__PURE__ */b(V,{size:14})]}):/* @__PURE__ */b("a",{href:e,target:c,rel:u,onClick:l,className:"font-bold underline decoration-primary/30 hover:decoration-primary transition-all break-words",style:{color:m?"inherit":x},children:t})},N=({src:e,alt:t})=>e?/* @__PURE__ */b(h,{fallback:/* @__PURE__ */b("div",{className:"my-3 animate-pulse",children:/* @__PURE__ */b("div",{className:"w-full h-48 bg-muted rounded-xl"})}),children:/* @__PURE__ */b(ql,{images:[{src:e,alt:t}],radius:"rounded-xl"})}):null;return"tool_proposal"===e.type?/* @__PURE__ */b(Bl,{message:e,primaryColor:t,onConfirm:e=>p?.(e,"confirm"),onCancel:e=>p?.(e,"reject")}):g?/* @__PURE__ */b("div",{className:"flex justify-center my-4 animate-in fade-in zoom-in-95 w-full",children:/* @__PURE__ */b("span",{className:"px-3 py-1 border rounded-full text-[9px] font-black uppercase tracking-widest",style:{backgroundColor:"hsl(var(--muted))",borderColor:"hsl(var(--border))",color:"hsl(var(--muted-foreground))"},children:e.content})}):/* @__PURE__ */y("div",{className:Mt("flex w-full mb-0.5 group",S,m?"justify-end":"justify-start gap-3",s&&"mt-3",l&&"mb-3"),style:{animationDelay:50*c+"ms"},children:[!m&&/* @__PURE__ */b("div",{className:"w-9 shrink-0 flex flex-col justify-end pb-1",children:/* @__PURE__ */b("div",l?{className:"h-9 w-9 rounded-full overflow-hidden border shadow-sm",style:{borderColor:"hsl(var(--border))",backgroundColor:"hsl(var(--background))"},children:E?/* @__PURE__ */b("img",{src:C||"",alt:r,className:"h-full w-full object-cover",onError:()=>_(!0)}):/* @__PURE__ */b("div",{className:"h-full w-full flex items-center justify-center bg-muted text-muted-foreground",children:/* @__PURE__ */b("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:/* @__PURE__ */b("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"})})})}:{className:"w-9"})}),
40
- /* @__PURE__ */y("div",{className:Mt("max-w-[85%] shadow-sm transition-all duration-300 relative",m?"text-primary-foreground":"border",m?Mt("rounded-[var(--bubble-radius,18px)]",s&&"rounded-tr-[4px]",!l&&"rounded-br-[4px]",!s&&!l&&"rounded-r-[4px]"):Mt("rounded-[var(--bubble-radius,18px)]",s&&"rounded-tl-[4px]",!l&&"rounded-bl-[4px]",!s&&!l&&"rounded-l-[4px]")),style:m?{padding:"var(--spacing-4) var(--spacing-5)",backgroundColor:x,boxShadow:l?`0 8px 20px -6px ${x}33`:"none"}:{padding:"var(--spacing-4) var(--spacing-5)",backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border) / 0.6)",color:"hsl(var(--foreground))"},children:[(()=>{switch(e.type){case"audio":/* @__PURE__ */
40
+ /* @__PURE__ */y("div",{className:Mt("max-w-[85%] shadow-sm transition-all duration-300 relative",m?"text-primary-foreground":"border",m?Mt("rounded-[var(--bubble-radius,18px)]",s&&"rounded-tr-[4px]",!l&&"rounded-br-[4px]",!s&&!l&&"rounded-r-[4px]"):Mt("rounded-[var(--bubble-radius,18px)]",s&&"rounded-tl-[4px]",!l&&"rounded-bl-[4px]",!s&&!l&&"rounded-l-[4px]")),style:m?{padding:"var(--spacing-4) var(--spacing-5)",backgroundColor:x,boxShadow:l?`0 8px 20px -6px ${x}33`:"none"}:{padding:"var(--spacing-4) var(--spacing-5)",backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border) / 0.6)",borderWidth:"var(--border-width, 1px)",color:"hsl(var(--foreground))"},children:[(()=>{switch(e.type){case"audio":/* @__PURE__ */
41
41
  return b(h,{fallback:/* @__PURE__ */y("div",{className:"flex items-center gap-3 py-1 min-w-[200px] animate-pulse",children:[
42
42
  /* @__PURE__ */b("div",{className:"w-8 h-8 rounded-full bg-muted"}),
43
43
  /* @__PURE__ */b("div",{className:"flex-1 space-y-1",children:/* @__PURE__ */b("div",{className:"h-1 w-full bg-muted rounded-full"})})]}),children:/* @__PURE__ */y("div",{children:[
@@ -95,7 +95,7 @@ return y("div",{className:"relative",children:[(C||z)&&/* @__PURE__ */b("div",{c
95
95
  /* @__PURE__ */b(G,{size:18,className:"text-purple-500"})," Archivos"]}),B.enableLocation&&s&&/* @__PURE__ */y("button",{onClick:()=>{T(!0),navigator.geolocation.getCurrentPosition(e=>{s?.({latitude:e.coords.latitude,longitude:e.coords.longitude}),T(!1),w(!1)},()=>T(!1))},className:"flex items-center border shadow-soft-2xl rounded-2xl transition-colors text-[10px] font-black uppercase tracking-widest",style:{gap:"var(--spacing-3)",padding:"var(--spacing-3) var(--spacing-5)",backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border))",color:"hsl(var(--card-foreground))"},children:[A?/* @__PURE__ */b(ee,{size:18,className:"animate-spin"}):/* @__PURE__ */b(te,{size:18,className:"text-emerald-500"})," ",c("ubicacion")]}),B.enableVoice&&l&&/* @__PURE__ */y("button",{onClick:()=>{l?.(),w(!1)},className:"flex items-center border shadow-soft-2xl rounded-2xl transition-colors text-[10px] font-black uppercase tracking-widest",style:{gap:"var(--spacing-3)",padding:"var(--spacing-3) var(--spacing-5)",backgroundColor:"hsl(var(--card))",borderColor:"hsl(var(--border))",color:"hsl(var(--card-foreground))"},children:[
96
96
  /* @__PURE__ */b(ae,{size:18,className:"text-amber-500"})," Llamar"]})]}),
97
97
  /* @__PURE__ */b("button",{onClick:()=>w(!g),className:Mt("h-10 w-10 rounded-full flex items-center justify-center transition-all shadow-sm z-10",g?"bg-muted text-foreground rotate-45":"bg-muted/50 text-muted-foreground hover:bg-muted"),children:/* @__PURE__ */b(se,{size:22,strokeWidth:2.5})})]}),
98
- /* @__PURE__ */b("div",{className:Mt("flex-1 relative flex items-center min-w-0 rounded-[var(--input-radius,24px)] border px-4 transition-all shadow-inner chat-input-pill",h&&"border-[hsl(var(--primary))] ring-2 ring-[hsl(var(--primary))]",x?"h-[44px]":"min-h-[40px] max-h-[120px]"),style:{backgroundColor:x?"hsl(var(--destructive) / 0.05)":"hsl(var(--muted))",borderColor:x?"hsl(var(--destructive))":h?"hsl(var(--primary))":"hsl(var(--border))"},children:/* @__PURE__ */y("div",x?{className:"flex items-center w-full animate-in zoom-in-95",style:{gap:"var(--spacing-4)"},children:[
98
+ /* @__PURE__ */b("div",{className:Mt("flex-1 relative flex items-center min-w-0 rounded-[var(--input-radius,24px)] border px-4 transition-all shadow-inner chat-input-pill",h&&"border-[hsl(var(--primary))] ring-2 ring-[hsl(var(--primary))]",x?"h-[44px]":"min-h-[40px] max-h-[120px]"),style:{backgroundColor:x?"hsl(var(--destructive) / 0.05)":"hsl(var(--muted))",borderWidth:"var(--border-width, 1px)",borderColor:x?"hsl(var(--destructive))":h?"hsl(var(--primary))":"hsl(var(--border))"},children:/* @__PURE__ */y("div",x?{className:"flex items-center w-full animate-in zoom-in-95",style:{gap:"var(--spacing-4)"},children:[
99
99
  /* @__PURE__ */b("button",{onClick:()=>H(!1),className:"text-destructive/50 hover:text-destructive",children:/* @__PURE__ */b(de,{size:18})}),
100
100
  /* @__PURE__ */y("div",{className:"flex-1 flex items-center",style:{gap:"var(--spacing-2)"},children:[
101
101
  /* @__PURE__ */b("div",{className:"flex gap-[3px]",children:[1,2,3,4].map(e=>/* @__PURE__ */b("span",{className:"w-[3px] h-3 bg-destructive/60 rounded-full animate-pulse",style:{animationDelay:.15*e+"s"}},e))}),
@@ -109,7 +109,7 @@ return b("div",{"data-testid":"quiz-dock",className:"shrink-0 border-t animate-i
109
109
  /* @__PURE__ */b("p",{className:"text-sm font-semibold mb-2 text-foreground break-words leading-snug",children:e.content}),
110
110
  /* @__PURE__ */b("div",{className:"flex flex-col gap-2",children:e.buttons.map((e,t)=>/* @__PURE__ */b("button",{type:"button",onClick:()=>n(e.label,e.id),className:"w-full text-left px-4 py-3 rounded-xl border text-sm font-semibold transition-all duration-200 cursor-pointer hover:scale-[1.02] hover:shadow-md active:scale-[0.97]",style:{backgroundColor:"hsl(var(--background))",borderColor:"hsl(var(--border))",color:"hsl(var(--foreground))"},children:/* @__PURE__ */y("span",{className:"flex items-center gap-3",children:[
111
111
  /* @__PURE__ */b("span",{className:"flex items-center justify-center w-6 h-6 rounded-full text-xs font-black shrink-0",style:{backgroundColor:r,color:"white"},children:String.fromCharCode(65+t)}),
112
- /* @__PURE__ */b("span",{children:e.label})]})},e.id))})]})})}function rc(e,t){let n=0,r=null;return function(...o){const i=Date.now(),a=i-n,s=()=>{n=i,e(...o)};a>=t?(r&&(clearTimeout(r),r=null),s()):r||(r=setTimeout(()=>{s(),r=null},t-a))}}function oc(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=rc(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const ic="24px",ac={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},sc=85,lc=.7,cc=200,uc=.5,dc=3e3,pc=1,hc=6,fc=7500,mc=.7,gc=-20,bc=8,yc=6,vc=.002,wc=.12,xc={openThreshold:.0125,floorGain:.12,attackStep:1,releaseStep:.16},kc={off:{openThreshold:0,floorGain:1,attackStep:1,releaseStep:1},low:{openThreshold:.008,floorGain:.25,attackStep:1,releaseStep:.12},standard:{...xc},high:{openThreshold:.02,floorGain:.05,attackStep:1,releaseStep:.2}};function _c(e=xc,t="voice-pcm-processor",n=1600){return`\nclass VoicePCMProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n this.gain = 1; // current applied gain — starts open\n }\n process(inputs) {\n const input = inputs[0]?.[0];\n if (!input) return true;\n for (let i = 0; i < input.length; i++) {\n this.buffer[this.bufferIndex++] = input[i];\n if (this.bufferIndex >= ${n}) {\n // 1. Frame RMS — near-field speaker vs. background energy\n let sumSq = 0;\n for (let j = 0; j < ${n}; j++) sumSq += this.buffer[j] * this.buffer[j];\n const rms = Math.sqrt(sumSq / ${n});\n\n // 2. Downward-expander target + smoothed gain (fast attack, slow release)\n const target = rms >= ${e.openThreshold} ? 1 : ${e.floorGain};\n let nextGain;\n if (target >= this.gain) {\n nextGain = Math.min(target, this.gain + ${e.attackStep});\n } else {\n nextGain = Math.max(target, this.gain - ${e.releaseStep});\n }\n\n // 3. Apply gain with a per-sample ramp (click-free) → Int16 PCM\n const int16 = new Int16Array(${n});\n const gStep = (nextGain - this.gain) / ${n};\n let g = this.gain;\n for (let j = 0; j < ${n}; j++) {\n g += gStep;\n const s = Math.max(-1, Math.min(1, this.buffer[j] * g));\n int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n this.gain = nextGain;\n\n // 4. ALWAYS post PCM + this frame's RMS. The client VAD gate decides\n // per frame what actually reaches the provider.\n this.port.postMessage({ pcm: int16.buffer, rms: rms }, [int16.buffer]);\n\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('${t}', VoicePCMProcessor);\n`}const Sc={low:{positiveSpeechThreshold:.4,negativeSpeechThreshold:.3,nearFieldRms:.012,bargeInRms:.022,onsetFrames:1,redemptionFrames:10},standard:{positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,nearFieldRms:.02,bargeInRms:.035,onsetFrames:2,redemptionFrames:8},high:{positiveSpeechThreshold:.6,negativeSpeechThreshold:.45,nearFieldRms:.032,bargeInRms:.055,onsetFrames:3,redemptionFrames:6}};function Cc(e){return void 0===e||"standard"===e?{...Sc.standard}:"string"==typeof e?{...Sc[e]??Sc.standard}:{...Sc.standard,...e}}class Ec{config;_state="silence";onsetCount=0;redemptionCount=0;constructor(e={}){this.config={...Sc.standard,...e}}get state(){return this._state}reset(){this._state="silence",this.onsetCount=0,this.redemptionCount=0}process(e){return"silence"===this._state?this.processSilence(e):this.processSpeech(e)}processSilence(e){const t=e.botSpeaking?this.config.bargeInRms:this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.positiveSpeechThreshold)&&e.rms>=t?(this.onsetCount+=1,this.onsetCount<this.config.onsetFrames?{shouldStream:!1,state:"silence"}:(this._state="speech",this.onsetCount=0,this.redemptionCount=0,{shouldStream:!0,state:"speech",event:e.botSpeaking?"barge_in":"speech_start"})):(this.onsetCount=0,{shouldStream:!1,state:"silence"})}processSpeech(e){const t=.5*this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.negativeSpeechThreshold)&&e.rms>=t?(this.redemptionCount=0,{shouldStream:!0,state:"speech"}):(this.redemptionCount+=1,this.redemptionCount<this.config.redemptionFrames?{shouldStream:!0,state:"speech"}:(this._state="silence",this.redemptionCount=0,{shouldStream:!1,state:"silence",event:"speech_end"}))}}const zc="0.0.30",Nc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${zc}/dist/`,Ac=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${zc}/+esm`;function Tc(e){if(0===e.length)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}async function Ic(){return await import(Ac)}class Oc{constructor(e){this.instance=e}_running=!1;get running(){return this._running}async start(){await this.instance.start(),this._running=!0}destroy(){try{this.instance.destroy()}catch(e){O.warn("[VAD] error while destroying detector",e)}this._running=!1}}const Mc=p(()=>import("./Avatar3D-CiD3ji3c.js")),Pc={happy:"😊",wink:"😉",thinking:"🤔",sad:"😢",excited:"🤩",love:"❤️",laugh:"😄",surprised:"😲",angry:"😠",confused:"😕",sorry:"😔",default:"💬"},Lc={idle:"Llamada de voz",connecting:"Conectando...",listening:"Escuchando...",thinking:"Pensando...",speaking:"Hablando..."},Dc={tagNames:["p","a","img","strong","em","ul","ol","li","br","span","code","hr"],attributes:{a:["href","target","rel"],img:["src","alt"],span:["className"],code:["className"]},protocols:{a:{href:["http","https","mailto","tel"]},img:{src:["http","https","data"]}}},jc=24e3;function Rc(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++)n+=String.fromCharCode(t[r]);return btoa(n)}class Fc extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){O.warn("[Avatar3D] Three.js failed, falling back to 2D orb:",e.message),this.props.onError()}render(){return this.state.hasError?null:this.props.children}}function $c({avatars:e,logoUrl:t,avatar3dUrl:n,emotion:r,callState:o,audioLevel:a,config:s}){const l=e&&Object.keys(e).length>0,c=!!t,[d,p]=i(!1),f=u(()=>l||c?l?e[r||"default"]||e.default||t||null:t||null:null,[l,c,e,r,t]),m="listening"===o||"speaking"===o,g="speaking"===o?s.speakingColor:"thinking"===o?s.thinkingColor:"listening"===o?s.listeningColor:"#ffffff20",v="speaking"===o?s.speakingScale:"thinking"===o?s.thinkingScale:1,w=s.orbSize;/* @__PURE__ */
112
+ /* @__PURE__ */b("span",{children:e.label})]})},e.id))})]})})}function rc(e,t){let n=0,r=null;return function(...o){const i=Date.now(),a=i-n,s=()=>{n=i,e(...o)};a>=t?(r&&(clearTimeout(r),r=null),s()):r||(r=setTimeout(()=>{s(),r=null},t-a))}}function oc(e=640){const[t,n]=i(()=>"undefined"!=typeof window&&window.innerWidth<e);return a(()=>{const t=rc(()=>{n(window.innerWidth<e)},250);return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[e]),t}const ic="24px",ac={sampleRate:16e3,channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},sc=85,lc=.7,cc=200,uc=.5,dc=3e3,pc=1,hc=6,fc=7500,mc=.7,gc=-20,bc=8,yc=6,vc=.002,wc=.12,xc={openThreshold:.0125,floorGain:.12,attackStep:1,releaseStep:.16},kc={off:{openThreshold:0,floorGain:1,attackStep:1,releaseStep:1},low:{openThreshold:.008,floorGain:.25,attackStep:1,releaseStep:.12},standard:{...xc},high:{openThreshold:.02,floorGain:.05,attackStep:1,releaseStep:.2}};function _c(e=xc,t="voice-pcm-processor",n=1600){return`\nclass VoicePCMProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n this.gain = 1; // current applied gain — starts open\n }\n process(inputs) {\n const input = inputs[0]?.[0];\n if (!input) return true;\n for (let i = 0; i < input.length; i++) {\n this.buffer[this.bufferIndex++] = input[i];\n if (this.bufferIndex >= ${n}) {\n // 1. Frame RMS — near-field speaker vs. background energy\n let sumSq = 0;\n for (let j = 0; j < ${n}; j++) sumSq += this.buffer[j] * this.buffer[j];\n const rms = Math.sqrt(sumSq / ${n});\n\n // 2. Downward-expander target + smoothed gain (fast attack, slow release)\n const target = rms >= ${e.openThreshold} ? 1 : ${e.floorGain};\n let nextGain;\n if (target >= this.gain) {\n nextGain = Math.min(target, this.gain + ${e.attackStep});\n } else {\n nextGain = Math.max(target, this.gain - ${e.releaseStep});\n }\n\n // 3. Apply gain with a per-sample ramp (click-free) → Int16 PCM\n const int16 = new Int16Array(${n});\n const gStep = (nextGain - this.gain) / ${n};\n let g = this.gain;\n for (let j = 0; j < ${n}; j++) {\n g += gStep;\n const s = Math.max(-1, Math.min(1, this.buffer[j] * g));\n int16[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;\n }\n this.gain = nextGain;\n\n // 4. ALWAYS post PCM + this frame's RMS. The client VAD gate decides\n // per frame what actually reaches the provider.\n this.port.postMessage({ pcm: int16.buffer, rms: rms }, [int16.buffer]);\n\n this.buffer = new Float32Array(${n});\n this.bufferIndex = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('${t}', VoicePCMProcessor);\n`}const Sc={low:{positiveSpeechThreshold:.4,negativeSpeechThreshold:.3,nearFieldRms:.012,bargeInRms:.022,onsetFrames:1,redemptionFrames:10},standard:{positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,nearFieldRms:.02,bargeInRms:.035,onsetFrames:2,redemptionFrames:8},high:{positiveSpeechThreshold:.6,negativeSpeechThreshold:.45,nearFieldRms:.032,bargeInRms:.055,onsetFrames:3,redemptionFrames:6}};function Cc(e){return void 0===e||"standard"===e?{...Sc.standard}:"string"==typeof e?{...Sc[e]??Sc.standard}:{...Sc.standard,...e}}class Ec{config;_state="silence";onsetCount=0;redemptionCount=0;constructor(e={}){this.config={...Sc.standard,...e}}get state(){return this._state}reset(){this._state="silence",this.onsetCount=0,this.redemptionCount=0}process(e){return"silence"===this._state?this.processSilence(e):this.processSpeech(e)}processSilence(e){const t=e.botSpeaking?this.config.bargeInRms:this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.positiveSpeechThreshold)&&e.rms>=t?(this.onsetCount+=1,this.onsetCount<this.config.onsetFrames?{shouldStream:!1,state:"silence"}:(this._state="speech",this.onsetCount=0,this.redemptionCount=0,{shouldStream:!0,state:"speech",event:e.botSpeaking?"barge_in":"speech_start"})):(this.onsetCount=0,{shouldStream:!1,state:"silence"})}processSpeech(e){const t=.5*this.config.nearFieldRms;return(this.config.energyOnly||e.speechProb>=this.config.negativeSpeechThreshold)&&e.rms>=t?(this.redemptionCount=0,{shouldStream:!0,state:"speech"}):(this.redemptionCount+=1,this.redemptionCount<this.config.redemptionFrames?{shouldStream:!0,state:"speech"}:(this._state="silence",this.redemptionCount=0,{shouldStream:!1,state:"silence",event:"speech_end"}))}}const zc="0.0.30",Nc=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${zc}/dist/`,Ac=`https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@${zc}/+esm`;function Tc(e){if(0===e.length)return 0;let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}async function Ic(){return await import(Ac)}class Oc{constructor(e){this.instance=e}_running=!1;get running(){return this._running}async start(){await this.instance.start(),this._running=!0}destroy(){try{this.instance.destroy()}catch(e){O.warn("[VAD] error while destroying detector",e)}this._running=!1}}const Mc=p(()=>import("./Avatar3D-B5aDSch9.js")),Pc={happy:"😊",wink:"😉",thinking:"🤔",sad:"😢",excited:"🤩",love:"❤️",laugh:"😄",surprised:"😲",angry:"😠",confused:"😕",sorry:"😔",default:"💬"},Lc={idle:"Llamada de voz",connecting:"Conectando...",listening:"Escuchando...",thinking:"Pensando...",speaking:"Hablando..."},Dc={tagNames:["p","a","img","strong","em","ul","ol","li","br","span","code","hr"],attributes:{a:["href","target","rel"],img:["src","alt"],span:["className"],code:["className"]},protocols:{a:{href:["http","https","mailto","tel"]},img:{src:["http","https","data"]}}},jc=24e3;function Rc(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.byteLength;r++)n+=String.fromCharCode(t[r]);return btoa(n)}class Fc extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){O.warn("[Avatar3D] Three.js failed, falling back to 2D orb:",e.message),this.props.onError()}render(){return this.state.hasError?null:this.props.children}}function $c({avatars:e,logoUrl:t,avatar3dUrl:n,emotion:r,callState:o,audioLevel:a,config:s}){const l=e&&Object.keys(e).length>0,c=!!t,[d,p]=i(!1),f=u(()=>l||c?l?e[r||"default"]||e.default||t||null:t||null:null,[l,c,e,r,t]),m="listening"===o||"speaking"===o,g="speaking"===o?s.speakingColor:"thinking"===o?s.thinkingColor:"listening"===o?s.listeningColor:"#ffffff20",v="speaking"===o?s.speakingScale:"thinking"===o?s.thinkingScale:1,w=s.orbSize;/* @__PURE__ */
113
113
  return y("div",n&&!d?{className:"relative flex flex-col items-center gap-4",children:[
114
114
  /* @__PURE__ */b(Fc,{onError:()=>p(!0),children:/* @__PURE__ */b(h,{fallback:/* @__PURE__ */b("div",{className:"rounded-full flex items-center justify-center animate-pulse",style:{width:`${s.orbSize}px`,height:`${s.orbSize}px`,background:`radial-gradient(circle at 35% 35%, ${s.speakingColor}40, ${s.speakingColor}10 60%, transparent 80%)`,boxShadow:`0 0 30px ${s.speakingColor}15`}}),children:/* @__PURE__ */b(Mc,{modelUrl:n,emotion:r,callState:o,audioLevel:a,primaryColor:s.speakingColor,size:s.orbSize})})}),s.showWaveform&&/* @__PURE__ */b(Bc,{isActive:"listening"===o||"speaking"===o,audioLevel:a,color:"speaking"===o?s.speakingColor:"thinking"===o?s.thinkingColor:s.listeningColor})]}:f?{className:"relative flex flex-col items-center gap-4",children:[
115
115
  /* @__PURE__ */y("div",{className:Mt("relative rounded-full flex items-center justify-center","transition-all duration-500 ease-out"),style:{width:`${w}px`,height:`${w}px`,boxShadow:m?`0 0 0 4px ${g}40, 0 0 30px ${g}30, 0 0 60px ${g}15`:`0 0 0 2px ${g}20`,transform:`scale(${v})`},children:[
@@ -152,7 +152,7 @@ return y("span",{style:{fontSize:"10px",padding:"2px 8px",borderRadius:"12px",ba
152
152
  /* @__PURE__ */b("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes pulse {\n 0%, 100% { opacity: 1; transform: scale(1); }\n 50% { opacity: 0.7; transform: scale(0.95); }\n }\n "})]})}function qc({isOpen:e,isConnected:t,isTyping:n,messages:r,botName:o="BotUyo",logoUrl:l,welcomeMessage:c,inputPlaceholder:u,mediaConfig:d,onClose:p,onSendMessage:h,bubbleStyles:m,avatars:g,onSendAttachment:w,onSendLocation:x,getSocket:k,avatar3dUrl:_,voiceConfig:S,theme:C,suggestedQuestions:E,activeQuiz:z,onQuizAnswer:N,onProposalAction:A,onVoiceActiveChange:T}){const[I,O]=i(!1),[M,P]=i(!1),[L,D]=i(!1),[j,R]=i(!1),{t:$}=F(),B=oc(),U=Dt({cssVariables:C?.cssVariables}),q=function({isOpen:e,height:t,bottom:n}){const r=oc(),[o,l]=i({}),c=s(()=>{if(r){const e=()=>{window.visualViewport?l({height:`${window.visualViewport.height}px`,transform:`translateY(${window.visualViewport.offsetTop}px)`}):l({height:"100dvh",transform:"none"})};return e(),window.visualViewport?.addEventListener("resize",e),window.visualViewport?.addEventListener("scroll",e),()=>{window.visualViewport?.removeEventListener("resize",e),window.visualViewport?.removeEventListener("scroll",e)}}{const e=parseFloat(n||ic)||24,r=window.innerHeight-64-e;if(t){const e=parseFloat(t)||700,o=Math.min(e,r);l({height:`${o}px`,maxHeight:`${r}px`,bottom:n||ic})}else{const e=Math.min(700,Math.max(500,r));l({height:`${e}px`,maxHeight:`${r}px`,bottom:n||ic})}}},[r,t,n]);return a(()=>{if(!e)return;const t=c();return window.addEventListener("resize",c),()=>{window.removeEventListener("resize",c),t&&t()}},[e,c]),o}({isOpen:e,height:C?.cssVariables?.windowHeight,bottom:C?.cssVariables?.windowBottom}),V=function({enabled:e,returnFocusRef:t,onEscape:n}){const r=f(null),o=f(null),i=f(n);i.current=n;const l=s(e=>{const t=r.current;if(t)if("Escape"!==e.key){if("Tab"===e.key){const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const r=n[0],o=n[n.length-1];e.shiftKey&&document.activeElement===r?(e.preventDefault(),o.focus()):e.shiftKey||document.activeElement!==o||(e.preventDefault(),r.focus())}}else i.current?.()},[]);return a(()=>{if(!e)return;o.current=document.activeElement;const n=t?.current,i=r.current;if(!i)return;const a=setTimeout(()=>{const e=i.querySelector('textarea, input[type="text"]');if(e)e.focus();else{const e=i.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');e.length>0?e[0].focus():i.focus()}},100);return document.addEventListener("keydown",l),()=>{clearTimeout(a),document.removeEventListener("keydown",l);const e=n||o.current;e&&"function"==typeof e.focus&&e.focus()}},[e,t,l]),r}({enabled:e,onEscape:p});if(a(()=>{if(e)return B&&(document.body.style.overflow="hidden"),()=>{document.body.style.overflow=""}},[e,B]),a(()=>{const e=()=>R(!0);return window.addEventListener("botuyo-chat:start-call",e),()=>window.removeEventListener("botuyo-chat:start-call",e)},[]),a(()=>{j&&t&&d?.enableVoice&&!M&&(R(!1),P(!0))},[j,t,d?.enableVoice,M]),a(()=>{T?.(M)},[M,T]),!e)return null;const W="bottom-left"===C?.position,H=z?r.filter(e=>e.id!==z.id):r;/* @__PURE__ */
153
153
  return y(v,{children:[
154
154
  /* @__PURE__ */b("div",{id:"chat-dialog-description",className:"sr-only",children:$("accessibility.dialogDescription",{botName:o??"BotUyo"})}),
155
- /* @__PURE__ */y("div",{ref:V,role:"dialog","aria-modal":"true","aria-labelledby":"chat-window-title","aria-describedby":"chat-dialog-description",tabIndex:-1,className:Mt("flex flex-col overflow-hidden transition-all duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]","text-foreground z-[9999]",!B&&["fixed",W?"left-6":"right-6","border","animate-in fade-in zoom-in-95","slide-in-from-bottom-10"],B&&["fixed inset-0 w-full"]),style:{...q,...B?{}:{width:"350px",minWidth:"350px",maxWidth:"350px",borderRadius:"32px",boxShadow:"0 25px 65px -5px rgba(0, 0, 0, 0.15), 0 8px 20px -8px rgba(0, 0, 0, 0.1)"},backgroundColor:"hsl(var(--background))",borderColor:"hsl(var(--border))",color:"hsl(var(--foreground))"},children:[
155
+ /* @__PURE__ */y("div",{ref:V,role:"dialog","aria-modal":"true","aria-labelledby":"chat-window-title","aria-describedby":"chat-dialog-description",tabIndex:-1,className:Mt("flex flex-col overflow-hidden transition-all duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]","text-foreground z-[9999]",!B&&["fixed",W?"left-6":"right-6","border","animate-in fade-in zoom-in-95","slide-in-from-bottom-10"],B&&["fixed inset-0 w-full"]),style:{...q,...B?{}:{width:"350px",minWidth:"350px",maxWidth:"350px",borderRadius:"var(--window-border-radius, 32px)",borderWidth:"var(--border-width, 1px)",boxShadow:"0 25px 65px -5px rgba(0, 0, 0, 0.15), 0 8px 20px -8px rgba(0, 0, 0, 0.1)"},backgroundColor:"hsl(var(--background))",borderColor:"hsl(var(--border))",color:"hsl(var(--foreground))"},children:[
156
156
  /* @__PURE__ */b("header",{className:"relative shrink-0 border-b z-20",style:{padding:"var(--spacing-5)",backgroundColor:"hsl(var(--background) / 0.9)",borderColor:"hsl(var(--border))",backdropFilter:"blur(24px)"},children:/* @__PURE__ */y("div",{className:"flex items-center justify-between",children:[
157
157
  /* @__PURE__ */y("div",{className:"flex items-center gap-3",children:[
158
158
  /* @__PURE__ */y("div",{className:"relative",children:[
@@ -201,7 +201,7 @@ return Jh(xm,e)}const _m=/* @__PURE__ */Su("ZodBoolean",(e,t)=>{jp.init(e,t),Kf.
201
201
  return Yh(Cm)}const zm=/* @__PURE__ */Su("ZodNever",(e,t)=>{$p.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),Nm=/* @__PURE__ */Su("ZodArray",(e,t)=>{Up.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;"number"==typeof a&&(o.minItems=a),"number"==typeof s&&(o.maxItems=s),o.type="array",o.items=Cf(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */af(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */af(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */of(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */sf(t,n)),e.unwrap=()=>e.element});function Am(e,t){/* @__PURE__ */
202
202
  return wf(Nm,e,t)}const Tm=/* @__PURE__ */Su("ZodObject",(e,t)=>{Zp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const a=i.shape;for(const c in a)o.properties[c]=Cf(a[c],t,{...r,path:[...r.path,"properties",c]});const s=new Set(Object.keys(a)),l=new Set([...s].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));l.size>0&&(o.required=Array.from(l)),"never"===i.catchall?._zod.def.type?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Cf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),Lu(e,"shape",()=>t.shape),e.keyof=()=>Dm(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Em()}),e.loose=()=>e.clone({...e._zod.def,catchall:Em()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */Qh(zm,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!Uu(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=ju(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Du(this,"shape",n),n}});return Hu(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!Uu(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=ju(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Du(this,"shape",n),n}});return Hu(e,n)}(e,t),e.merge=t=>function(e,t){const n=ju(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return Du(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return Hu(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return Hu(e,ju(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Du(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=ju(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Du(this,"shape",r),r},checks:[]});return Hu(e,o)}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const o=ju(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)o[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Du(this,"shape",o),o},checks:[]});return Hu(t,o)}(Rm,e,t[0]),e.required=(...t)=>function(e,t,n){const r=ju(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)o[t]=new e({type:"nonoptional",innerType:r[t]});return Du(this,"shape",o),o}});return Hu(t,r)}(Wm,e,t[0])});function Im(e,t){const n={type:"object",shape:e??{},...Zu(t)};return new Tm(n)}const Om=/* @__PURE__ */Su("ZodUnion",(e,t)=>{Kp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=!1===o.inclusive,a=o.options.map((e,n)=>Cf(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]}));i?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options}),Mm=/* @__PURE__ */Su("ZodIntersection",(e,t)=>{Gp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Cf(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=Cf(o.right,t,{...r,path:[...r.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length,l=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];n.allOf=l})(e,t,n,r)}),Pm=/* @__PURE__ */Su("ZodRecord",(e,t)=>{Xp.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object";const a=i.keyType,s=a._zod.bag,l=s?.patterns;if("loose"===i.mode&&l&&l.size>0){const e=Cf(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(const t of l)o.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(o.propertyNames=Cf(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=Cf(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const c=a._zod.values;if(c){const e=[...c].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(o.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType}),Lm=/* @__PURE__ */Su("ZodEnum",(e,t)=>{eh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Au(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const o={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);o[i]=t.entries[i]}return new Lm({...t,checks:[],...Zu(r),entries:o})},e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new Lm({...t,checks:[],...Zu(r),entries:o})}});function Dm(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Lm({type:"enum",entries:n,...Zu(t)})}const jm=/* @__PURE__ */Su("ZodTransform",(e,t)=>{th.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Eu(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(ed(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(ed(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),Rm=/* @__PURE__ */Su("ZodOptional",(e,t)=>{rh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>If(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Fm(e){return new Rm({type:"optional",innerType:e})}const $m=/* @__PURE__ */Su("ZodExactOptional",(e,t)=>{oh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>If(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Bm=/* @__PURE__ */Su("ZodNullable",(e,t)=>{ih.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Cf(o.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Um(e){return new Bm({type:"nullable",innerType:e})}const qm=/* @__PURE__ */Su("ZodDefault",(e,t)=>{ah.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),Vm=/* @__PURE__ */Su("ZodPrefault",(e,t)=>{lh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Wm=/* @__PURE__ */Su("ZodNonOptional",(e,t)=>{ch.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),Hm=/* @__PURE__ */Su("ZodCatch",(e,t)=>{dh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Zm=/* @__PURE__ */Su("ZodPipe",(e,t)=>{ph.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i="input"===t.io?"transform"===o.in._zod.def.type?o.out:o.in:o.out;Cf(i,t,r),t.seen.get(e).ref=i})(e,t,0,r),e.in=t.in,e.out=t.out});function Jm(e,t){return new Zm({type:"pipe",in:e,out:t})}const Km=/* @__PURE__ */Su("ZodReadonly",(e,t)=>{fh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Cf(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),Gm=/* @__PURE__ */Su("ZodCustom",(e,t)=>{gh.init(e,t),Kf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)}),Ym=/* @__PURE__ */Object.create(null);Ym.open="0",Ym.close="1",Ym.ping="2",Ym.pong="3",Ym.message="4",Ym.upgrade="5",Ym.noop="6";const Qm=/* @__PURE__ */Object.create(null);Object.keys(Ym).forEach(e=>{Qm[Ym[e]]=e});const Xm={type:"error",data:"parser error"},eg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),tg="function"==typeof ArrayBuffer,ng=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rg=({type:e,data:t},n,r)=>eg&&t instanceof Blob?n?r(t):og(t,r):tg&&(t instanceof ArrayBuffer||ng(t))?n?r(t):og(new Blob([t]),r):r(Ym[e]+(t||"")),og=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function ig(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ag;const sg="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let uy=0;uy<64;uy++)sg["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(uy)]=uy;const lg="function"==typeof ArrayBuffer,cg=(e,t)=>{if("string"!=typeof e)return{type:"message",data:dg(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:ug(e.substring(1),t)}:Qm[n]?e.length>1?{type:Qm[n],data:e.substring(1)}:{type:Qm[n]}:Xm},ug=(e,t)=>{if(lg){const n=(e=>{let t,n,r,o,i,a=.75*e.length,s=e.length,l=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);const c=new ArrayBuffer(a),u=new Uint8Array(c);for(t=0;t<s;t+=4)n=sg[e.charCodeAt(t)],r=sg[e.charCodeAt(t+1)],o=sg[e.charCodeAt(t+2)],i=sg[e.charCodeAt(t+3)],u[l++]=n<<2|r>>4,u[l++]=(15&r)<<4|o>>2,u[l++]=(3&o)<<6|63&i;return c})(e);return dg(n,t)}return{base64:!0,data:e}},dg=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,pg=String.fromCharCode(30);let hg;function fg(e){return e.reduce((e,t)=>e+t.length,0)}function mg(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;o<t;o++)n[o]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function gg(e){if(e)return function(e){for(var t in gg.prototype)e[t]=gg.prototype[t];return e}(e)}gg.prototype.on=gg.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},gg.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},gg.prototype.off=gg.prototype.removeListener=gg.prototype.removeAllListeners=gg.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;o<r.length;o++)if((n=r[o])===t||n.fn===t){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},gg.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,t)}return this},gg.prototype.emitReserved=gg.prototype.emit,gg.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},gg.prototype.hasListeners=function(e){return!!this.listeners(e).length};const bg="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),yg="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function vg(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const wg=yg.setTimeout,xg=yg.clearTimeout;function kg(e,t){t.useNativeTimers?(e.setTimeoutFn=wg.bind(yg),e.clearTimeoutFn=xg.bind(yg)):(e.setTimeoutFn=yg.setTimeout.bind(yg),e.clearTimeoutFn=yg.clearTimeout.bind(yg))}function _g(e){return"string"==typeof e?function(e){let t=0,n=0;for(let r=0,o=e.length;r<o;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function Sg(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Cg extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Eg extends gg{constructor(e){super(),this.writable=!1,kg(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new Cg(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=cg(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class zg extends Eg{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(pg),r=[];for(let o=0;o<n.length;o++){const e=cg(n[o],t);if(r.push(e),"error"===e.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((e,i)=>{rg(e,!1,e=>{r[i]=e,++o===n&&t(r.join(pg))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Sg()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Ng=!1;try{Ng="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(cy){}const Ag=Ng;function Tg(){}class Ig extends zg{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class Og extends gg{constructor(e,t,n){super(),this.createRequest=e,kg(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=vg(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(r){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(r){}try{n.setRequestHeader("Accept","*/*")}catch(r){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(r){return void this.setTimeoutFn(()=>{this._onError(r)},0)}"undefined"!=typeof document&&(this._index=Og.requestsCount++,Og.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=Tg,e)try{this._xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Og.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function Mg(){for(let e in Og.requests)Og.requests.hasOwnProperty(e)&&Og.requests[e].abort()}Og.requestsCount=0,Og.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",Mg):"function"==typeof addEventListener&&addEventListener("onpagehide"in yg?"pagehide":"unload",Mg,!1));const Pg=function(){const e=Lg({xdomain:!1});return e&&null!==e.responseType}();function Lg(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Ag))return new XMLHttpRequest}catch(n){}if(!t)try{return new(yg[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(n){}}const Dg="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class jg extends Eg{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Dg?{}:vg(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(cy){return this.emitReserved("error",cy)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;rg(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(t){}r&&bg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Sg()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Rg=yg.WebSocket||yg.MozWebSocket,Fg={websocket:class extends jg{createSocket(e,t,n){return Dg?new Rg(e,t,n):t?new Rg(e,t):new Rg(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends Eg{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(cy){return this.emitReserved("error",cy)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){hg||(hg=new TextDecoder);const n=[];let r=0,o=-1,i=!1;return new TransformStream({transform(a,s){for(n.push(a);;){if(0===r){if(fg(n)<1)break;const e=mg(n,1);i=!(128&~e[0]),o=127&e[0],r=o<126?3:126===o?1:2}else if(1===r){if(fg(n)<2)break;const e=mg(n,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(fg(n)<8)break;const e=mg(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){s.enqueue(Xm);break}o=i*Math.pow(2,32)+t.getUint32(4),r=3}else{if(fg(n)<o)break;const e=mg(n,o);s.enqueue(cg(i?e:hg.decode(e),t)),r=0}if(0===o||o>e){s.enqueue(Xm);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){eg&&e.data instanceof Blob?e.data.arrayBuffer().then(ig).then(t):tg&&(e.data instanceof ArrayBuffer||ng(e.data))?t(ig(e.data)):rg(e,!1,e=>{ag||(ag=new TextEncoder),t(ag.encode(e))})}(e,n=>{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}});r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const o=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this._writer.write(i).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&bg(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Ig{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Pg&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Og(Lg,this.uri(),e)}}},$g=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Bg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ug(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=$g.exec(e||""),i={},a=14;for(;a--;)i[Bg[a]]=o[a]||"";return-1!=n&&-1!=r&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,i.path),i.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}(0,i.query),i}const qg="function"==typeof addEventListener&&"function"==typeof removeEventListener,Vg=[];qg&&addEventListener("offline",()=>{Vg.forEach(e=>e())},!1);class Wg extends gg{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=Ug(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Ug(t.host).host);kg(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let r=0,o=n.length;r<o;r++){let e=n[r].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),qg&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Vg.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Wg.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Wg.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=_g(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,bg(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const o={type:e,data:t,options:n};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Wg.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),qg&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Vg.indexOf(this._offlineEventListener);-1!==e&&Vg.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Wg.protocol=4;class Hg extends Wg{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Wg.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Wg.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function o(){n||(n=!0,c(),t.close(),t=null)}const i=e=>{const n=new Error("probe error: "+e);n.transport=t.name,o(),this.emitReserved("upgradeError",n)};function a(){i("transport closed")}function s(){i("socket closed")}function l(e){t&&e.name!==t.name&&o()}const c=()=>{t.removeListener("open",r),t.removeListener("error",i),t.removeListener("close",a),this.off("close",s),this.off("upgrading",l)};t.once("open",r),t.once("error",i),t.once("close",a),this.once("close",s),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let Zg=class extends Hg{constructor(e,t={}){const n="object"==typeof e?e:t;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(e=>Fg[e]).filter(e=>!!e)),super(e,n)}};const Jg="function"==typeof ArrayBuffer,Kg=Object.prototype.toString,Gg="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Kg.call(Blob),Yg="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Kg.call(File);function Qg(e){return Jg&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Gg&&e instanceof Blob||Yg&&e instanceof File}function Xg(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Xg(e[t]))return!0;return!1}if(Qg(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Xg(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&Xg(e[n]))return!0;return!1}function eb(e){const t=[],n=e.data,r=e;return r.data=tb(n,t),r.attachments=t.length,{packet:r,buffers:t}}function tb(e,t){if(!e)return e;if(Qg(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=tb(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=tb(e[r],t));return n}return e}function nb(e,t){return e.data=rb(e.data,t),delete e.attachments,e}function rb(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=rb(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=rb(e[n],t));return e}const ob=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ib,ab;(ab=ib||(ib={}))[ab.CONNECT=0]="CONNECT",ab[ab.DISCONNECT=1]="DISCONNECT",ab[ab.EVENT=2]="EVENT",ab[ab.ACK=3]="ACK",ab[ab.CONNECT_ERROR=4]="CONNECT_ERROR",ab[ab.BINARY_EVENT=5]="BINARY_EVENT",ab[ab.BINARY_ACK=6]="BINARY_ACK";class sb extends gg{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof e?{reviver:e}:e)}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===ib.BINARY_EVENT;n||t.type===ib.BINARY_ACK?(t.type=n?ib.EVENT:ib.ACK,this.reconstructor=new lb(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Qg(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===ib[n.type])throw new Error("unknown packet type "+n.type);if(n.type===ib.BINARY_EVENT||n.type===ib.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(r,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");const i=Number(o);if(!cb(i)||i<0)throw new Error("Illegal attachments");if(i>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=i}if("/"===e.charAt(t+1)){const r=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!sb.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(e,t){switch(e){case ib.CONNECT:return ub(t);case ib.DISCONNECT:return void 0===t;case ib.CONNECT_ERROR:return"string"==typeof t||ub(t);case ib.EVENT:case ib.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ob.indexOf(t[0]));case ib.ACK:case ib.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class lb{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=nb(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const cb=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function ub(e){return"[object Object]"===Object.prototype.toString.call(e)}const db=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Decoder:sb,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==ib.EVENT&&e.type!==ib.ACK||!Xg(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===ib.EVENT?ib.BINARY_EVENT:ib.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==ib.BINARY_EVENT&&e.type!==ib.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=eb(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},get PacketType(){return ib}},Symbol.toStringTag,{value:"Module"}));function pb(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const hb=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class fb extends gg{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[pb(e,"open",this.onopen.bind(this)),pb(e,"packet",this.onpacket.bind(this)),pb(e,"error",this.onerror.bind(this)),pb(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,r,o;if(hb.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:ib.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),i.id=e}const a=null===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,s=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!a||(s?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const o=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),i=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{const o=(e,t)=>e?r(e):n(t);o.withError=!0,t.push(o),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:ib.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case ib.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ib.EVENT:case ib.BINARY_EVENT:this.onevent(e);break;case ib.ACK:case ib.BINARY_ACK:this.onack(e);break;case ib.DISCONNECT:this.ondisconnect();break;case ib.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,t.packet({type:ib.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ib.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function mb(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}mb.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},mb.prototype.reset=function(){this.attempts=0},mb.prototype.setMin=function(e){this.ms=e},mb.prototype.setMax=function(e){this.max=e},mb.prototype.setJitter=function(e){this.jitter=e};class gb extends gg{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,kg(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new mb({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const r=t.parser||db;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Zg(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=pb(t,"open",function(){n.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=pb(t,"error",o);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{r(),o(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(pb(e,"ping",this.onping.bind(this)),pb(e,"data",this.ondata.bind(this)),pb(e,"error",this.onerror.bind(this)),pb(e,"close",this.onclose.bind(this)),pb(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){bg(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new fb(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const bb={};function yb(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),r=Ug(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const o=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port+t,r.href=r.protocol+"://"+o+(n&&n.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=n.source,o=n.id,i=n.path,a=bb[o]&&i in bb[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new gb(r,t):(bb[o]||(bb[o]=new gb(r,t)),s=bb[o]),n.query&&!t.query&&(t.query=n.queryKey),s.socket(n.path,t)}Object.assign(yb,{Manager:gb,Socket:fb,io:yb,connect:yb});const vb=Im({proposalId:Qf().min(1),tool:Qf().min(1),title:Qf().optional(),summary:Qf().optional(),args:(wb=Qf(),xb=Em(),new Pm({type:"record",keyType:wb,valueType:xb,...Zu(void 0)})).optional(),ownerOnly:/* @__PURE__ */Kh(_m,void 0).optional()});var wb,xb;const kb=Im({proposalId:Qf().min(1),status:Dm(["confirmed","cancelled","expired"]).optional()}),_b="chat_device_id";function Sb(){const e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if("function"==typeof e?.randomUUID)return e.randomUUID();if("function"==typeof e?.getRandomValues){const t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=Array.from(t,e=>e.toString(16).padStart(2,"0"));return n.slice(0,4).join("")+"-"+n.slice(4,6).join("")+"-"+n.slice(6,8).join("")+"-"+n.slice(8,10).join("")+"-"+n.slice(10,16).join("")}return O.warn("[deviceId] Web Crypto API unavailable, falling back to Math.random()"),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const Cb=Im({id:Qf().optional(),type:Dm(["text","image","audio","location","system"]).default("text"),content:Qf().optional(),imageUrl:Qf().url().optional(),audioUrl:Qf().optional(),latitude:wm().optional(),longitude:wm().optional(),timestamp:Qf().optional(),sender:Dm(["bot","user","system"]).optional(),emotion:/* @__PURE__ */Gh(Sm).optional(),sources:Am(Qf()).optional()}),Eb=Im({agentId:Qf().optional(),name:Qf().optional(),label:Qf().optional(),avatarUrl:Qf().optional(),variantKey:Qf().optional()}),zb=Im({imageUrl:Qf().url(),caption:Qf().optional(),alt:Qf().optional(),attribution:Qf().optional(),sourceUrl:Qf().url().optional(),license:Qf().optional()}),Nb=/USER_IDENTITY_REQUIRED|AUTH_EXPIRED|AUTH_INVALID|AUTH_REQUIRED|unauthorized/i;const Ab=`data:image/svg+xml,${encodeURIComponent('\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">\n <defs>\n <linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">\n <stop offset="0%" style="stop-color:#10b981"/>\n <stop offset="100%" style="stop-color:#059669"/>\n </linearGradient>\n </defs>\n <circle cx="32" cy="32" r="32" fill="url(#bg)"/>\n <rect x="16" y="20" width="32" height="24" rx="4" fill="white"/>\n <circle cx="24" cy="30" r="3" fill="#10b981"/>\n <circle cx="40" cy="30" r="3" fill="#10b981"/>\n <rect x="22" y="36" width="20" height="3" rx="1.5" fill="#10b981"/>\n <rect x="28" y="12" width="8" height="8" rx="2" fill="white"/>\n</svg>\n')}`,Tb=function(){const e=Math.floor(1200),t=2*e,n=44+t,r=new ArrayBuffer(n),o=new DataView(r);Ib(o,0,"RIFF"),o.setUint32(4,n-8,!0),Ib(o,8,"WAVE"),Ib(o,12,"fmt "),o.setUint32(16,16,!0),o.setUint16(20,1,!0),o.setUint16(22,1,!0),o.setUint32(24,8e3,!0),o.setUint32(28,16e3,!0),o.setUint16(32,2,!0),o.setUint16(34,16,!0),Ib(o,36,"data"),o.setUint32(40,t,!0);for(let s=0;s<e;s++){const t=s/8e3,n=1-s/e,r=Math.sin(2*Math.PI*880*t)*n*.5*32767;o.setInt16(44+2*s,r,!0)}const i=new Uint8Array(r);let a="";for(let s=0;s<i.length;s++)a+=String.fromCharCode(i[s]);return`data:audio/wav;base64,${btoa(a)}`}();function Ib(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}class Ob{queue=[];endpoint;apiKey;flushInterval=null;isFlushing=!1;isDisabled=!1;MAX_QUEUE_SIZE=100;FLUSH_INTERVAL_MS=3e4;BATCH_SIZE=10;constructor(e,t){this.endpoint=e,this.apiKey=t,this.startAutoFlush()}startAutoFlush(){this.flushInterval=setInterval(()=>{!this.isDisabled&&this.queue.length>0&&this.flush()},this.FLUSH_INTERVAL_MS)}trackOpen(){this.track("chat_opened")}trackClose(){this.track("chat_closed")}trackMessageSent(e){this.track("message_sent",{type:e})}trackMessageReceived(e,t){this.track("message_received",{type:e,latency:t})}trackError(e,t){this.track("error",{error:e,context:t})}trackConnectionStatus(e){this.track("connection_status",{isConnected:e})}trackFeatureUsed(e){this.track("feature_used",{feature:e})}trackTypingStarted(){this.track("typing_started")}trackAttachmentSent(e,t){this.track("attachment_sent",{type:e,size:t})}track(e,t){this.isDisabled||(this.queue.push({event:e,properties:{...t,userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0,url:"undefined"!=typeof window?window.location.href:void 0},timestamp:Date.now()}),this.queue.length>=this.BATCH_SIZE&&this.flush(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE),O.warn("Analytics queue overflow, dropping old events")))}async flush(){if(this.isDisabled||0===this.queue.length||this.isFlushing)return;this.isFlushing=!0;const e=[...this.queue];this.queue=[];try{const t=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({events:e}),keepalive:!0});t.ok?O.debug(`Analytics: Flushed ${e.length} events`):(this.isDisabled=!0,this.queue=[],O.debug(`Analytics disabled: endpoint returned ${t.status}`))}catch(t){this.isDisabled=!0,this.queue=[],O.debug("Analytics disabled due to network error")}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}const Mb=e=>{const t=new Date(e.timestamp).getTime();return Number.isFinite(t)?t:0},Pb=e=>`${e.sender}|${(e=>{const t=e.content;return"string"==typeof t?t:""})(e).trim()}`;let Lb=null,Db=null;function jb(e){Lb=e}function Rb(e){Db=e}const Fb=r(null);function $b({children:e,defaultLocale:t,initialState:n,onStateChange:r,...o}){const[a,l]=i(n?.isOpen??!1),[c,u]=i(0),d=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:open"))},[r]),p=s(()=>{l(!1),r?.(!1),window.dispatchEvent(new CustomEvent("botuyo-chat:close"))},[r]),h=s(()=>{l(e=>{const t=!e;return t&&u(0),r?.(t),t}),window.dispatchEvent(new CustomEvent("botuyo-chat:toggle"))},[r]),f=s(()=>{l(!0),u(0),r?.(!0),window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))},[r]),m=s(e=>{Lb?(Lb(e),O.debug("ChatWidgetProvider sendMessage:",e)):O.warn("sendMessage called but no handler registered")},[]),g=s(()=>{Db?(Db(),O.debug("ChatWidgetProvider clearMessages called")):O.warn("clearMessages called but no handler registered")},[]),v={isOpen:a,open:d,close:p,toggle:h,startCall:f,sendMessage:m,clearMessages:g,unreadCount:c},w=s((e,t)=>{"message:received"!==e||a||u(e=>e+1),o.onEvent?.(e,t)},[a,o]);/* @__PURE__ */
203
203
  return y(Fb.Provider,{value:v,children:[e,
204
- /* @__PURE__ */b(Zb,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:w})]})}function Bb(){const e=o(Fb);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const Ub=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function qb(e){const{apiKey:t,apiBaseUrl:r,agentId:o,pageContext:l,includeSEOMetadata:c=!1,theme:d,userContext:p,onLogin:h,onNavigate:m,onEvent:b,onStateChange:y,getUserToken:v,onAuthRequired:w,onThemeUpdate:x}=e,[k,_]=i(0),S=f(0),C=f(!1),{t:E}=F(),z=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new Ob(o,t);const i=()=>r.current?.flush(),a=()=>{"hidden"===document.visibilityState&&r.current?.flush()};return window.addEventListener("beforeunload",i),window.addEventListener("visibilitychange",a),()=>{window.removeEventListener("beforeunload",i),window.removeEventListener("visibilitychange",a),r.current?.destroy()}},[e,t,n]),{trackOpen:s(()=>{r.current?.trackOpen()},[]),trackClose:s(()=>{r.current?.trackClose()},[]),trackMessageSent:s(e=>{r.current?.trackMessageSent(e)},[]),trackMessageReceived:s((e,t)=>{r.current?.trackMessageReceived(e,t)},[]),trackError:s((e,t)=>{r.current?.trackError(e,t)},[]),trackConnectionStatus:s(e=>{r.current?.trackConnectionStatus(e)},[]),trackFeatureUsed:s(e=>{r.current?.trackFeatureUsed(e)},[])}}(r,t,!0),N=function({enabled:e=!0,soundEnabled:t=!0,desktopEnabled:n=!0,botName:r="BotUyo",logoUrl:o,notificationSoundUrl:l}={}){const[c,u]=i("default"),d=f(null),p=o||Ab,h=l||Tb;a(()=>{t&&"undefined"!=typeof window&&(d.current=new Audio(h),d.current.volume=.3)},[t,h]),a(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const m=s(async()=>{if("undefined"==typeof window||!("Notification"in window))return O.warn("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),O.info("Notification permission:",e),"granted"===e}catch(e){return O.error("Error requesting notification permission:",e),!1}},[]),g=s(t=>{if(e&&n&&"granted"===c&&("undefined"==typeof document||!document.hasFocus()))try{const e=`Nuevo mensaje de ${r}`;let n="Mensaje recibido";"text"===t.type&&"content"in t?n=t.content?.slice(0,100)||"Mensaje recibido":"image"===t.type?n="📷 Imagen":"audio"===t.type?n="🎵 Audio":"location"===t.type&&(n="📍 Ubicación");const o=new Notification(e,{body:n,icon:p,tag:"chat-message",requireInteraction:!1,silent:!1});o.onclick=()=>{window.focus(),o.close()},setTimeout(()=>o.close(),5e3)}catch(o){O.error("Error showing notification:",o)}},[e,n,c,r,p]),b=s(()=>{if(e&&t&&("undefined"==typeof document||!document.hasFocus()))try{d.current?.play().catch(e=>{O.debug("Audio playback blocked:",e)})}catch(n){O.error("Error playing sound:",n)}},[e,t]),y=s(e=>{g(e),b()},[g,b]);return{permission:c,requestPermission:m,notify:g,playSound:b,notifyWithSound:y}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:d?.botName||"BotUyo",logoUrl:d?.logoUrl}),A=function(e=10,t=6e4){const n=f([]);return{isAllowed:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),!(n.current.length>=e||(n.current.push(r),0))},[e,t]),getRemainingAttempts:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),Math.max(0,e-n.current.length)},[e,t]),getTimeUntilReset:s(()=>{if(0===n.current.length)return 0;const e=Date.now(),r=n.current[0],o=t-(e-r);return Math.max(0,o)},[t]),reset:s(()=>{n.current=[]},[])}}(10,6e4),{state:T,actions:I}=function(e,t="default"){const[r,o]=g(_u,yu),[l,c]=i(!1),u=n.useMemo(()=>function(e,t="default"){return`botuyo_chat_v1_${e}_${t}`}(e,t),[e,t]),d=n.useMemo(()=>((e,t="default")=>{const n=`${e}_${t}`;return bu.has(n)||bu.set(n,new gu(e,t)),bu.get(n)})(e,t),[e,t]);a(()=>{"undefined"==typeof window||l||(async()=>{try{await d.migrateFromLocalStorage(e,t);const n=await d.getMessages(100),r=await d.getMetadata();if(n.length>0||r){const e={messages:n.map(e=>({...e,timestamp:new Date(e.timestamp)})),sessionId:r?.sessionId||null,isOpen:r?.isOpen||!1};o({type:"RESTORE_SESSION",payload:e})}}catch(n){O.warn("Chat: Error rehydrating from IndexedDB",n);try{const e=localStorage.getItem(u);if(e){const t=JSON.parse(e);t.messages&&(t.messages=t.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}))),o({type:"RESTORE_SESSION",payload:t})}}catch(r){O.error("Chat: Fallback rehydration failed",r)}}finally{c(!0)}})()},[l]),a(()=>{if(!l)return;const e=setTimeout(async()=>{try{await d.saveMessages(r.messages),await d.setMetadata({isOpen:r.isOpen,sessionId:r.sessionId})}catch(e){O.error("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){O.error("Chat: Fallback persistence failed",t)}}},500);return()=>clearTimeout(e)},[r.isOpen,r.messages,r.sessionId,l]);const p=s(e=>{o({type:"ADD_MESSAGE",payload:e})},[]),h=s(()=>o({type:"TOGGLE_WINDOW"}),[]),f=s(()=>o({type:"OPEN_WINDOW"}),[]),m=s(()=>o({type:"CLOSE_WINDOW"}),[]),b=s(e=>o({type:"SET_CONNECTED",payload:e}),[]),y=s(e=>o({type:"SET_TYPING",payload:e}),[]),v=s(e=>o({type:"SET_MESSAGES",payload:e}),[]),w=s(e=>o({type:"SET_ERROR",payload:e}),[]),x=s(e=>o({type:"SET_SESSION_ID",payload:e}),[]),k=s(()=>{localStorage.removeItem(u),o({type:"CLEAR_CHAT"})},[]),_=s(()=>{o({type:"SET_MESSAGES",payload:[]})},[]),S=s((e,t)=>o({type:"ANSWER_QUIZ",payload:{messageId:e,buttonId:t}}),[]),C=s((e,t)=>o({type:"RESOLVE_PROPOSAL",payload:{proposalId:e,status:t}}),[]);return{state:r,isHydrated:l,actions:{toggleWindow:h,openWindow:f,closeWindow:m,setConnected:b,setTyping:y,addMessage:p,setMessages:v,setError:w,setSessionId:x,clearChat:k,clearMessages:_,answerQuiz:S,resolveProposal:C}}}(t,o),M=function(e=!1){const t="undefined"!=typeof window?window.location.pathname:"",n=u(()=>t,[t]),[r,o]=i({});return a(()=>{if(!e)return void o({});const t=setTimeout(()=>{const e=function(){if("undefined"==typeof window)return{};const e={};e.title=document.title,document.querySelectorAll("meta").forEach(t=>{const n=t.getAttribute("name"),r=t.getAttribute("property"),o=t.getAttribute("content");if(o){if(n)switch(n){case"description":e.description=o;break;case"keywords":e.keywords=o.split(",").map(e=>e.trim());break;case"author":e.author=o}if(r){if(r.startsWith("og:")){const t=r.replace("og:","og_");e[t]=o}if(r.startsWith("twitter:")){const t=r.replace("twitter:","twitter_");e[t]=o}}}});try{const t=document.querySelectorAll('script[type="application/ld+json"]');if(t.length>0){const n=[];t.forEach(e=>{try{const t=JSON.parse(e.textContent||"");n.push(t)}catch{}}),n.length>0&&(e.structuredData=n)}}catch{}return e}();o(e)},100);return()=>clearTimeout(t)},[n,e]),e&&Object.keys(r).length>0?r:void 0}(c),P=function(e){const{apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,userContext:l}=e,c=f(e);a(()=>{c.current=e},[e]);const d=f(null),[p,h]=i(!1),[m,g]=i(!1),b=f(function(){try{const e=localStorage.getItem(_b);if(e)return e;const t=Sb();return localStorage.setItem(_b,t),t}catch{return O.warn("localStorage not available, using session-only device ID"),Sb()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=Cb.safeParse(e),r=t.success&&t.data.id?t.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=t.success&&t.data.sender?t.data.sender:"bot",i=t.success&&t.data.timestamp?new Date(t.data.timestamp):/* @__PURE__ */new Date,a=t.success?t.data:{type:"text"};switch(a.type){case"image":return{id:r,type:"image",sender:o,timestamp:i,imageUrl:a.imageUrl||a.content||"",altText:"Imagen enviada"};case"audio":{const e=a.audioUrl||"";return{id:r,type:"audio",sender:o,timestamp:i,content:e.startsWith("http://")||e.startsWith("https://")?e:e?`${n}/api/voice/audio/${r}`:a.content||"",text:a.content||void 0}}case"location":return{id:r,type:"location",sender:o,timestamp:i,latitude:Number(a.latitude||0),longitude:Number(a.longitude||0),name:a.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:i,content:String(a.content||"")};default:return{id:r,type:"text",sender:o,timestamp:i,content:String(a.content||"Sin contenido"),emotion:a.emotion,...a.sources?.length?{sources:a.sources}:{}}}},[]),w=s(()=>{if(!t||!n)return;if(d.current?.connected)return;h(!0);const e=e=>{const o=yb(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});o.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),o.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),o.on("connect_error",e=>{h(!1);const n=String(e?.data instanceof Object?e?.data?.code:e?.data??e?.message??"");if(Nb.test(n)||Nb.test(e?.message??"")){c.current.onAuthRequired?.();const e=c.current.getUserToken;e&&e().then(e=>{d.current&&(d.current.auth={apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata})}).catch(e=>O.error("[useChatSocket] Token refresh failed:",e))}c.current.onError(`Error de conexión: ${e.message}`)}),o.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),o.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){O.error("ChatSocket Error processing bot_message:",t)}}),o.on("chat_history",e=>{if(e.messages&&Array.isArray(e.messages))if(c.current.onHistoryLoaded){const t=e.messages.map(e=>{try{return v(e)}catch(t){return O.debug("Error processing history message:",t),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){O.debug("Error processing history message:",t)}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),o.on("bot_typing",e=>c.current.onTyping(e));const i=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};o.on("onboarding:command",e=>i(e)),o.on("form:command",e=>i(e)),o.on("request_form_state",()=>{i({type:"botuyo-request-form-state"})}),o.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),o.on("custom_event",e=>{if(i({type:"botuyo-custom-event",...e}),"quiz_question"===e?.eventName&&e?.data&&!c.current.isVoiceCallActive?.()){const{question:t,buttons:n}=e.data;if(t&&n?.length){const e={id:`quiz-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"buttons",sender:"bot",timestamp:/* @__PURE__ */new Date,content:t,buttons:n};c.current.onMessage(e)}}if("show_image"===e?.eventName&&e?.data&&!c.current.isVoiceCallActive?.()){const t=zb.safeParse(e.data);if(t.success){const e=t.data,n={id:`img-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"image",sender:"bot",timestamp:/* @__PURE__ */new Date,imageUrl:e.imageUrl,altText:e.alt||e.caption||"Imagen",...e.caption?{caption:e.caption}:{},...e.attribution?{attribution:e.attribution}:{},...e.sourceUrl?{sourceUrl:e.sourceUrl}:{}};c.current.onMessage(n)}else O.debug("ChatSocket: dropped malformed show_image payload")}if("agent_switched"===e?.eventName&&e?.data){const t=Eb.safeParse(e.data);t.success?c.current.onAgentSwitched?.(t.data):O.debug("ChatSocket: dropped malformed agent_switched payload")}if("tool_proposal"===e?.eventName&&e?.data){const t=vb.safeParse(e.data);if(t.success){const e=t.data,n={id:`proposal-${e.proposalId}`,type:"tool_proposal",sender:"bot",timestamp:/* @__PURE__ */new Date,proposalId:e.proposalId,toolName:e.tool,title:e.title,summary:e.summary,ownerOnly:e.ownerOnly,status:"pending"};c.current.onMessage(n)}else O.debug("ChatSocket: dropped malformed tool_proposal payload")}if(("tool_proposal_resolved"===e?.eventName||"tool_proposal_expired"===e?.eventName)&&e?.data){const t=kb.safeParse(e.data);if(t.success){const n="tool_proposal_expired"===e.eventName?"expired":t.data.status??"confirmed";c.current.onToolProposalResolved?.(t.data.proposalId,n)}else O.debug("ChatSocket: dropped malformed tool_proposal_resolved payload")}});const a=e=>{const{type:t}=e.data||{};"botuyo-onboarding-state"!==t&&"botuyo-form-state"!==t||o.emit("form_state",e.data)};window.addEventListener("message",a),d.current=o,o.__formCleanup=()=>window.removeEventListener("message",a)},o=c.current.getUserToken;o?o().then(t=>e(t)).catch(t=>{O.error("[useChatSocket] getUserToken failed:",t),c.current.onAuthRequired?.(),e(l?.token)}):e(l?.token)},[t,n]),x=s(()=>{d.current&&(d.current.disconnect(),d.current=null,g(!1))},[]),k=f(w);k.current=w,a(()=>(k.current(),()=>{d.current&&(d.current.disconnect(),d.current=null)}),[]);const _=f([]),S=f([]),C=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),E=s(()=>{if(d.current?.connected)for(;_.current.length>0;){const e=_.current.shift();d.current.emit("user_message",e)}},[]);a(()=>{m&&E()},[m,E]),a(()=>{if(!m)return;const e=setInterval(()=>{const e=Date.now();S.current=S.current.filter(t=>e<t.nextRetryAt||(t.attempts>=t.maxAttempts?(c.current.onEvent?.("message_failed",{id:t.id,payload:t.payload}),O.error("Message failed after max retries:",t.id),!1):!d.current?.connected||(d.current.emit("user_message",t.payload,e=>{e?.success&&c.current.onEvent?.("message_sent",{id:t.id})}),t.attempts++,t.nextRetryAt=e+1e3*Math.pow(2,t.attempts),t.attempts<t.maxAttempts)))},500);return()=>clearInterval(e)},[m]);const z=s((e,t="text")=>{const n=C(),r={...y.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:b.current},o={id:n,content:e.trim(),type:t,metadata:r};return d.current?.connected?(d.current.emit("user_message",o,e=>{!1!==e?.success&&e?c.current.onEvent?.("message_sent",{id:n}):(S.current.push({id:n,payload:o,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),c.current.onEvent?.("message_retry_queued",{id:n}))}),n):(_.current.push(o),c.current.onEvent?.("queued_message",{id:n,payload:o}),n)},[C]),N=u(()=>rc(e=>{d.current?.emit("typing",e)},250),[]);return{isConnected:m,isConnecting:p,sendMessage:z,sendTyping:N,getSocket:s(()=>d.current,[]),requestHistory:s(()=>{d.current?.emit("request_history")},[]),reconnect:w,disconnect:x,confirmProposal:s(e=>{d.current?.emit("tool_confirm",{proposalId:e})},[]),rejectProposal:s(e=>{d.current?.emit("tool_reject",{proposalId:e})},[])}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>M?{...l||{},seo:{...M||{}}}:l,[l,M]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=S.current>0?t-S.current:void 0;S.current=t,I.addMessage(e),z.trackMessageReceived(e.type,n),T.isOpen||"bot"!==e.sender||(_(e=>e+1),N.notifyWithSound(e))},[I,T.isOpen,z,N]),onConnected:s((e,t)=>{I.setConnected(!0),I.setSessionId(e),z.trackConnectionStatus(!0),t&&x&&x(t),t&&b&&b("backend_config",t)},[I,b,x,z]),onDisconnected:s(()=>{I.setConnected(!1),z.trackConnectionStatus(!1)},[I,z]),onTyping:s(e=>I.setTyping(e),[I]),onError:s(e=>{I.setError(e),z.trackError(e)},[I,z]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:x,onAgentSwitched:s(e=>{const t=function(e,t){const n=(e||"").trim(),r=(t||"").trim();return n&&r&&!n.toLowerCase().includes(r.toLowerCase())?`${n} · ${r}`:n||r}(e.name,e.label);x&&x(n=>({...n||{},...t?{botName:t}:{},...e.avatarUrl?{logoUrl:e.avatarUrl}:{}})),t&&I.addMessage({id:`agent-switched-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"system",sender:"system",timestamp:/* @__PURE__ */new Date,content:E("agent_switched",{name:t})})},[x,I,E]),onHistoryLoaded:s(e=>{0!==e.length&&I.setMessages(function(e,t){if(!t||0===t.length)return e;const n=t.reduce((e,t)=>Math.max(e,Mb(t)),0),r=new Set(t.map(e=>e.id)),o=new Set(t.map(Pb)),i=e.filter(e=>!r.has(e.id)&&Mb(e)>n&&!o.has(Pb(e)));return[...t,...i].sort((e,t)=>Mb(e)-Mb(t))}(T.messages,e))},[T.messages,I]),getUserToken:v,onAuthRequired:w,onToolProposalResolved:s((e,t)=>I.resolveProposal(e,t),[I]),isVoiceCallActive:s(()=>C.current,[])}),L=s(e=>{C.current=e},[]),D=u(()=>function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("buttons"===n.type&&!n.answered)return n}return null}(T.messages),[T.messages]),j=f(D);a(()=>{j.current=D},[D]);const R=s(()=>{O.debug("ChatWidget handleToggle called, current isOpen:",T.isOpen),T.isOpen?(I.closeWindow(),z.trackClose(),y?.(!1),O.debug("ChatWidget Closing window")):(I.openWindow(),_(0),z.trackOpen(),y?.(!0),O.debug("ChatWidget Opening window"))},[T.isOpen,I,y,z]),$=s(e=>{if(!A.isAllowed()){const e=A.getTimeUntilReset(),t=Math.ceil(e/1e3);return void I.setError(E("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};I.addMessage(t),z.trackMessageSent("text"),P.sendMessage(e,"text"),j.current&&I.answerQuiz(j.current.id)},[I,P,A,z,E]),B=s((e,t,n)=>{I.answerQuiz(e.id,n),I.addMessage({id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:t}),P.sendMessage(`Answer: ${t}`,"text"),z.trackMessageSent("text")},[I,P,z]),U=s(e=>{I.resolveProposal(e,"confirmed"),P.confirmProposal(e)},[I,P]),q=s(e=>{I.resolveProposal(e,"cancelled"),P.rejectProposal(e)},[I,P]),V=s(async(e,t)=>{let n;n="audio"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"audio",sender:"user",timestamp:/* @__PURE__ */new Date,content:URL.createObjectURL(e)}:"image"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"image",sender:"user",timestamp:/* @__PURE__ */new Date,imageUrl:URL.createObjectURL(e)}:{id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:`📎 ${e.name}`},I.addMessage(n);const r=await Ub(e);P.sendMessage(r,t)},[I,P]),W=s(e=>{const t={id:`temp-${Date.now()}-${Math.random()}`,type:"location",sender:"user",timestamp:/* @__PURE__ */new Date,latitude:e.latitude,longitude:e.longitude,name:"Mi ubicación"};I.addMessage(t),P.sendMessage(JSON.stringify(e),"location")},[I,P]);a(()=>{const e=()=>{T.isOpen||I.openWindow()},t=()=>{T.isOpen&&I.closeWindow()},n=()=>{T.isOpen?I.closeWindow():I.openWindow()},r=e=>{e.detail?.message&&$(e.detail.message)},o=()=>{T.isOpen||I.openWindow()};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),window.addEventListener("botuyo-chat:start-call",o),window.addEventListener("botuyo-chat:send-message",r),()=>{window.removeEventListener("botuyo-chat:open",e),window.removeEventListener("botuyo-chat:close",t),window.removeEventListener("botuyo-chat:toggle",n),window.removeEventListener("botuyo-chat:start-call",o),window.removeEventListener("botuyo-chat:send-message",r)}},[T.isOpen,I,$]),a(()=>(jb($),()=>jb(null)),[$]);const H=s(()=>{I.clearMessages(),O.info("Chat history cleared")},[I]);a(()=>(Rb(H),()=>Rb(null)),[H]);const Z=u(()=>{if(T.isTyping)return"thinking";const e=[...T.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[T.isTyping,T.messages]);return{state:T,actions:I,unreadCount:k,currentBotEmotion:Z,isConnected:P.isConnected,getSocket:P.getSocket,activeQuiz:D,handleToggle:R,handleSendText:$,handleSendAttachment:V,handleSendLocation:W,handleQuizAnswer:B,handleConfirmProposal:U,handleCancelProposal:q,setVoiceCallActive:L}}function Vb({children:e}){const t=f(null),n=f(null),[r,o]=i(!1);return a(()=>{if("undefined"==typeof document)return;let e,r,i=document.getElementById("botuyo-chat-widget-root");if(i&&i.shadowRoot)e=i.shadowRoot,r=e.getElementById("botuyo-chat-widget-root")||e.querySelector("div");else{i=document.createElement("div"),i.id="botuyo-chat-widget-root",document.body.appendChild(i),e=i.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=R.replace(/:root/g,":host"),e.appendChild(t),r=document.createElement("div"),r.id="botuyo-chat-widget-root",e.appendChild(r)}return n.current=i,t.current=r,o(!0),O.debug("ShadowDOMHost initialized"),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function Wb(e){const{apiKey:t,apiBaseUrl:n="https://api.botuyo.com",agentId:r,pageContext:o,includeSEOMetadata:l=!1,theme:c,mediaConfig:d,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,initialOpen:k=!1,hideLauncher:_=!1,voiceFirst:S=!1}=e,C=f(null),E=oc(),z=function(e){const[t,n]=i(!1);return a(()=>{let t=null;const r=()=>{if(!e.current)return;const t=!!e.current.parentElement?.closest(".dark"),r=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),o=document.getElementById("botuyo-chat-widget-root"),i=!!o?.parentElement?.closest(".dark"),a=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),l="dark"===document.documentElement.getAttribute("data-theme"),c="dark"===document.body.getAttribute("data-theme"),u=!!e.current.parentElement?.closest('[data-theme="dark"]'),d=window.matchMedia("(prefers-color-scheme: dark)").matches,p=t||r||i||a||s||l||c||u||d;e.current&&(p?e.current.classList.add("dark"):e.current.classList.remove("dark")),n(p)};r();const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r();o.addEventListener("change",i);const a=new MutationObserver(()=>{r()}),s=document.getElementById("botuyo-chat-widget-root");s&&(a.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(a.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=s.parentElement)),a.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),a.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let l=e.current?.parentElement;for(;l;)a.observe(l,{attributes:!0,attributeFilter:["class","data-theme"]}),l=l.parentElement;const c=setInterval(()=>{const e=document.getElementById("botuyo-chat-widget-root");e&&e.parentElement!==t&&(t&&e.parentElement&&(a.observe(e.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=e.parentElement),r())},100);return()=>{a.disconnect(),o.removeEventListener("change",i),clearInterval(c)}},[e]),t}(C),[N,A]=i(),{mergedTheme:T,mergedStyles:I,getContainerStyle:O}=function(e,t){const n=function(){const[e,t]=i(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return a(()=>{const e=window.matchMedia("(prefers-contrast: high)"),n=window.matchMedia("(prefers-contrast: more)"),r=e=>{t(e.matches)};return e.addEventListener("change",r),n.addEventListener("change",r),()=>{e.removeEventListener("change",r),n.removeEventListener("change",r)}},[]),e}(),r=u(()=>{const r=function(e,t){const n={...Pt,...t?.cssVariables||{},...e?.cssVariables||{}};return{botName:e?.botName||t?.botName||"BotUyo",logoUrl:e?.logoUrl||t?.logoUrl||"",position:e?.position||t?.position||"bottom-right",welcomeMessage:e?.welcomeMessage||t?.welcomeMessage||"¡Hola! ¿En qué puedo ayudarte?",inputPlaceholder:e?.inputPlaceholder||t?.inputPlaceholder||"Escribe un mensaje...",cssVariables:n,isHidden:e?.isHidden??t?.isHidden??!1}}(e,t);return n?{...r,cssVariables:{...r.cssVariables,primary:"0 0% 0%",primaryForeground:"0 0% 100%",background:"0 0% 100%",foreground:"0 0% 0%",card:"0 0% 100%",cardForeground:"0 0% 0%",muted:"0 0% 96%",mutedForeground:"0 0% 0%",border:"0 0% 0%"}}:r},[e,t,n]),o=u(()=>({radius:{...Wc,...e?.bubbleStyles?.radius},bot:{...Hc,...e?.bubbleStyles?.bot},user:{...Zc,...e?.bubbleStyles?.user},launcher:{...e?.bubbleStyles?.launcher},mapCard:{...e?.bubbleStyles?.mapCard}}),[e?.bubbleStyles]);return{mergedTheme:r,mergedStyles:o,getContainerStyle:(e,t,n)=>({"--chat-primary":`hsl(${r.cssVariables.primary})`,zIndex:e?2147483647:9999,position:"fixed",top:t&&e?0:"auto",left:t&&e?0:"bottom-left"===n?"24px":"auto",right:t&&e?0:"bottom-right"!==n&&n?"auto":"24px",bottom:t&&e?0:"24px",width:t&&e?"100%":"auto",height:t&&e?"100%":"auto"})}}(c,N);a(()=>{T.isHidden&&console.warn('[BotUyo] ⚠️ El agente (o Flow) de IA asociado a esta API Key se encuentra pausado o en estado "boceto" (draft). El widget no se mostrará hasta que lo publiques dentro de la plataforma BotUyo.')},[T.isHidden]);const{state:M,actions:P,unreadCount:L,currentBotEmotion:D,isConnected:j,handleToggle:R,handleSendText:F,handleSendAttachment:$,handleSendLocation:B,getSocket:U,activeQuiz:q,handleQuizAnswer:V,handleConfirmProposal:W,handleCancelProposal:H,setVoiceCallActive:Z}=qb({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,onThemeUpdate:A}),J=f(!1);a(()=>{k&&N&&!J.current&&(J.current=!0,M.isOpen||P.openWindow())},[k,N,M.isOpen,P]);const K=u(()=>{const e={...d||{}},t=N;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,N]),G=s(()=>{P.closeWindow()},[P]),Y=s(e=>{e.stopPropagation()},[]),Q=O(M.isOpen,E,c?.position),X=u(()=>{const e={"--background":"0 0% 100%","--foreground":"240 10% 3.9%","--card":"0 0% 100%","--card-foreground":"240 10% 3.9%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 4.8% 95.9%","--muted-foreground":"240 3.8% 46.1%","--border":"240 5.9% 90%","--destructive":"0 84.2% 60.2%","--radius":"0.5rem","--window-border-radius":"24px","--launcher-border-radius":"50%","--bubble-radius":"18px","--input-radius":"24px","--window-height":"700px","--window-bottom":"24px","--spacing-1":"0.25rem","--spacing-2":"0.5rem","--spacing-3":"0.75rem","--spacing-4":"1rem","--spacing-5":"0.75rem","--spacing-6":"1.5rem","--spacing-7":"1.75rem","--spacing-8":"2rem"};if(!T.cssVariables)return e;let t={...T.cssVariables};if(z){const e=N?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Lt,...e,...n}}const n={...e};return t.background&&(n["--background"]=t.background),t.foreground&&(n["--foreground"]=t.foreground),t.card&&(n["--card"]=t.card),t.cardForeground&&(n["--card-foreground"]=t.cardForeground),t.primary&&(n["--primary"]=t.primary),t.primaryForeground&&(n["--primary-foreground"]=t.primaryForeground),t.muted&&(n["--muted"]=t.muted),t.mutedForeground&&(n["--muted-foreground"]=t.mutedForeground),t.border&&(n["--border"]=t.border),t.destructive&&(n["--destructive"]=t.destructive),t.radius&&(n["--radius"]=t.radius),t.windowBorderRadius&&(n["--window-border-radius"]=t.windowBorderRadius),t.launcherBorderRadius&&(n["--launcher-border-radius"]=t.launcherBorderRadius),t.bubbleRadius&&(n["--bubble-radius"]=t.bubbleRadius),t.inputRadius&&(n["--input-radius"]=t.inputRadius),t.windowHeight&&(n["--window-height"]=t.windowHeight),t.windowBottom&&(n["--window-bottom"]=t.windowBottom),t.spacing1&&(n["--spacing-1"]=t.spacing1),t.spacing2&&(n["--spacing-2"]=t.spacing2),t.spacing3&&(n["--spacing-3"]=t.spacing3),t.spacing4&&(n["--spacing-4"]=t.spacing4),t.spacing5&&(n["--spacing-5"]=t.spacing5),t.spacing6&&(n["--spacing-6"]=t.spacing6),t.spacing7&&(n["--spacing-7"]=t.spacing7),t.spacing8&&(n["--spacing-8"]=t.spacing8),n},[T.cssVariables,z,N,c?.darkCssVariables]),ee=c?.voiceNoiseGate??N?.voiceNoiseGate,te=u(()=>({noiseGate:ee}),[ee]),[ne,re]=i(!1);return a(()=>{S&&j&&re(!0)},[S,j]),T.isHidden?null:N?S?/* @__PURE__ */b("div",{ref:C,id:"botuyo-chat-widget-root",className:"botuyo-chat-widget",style:{position:"fixed",inset:0,zIndex:2147483e3,...X},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,children:/* @__PURE__ */b(Vc,{children:/* @__PURE__ */b(Uc,{isOpen:ne,onClose:()=>g?.("voice_first_ended",{}),onCallEnded:e=>g?.("voice_call_ended",{reason:e}),primaryColor:Dt(T),avatars:c?.avatars||N?.avatars||N?.avatarAnimations||{},logoUrl:T.logoUrl,avatar3dUrl:c?.avatar3dUrl||N?.avatar3dUrl,voiceConfig:te,getSocket:U})})}):/* @__PURE__ */y("div",{ref:C,id:"botuyo-chat-widget-root",className:Mt("botuyo-chat-widget flex flex-col",!E&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...Q,...X,pointerEvents:"auto",backgroundColor:"transparent"},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,"data-effects-glassmorphism":!1===c?.effects?.glassmorphism?"false":void 0,"data-effects-shadows":!1===c?.effects?.softShadows?"false":void 0,children:[
204
+ /* @__PURE__ */b(Zb,{...o,onStateChange:e=>{l(e),e&&u(0),r?.(e)},onEvent:w})]})}function Bb(){const e=o(Fb);if(!e)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return e}const Ub=e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)});function qb(e){const{apiKey:t,apiBaseUrl:r,agentId:o,pageContext:l,includeSEOMetadata:c=!1,theme:d,userContext:p,onLogin:h,onNavigate:m,onEvent:b,onStateChange:y,getUserToken:v,onAuthRequired:w,onThemeUpdate:x}=e,[k,_]=i(0),S=f(0),C=f(!1),{t:E}=F(),z=function(e,t,n=!0){const r=f(null);return a(()=>{if(!n||!e||!t)return;const o=`${e}/analytics`;r.current=new Ob(o,t);const i=()=>r.current?.flush(),a=()=>{"hidden"===document.visibilityState&&r.current?.flush()};return window.addEventListener("beforeunload",i),window.addEventListener("visibilitychange",a),()=>{window.removeEventListener("beforeunload",i),window.removeEventListener("visibilitychange",a),r.current?.destroy()}},[e,t,n]),{trackOpen:s(()=>{r.current?.trackOpen()},[]),trackClose:s(()=>{r.current?.trackClose()},[]),trackMessageSent:s(e=>{r.current?.trackMessageSent(e)},[]),trackMessageReceived:s((e,t)=>{r.current?.trackMessageReceived(e,t)},[]),trackError:s((e,t)=>{r.current?.trackError(e,t)},[]),trackConnectionStatus:s(e=>{r.current?.trackConnectionStatus(e)},[]),trackFeatureUsed:s(e=>{r.current?.trackFeatureUsed(e)},[])}}(r,t,!0),N=function({enabled:e=!0,soundEnabled:t=!0,desktopEnabled:n=!0,botName:r="BotUyo",logoUrl:o,notificationSoundUrl:l}={}){const[c,u]=i("default"),d=f(null),p=o||Ab,h=l||Tb;a(()=>{t&&"undefined"!=typeof window&&(d.current=new Audio(h),d.current.volume=.3)},[t,h]),a(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const m=s(async()=>{if("undefined"==typeof window||!("Notification"in window))return O.warn("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),O.info("Notification permission:",e),"granted"===e}catch(e){return O.error("Error requesting notification permission:",e),!1}},[]),g=s(t=>{if(e&&n&&"granted"===c&&("undefined"==typeof document||!document.hasFocus()))try{const e=`Nuevo mensaje de ${r}`;let n="Mensaje recibido";"text"===t.type&&"content"in t?n=t.content?.slice(0,100)||"Mensaje recibido":"image"===t.type?n="📷 Imagen":"audio"===t.type?n="🎵 Audio":"location"===t.type&&(n="📍 Ubicación");const o=new Notification(e,{body:n,icon:p,tag:"chat-message",requireInteraction:!1,silent:!1});o.onclick=()=>{window.focus(),o.close()},setTimeout(()=>o.close(),5e3)}catch(o){O.error("Error showing notification:",o)}},[e,n,c,r,p]),b=s(()=>{if(e&&t&&("undefined"==typeof document||!document.hasFocus()))try{d.current?.play().catch(e=>{O.debug("Audio playback blocked:",e)})}catch(n){O.error("Error playing sound:",n)}},[e,t]),y=s(e=>{g(e),b()},[g,b]);return{permission:c,requestPermission:m,notify:g,playSound:b,notifyWithSound:y}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:d?.botName||"BotUyo",logoUrl:d?.logoUrl}),A=function(e=10,t=6e4){const n=f([]);return{isAllowed:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),!(n.current.length>=e||(n.current.push(r),0))},[e,t]),getRemainingAttempts:s(()=>{const r=Date.now();return n.current=n.current.filter(e=>r-e<t),Math.max(0,e-n.current.length)},[e,t]),getTimeUntilReset:s(()=>{if(0===n.current.length)return 0;const e=Date.now(),r=n.current[0],o=t-(e-r);return Math.max(0,o)},[t]),reset:s(()=>{n.current=[]},[])}}(10,6e4),{state:T,actions:I}=function(e,t="default"){const[r,o]=g(_u,yu),[l,c]=i(!1),u=n.useMemo(()=>function(e,t="default"){return`botuyo_chat_v1_${e}_${t}`}(e,t),[e,t]),d=n.useMemo(()=>((e,t="default")=>{const n=`${e}_${t}`;return bu.has(n)||bu.set(n,new gu(e,t)),bu.get(n)})(e,t),[e,t]);a(()=>{"undefined"==typeof window||l||(async()=>{try{await d.migrateFromLocalStorage(e,t);const n=await d.getMessages(100),r=await d.getMetadata();if(n.length>0||r){const e={messages:n.map(e=>({...e,timestamp:new Date(e.timestamp)})),sessionId:r?.sessionId||null,isOpen:r?.isOpen||!1};o({type:"RESTORE_SESSION",payload:e})}}catch(n){O.warn("Chat: Error rehydrating from IndexedDB",n);try{const e=localStorage.getItem(u);if(e){const t=JSON.parse(e);t.messages&&(t.messages=t.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}))),o({type:"RESTORE_SESSION",payload:t})}}catch(r){O.error("Chat: Fallback rehydration failed",r)}}finally{c(!0)}})()},[l]),a(()=>{if(!l)return;const e=setTimeout(async()=>{try{await d.saveMessages(r.messages),await d.setMetadata({isOpen:r.isOpen,sessionId:r.sessionId})}catch(e){O.error("Chat Persistence Error:",e);try{const e={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(u,JSON.stringify(e))}catch(t){O.error("Chat: Fallback persistence failed",t)}}},500);return()=>clearTimeout(e)},[r.isOpen,r.messages,r.sessionId,l]);const p=s(e=>{o({type:"ADD_MESSAGE",payload:e})},[]),h=s(()=>o({type:"TOGGLE_WINDOW"}),[]),f=s(()=>o({type:"OPEN_WINDOW"}),[]),m=s(()=>o({type:"CLOSE_WINDOW"}),[]),b=s(e=>o({type:"SET_CONNECTED",payload:e}),[]),y=s(e=>o({type:"SET_TYPING",payload:e}),[]),v=s(e=>o({type:"SET_MESSAGES",payload:e}),[]),w=s(e=>o({type:"SET_ERROR",payload:e}),[]),x=s(e=>o({type:"SET_SESSION_ID",payload:e}),[]),k=s(()=>{localStorage.removeItem(u),o({type:"CLEAR_CHAT"})},[]),_=s(()=>{o({type:"SET_MESSAGES",payload:[]})},[]),S=s((e,t)=>o({type:"ANSWER_QUIZ",payload:{messageId:e,buttonId:t}}),[]),C=s((e,t)=>o({type:"RESOLVE_PROPOSAL",payload:{proposalId:e,status:t}}),[]);return{state:r,isHydrated:l,actions:{toggleWindow:h,openWindow:f,closeWindow:m,setConnected:b,setTyping:y,addMessage:p,setMessages:v,setError:w,setSessionId:x,clearChat:k,clearMessages:_,answerQuiz:S,resolveProposal:C}}}(t,o),M=function(e=!1){const t="undefined"!=typeof window?window.location.pathname:"",n=u(()=>t,[t]),[r,o]=i({});return a(()=>{if(!e)return void o({});const t=setTimeout(()=>{const e=function(){if("undefined"==typeof window)return{};const e={};e.title=document.title,document.querySelectorAll("meta").forEach(t=>{const n=t.getAttribute("name"),r=t.getAttribute("property"),o=t.getAttribute("content");if(o){if(n)switch(n){case"description":e.description=o;break;case"keywords":e.keywords=o.split(",").map(e=>e.trim());break;case"author":e.author=o}if(r){if(r.startsWith("og:")){const t=r.replace("og:","og_");e[t]=o}if(r.startsWith("twitter:")){const t=r.replace("twitter:","twitter_");e[t]=o}}}});try{const t=document.querySelectorAll('script[type="application/ld+json"]');if(t.length>0){const n=[];t.forEach(e=>{try{const t=JSON.parse(e.textContent||"");n.push(t)}catch{}}),n.length>0&&(e.structuredData=n)}}catch{}return e}();o(e)},100);return()=>clearTimeout(t)},[n,e]),e&&Object.keys(r).length>0?r:void 0}(c),P=function(e){const{apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,userContext:l}=e,c=f(e);a(()=>{c.current=e},[e]);const d=f(null),[p,h]=i(!1),[m,g]=i(!1),b=f(function(){try{const e=localStorage.getItem(_b);if(e)return e;const t=Sb();return localStorage.setItem(_b,t),t}catch{return O.warn("localStorage not available, using session-only device ID"),Sb()}}()),y=f(o);a(()=>{y.current=o},[o]);const v=s(e=>{const t=Cb.safeParse(e),r=t.success&&t.data.id?t.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=t.success&&t.data.sender?t.data.sender:"bot",i=t.success&&t.data.timestamp?new Date(t.data.timestamp):/* @__PURE__ */new Date,a=t.success?t.data:{type:"text"};switch(a.type){case"image":return{id:r,type:"image",sender:o,timestamp:i,imageUrl:a.imageUrl||a.content||"",altText:"Imagen enviada"};case"audio":{const e=a.audioUrl||"";return{id:r,type:"audio",sender:o,timestamp:i,content:e.startsWith("http://")||e.startsWith("https://")?e:e?`${n}/api/voice/audio/${r}`:a.content||"",text:a.content||void 0}}case"location":return{id:r,type:"location",sender:o,timestamp:i,latitude:Number(a.latitude||0),longitude:Number(a.longitude||0),name:a.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:i,content:String(a.content||"")};default:return{id:r,type:"text",sender:o,timestamp:i,content:String(a.content||"Sin contenido"),emotion:a.emotion,...a.sources?.length?{sources:a.sources}:{}}}},[]),w=s(()=>{if(!t||!n)return;if(d.current?.connected)return;h(!0);const e=e=>{const o=yb(`${n}/webchat`,{auth:{apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});o.on("connect",()=>{h(!1),g(!0),c.current.onConnected(`temp-${Date.now()}`,void 0)}),o.on("disconnect",e=>{h(!1),g(!1),c.current.onDisconnected()}),o.on("connect_error",e=>{h(!1);const n=String(e?.data instanceof Object?e?.data?.code:e?.data??e?.message??"");if(Nb.test(n)||Nb.test(e?.message??"")){c.current.onAuthRequired?.();const e=c.current.getUserToken;e&&e().then(e=>{d.current&&(d.current.auth={apiKey:t,deviceId:b.current,agentId:r,token:e,metadata:l?.metadata})}).catch(e=>O.error("[useChatSocket] Token refresh failed:",e))}c.current.onError(`Error de conexión: ${e.message}`)}),o.on("connection_ack",e=>{c.current.onConnected(e.sessionId,e.config)}),o.on("bot_message",e=>{try{c.current.onMessage(v(e))}catch(t){O.error("ChatSocket Error processing bot_message:",t)}}),o.on("chat_history",e=>{if(e.messages&&Array.isArray(e.messages))if(c.current.onHistoryLoaded){const t=e.messages.map(e=>{try{return v(e)}catch(t){return O.debug("Error processing history message:",t),null}}).filter(e=>null!==e);c.current.onHistoryLoaded(t)}else e.messages.forEach(e=>{try{c.current.onMessage(v(e))}catch(t){O.debug("Error processing history message:",t)}});c.current.onEvent&&c.current.onEvent("history_loaded",e)}),o.on("bot_typing",e=>c.current.onTyping(e));const i=e=>{try{window.parent.postMessage(e,"*")}catch(t){window.postMessage(e,"*")}};o.on("onboarding:command",e=>i(e)),o.on("form:command",e=>i(e)),o.on("request_form_state",()=>{i({type:"botuyo-request-form-state"})}),o.on("auth_success",e=>{c.current.onLogin&&c.current.onLogin(e),e.theme&&c.current.onThemeUpdate&&c.current.onThemeUpdate(e.theme)}),o.on("custom_event",e=>{if(i({type:"botuyo-custom-event",...e}),"quiz_question"===e?.eventName&&e?.data&&!c.current.isVoiceCallActive?.()){const{question:t,buttons:n}=e.data;if(t&&n?.length){const e={id:`quiz-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"buttons",sender:"bot",timestamp:/* @__PURE__ */new Date,content:t,buttons:n};c.current.onMessage(e)}}if("show_image"===e?.eventName&&e?.data&&!c.current.isVoiceCallActive?.()){const t=zb.safeParse(e.data);if(t.success){const e=t.data,n={id:`img-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,type:"image",sender:"bot",timestamp:/* @__PURE__ */new Date,imageUrl:e.imageUrl,altText:e.alt||e.caption||"Imagen",...e.caption?{caption:e.caption}:{},...e.attribution?{attribution:e.attribution}:{},...e.sourceUrl?{sourceUrl:e.sourceUrl}:{}};c.current.onMessage(n)}else O.debug("ChatSocket: dropped malformed show_image payload")}if("agent_switched"===e?.eventName&&e?.data){const t=Eb.safeParse(e.data);t.success?c.current.onAgentSwitched?.(t.data):O.debug("ChatSocket: dropped malformed agent_switched payload")}if("tool_proposal"===e?.eventName&&e?.data){const t=vb.safeParse(e.data);if(t.success){const e=t.data,n={id:`proposal-${e.proposalId}`,type:"tool_proposal",sender:"bot",timestamp:/* @__PURE__ */new Date,proposalId:e.proposalId,toolName:e.tool,title:e.title,summary:e.summary,ownerOnly:e.ownerOnly,status:"pending"};c.current.onMessage(n)}else O.debug("ChatSocket: dropped malformed tool_proposal payload")}if(("tool_proposal_resolved"===e?.eventName||"tool_proposal_expired"===e?.eventName)&&e?.data){const t=kb.safeParse(e.data);if(t.success){const n="tool_proposal_expired"===e.eventName?"expired":t.data.status??"confirmed";c.current.onToolProposalResolved?.(t.data.proposalId,n)}else O.debug("ChatSocket: dropped malformed tool_proposal_resolved payload")}});const a=e=>{const{type:t}=e.data||{};"botuyo-onboarding-state"!==t&&"botuyo-form-state"!==t||o.emit("form_state",e.data)};window.addEventListener("message",a),d.current=o,o.__formCleanup=()=>window.removeEventListener("message",a)},o=c.current.getUserToken;o?o().then(t=>e(t)).catch(t=>{O.error("[useChatSocket] getUserToken failed:",t),c.current.onAuthRequired?.(),e(l?.token)}):e(l?.token)},[t,n]),x=s(()=>{d.current&&(d.current.disconnect(),d.current=null,g(!1))},[]),k=f(w);k.current=w,a(()=>(k.current(),()=>{d.current&&(d.current.disconnect(),d.current=null)}),[]);const _=f([]),S=f([]),C=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),E=s(()=>{if(d.current?.connected)for(;_.current.length>0;){const e=_.current.shift();d.current.emit("user_message",e)}},[]);a(()=>{m&&E()},[m,E]),a(()=>{if(!m)return;const e=setInterval(()=>{const e=Date.now();S.current=S.current.filter(t=>e<t.nextRetryAt||(t.attempts>=t.maxAttempts?(c.current.onEvent?.("message_failed",{id:t.id,payload:t.payload}),O.error("Message failed after max retries:",t.id),!1):!d.current?.connected||(d.current.emit("user_message",t.payload,e=>{e?.success&&c.current.onEvent?.("message_sent",{id:t.id})}),t.attempts++,t.nextRetryAt=e+1e3*Math.pow(2,t.attempts),t.attempts<t.maxAttempts)))},500);return()=>clearInterval(e)},[m]);const z=s((e,t="text")=>{const n=C(),r={...y.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:b.current},o={id:n,content:e.trim(),type:t,metadata:r};return d.current?.connected?(d.current.emit("user_message",o,e=>{!1!==e?.success&&e?c.current.onEvent?.("message_sent",{id:n}):(S.current.push({id:n,payload:o,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),c.current.onEvent?.("message_retry_queued",{id:n}))}),n):(_.current.push(o),c.current.onEvent?.("queued_message",{id:n,payload:o}),n)},[C]),N=u(()=>rc(e=>{d.current?.emit("typing",e)},250),[]);return{isConnected:m,isConnecting:p,sendMessage:z,sendTyping:N,getSocket:s(()=>d.current,[]),requestHistory:s(()=>{d.current?.emit("request_history")},[]),reconnect:w,disconnect:x,confirmProposal:s(e=>{d.current?.emit("tool_confirm",{proposalId:e})},[]),rejectProposal:s(e=>{d.current?.emit("tool_reject",{proposalId:e})},[])}}({apiKey:t,apiBaseUrl:r,agentId:o,pageContext:u(()=>M?{...l||{},seo:{...M||{}}}:l,[l,M]),userContext:p,onMessage:s(e=>{const t=Date.now(),n=S.current>0?t-S.current:void 0;S.current=t,I.addMessage(e),z.trackMessageReceived(e.type,n),T.isOpen||"bot"!==e.sender||(_(e=>e+1),N.notifyWithSound(e))},[I,T.isOpen,z,N]),onConnected:s((e,t)=>{I.setConnected(!0),I.setSessionId(e),z.trackConnectionStatus(!0),t&&x&&x(t),t&&b&&b("backend_config",t)},[I,b,x,z]),onDisconnected:s(()=>{I.setConnected(!1),z.trackConnectionStatus(!1)},[I,z]),onTyping:s(e=>I.setTyping(e),[I]),onError:s(e=>{I.setError(e),z.trackError(e)},[I,z]),onLogin:h,onNavigate:m,onEvent:b,onThemeUpdate:x,onAgentSwitched:s(e=>{const t=function(e,t){const n=(e||"").trim(),r=(t||"").trim();return n&&r&&!n.toLowerCase().includes(r.toLowerCase())?`${n} · ${r}`:n||r}(e.name,e.label);x&&x(n=>({...n||{},...t?{botName:t}:{},...e.avatarUrl?{logoUrl:e.avatarUrl}:{}})),t&&I.addMessage({id:`agent-switched-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"system",sender:"system",timestamp:/* @__PURE__ */new Date,content:E("agent_switched",{name:t})})},[x,I,E]),onHistoryLoaded:s(e=>{0!==e.length&&I.setMessages(function(e,t){if(!t||0===t.length)return e;const n=t.reduce((e,t)=>Math.max(e,Mb(t)),0),r=new Set(t.map(e=>e.id)),o=new Set(t.map(Pb)),i=e.filter(e=>!r.has(e.id)&&Mb(e)>n&&!o.has(Pb(e)));return[...t,...i].sort((e,t)=>Mb(e)-Mb(t))}(T.messages,e))},[T.messages,I]),getUserToken:v,onAuthRequired:w,onToolProposalResolved:s((e,t)=>I.resolveProposal(e,t),[I]),isVoiceCallActive:s(()=>C.current,[])}),L=s(e=>{C.current=e},[]),D=u(()=>function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("buttons"===n.type&&!n.answered)return n}return null}(T.messages),[T.messages]),j=f(D);a(()=>{j.current=D},[D]);const R=s(()=>{O.debug("ChatWidget handleToggle called, current isOpen:",T.isOpen),T.isOpen?(I.closeWindow(),z.trackClose(),y?.(!1),O.debug("ChatWidget Closing window")):(I.openWindow(),_(0),z.trackOpen(),y?.(!0),O.debug("ChatWidget Opening window"))},[T.isOpen,I,y,z]),$=s(e=>{if(!A.isAllowed()){const e=A.getTimeUntilReset(),t=Math.ceil(e/1e3);return void I.setError(E("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};I.addMessage(t),z.trackMessageSent("text"),P.sendMessage(e,"text"),j.current&&I.answerQuiz(j.current.id)},[I,P,A,z,E]),B=s((e,t,n)=>{I.answerQuiz(e.id,n),I.addMessage({id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:t}),P.sendMessage(`Answer: ${t}`,"text"),z.trackMessageSent("text")},[I,P,z]),U=s(e=>{I.resolveProposal(e,"confirmed"),P.confirmProposal(e)},[I,P]),q=s(e=>{I.resolveProposal(e,"cancelled"),P.rejectProposal(e)},[I,P]),V=s(async(e,t)=>{let n;n="audio"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"audio",sender:"user",timestamp:/* @__PURE__ */new Date,content:URL.createObjectURL(e)}:"image"===t?{id:`temp-${Date.now()}-${Math.random()}`,type:"image",sender:"user",timestamp:/* @__PURE__ */new Date,imageUrl:URL.createObjectURL(e)}:{id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:`📎 ${e.name}`},I.addMessage(n);const r=await Ub(e);P.sendMessage(r,t)},[I,P]),W=s(e=>{const t={id:`temp-${Date.now()}-${Math.random()}`,type:"location",sender:"user",timestamp:/* @__PURE__ */new Date,latitude:e.latitude,longitude:e.longitude,name:"Mi ubicación"};I.addMessage(t),P.sendMessage(JSON.stringify(e),"location")},[I,P]);a(()=>{const e=()=>{T.isOpen||I.openWindow()},t=()=>{T.isOpen&&I.closeWindow()},n=()=>{T.isOpen?I.closeWindow():I.openWindow()},r=e=>{e.detail?.message&&$(e.detail.message)},o=()=>{T.isOpen||I.openWindow()};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),window.addEventListener("botuyo-chat:start-call",o),window.addEventListener("botuyo-chat:send-message",r),()=>{window.removeEventListener("botuyo-chat:open",e),window.removeEventListener("botuyo-chat:close",t),window.removeEventListener("botuyo-chat:toggle",n),window.removeEventListener("botuyo-chat:start-call",o),window.removeEventListener("botuyo-chat:send-message",r)}},[T.isOpen,I,$]),a(()=>(jb($),()=>jb(null)),[$]);const H=s(()=>{I.clearMessages(),O.info("Chat history cleared")},[I]);a(()=>(Rb(H),()=>Rb(null)),[H]);const Z=u(()=>{if(T.isTyping)return"thinking";const e=[...T.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[T.isTyping,T.messages]);return{state:T,actions:I,unreadCount:k,currentBotEmotion:Z,isConnected:P.isConnected,getSocket:P.getSocket,activeQuiz:D,handleToggle:R,handleSendText:$,handleSendAttachment:V,handleSendLocation:W,handleQuizAnswer:B,handleConfirmProposal:U,handleCancelProposal:q,setVoiceCallActive:L}}function Vb({children:e}){const t=f(null),n=f(null),[r,o]=i(!1);return a(()=>{if("undefined"==typeof document)return;let e,r,i=document.getElementById("botuyo-chat-widget-root");if(i&&i.shadowRoot)e=i.shadowRoot,r=e.getElementById("botuyo-chat-widget-root")||e.querySelector("div");else{i=document.createElement("div"),i.id="botuyo-chat-widget-root",document.body.appendChild(i),e=i.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=R.replace(/:root/g,":host"),e.appendChild(t),r=document.createElement("div"),r.id="botuyo-chat-widget-root",e.appendChild(r)}return n.current=i,t.current=r,o(!0),O.debug("ShadowDOMHost initialized"),()=>{n.current&&(n.current.remove(),n.current=null,t.current=null)}},[]),r&&t.current?x(e,t.current):null}function Wb(e){const{apiKey:t,apiBaseUrl:n="https://api.botuyo.com",agentId:r,pageContext:o,includeSEOMetadata:l=!1,theme:c,mediaConfig:d,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,initialOpen:k=!1,hideLauncher:_=!1,voiceFirst:S=!1}=e,C=f(null),E=oc(),z=function(e){const[t,n]=i(!1);return a(()=>{let t=null;const r=()=>{if(!e.current)return;const t=!!e.current.parentElement?.closest(".dark"),r=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),o=document.getElementById("botuyo-chat-widget-root"),i=!!o?.parentElement?.closest(".dark"),a=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),l="dark"===document.documentElement.getAttribute("data-theme"),c="dark"===document.body.getAttribute("data-theme"),u=!!e.current.parentElement?.closest('[data-theme="dark"]'),d=window.matchMedia("(prefers-color-scheme: dark)").matches,p=t||r||i||a||s||l||c||u||d;e.current&&(p?e.current.classList.add("dark"):e.current.classList.remove("dark")),n(p)};r();const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r();o.addEventListener("change",i);const a=new MutationObserver(()=>{r()}),s=document.getElementById("botuyo-chat-widget-root");s&&(a.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(a.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=s.parentElement)),a.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),a.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let l=e.current?.parentElement;for(;l;)a.observe(l,{attributes:!0,attributeFilter:["class","data-theme"]}),l=l.parentElement;const c=setInterval(()=>{const e=document.getElementById("botuyo-chat-widget-root");e&&e.parentElement!==t&&(t&&e.parentElement&&(a.observe(e.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),t=e.parentElement),r())},100);return()=>{a.disconnect(),o.removeEventListener("change",i),clearInterval(c)}},[e]),t}(C),[N,A]=i(),{mergedTheme:T,mergedStyles:I,getContainerStyle:O}=function(e,t){const n=function(){const[e,t]=i(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return a(()=>{const e=window.matchMedia("(prefers-contrast: high)"),n=window.matchMedia("(prefers-contrast: more)"),r=e=>{t(e.matches)};return e.addEventListener("change",r),n.addEventListener("change",r),()=>{e.removeEventListener("change",r),n.removeEventListener("change",r)}},[]),e}(),r=u(()=>{const r=function(e,t){const n={...Pt,...t?.cssVariables||{},...e?.cssVariables||{}};return{botName:e?.botName||t?.botName||"BotUyo",logoUrl:e?.logoUrl||t?.logoUrl||"",position:e?.position||t?.position||"bottom-right",welcomeMessage:e?.welcomeMessage||t?.welcomeMessage||"¡Hola! ¿En qué puedo ayudarte?",inputPlaceholder:e?.inputPlaceholder||t?.inputPlaceholder||"Escribe un mensaje...",cssVariables:n,isHidden:e?.isHidden??t?.isHidden??!1}}(e,t);return n?{...r,cssVariables:{...r.cssVariables,primary:"0 0% 0%",primaryForeground:"0 0% 100%",background:"0 0% 100%",foreground:"0 0% 0%",card:"0 0% 100%",cardForeground:"0 0% 0%",muted:"0 0% 96%",mutedForeground:"0 0% 0%",border:"0 0% 0%"}}:r},[e,t,n]),o=u(()=>({radius:{...Wc,...e?.bubbleStyles?.radius},bot:{...Hc,...e?.bubbleStyles?.bot},user:{...Zc,...e?.bubbleStyles?.user},launcher:{...e?.bubbleStyles?.launcher},mapCard:{...e?.bubbleStyles?.mapCard}}),[e?.bubbleStyles]);return{mergedTheme:r,mergedStyles:o,getContainerStyle:(e,t,n)=>({"--chat-primary":`hsl(${r.cssVariables.primary})`,zIndex:e?2147483647:9999,position:"fixed",top:t&&e?0:"auto",left:t&&e?0:"bottom-left"===n?"24px":"auto",right:t&&e?0:"bottom-right"!==n&&n?"auto":"24px",bottom:t&&e?0:"24px",width:t&&e?"100%":"auto",height:t&&e?"100%":"auto"})}}(c,N);a(()=>{T.isHidden&&console.warn('[BotUyo] ⚠️ El agente (o Flow) de IA asociado a esta API Key se encuentra pausado o en estado "boceto" (draft). El widget no se mostrará hasta que lo publiques dentro de la plataforma BotUyo.')},[T.isHidden]);const{state:M,actions:P,unreadCount:L,currentBotEmotion:D,isConnected:j,handleToggle:R,handleSendText:F,handleSendAttachment:$,handleSendLocation:B,getSocket:U,activeQuiz:q,handleQuizAnswer:V,handleConfirmProposal:W,handleCancelProposal:H,setVoiceCallActive:Z}=qb({apiKey:t,apiBaseUrl:n,agentId:r,pageContext:o,includeSEOMetadata:l,theme:c,userContext:p,onLogin:h,onNavigate:m,onEvent:g,onStateChange:v,getUserToken:w,onAuthRequired:x,onThemeUpdate:A}),J=f(!1);a(()=>{k&&N&&!J.current&&(J.current=!0,M.isOpen||P.openWindow())},[k,N,M.isOpen,P]);const K=u(()=>{const e={...d||{}},t=N;return null!=t?.voiceEnabled&&(e.enableVoice=t.voiceEnabled),e},[d,N]),G=s(()=>{P.closeWindow()},[P]),Y=s(e=>{e.stopPropagation()},[]),Q=O(M.isOpen,E,c?.position),X=u(()=>{const e={"--background":"0 0% 100%","--foreground":"240 10% 3.9%","--card":"0 0% 100%","--card-foreground":"240 10% 3.9%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 4.8% 95.9%","--muted-foreground":"240 3.8% 46.1%","--border":"240 5.9% 90%","--destructive":"0 84.2% 60.2%","--radius":"0.5rem","--window-border-radius":"24px","--launcher-border-radius":"50%","--bubble-radius":"18px","--input-radius":"24px","--window-height":"700px","--window-bottom":"24px","--spacing-1":"0.25rem","--spacing-2":"0.5rem","--spacing-3":"0.75rem","--spacing-4":"1rem","--spacing-5":"0.75rem","--spacing-6":"1.5rem","--spacing-7":"1.75rem","--spacing-8":"2rem"};if(!T.cssVariables)return e;let t={...T.cssVariables};if(z){const e=N?.darkCssVariables||{},n=c?.darkCssVariables||{};t={...t,...Lt,...e,...n}}const n={...e};return t.background&&(n["--background"]=t.background),t.foreground&&(n["--foreground"]=t.foreground),t.card&&(n["--card"]=t.card),t.cardForeground&&(n["--card-foreground"]=t.cardForeground),t.primary&&(n["--primary"]=t.primary),t.primaryForeground&&(n["--primary-foreground"]=t.primaryForeground),t.muted&&(n["--muted"]=t.muted),t.mutedForeground&&(n["--muted-foreground"]=t.mutedForeground),t.border&&(n["--border"]=t.border),t.destructive&&(n["--destructive"]=t.destructive),t.radius&&(n["--radius"]=t.radius),t.windowBorderRadius&&(n["--window-border-radius"]=t.windowBorderRadius),t.launcherBorderRadius&&(n["--launcher-border-radius"]=t.launcherBorderRadius),t.bubbleRadius&&(n["--bubble-radius"]=t.bubbleRadius),t.inputRadius&&(n["--input-radius"]=t.inputRadius),t.borderWidth&&(n["--border-width"]=t.borderWidth),t.fontFamily&&(n["--font-family"]=t.fontFamily),t.windowHeight&&(n["--window-height"]=t.windowHeight),t.windowBottom&&(n["--window-bottom"]=t.windowBottom),t.spacing1&&(n["--spacing-1"]=t.spacing1),t.spacing2&&(n["--spacing-2"]=t.spacing2),t.spacing3&&(n["--spacing-3"]=t.spacing3),t.spacing4&&(n["--spacing-4"]=t.spacing4),t.spacing5&&(n["--spacing-5"]=t.spacing5),t.spacing6&&(n["--spacing-6"]=t.spacing6),t.spacing7&&(n["--spacing-7"]=t.spacing7),t.spacing8&&(n["--spacing-8"]=t.spacing8),n},[T.cssVariables,z,N,c?.darkCssVariables]),ee=c?.voiceNoiseGate??N?.voiceNoiseGate,te=u(()=>({noiseGate:ee}),[ee]),[ne,re]=i(!1);return a(()=>{S&&j&&re(!0)},[S,j]),T.isHidden?null:N?S?/* @__PURE__ */b("div",{ref:C,id:"botuyo-chat-widget-root",className:"botuyo-chat-widget",style:{position:"fixed",inset:0,zIndex:2147483e3,fontFamily:"var(--font-family, inherit)",...X},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,children:/* @__PURE__ */b(Vc,{children:/* @__PURE__ */b(Uc,{isOpen:ne,onClose:()=>g?.("voice_first_ended",{}),onCallEnded:e=>g?.("voice_call_ended",{reason:e}),primaryColor:Dt(T),avatars:c?.avatars||N?.avatars||N?.avatarAnimations||{},logoUrl:T.logoUrl,avatar3dUrl:c?.avatar3dUrl||N?.avatar3dUrl,voiceConfig:te,getSocket:U})})}):/* @__PURE__ */y("div",{ref:C,id:"botuyo-chat-widget-root",className:Mt("botuyo-chat-widget flex flex-col",!E&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...Q,...X,fontFamily:"var(--font-family, inherit)",pointerEvents:"auto",backgroundColor:"transparent"},"data-animations-disabled":!1===c?.animations?.enabled?"true":void 0,"data-effects-glassmorphism":!1===c?.effects?.glassmorphism?"false":void 0,"data-effects-shadows":!1===c?.effects?.softShadows?"false":void 0,children:[
205
205
  /* @__PURE__ */b("div",{className:Mt("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",E?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",M.isOpen?"opacity-100 scale-100 h-full w-full translate-y-0 pointer-events-auto":"opacity-0 scale-[0.85] pointer-events-none translate-y-8 h-0 w-0"),style:{pointerEvents:M.isOpen?"auto":"none"},onMouseDown:Y,onTouchStart:Y,children:/* @__PURE__ */b(Vc,{children:/* @__PURE__ */b(qc,{isOpen:M.isOpen,isConnected:j,isTyping:M.isTyping,messages:M.messages,onClose:G,onSendMessage:F,onSendAttachment:$,onSendLocation:B,botName:T.botName,logoUrl:T.logoUrl,welcomeMessage:T.welcomeMessage,inputPlaceholder:c?.inputPlaceholder||N?.inputPlaceholder,position:c?.position,bubbleStyles:I,avatars:c?.avatars||N?.avatars||N?.avatarAnimations||{},mediaConfig:K,theme:T,avatar3dUrl:c?.avatar3dUrl||N?.avatar3dUrl,voiceConfig:te,getSocket:U,suggestedQuestions:N?.suggestedQuestions,activeQuiz:q,onQuizAnswer:V,onProposalAction:(e,t)=>"confirm"===t?W(e):H(e),onVoiceActiveChange:Z})})}),!_&&/* @__PURE__ */b("div",{className:Mt(M.isOpen?"hidden":"block",!E&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:Y,onTouchStart:Y,children:/* @__PURE__ */b(Ut,{isOpen:M.isOpen,onClick:R,unreadCount:L,position:c?.position||"bottom-right",primaryColor:Dt(T),logoUrl:T.logoUrl,starterPrompt:c?.starterPrompt||N?.starterPrompt,avatars:c?.avatars||N?.avatars||N?.avatarAnimations||{},emotion:D,styles:I,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale??N?.avatarScale,showPromptAvatar:c?.showPromptAvatar??N?.showPromptAvatar})})]}):null}function Hb(e){/* @__PURE__ */
206
206
  return b(Bt,{animations:e.theme?.animations,effects:e.theme?.effects,children:/* @__PURE__ */b(Wb,{...e})})}function Zb(e){/* @__PURE__ */
207
207
  return b(D,{defaultLocale:e.theme?.defaultLocale,children:/* @__PURE__ */b(Vb,{children:/* @__PURE__ */b(Hb,{...e})})})}const Jb=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:Zb,ChatWidgetInner:Wb,ChatWidgetWithProviders:Hb},Symbol.toStringTag,{value:"Module"}));function Kb({apiKey:e,apiBaseUrl:t="https://api.botuyo.com",sessionKey:n,locale:r="es",onReady:o}){const i=u(()=>({apiKey:e,apiBaseUrl:t,initialOpen:!0,hideLauncher:!0,theme:{position:"bottom-right",defaultLocale:r,cssVariables:{windowBorderRadius:"0px",windowHeight:"100%",windowBottom:"0px"}},onEvent:e=>{"connected"===e&&o&&o()}}),[e,t,r,o]);/* @__PURE__ */
@@ -217,5 +217,5 @@ return y("div",{className:`relative h-full w-full overflow-hidden ${t}`,children
217
217
  /* @__PURE__ */b("pointLight",{position:[0,-.5,.5],intensity:.25,distance:4}),
218
218
  /* @__PURE__ */b(Xb,{url:e,autoRotate:S,hasCustomCamera:_,frameRef:v,onLoaded:w,onError:x})]},e),"loading"===g&&/* @__PURE__ */y("div",{className:"pointer-events-none absolute inset-0 z-20 flex flex-col items-center justify-center gap-2 text-gray-400",children:[
219
219
  /* @__PURE__ */b("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-current border-t-transparent opacity-70"}),c&&/* @__PURE__ */b("span",{className:"text-xs",children:c})]}),"error"===g&&/* @__PURE__ */y("div",{className:"absolute inset-0 z-20 flex flex-col items-center justify-center gap-1 px-3 text-center text-gray-400",children:[
220
- /* @__PURE__ */b(pe,{className:"h-5 w-5","aria-hidden":!0}),u&&/* @__PURE__ */b("span",{className:"text-xs",children:u})]})]})}const ry="https://api.botuyo.com";class oy extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error("[BotUyoChat] Widget error:",e,t)}render(){return this.state.hasError?null:this.props.children}}const iy={"--background":"240 10% 3.9%","--foreground":"0 0% 98%","--card":"240 10% 3.9%","--card-foreground":"0 0% 98%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 3.7% 15.9%","--muted-foreground":"240 5% 64.9%","--border":"240 3.7% 15.9%"},ay=p(()=>Promise.resolve().then(()=>Jb).then(e=>({default:e.ChatWidgetWithProviders})));class sy{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||ry},this.render(),this.setupDarkModeDetection(),this}render(){if(!this.config)return void console.error("[BotUyoChat] No configuration provided");if(!this.container){this.container=document.createElement("div"),this.container.id="botuyo-chat-widget-root",document.body.appendChild(this.container),this.shadowRoot=this.container.attachShadow({mode:"open"});const e=document.createElement("style");e.textContent=R.replace(/:root/g,":host"),this.shadowRoot.appendChild(e),this.mountPoint=document.createElement("div"),this.mountPoint.id="botuyo-chat-widget-root",this.shadowRoot.appendChild(this.mountPoint)}if(this.config.theme?.cssVariables&&this.mountPoint){const e=this.config.theme.cssVariables;[["--background",e.background],["--foreground",e.foreground],["--card",e.card],["--card-foreground",e.cardForeground],["--primary",e.primary],["--primary-foreground",e.primaryForeground],["--muted",e.muted],["--muted-foreground",e.mutedForeground],["--border",e.border],["--destructive",e.destructive],["--radius",e.radius],["--window-border-radius",e.windowBorderRadius],["--launcher-border-radius",e.launcherBorderRadius],["--bubble-radius",e.bubbleRadius],["--input-radius",e.inputRadius],["--window-height",e.windowHeight],["--window-bottom",e.windowBottom],["--spacing-1",e.spacing1],["--spacing-2",e.spacing2],["--spacing-3",e.spacing3],["--spacing-4",e.spacing4],["--spacing-5",e.spacing5],["--spacing-6",e.spacing6],["--spacing-7",e.spacing7],["--spacing-8",e.spacing8]].forEach(([e,t])=>{void 0!==t&&this.mountPoint.style.setProperty(e,t)})}this.mountPoint&&!this.config.theme?.cssVariables&&(!function(){const e=document.documentElement.getAttribute("data-theme");return"dark"===e||"light"!==e&&window.matchMedia("(prefers-color-scheme: dark)").matches}()?Object.keys(iy).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(iy).forEach(([e,t])=>{this.mountPoint.style.setProperty(e,t)})),!this.root&&this.mountPoint&&(this.root=e(this.mountPoint));const t={apiKey:this.config.apiKey,apiBaseUrl:this.config.apiBaseUrl||ry,agentId:this.config.agentId,theme:{botName:"Asistente Virtual",position:"bottom-right",welcomeMessage:"¡Hola! 👋 ¿En qué puedo ayudarte?",inputPlaceholder:"Escribe tu mensaje...",cssVariables:{primary:"160 84% 39%",windowBorderRadius:"24px",launcherBorderRadius:"50%"},...this.config.theme},userContext:this.config.userContext,pageContext:this.config.pageContext,includeSEOMetadata:this.config.includeSEOMetadata??!1,mediaConfig:this.config.mediaConfig,onNavigate:this.config.onNavigate,onLogin:this.config.onLogin,onEvent:this.config.onEvent,onStateChange:this.config.onStateChange},r=n.createElement(h,{fallback:n.createElement("div",{style:{position:"fixed",bottom:"24px",right:"24px",width:"60px",height:"60px",borderRadius:"50%",backgroundColor:"#10b981",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",cursor:"wait"}},n.createElement("div",{style:{width:"24px",height:"24px",border:"3px solid rgba(255, 255, 255, 0.3)",borderTopColor:"#fff",borderRadius:"50%",animation:"spin 1s linear infinite"}}))},n.createElement(ay,t));this.root.render(n.createElement(oy,null,n.createElement(D,{defaultLocale:this.config.theme?.defaultLocale,children:r}))),console.log("[BotUyoChat] Widget initialized",t)}update(e){this.config?(this.config={...this.config,...e,theme:{...this.config.theme,...e.theme}},this.render()):console.error("[BotUyoChat] Widget not initialized")}destroy(){this.darkModeObserver&&(this.darkModeObserver.disconnect(),this.darkModeObserver=null),this.darkModeMediaQuery&&(this.darkModeMediaQuery.removeEventListener("change",this.handleDarkModeChange),this.darkModeMediaQuery=null),this.root&&(this.root.unmount(),this.root=null),this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null,this.shadowRoot=null,this.mountPoint=null),this.config=null,console.log("[BotUyoChat] Widget destroyed")}setupDarkModeDetection(){this.config?.theme?.cssVariables||(this.handleDarkModeChange=()=>this.render(),this.darkModeObserver=new MutationObserver(this.handleDarkModeChange),this.darkModeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),this.darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.darkModeMediaQuery.addEventListener("change",this.handleDarkModeChange))}handleDarkModeChange=()=>{};open(){window.dispatchEvent(new CustomEvent("botuyo-chat:open"))}close(){window.dispatchEvent(new CustomEvent("botuyo-chat:close"))}startCall(){window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))}sendMessage(e){window.dispatchEvent(new CustomEvent("botuyo-chat:send-message",{detail:{message:e}}))}getState(){return null}}const ly=new sy;window.BotUyoChat=ly;export{ny as A,sy as B,Zb as C,ee as L,Kb as P,fe as X,q as a,Mt as b,Gb as c,$b as d,Hb as e,D as f,Dt as g,Bb as h,ly as i,j,O as l,Qb as s,F as u};
221
- //# sourceMappingURL=standalone-DjuayqcY.js.map
220
+ /* @__PURE__ */b(pe,{className:"h-5 w-5","aria-hidden":!0}),u&&/* @__PURE__ */b("span",{className:"text-xs",children:u})]})]})}const ry="https://api.botuyo.com";class oy extends m{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error("[BotUyoChat] Widget error:",e,t)}render(){return this.state.hasError?null:this.props.children}}const iy={"--background":"240 10% 3.9%","--foreground":"0 0% 98%","--card":"240 10% 3.9%","--card-foreground":"0 0% 98%","--primary":"160 84% 39%","--primary-foreground":"0 0% 100%","--muted":"240 3.7% 15.9%","--muted-foreground":"240 5% 64.9%","--border":"240 3.7% 15.9%"},ay=p(()=>Promise.resolve().then(()=>Jb).then(e=>({default:e.ChatWidgetWithProviders})));class sy{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(e){return this.config={...e,apiBaseUrl:e.apiBaseUrl||ry},this.render(),this.setupDarkModeDetection(),this}render(){if(!this.config)return void console.error("[BotUyoChat] No configuration provided");if(!this.container){this.container=document.createElement("div"),this.container.id="botuyo-chat-widget-root",document.body.appendChild(this.container),this.shadowRoot=this.container.attachShadow({mode:"open"});const e=document.createElement("style");e.textContent=R.replace(/:root/g,":host"),this.shadowRoot.appendChild(e),this.mountPoint=document.createElement("div"),this.mountPoint.id="botuyo-chat-widget-root",this.shadowRoot.appendChild(this.mountPoint)}if(this.config.theme?.cssVariables&&this.mountPoint){const e=this.config.theme.cssVariables;[["--background",e.background],["--foreground",e.foreground],["--card",e.card],["--card-foreground",e.cardForeground],["--primary",e.primary],["--primary-foreground",e.primaryForeground],["--muted",e.muted],["--muted-foreground",e.mutedForeground],["--border",e.border],["--destructive",e.destructive],["--radius",e.radius],["--window-border-radius",e.windowBorderRadius],["--launcher-border-radius",e.launcherBorderRadius],["--bubble-radius",e.bubbleRadius],["--input-radius",e.inputRadius],["--border-width",e.borderWidth],["--font-family",e.fontFamily],["--window-height",e.windowHeight],["--window-bottom",e.windowBottom],["--spacing-1",e.spacing1],["--spacing-2",e.spacing2],["--spacing-3",e.spacing3],["--spacing-4",e.spacing4],["--spacing-5",e.spacing5],["--spacing-6",e.spacing6],["--spacing-7",e.spacing7],["--spacing-8",e.spacing8]].forEach(([e,t])=>{void 0!==t&&this.mountPoint.style.setProperty(e,t)})}this.mountPoint&&!this.config.theme?.cssVariables&&(!function(){const e=document.documentElement.getAttribute("data-theme");return"dark"===e||"light"!==e&&window.matchMedia("(prefers-color-scheme: dark)").matches}()?Object.keys(iy).forEach(e=>{this.mountPoint.style.removeProperty(e)}):Object.entries(iy).forEach(([e,t])=>{this.mountPoint.style.setProperty(e,t)})),!this.root&&this.mountPoint&&(this.root=e(this.mountPoint));const t={apiKey:this.config.apiKey,apiBaseUrl:this.config.apiBaseUrl||ry,agentId:this.config.agentId,theme:{botName:"Asistente Virtual",position:"bottom-right",welcomeMessage:"¡Hola! 👋 ¿En qué puedo ayudarte?",inputPlaceholder:"Escribe tu mensaje...",cssVariables:{primary:"160 84% 39%",windowBorderRadius:"24px",launcherBorderRadius:"50%"},...this.config.theme},userContext:this.config.userContext,pageContext:this.config.pageContext,includeSEOMetadata:this.config.includeSEOMetadata??!1,mediaConfig:this.config.mediaConfig,onNavigate:this.config.onNavigate,onLogin:this.config.onLogin,onEvent:this.config.onEvent,onStateChange:this.config.onStateChange},r=n.createElement(h,{fallback:n.createElement("div",{style:{position:"fixed",bottom:"24px",right:"24px",width:"60px",height:"60px",borderRadius:"50%",backgroundColor:"#10b981",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",cursor:"wait"}},n.createElement("div",{style:{width:"24px",height:"24px",border:"3px solid rgba(255, 255, 255, 0.3)",borderTopColor:"#fff",borderRadius:"50%",animation:"spin 1s linear infinite"}}))},n.createElement(ay,t));this.root.render(n.createElement(oy,null,n.createElement(D,{defaultLocale:this.config.theme?.defaultLocale,children:r}))),console.log("[BotUyoChat] Widget initialized",t)}update(e){this.config?(this.config={...this.config,...e,theme:{...this.config.theme,...e.theme}},this.render()):console.error("[BotUyoChat] Widget not initialized")}destroy(){this.darkModeObserver&&(this.darkModeObserver.disconnect(),this.darkModeObserver=null),this.darkModeMediaQuery&&(this.darkModeMediaQuery.removeEventListener("change",this.handleDarkModeChange),this.darkModeMediaQuery=null),this.root&&(this.root.unmount(),this.root=null),this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null,this.shadowRoot=null,this.mountPoint=null),this.config=null,console.log("[BotUyoChat] Widget destroyed")}setupDarkModeDetection(){this.config?.theme?.cssVariables||(this.handleDarkModeChange=()=>this.render(),this.darkModeObserver=new MutationObserver(this.handleDarkModeChange),this.darkModeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),this.darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.darkModeMediaQuery.addEventListener("change",this.handleDarkModeChange))}handleDarkModeChange=()=>{};open(){window.dispatchEvent(new CustomEvent("botuyo-chat:open"))}close(){window.dispatchEvent(new CustomEvent("botuyo-chat:close"))}startCall(){window.dispatchEvent(new CustomEvent("botuyo-chat:start-call"))}sendMessage(e){window.dispatchEvent(new CustomEvent("botuyo-chat:send-message",{detail:{message:e}}))}getState(){return null}}const ly=new sy;window.BotUyoChat=ly;export{ny as A,sy as B,Zb as C,ee as L,Kb as P,fe as X,q as a,Mt as b,Gb as c,$b as d,Hb as e,D as f,Dt as g,Bb as h,ly as i,j,O as l,Qb as s,F as u};
221
+ //# sourceMappingURL=standalone-gEpLWRlV.js.map