@botuyo/chat-widget-standalone 1.0.3 → 1.0.6

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.
Files changed (37) hide show
  1. package/README.md +158 -226
  2. package/dist/{ChatWidget-DQS2YAHX.js → ChatWidget-3m1RqH_c.js} +6 -6
  3. package/dist/{ChatWidget-DQS2YAHX.js.map → ChatWidget-3m1RqH_c.js.map} +1 -1
  4. package/dist/botuyo-chat.css +1 -1
  5. package/dist/botuyo-chat.es.js +1 -1
  6. package/dist/botuyo-chat.es.js.map +1 -1
  7. package/dist/botuyo-chat.umd.css +1 -1
  8. package/dist/botuyo-chat.umd.js +1 -1
  9. package/dist/botuyo-chat.umd.js.map +1 -1
  10. package/dist/chunk-audio-C4Q6VB-1.js +13 -0
  11. package/dist/chunk-audio-C4Q6VB-1.js.map +1 -0
  12. package/dist/chunk-chat-ui-DmqgsaBa.js +104 -0
  13. package/dist/chunk-chat-ui-DmqgsaBa.js.map +1 -0
  14. package/dist/{chunk-gallery-DsrT5sHg.js → chunk-gallery-Ca7lW3V4.js} +2 -2
  15. package/dist/{chunk-gallery-DsrT5sHg.js.map → chunk-gallery-Ca7lW3V4.js.map} +1 -1
  16. package/dist/src/chat-widget/ChatWidget.d.ts.map +1 -1
  17. package/dist/src/chat-widget/components/AudioPlayer.d.ts.map +1 -1
  18. package/dist/src/chat-widget/components/ChatWindow.d.ts +2 -1
  19. package/dist/src/chat-widget/components/ChatWindow.d.ts.map +1 -1
  20. package/dist/src/chat-widget/components/Icons.d.ts +4 -1
  21. package/dist/src/chat-widget/components/Icons.d.ts.map +1 -1
  22. package/dist/src/chat-widget/components/InputArea.d.ts +2 -1
  23. package/dist/src/chat-widget/components/InputArea.d.ts.map +1 -1
  24. package/dist/src/chat-widget/components/InputArea.stories.d.ts +1 -0
  25. package/dist/src/chat-widget/components/InputArea.stories.d.ts.map +1 -1
  26. package/dist/src/chat-widget/components/VoiceCallDemo.d.ts +15 -0
  27. package/dist/src/chat-widget/components/VoiceCallDemo.d.ts.map +1 -0
  28. package/dist/src/chat-widget/types/index.d.ts +2 -0
  29. package/dist/src/chat-widget/types/index.d.ts.map +1 -1
  30. package/dist/standalone.d.ts.map +1 -1
  31. package/dist/stats-umd.html +1 -1
  32. package/dist/stats.html +1 -1
  33. package/package.json +149 -147
  34. package/dist/chunk-audio-DG36n3qS.js +0 -10
  35. package/dist/chunk-audio-DG36n3qS.js.map +0 -1
  36. package/dist/chunk-chat-ui-TnfA4tMe.js +0 -90
  37. package/dist/chunk-chat-ui-TnfA4tMe.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import{r as e,j as t}from"./vendor-react-CtfcjTlq.js";import{u as n,g as r,e as o,f as s,D as i,c as a,X as c,M as u,l as d,m as l,t as p,h as f,i as m,j as h,k as g}from"./chunk-chat-ui-TnfA4tMe.js";import{l as y}from"./vendor-socket-DMqyM-90.js";function v({isOpen:l,onClick:p,unreadCount:f=0,primaryColor:m,logoUrl:h,starterPrompt:g,position:y="bottom-right",emotion:v="default",avatars:b={},styles:_,promptPersistence:w="session",avatarScale:k=1}){const{t:z}=n("extracted"),x=r({primaryColor:m}),E=_?.launcher?.bg,S=o(),{triggerHaptic:O,getGlowClass:I}=s(),$=S.launcherPulse&&!1!==_?.launcher?.pulse,[N,C]=e.useState(!1),[T,A]=e.useState(!1),[j,Z]=e.useState(!1),[M,P]=e.useState(!1),D="bottom-right"===y,F="chat_launcher_prompt_state",R=e.useMemo(()=>b[v]||b.default||h||i,[v,b,h]);e.useEffect(()=>{P(!1)},[R]),e.useEffect(()=>{const e=Object.values(b).filter(e=>!!e);h&&e.push(h),e.forEach(e=>{(new Image).src=e})},[b,h]),e.useEffect(()=>{"forever"===w&&"dismissed"===localStorage.getItem(F)&&Z(!0)},[w]);const L=e.useCallback(()=>{A(!0),setTimeout(()=>C(!1),500),"always"!==w&&(Z(!0),"forever"===w&&localStorage.setItem(F,"dismissed"))},[w]);return e.useEffect(()=>{if("always"!==w&&j||!g||l)return void C(!1);const e=setTimeout(()=>{C(!0),A(!1)},2e3),t=setTimeout(()=>L(),12e3);return()=>{clearTimeout(e),clearTimeout(t)}},[g,l,j,w,L]),/* @__PURE__ */t.jsxs("div",{className:a("flex items-center w-fit transition-all duration-500",D?"flex-row ml-auto":"flex-row-reverse mr-auto"),children:[
1
+ import{r as e,j as t}from"./vendor-react-CtfcjTlq.js";import{u as n,g as r,f as o,h as s,D as i,c as a,X as c,M as u,l as d,m as l,t as p,i as f,j as m,k as h,n as g}from"./chunk-chat-ui-DmqgsaBa.js";import{l as y}from"./vendor-socket-DMqyM-90.js";function v({isOpen:l,onClick:p,unreadCount:f=0,primaryColor:m,logoUrl:h,starterPrompt:g,position:y="bottom-right",emotion:v="default",avatars:b={},styles:_,promptPersistence:w="session",avatarScale:k=1}){const{t:z}=n("extracted"),x=r({primaryColor:m}),E=_?.launcher?.bg,S=o(),{triggerHaptic:O,getGlowClass:I}=s(),$=S.launcherPulse&&!1!==_?.launcher?.pulse,[N,C]=e.useState(!1),[T,A]=e.useState(!1),[j,Z]=e.useState(!1),[M,P]=e.useState(!1),D="bottom-right"===y,F="chat_launcher_prompt_state",R=e.useMemo(()=>b[v]||b.default||h||i,[v,b,h]);e.useEffect(()=>{P(!1)},[R]),e.useEffect(()=>{const e=Object.values(b).filter(e=>!!e);h&&e.push(h),e.forEach(e=>{(new Image).src=e})},[b,h]),e.useEffect(()=>{"forever"===w&&"dismissed"===localStorage.getItem(F)&&Z(!0)},[w]);const L=e.useCallback(()=>{A(!0),setTimeout(()=>C(!1),500),"always"!==w&&(Z(!0),"forever"===w&&localStorage.setItem(F,"dismissed"))},[w]);return e.useEffect(()=>{if("always"!==w&&j||!g||l)return void C(!1);const e=setTimeout(()=>{C(!0),A(!1)},2e3),t=setTimeout(()=>L(),12e3);return()=>{clearTimeout(e),clearTimeout(t)}},[g,l,j,w,L]),/* @__PURE__ */t.jsxs("div",{className:a("flex items-center w-fit transition-all duration-500",D?"flex-row ml-auto":"flex-row-reverse mr-auto"),children:[
2
2
  /* @__PURE__ */t.jsx("div",{className:a("transition-all duration-700 ease-in-out flex items-center",N?a("opacity-100 translate-x-0 w-auto max-w-[350px]",D?"mr-4":"ml-4"):"opacity-0 translate-x-8 w-0 max-w-0 overflow-hidden"),children:/* @__PURE__ */t.jsxs("div",{className:a("relative px-5 py-3.5 shadow-soft-xl border flex items-center gap-3",_?.radius?.card||"rounded-[20px]",T&&"opacity-0 scale-95 transition-all duration-300",!N&&"hidden"),style:{width:"max-content",maxWidth:"280px",backgroundColor:"hsl(var(--background))",color:"hsl(var(--foreground))",borderColor:"hsl(var(--border))"},children:[
3
3
  /* @__PURE__ */t.jsx("span",{className:"text-sm font-semibold leading-tight tracking-tight whitespace-nowrap",children:g}),
4
4
  /* @__PURE__ */t.jsx("button",{onClick:e=>{e.stopPropagation(),L()},className:"text-muted-foreground hover:text-foreground transition-colors p-1 rounded-full hover:bg-muted shrink-0",children:/* @__PURE__ */t.jsx(c,{className:"h-3.5 w-3.5 stroke-[2.5]"})}),
@@ -26,8 +26,8 @@ return hr(no,e)}(t))});function _o(e){/* @__PURE__ */
26
26
  return Jn(bo,e)}const wo=/* @__PURE__ */K("ZodStringFormat",(e,t)=>{jt.init(e,t),vo.init(e,t)}),ko=/* @__PURE__ */K("ZodEmail",(e,t)=>{Pt.init(e,t),wo.init(e,t)}),zo=/* @__PURE__ */K("ZodGUID",(e,t)=>{Zt.init(e,t),wo.init(e,t)}),xo=/* @__PURE__ */K("ZodUUID",(e,t)=>{Mt.init(e,t),wo.init(e,t)}),Eo=/* @__PURE__ */K("ZodURL",(e,t)=>{Dt.init(e,t),wo.init(e,t)}),So=/* @__PURE__ */K("ZodEmoji",(e,t)=>{Ft.init(e,t),wo.init(e,t)}),Oo=/* @__PURE__ */K("ZodNanoID",(e,t)=>{Rt.init(e,t),wo.init(e,t)}),Io=/* @__PURE__ */K("ZodCUID",(e,t)=>{Lt.init(e,t),wo.init(e,t)}),$o=/* @__PURE__ */K("ZodCUID2",(e,t)=>{Ut.init(e,t),wo.init(e,t)}),No=/* @__PURE__ */K("ZodULID",(e,t)=>{Jt.init(e,t),wo.init(e,t)}),Co=/* @__PURE__ */K("ZodXID",(e,t)=>{Bt.init(e,t),wo.init(e,t)}),To=/* @__PURE__ */K("ZodKSUID",(e,t)=>{Wt.init(e,t),wo.init(e,t)}),Ao=/* @__PURE__ */K("ZodIPv4",(e,t)=>{Ht.init(e,t),wo.init(e,t)}),jo=/* @__PURE__ */K("ZodIPv6",(e,t)=>{Yt.init(e,t),wo.init(e,t)}),Zo=/* @__PURE__ */K("ZodCIDRv4",(e,t)=>{Xt.init(e,t),wo.init(e,t)}),Mo=/* @__PURE__ */K("ZodCIDRv6",(e,t)=>{Qt.init(e,t),wo.init(e,t)}),Po=/* @__PURE__ */K("ZodBase64",(e,t)=>{tn.init(e,t),wo.init(e,t)}),Do=/* @__PURE__ */K("ZodBase64URL",(e,t)=>{nn.init(e,t),wo.init(e,t)}),Fo=/* @__PURE__ */K("ZodE164",(e,t)=>{rn.init(e,t),wo.init(e,t)}),Ro=/* @__PURE__ */K("ZodJWT",(e,t)=>{on.init(e,t),wo.init(e,t)}),Lo=/* @__PURE__ */K("ZodNumber",(e,t)=>{sn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:o,maximum:s,format:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u}=e._zod.bag;"string"==typeof i&&i.includes("int")?r.type="integer":r.type="number","number"==typeof u&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u),"number"==typeof o&&(r.minimum=o,"number"==typeof u&&"draft-04"!==t.target&&(u>=o?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof c&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c),"number"==typeof s&&(r.maximum=s,"number"==typeof c&&"draft-04"!==t.target&&(c<=s?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof a&&(r.multipleOf=a)})(e,t,n),e.gt=(t,n)=>e.check(/* @__PURE__ */zr(t,n)),e.gte=(t,n)=>e.check(/* @__PURE__ */xr(t,n)),e.min=(t,n)=>e.check(/* @__PURE__ */xr(t,n)),e.lt=(t,n)=>e.check(/* @__PURE__ */wr(t,n)),e.lte=(t,n)=>e.check(/* @__PURE__ */kr(t,n)),e.max=(t,n)=>e.check(/* @__PURE__ */kr(t,n)),e.int=t=>e.check(Bo(t)),e.safe=t=>e.check(Bo(t)),e.positive=t=>e.check(/* @__PURE__ */zr(0,t)),e.nonnegative=t=>e.check(/* @__PURE__ */xr(0,t)),e.negative=t=>e.check(/* @__PURE__ */wr(0,t)),e.nonpositive=t=>e.check(/* @__PURE__ */kr(0,t)),e.multipleOf=(t,n)=>e.check(/* @__PURE__ */Er(t,n)),e.step=(t,n)=>e.check(/* @__PURE__ */Er(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Uo(e){/* @__PURE__ */
27
27
  return gr(Lo,e)}const Jo=/* @__PURE__ */K("ZodNumberFormat",(e,t)=>{an.init(e,t),Lo.init(e,t)});function Bo(e){/* @__PURE__ */
28
28
  return yr(Jo,e)}const Wo=/* @__PURE__ */K("ZodAny",(e,t)=>{cn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}}),Vo=/* @__PURE__ */K("ZodUnknown",(e,t)=>{un.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function qo(){/* @__PURE__ */
29
- return br(Vo)}const Go=/* @__PURE__ */K("ZodNever",(e,t)=>{dn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),Ko=/* @__PURE__ */K("ZodArray",(e,t)=>{pn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;"number"==typeof i&&(o.minItems=i),"number"==typeof a&&(o.maxItems=a),o.type="array",o.items=Vr(s.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */Or(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */Or(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */Sr(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */Ir(t,n)),e.unwrap=()=>e.element}),Ho=/* @__PURE__ */K("ZodObject",(e,t)=>{yn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,s=e._zod.def;o.type="object",o.properties={};const i=s.shape;for(const u in i)o.properties[u]=Vr(i[u],t,{...r,path:[...r.path,"properties",u]});const a=new Set(Object.keys(i)),c=new Set([...a].filter(e=>{const n=s.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(o.required=Array.from(c)),"never"===s.catchall?._zod.def.type?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=Vr(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),ie(e,"shape",()=>t.shape),e.keyof=()=>es(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:qo()}),e.loose=()=>e.clone({...e._zod.def,catchall:qo()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */_r(Go,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!fe(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=ce(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return ae(this,"shape",n),n}});return ye(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!fe(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=ce(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return ae(this,"shape",n),n}});return ye(e,n)}(e,t),e.merge=t=>function(e,t){const n=ce(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return ae(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return ye(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 ye(e,ce(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 ae(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=ce(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 ae(this,"shape",r),r},checks:[]});return ye(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=ce(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 ae(this,"shape",o),o},checks:[]});return ye(t,o)}(ns,e,t[0]),e.required=(...t)=>function(e,t,n){const r=ce(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 ae(this,"shape",o),o}});return ye(t,r)}(us,e,t[0])}),Yo=/* @__PURE__ */K("ZodUnion",(e,t)=>{bn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,s=!1===o.inclusive,i=o.options.map((e,n)=>Vr(e,t,{...r,path:[...r.path,s?"oneOf":"anyOf",n]}));s?n.oneOf=i:n.anyOf=i})(e,t,n,r),e.options=t.options}),Xo=/* @__PURE__ */K("ZodIntersection",(e,t)=>{_n.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,s=Vr(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=Vr(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c})(e,t,n,r)}),Qo=/* @__PURE__ */K("ZodEnum",(e,t)=>{zn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=ee(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 s of e){if(!n.has(s))throw new Error(`Key ${s} not found in enum`);o[s]=t.entries[s]}return new Qo({...t,checks:[],...ve(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 Qo({...t,checks:[],...ve(r),entries:o})}});function es(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Qo({type:"enum",entries:n,...ve(t)})}const ts=/* @__PURE__ */K("ZodTransform",(e,t)=>{xn.init(e,t),yo.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 Y(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Ee(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(Ee(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),ns=/* @__PURE__ */K("ZodOptional",(e,t)=>{Sn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xr(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function rs(e){return new ns({type:"optional",innerType:e})}const os=/* @__PURE__ */K("ZodExactOptional",(e,t)=>{On.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xr(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),ss=/* @__PURE__ */K("ZodNullable",(e,t)=>{In.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,s=Vr(o.innerType,t,r),i=t.seen.get(e);"openapi-3.0"===t.target?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function is(e){return new ss({type:"nullable",innerType:e})}const as=/* @__PURE__ */K("ZodDefault",(e,t)=>{$n.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Vr(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}),cs=/* @__PURE__ */K("ZodPrefault",(e,t)=>{Cn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Vr(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}),us=/* @__PURE__ */K("ZodNonOptional",(e,t)=>{Tn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Vr(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),ds=/* @__PURE__ */K("ZodCatch",(e,t)=>{jn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let s;Vr(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),ls=/* @__PURE__ */K("ZodPipe",(e,t)=>{Zn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,s="input"===t.io?"transform"===o.in._zod.def.type?o.out:o.in:o.out;Vr(s,t,r),t.seen.get(e).ref=s})(e,t,0,r),e.in=t.in,e.out=t.out});function ps(e,t){return new ls({type:"pipe",in:e,out:t})}const fs=/* @__PURE__ */K("ZodReadonly",(e,t)=>{Pn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Vr(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),ms=/* @__PURE__ */K("ZodCustom",(e,t)=>{Fn.init(e,t),yo.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)}),hs="chat_device_id";function gs(){return"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 ys=function(){const e={type:"object",shape:{id:_o().optional(),type:es(["text","image","audio","location","system"]).default("text"),content:_o().optional(),imageUrl:_o().url().optional(),audioUrl:_o().url().optional(),latitude:Uo().optional(),longitude:Uo().optional(),timestamp:_o().optional(),sender:es(["bot","user","system"]).optional(),emotion:/* @__PURE__ */vr(Wo).optional()}??{},...ve(void 0)};return new Ho(e)}();class vs{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),d.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?d.debug(`Analytics: Flushed ${e.length} events`):(this.isDisabled=!0,this.queue=[],d.debug(`Analytics disabled: endpoint returned ${t.status}`))}catch(t){this.isDisabled=!0,this.queue=[],d.debug("Analytics disabled due to network error")}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}function bs(t){const{apiKey:r,apiBaseUrl:o,pageContext:s,includeSEOMetadata:a=!1,theme:c,userContext:u,onLogin:l,onNavigate:m,onEvent:h,onStateChange:g,onThemeUpdate:v}=t,[b,_]=e.useState(0),w=e.useRef(0),{t:k}=n(),z=function(t,n,r=!0){const o=e.useRef(null);return e.useEffect(()=>{if(!r||!t||!n)return;const e=`${t}/analytics`;o.current=new vs(e,n);const s=()=>o.current?.flush(),i=()=>{"hidden"===document.visibilityState&&o.current?.flush()};return window.addEventListener("beforeunload",s),window.addEventListener("visibilitychange",i),()=>{window.removeEventListener("beforeunload",s),window.removeEventListener("visibilitychange",i),o.current?.destroy()}},[t,n,r]),{trackOpen:e.useCallback(()=>{o.current?.trackOpen()},[]),trackClose:e.useCallback(()=>{o.current?.trackClose()},[]),trackMessageSent:e.useCallback(e=>{o.current?.trackMessageSent(e)},[]),trackMessageReceived:e.useCallback((e,t)=>{o.current?.trackMessageReceived(e,t)},[]),trackError:e.useCallback((e,t)=>{o.current?.trackError(e,t)},[]),trackConnectionStatus:e.useCallback(e=>{o.current?.trackConnectionStatus(e)},[]),trackFeatureUsed:e.useCallback(e=>{o.current?.trackFeatureUsed(e)},[])}}(o,r,!0),x=function({enabled:t=!0,soundEnabled:n=!0,desktopEnabled:r=!0,botName:o="Asistente",logoUrl:s,notificationSoundUrl:a}={}){const[c,u]=e.useState("default"),l=e.useRef(null),p=s||i,m=a||f;e.useEffect(()=>{n&&"undefined"!=typeof window&&(l.current=new Audio(m),l.current.volume=.3)},[n,m]),e.useEffect(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const h=e.useCallback(async()=>{if("undefined"==typeof window||!("Notification"in window))return d.warn("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),d.info("Notification permission:",e),"granted"===e}catch(e){return d.error("Error requesting notification permission:",e),!1}},[]),g=e.useCallback(e=>{if(t&&r&&"granted"===c&&("undefined"==typeof document||!document.hasFocus()))try{const t=`Nuevo mensaje de ${o}`;let n="Mensaje recibido";"text"===e.type&&"content"in e?n=e.content?.slice(0,100)||"Mensaje recibido":"image"===e.type?n="📷 Imagen":"audio"===e.type?n="🎵 Audio":"location"===e.type&&(n="📍 Ubicación");const r=new Notification(t,{body:n,icon:p,tag:"chat-message",requireInteraction:!1,silent:!1});r.onclick=()=>{window.focus(),r.close()},setTimeout(()=>r.close(),5e3)}catch(n){d.error("Error showing notification:",n)}},[t,r,c,o,p]),y=e.useCallback(()=>{if(t&&n&&("undefined"==typeof document||!document.hasFocus()))try{l.current?.play().catch(e=>{d.debug("Audio playback blocked:",e)})}catch(e){d.error("Error playing sound:",e)}},[t,n]),v=e.useCallback(e=>{g(e),y()},[g,y]);return{permission:c,requestPermission:h,notify:g,playSound:y,notifyWithSound:v}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:c?.botName||"Asistente",logoUrl:c?.logoUrl}),E=function(t=10,n=6e4){const r=e.useRef([]);return{isAllowed:e.useCallback(()=>{const e=Date.now();return r.current=r.current.filter(t=>e-t<n),!(r.current.length>=t||(r.current.push(e),0))},[t,n]),getRemainingAttempts:e.useCallback(()=>{const e=Date.now();return r.current=r.current.filter(t=>e-t<n),Math.max(0,t-r.current.length)},[t,n]),getTimeUntilReset:e.useCallback(()=>{if(0===r.current.length)return 0;const e=Date.now(),t=r.current[0],o=n-(e-t);return Math.max(0,o)},[n]),reset:e.useCallback(()=>{r.current=[]},[])}}(10,6e4),{state:S,actions:O}=function(){const[t,n]=e.useReducer(G,q),[r,o]=e.useState(!1);e.useEffect(()=>{"undefined"==typeof window||r||(async()=>{try{await W.migrateFromLocalStorage();const e=await W.getMessages(100),t=await W.getMetadata();if(e.length>0||t){const r={messages:e.map(e=>({...e,timestamp:new Date(e.timestamp)})),sessionId:t?.sessionId||null,isOpen:t?.isOpen||!1};n({type:"RESTORE_SESSION",payload:r})}}catch(e){d.warn("Chat: Error rehydrating from IndexedDB",e);try{const e=localStorage.getItem(V);if(e){const t=JSON.parse(e);t.messages&&(t.messages=t.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}))),n({type:"RESTORE_SESSION",payload:t})}}catch(t){d.error("Chat: Fallback rehydration failed",t)}}finally{o(!0)}})()},[r]),e.useEffect(()=>{if(!r)return;const e=setTimeout(async()=>{try{await W.saveMessages(t.messages),await W.setMetadata({isOpen:t.isOpen,sessionId:t.sessionId})}catch(e){d.error("Chat Persistence Error:",e);try{const e={isOpen:t.isOpen,messages:t.messages,sessionId:t.sessionId};localStorage.setItem(V,JSON.stringify(e))}catch(n){d.error("Chat: Fallback persistence failed",n)}}},500);return()=>clearTimeout(e)},[t.isOpen,t.messages,t.sessionId,r]);const s=e.useCallback(e=>{n({type:"ADD_MESSAGE",payload:e})},[]),i=e.useCallback(()=>n({type:"TOGGLE_WINDOW"}),[]),a=e.useCallback(()=>n({type:"OPEN_WINDOW"}),[]),c=e.useCallback(()=>n({type:"CLOSE_WINDOW"}),[]),u=e.useCallback(e=>n({type:"SET_CONNECTED",payload:e}),[]),l=e.useCallback(e=>n({type:"SET_TYPING",payload:e}),[]),p=e.useCallback(e=>n({type:"SET_MESSAGES",payload:e}),[]),f=e.useCallback(e=>n({type:"SET_ERROR",payload:e}),[]),m=e.useCallback(e=>n({type:"SET_SESSION_ID",payload:e}),[]),h=e.useCallback(()=>{localStorage.removeItem(V),n({type:"CLEAR_CHAT"})},[]),g=e.useCallback(()=>{n({type:"SET_MESSAGES",payload:[]})},[]);return{state:t,isHydrated:r,actions:{toggleWindow:i,openWindow:a,closeWindow:c,setConnected:u,setTyping:l,addMessage:s,setMessages:p,setError:f,setSessionId:m,clearChat:h,clearMessages:g}}}(),I=function(t=!1){const n="undefined"!=typeof window?window.location.pathname:"",r=e.useMemo(()=>n,[n]),[o,s]=e.useState({});return e.useEffect(()=>{if(!t)return void s({});const e=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}();s(e)},100);return()=>clearTimeout(e)},[r,t]),t&&Object.keys(o).length>0?o:void 0}(a),$=function(t){const{apiKey:n,apiBaseUrl:r,pageContext:o,userContext:s}=t,i=e.useRef(t);e.useEffect(()=>{i.current=t},[t]);const a=e.useRef(null),[c,u]=e.useState(!1),[l,f]=e.useState(!1),m=e.useRef(function(){try{const e=localStorage.getItem(hs);if(e)return e;const t=gs();return localStorage.setItem(hs,t),t}catch{return d.warn("localStorage not available, using session-only device ID"),gs()}}()),h=e.useRef(o);e.useEffect(()=>{h.current=o},[o]);const g=e.useCallback(e=>{const t=ys.safeParse(e),n=t.success&&t.data.id?t.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,r=t.success&&t.data.sender?t.data.sender:"bot",o=t.success&&t.data.timestamp?new Date(t.data.timestamp):/* @__PURE__ */new Date,s=t.success?t.data:{type:"text"};switch(s.type){case"image":return{id:n,type:"image",sender:r,timestamp:o,imageUrl:s.imageUrl||s.content||"",altText:"Imagen enviada"};case"audio":return{id:n,type:"audio",sender:r,timestamp:o,content:s.audioUrl||s.content||""};case"location":return{id:n,type:"location",sender:r,timestamp:o,latitude:Number(s.latitude||0),longitude:Number(s.longitude||0),name:s.content||"Ubicación compartida"};case"system":return{id:n,type:"system",sender:"system",timestamp:o,content:String(s.content||"")};default:return{id:n,type:"text",sender:r,timestamp:o,content:String(s.content||"Sin contenido"),emotion:s.emotion}}},[]),v=e.useCallback(()=>{if(!n||!r)return;if(a.current?.connected)return;u(!0);const e=y(r,{path:"/webchat",auth:{apiKey:n,deviceId:m.current,token:s?.token,metadata:s?.metadata},transports:["websocket"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});e.on("connect",()=>{u(!1),f(!0),i.current.onConnected(`temp-${Date.now()}`,void 0)}),e.on("disconnect",e=>{u(!1),f(!1),i.current.onDisconnected()}),e.on("connect_error",e=>{u(!1),i.current.onError(`Error de conexión: ${e.message}`)}),e.on("connection_ack",e=>{i.current.onConnected(e.sessionId,e.config)}),e.on("bot_message",e=>{try{i.current.onMessage(g(e))}catch(t){d.error("ChatSocket Error processing bot_message:",t)}}),e.on("chat_history",e=>{e.messages&&Array.isArray(e.messages)&&e.messages.forEach(e=>{try{i.current.onMessage(g(e))}catch(t){d.debug("Error processing history message:",t)}}),i.current.onEvent&&i.current.onEvent("history_loaded",e)}),e.on("bot_typing",e=>i.current.onTyping(e)),e.on("auth_success",e=>{i.current.onLogin&&i.current.onLogin(e),e.theme&&i.current.onThemeUpdate&&i.current.onThemeUpdate(e.theme)}),a.current=e},[n,r]),b=e.useCallback(()=>{a.current&&(a.current.disconnect(),a.current=null,f(!1))},[]),_=e.useRef(v);_.current=v,e.useEffect(()=>(_.current(),()=>{a.current&&(a.current.disconnect(),a.current=null)}),[]);const w=e.useRef([]),k=e.useRef([]),z=e.useCallback(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),x=e.useCallback(()=>{if(a.current?.connected)for(;w.current.length>0;){const e=w.current.shift();a.current.emit("user_message",e)}},[]);e.useEffect(()=>{l&&x()},[l,x]),e.useEffect(()=>{if(!l)return;const e=setInterval(()=>{const e=Date.now();k.current=k.current.filter(t=>e<t.nextRetryAt||(t.attempts>=t.maxAttempts?(i.current.onEvent?.("message_failed",{id:t.id,payload:t.payload}),d.error("Message failed after max retries:",t.id),!1):!a.current?.connected||(a.current.emit("user_message",t.payload,e=>{e?.success&&i.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)},[l]);const E=e.useCallback((e,t="text")=>{const n=z(),r={...h.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:m.current},o={id:n,content:e.trim(),type:t,metadata:r};return a.current?.connected?(a.current.emit("user_message",o,e=>{!1!==e?.success&&e?i.current.onEvent?.("message_sent",{id:n}):(k.current.push({id:n,payload:o,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),i.current.onEvent?.("message_retry_queued",{id:n}))}),n):(w.current.push(o),i.current.onEvent?.("queued_message",{id:n,payload:o}),n)},[z]),S=e.useMemo(()=>p(e=>{a.current?.emit("typing",e)},250),[]);return{isConnected:l,isConnecting:c,sendMessage:E,sendTyping:S,requestHistory:e.useCallback(()=>{a.current?.emit("request_history")},[]),reconnect:v,disconnect:b}}({apiKey:r,apiBaseUrl:o,pageContext:e.useMemo(()=>I?{...s||{},seo:{...I||{}}}:s,[s,I]),userContext:u,onMessage:e.useCallback(e=>{const t=Date.now(),n=w.current>0?t-w.current:void 0;w.current=t,O.addMessage(e),z.trackMessageReceived(e.type,n),S.isOpen||"bot"!==e.sender||(_(e=>e+1),x.notifyWithSound(e))},[O,S.isOpen,z,x]),onConnected:e.useCallback((e,t)=>{O.setConnected(!0),O.setSessionId(e),z.trackConnectionStatus(!0),t&&h&&h("backend_config",t)},[O,h,z]),onDisconnected:e.useCallback(()=>{O.setConnected(!1),z.trackConnectionStatus(!1)},[O,z]),onTyping:e.useCallback(e=>O.setTyping(e),[O]),onError:e.useCallback(e=>{O.setError(e),z.trackError(e)},[O,z]),onLogin:l,onNavigate:m,onEvent:h,onThemeUpdate:v}),N=e.useCallback(()=>{d.debug("ChatWidget handleToggle called, current isOpen:",S.isOpen),S.isOpen?(O.closeWindow(),z.trackClose(),g?.(!1),d.debug("ChatWidget Closing window")):(O.openWindow(),_(0),z.trackOpen(),g?.(!0),d.debug("ChatWidget Opening window"))},[S.isOpen,O,g,z]),C=e.useCallback(e=>{if(!E.isAllowed()){const e=E.getTimeUntilReset(),t=Math.ceil(e/1e3);return void O.setError(k("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};O.addMessage(t),z.trackMessageSent("text"),$.sendMessage(e,"text")},[O,$,E,z,k]),T=e.useCallback(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}`},O.addMessage(n);const r=await(e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)}))(e);$.sendMessage(r,t)},[O,$]),A=e.useCallback(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"};O.addMessage(t),$.sendMessage(JSON.stringify(e),"location")},[O,$]);e.useEffect(()=>{const e=()=>{S.isOpen||O.openWindow()},t=()=>{S.isOpen&&O.closeWindow()},n=()=>{S.isOpen?O.closeWindow():O.openWindow()},r=e=>{e.detail?.message&&C(e.detail.message)};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),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:send-message",r)}},[S.isOpen,O,C]),e.useEffect(()=>()=>{},[C]);const j=e.useCallback(()=>{O.clearMessages(),d.info("Chat history cleared")},[O]);e.useEffect(()=>()=>{},[j]);const Z=e.useMemo(()=>{if(S.isTyping)return"thinking";const e=[...S.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[S.isTyping,S.messages]);return{state:S,actions:O,unreadCount:b,currentBotEmotion:Z,isConnected:$.isConnected,handleToggle:N,handleSendText:C,handleSendAttachment:T,handleSendLocation:A}}function _s(n){const{apiKey:r,apiBaseUrl:o,pageContext:s,includeSEOMetadata:i=!1,theme:c,mediaConfig:u,userContext:d,onLogin:p,onNavigate:f,onEvent:y,onStateChange:z}=n,x=e.useRef(null),E=m();!function(t){const[n,r]=e.useState(!1);e.useEffect(()=>{let e=null;const n=()=>{if(!t.current)return;const e=!!t.current.parentElement?.closest(".dark"),n=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),o=document.getElementById("botuyo-chat-widget-root"),s=!!o?.parentElement?.closest(".dark"),i=document.documentElement.classList.contains("dark"),a=document.body.classList.contains("dark"),c=window.matchMedia("(prefers-color-scheme: dark)").matches,u=e||n||s||i||a||c;t.current&&(u?t.current.classList.add("dark"):t.current.classList.remove("dark")),r(u)};n();const o=window.matchMedia("(prefers-color-scheme: dark)"),s=()=>n();o.addEventListener("change",s);const i=new MutationObserver(()=>{n()}),a=document.getElementById("botuyo-chat-widget-root");a&&(i.observe(a,{attributes:!0,attributeFilter:["class"]}),a.parentElement&&(i.observe(a.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=a.parentElement)),i.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),i.observe(document.body,{attributes:!0,attributeFilter:["class"]});let c=t.current?.parentElement;for(;c;)i.observe(c,{attributes:!0,attributeFilter:["class"]}),c=c.parentElement;const u=setInterval(()=>{const t=document.getElementById("botuyo-chat-widget-root");t&&t.parentElement!==e&&(e&&t.parentElement&&(i.observe(t.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=t.parentElement),n())},100);return()=>{i.disconnect(),o.removeEventListener("change",s),clearInterval(u)}},[t])}(x);const[S,O]=e.useState(),{mergedTheme:I,mergedStyles:$,getContainerStyle:N}=function(t,n){const r=function(){const[t,n]=e.useState(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return e.useEffect(()=>{const e=window.matchMedia("(prefers-contrast: high)"),t=window.matchMedia("(prefers-contrast: more)"),r=e=>{n(e.matches)};return e.addEventListener("change",r),t.addEventListener("change",r),()=>{e.removeEventListener("change",r),t.removeEventListener("change",r)}},[]),t}(),o=e.useMemo(()=>{const e=l(t,n);return r?{...e,primaryColor:"#000000",cssVariables:{...e.cssVariables,background:"#FFFFFF",foreground:"#000000",card:"#FFFFFF",cardForeground:"#000000",primary:"#000000",primaryForeground:"#FFFFFF",muted:"#F5F5F5",mutedForeground:"#000000",border:"#000000"}}:e},[t,n,r]),s=e.useMemo(()=>({radius:{..._,...t?.bubbleStyles?.radius},bot:{...w,...t?.bubbleStyles?.bot},user:{...k,...t?.bubbleStyles?.user},launcher:{...t?.bubbleStyles?.launcher},mapCard:{...t?.bubbleStyles?.mapCard}}),[t?.bubbleStyles]);return{mergedTheme:o,mergedStyles:s,getContainerStyle:(e,t,n)=>({"--chat-primary":o.primaryColor,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:"100px",width:t&&e?"100%":"auto",height:t&&e?"100%":"auto"})}}(c,S),{state:C,actions:T,unreadCount:A,currentBotEmotion:j,isConnected:Z,handleToggle:M,handleSendText:P,handleSendAttachment:D,handleSendLocation:F}=bs({apiKey:r,apiBaseUrl:o,pageContext:s,includeSEOMetadata:i,theme:c,userContext:d,onLogin:p,onNavigate:f,onEvent:y,onStateChange:z,onThemeUpdate:O}),R=e.useCallback(e=>{e.stopPropagation()},[]),L=N(C.isOpen,E,c?.position),U=e.useMemo(()=>{if(!I.cssVariables)return{};const e={},t=I.cssVariables;return t.background&&(e["--background"]=t.background),t.foreground&&(e["--foreground"]=t.foreground),t.card&&(e["--card"]=t.card),t.cardForeground&&(e["--card-foreground"]=t.cardForeground),t.primary&&(e["--primary"]=t.primary),t.primaryForeground&&(e["--primary-foreground"]=t.primaryForeground),t.muted&&(e["--muted"]=t.muted),t.mutedForeground&&(e["--muted-foreground"]=t.mutedForeground),t.border&&(e["--border"]=t.border),t.destructive&&(e["--destructive"]=t.destructive),t.radius&&(e["--radius"]=t.radius),t.spacing1&&(e["--spacing-1"]=t.spacing1),t.spacing2&&(e["--spacing-2"]=t.spacing2),t.spacing3&&(e["--spacing-3"]=t.spacing3),t.spacing4&&(e["--spacing-4"]=t.spacing4),t.spacing5&&(e["--spacing-5"]=t.spacing5),t.spacing6&&(e["--spacing-6"]=t.spacing6),t.spacing8&&(e["--spacing-8"]=t.spacing8),e},[I.cssVariables]);/* @__PURE__ */
30
- return t.jsx(h,{animations:c?.animations,effects:c?.effects,children:/* @__PURE__ */t.jsxs("div",{ref:x,id:"botuyo-chat-widget",className:a("botuyo-chat-widget flex flex-col",!E&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...L,...U,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:[
31
- /* @__PURE__ */t.jsx("div",{className:a("transition-all duration-500 ease-in-out origin-bottom",C.isOpen?"opacity-100 scale-100 h-full w-full translate-y-0 pointer-events-auto":"opacity-0 scale-95 pointer-events-none translate-y-full h-0 w-0"),style:{pointerEvents:C.isOpen?"auto":"none"},onMouseDown:R,onTouchStart:R,children:/* @__PURE__ */t.jsx(b,{children:/* @__PURE__ */t.jsx(g,{isOpen:C.isOpen,isConnected:Z,isTyping:C.isTyping,messages:C.messages,onClose:()=>T.closeWindow(),onSendMessage:P,onSendAttachment:D,onSendLocation:F,botName:c?.botName,logoUrl:c?.logoUrl,welcomeMessage:c?.welcomeMessage,inputPlaceholder:c?.inputPlaceholder,primaryColor:c?.primaryColor,position:c?.position,bubbleStyles:$,avatars:c?.avatars,mediaConfig:u,theme:I})})}),
32
- /* @__PURE__ */t.jsx("div",{className:a(C.isOpen?"hidden":"block",!E&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:R,onTouchStart:R,children:/* @__PURE__ */t.jsx(v,{isOpen:C.isOpen,onClick:M,unreadCount:A,position:c?.position||"bottom-right",primaryColor:c?.primaryColor,logoUrl:c?.logoUrl,starterPrompt:c?.starterPrompt,avatars:c?.avatars,emotion:j,styles:$,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale})})]})})}e.createContext(null);export{_s as ChatWidget};
33
- //# sourceMappingURL=ChatWidget-DQS2YAHX.js.map
29
+ return br(Vo)}const Go=/* @__PURE__ */K("ZodNever",(e,t)=>{dn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)}),Ko=/* @__PURE__ */K("ZodArray",(e,t)=>{pn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;"number"==typeof i&&(o.minItems=i),"number"==typeof a&&(o.maxItems=a),o.type="array",o.items=Vr(s.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(/* @__PURE__ */Or(t,n)),e.nonempty=t=>e.check(/* @__PURE__ */Or(1,t)),e.max=(t,n)=>e.check(/* @__PURE__ */Sr(t,n)),e.length=(t,n)=>e.check(/* @__PURE__ */Ir(t,n)),e.unwrap=()=>e.element}),Ho=/* @__PURE__ */K("ZodObject",(e,t)=>{yn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,s=e._zod.def;o.type="object",o.properties={};const i=s.shape;for(const u in i)o.properties[u]=Vr(i[u],t,{...r,path:[...r.path,"properties",u]});const a=new Set(Object.keys(i)),c=new Set([...a].filter(e=>{const n=s.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(o.required=Array.from(c)),"never"===s.catchall?._zod.def.type?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=Vr(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),ie(e,"shape",()=>t.shape),e.keyof=()=>es(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:qo()}),e.loose=()=>e.clone({...e._zod.def,catchall:qo()}),e.strict=()=>e.clone({...e._zod.def,catchall:/* @__PURE__ */_r(Go,void 0)}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!fe(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=ce(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return ae(this,"shape",n),n}});return ye(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!fe(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=ce(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return ae(this,"shape",n),n}});return ye(e,n)}(e,t),e.merge=t=>function(e,t){const n=ce(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return ae(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return ye(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 ye(e,ce(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 ae(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=ce(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 ae(this,"shape",r),r},checks:[]});return ye(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=ce(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 ae(this,"shape",o),o},checks:[]});return ye(t,o)}(ns,e,t[0]),e.required=(...t)=>function(e,t,n){const r=ce(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 ae(this,"shape",o),o}});return ye(t,r)}(us,e,t[0])}),Yo=/* @__PURE__ */K("ZodUnion",(e,t)=>{bn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,s=!1===o.inclusive,i=o.options.map((e,n)=>Vr(e,t,{...r,path:[...r.path,s?"oneOf":"anyOf",n]}));s?n.oneOf=i:n.anyOf=i})(e,t,n,r),e.options=t.options}),Xo=/* @__PURE__ */K("ZodIntersection",(e,t)=>{_n.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,s=Vr(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=Vr(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c})(e,t,n,r)}),Qo=/* @__PURE__ */K("ZodEnum",(e,t)=>{zn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=ee(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 s of e){if(!n.has(s))throw new Error(`Key ${s} not found in enum`);o[s]=t.entries[s]}return new Qo({...t,checks:[],...ve(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 Qo({...t,checks:[],...ve(r),entries:o})}});function es(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Qo({type:"enum",entries:n,...ve(t)})}const ts=/* @__PURE__ */K("ZodTransform",(e,t)=>{xn.init(e,t),yo.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 Y(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Ee(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(Ee(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n)):(n.value=o,n)}}),ns=/* @__PURE__ */K("ZodOptional",(e,t)=>{Sn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xr(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function rs(e){return new ns({type:"optional",innerType:e})}const os=/* @__PURE__ */K("ZodExactOptional",(e,t)=>{On.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xr(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),ss=/* @__PURE__ */K("ZodNullable",(e,t)=>{In.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,s=Vr(o.innerType,t,r),i=t.seen.get(e);"openapi-3.0"===t.target?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function is(e){return new ss({type:"nullable",innerType:e})}const as=/* @__PURE__ */K("ZodDefault",(e,t)=>{$n.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Vr(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}),cs=/* @__PURE__ */K("ZodPrefault",(e,t)=>{Cn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Vr(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}),us=/* @__PURE__ */K("ZodNonOptional",(e,t)=>{Tn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Vr(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType}),ds=/* @__PURE__ */K("ZodCatch",(e,t)=>{jn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let s;Vr(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),ls=/* @__PURE__ */K("ZodPipe",(e,t)=>{Zn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,s="input"===t.io?"transform"===o.in._zod.def.type?o.out:o.in:o.out;Vr(s,t,r),t.seen.get(e).ref=s})(e,t,0,r),e.in=t.in,e.out=t.out});function ps(e,t){return new ls({type:"pipe",in:e,out:t})}const fs=/* @__PURE__ */K("ZodReadonly",(e,t)=>{Pn.init(e,t),yo.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Vr(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType}),ms=/* @__PURE__ */K("ZodCustom",(e,t)=>{Fn.init(e,t),yo.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)}),hs="chat_device_id";function gs(){return"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 ys=function(){const e={type:"object",shape:{id:_o().optional(),type:es(["text","image","audio","location","system"]).default("text"),content:_o().optional(),imageUrl:_o().url().optional(),audioUrl:_o().url().optional(),latitude:Uo().optional(),longitude:Uo().optional(),timestamp:_o().optional(),sender:es(["bot","user","system"]).optional(),emotion:/* @__PURE__ */vr(Wo).optional()}??{},...ve(void 0)};return new Ho(e)}();class vs{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),d.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?d.debug(`Analytics: Flushed ${e.length} events`):(this.isDisabled=!0,this.queue=[],d.debug(`Analytics disabled: endpoint returned ${t.status}`))}catch(t){this.isDisabled=!0,this.queue=[],d.debug("Analytics disabled due to network error")}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}function bs(t){const{apiKey:r,apiBaseUrl:o,pageContext:s,includeSEOMetadata:a=!1,theme:c,userContext:u,onLogin:l,onNavigate:m,onEvent:h,onStateChange:g,onThemeUpdate:v}=t,[b,_]=e.useState(0),w=e.useRef(0),{t:k}=n(),z=function(t,n,r=!0){const o=e.useRef(null);return e.useEffect(()=>{if(!r||!t||!n)return;const e=`${t}/analytics`;o.current=new vs(e,n);const s=()=>o.current?.flush(),i=()=>{"hidden"===document.visibilityState&&o.current?.flush()};return window.addEventListener("beforeunload",s),window.addEventListener("visibilitychange",i),()=>{window.removeEventListener("beforeunload",s),window.removeEventListener("visibilitychange",i),o.current?.destroy()}},[t,n,r]),{trackOpen:e.useCallback(()=>{o.current?.trackOpen()},[]),trackClose:e.useCallback(()=>{o.current?.trackClose()},[]),trackMessageSent:e.useCallback(e=>{o.current?.trackMessageSent(e)},[]),trackMessageReceived:e.useCallback((e,t)=>{o.current?.trackMessageReceived(e,t)},[]),trackError:e.useCallback((e,t)=>{o.current?.trackError(e,t)},[]),trackConnectionStatus:e.useCallback(e=>{o.current?.trackConnectionStatus(e)},[]),trackFeatureUsed:e.useCallback(e=>{o.current?.trackFeatureUsed(e)},[])}}(o,r,!0),x=function({enabled:t=!0,soundEnabled:n=!0,desktopEnabled:r=!0,botName:o="Asistente",logoUrl:s,notificationSoundUrl:a}={}){const[c,u]=e.useState("default"),l=e.useRef(null),p=s||i,m=a||f;e.useEffect(()=>{n&&"undefined"!=typeof window&&(l.current=new Audio(m),l.current.volume=.3)},[n,m]),e.useEffect(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const h=e.useCallback(async()=>{if("undefined"==typeof window||!("Notification"in window))return d.warn("Notifications API not available"),!1;try{const e=await Notification.requestPermission();return u(e),d.info("Notification permission:",e),"granted"===e}catch(e){return d.error("Error requesting notification permission:",e),!1}},[]),g=e.useCallback(e=>{if(t&&r&&"granted"===c&&("undefined"==typeof document||!document.hasFocus()))try{const t=`Nuevo mensaje de ${o}`;let n="Mensaje recibido";"text"===e.type&&"content"in e?n=e.content?.slice(0,100)||"Mensaje recibido":"image"===e.type?n="📷 Imagen":"audio"===e.type?n="🎵 Audio":"location"===e.type&&(n="📍 Ubicación");const r=new Notification(t,{body:n,icon:p,tag:"chat-message",requireInteraction:!1,silent:!1});r.onclick=()=>{window.focus(),r.close()},setTimeout(()=>r.close(),5e3)}catch(n){d.error("Error showing notification:",n)}},[t,r,c,o,p]),y=e.useCallback(()=>{if(t&&n&&("undefined"==typeof document||!document.hasFocus()))try{l.current?.play().catch(e=>{d.debug("Audio playback blocked:",e)})}catch(e){d.error("Error playing sound:",e)}},[t,n]),v=e.useCallback(e=>{g(e),y()},[g,y]);return{permission:c,requestPermission:h,notify:g,playSound:y,notifyWithSound:v}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:c?.botName||"Asistente",logoUrl:c?.logoUrl}),E=function(t=10,n=6e4){const r=e.useRef([]);return{isAllowed:e.useCallback(()=>{const e=Date.now();return r.current=r.current.filter(t=>e-t<n),!(r.current.length>=t||(r.current.push(e),0))},[t,n]),getRemainingAttempts:e.useCallback(()=>{const e=Date.now();return r.current=r.current.filter(t=>e-t<n),Math.max(0,t-r.current.length)},[t,n]),getTimeUntilReset:e.useCallback(()=>{if(0===r.current.length)return 0;const e=Date.now(),t=r.current[0],o=n-(e-t);return Math.max(0,o)},[n]),reset:e.useCallback(()=>{r.current=[]},[])}}(10,6e4),{state:S,actions:O}=function(){const[t,n]=e.useReducer(G,q),[r,o]=e.useState(!1);e.useEffect(()=>{"undefined"==typeof window||r||(async()=>{try{await W.migrateFromLocalStorage();const e=await W.getMessages(100),t=await W.getMetadata();if(e.length>0||t){const r={messages:e.map(e=>({...e,timestamp:new Date(e.timestamp)})),sessionId:t?.sessionId||null,isOpen:t?.isOpen||!1};n({type:"RESTORE_SESSION",payload:r})}}catch(e){d.warn("Chat: Error rehydrating from IndexedDB",e);try{const e=localStorage.getItem(V);if(e){const t=JSON.parse(e);t.messages&&(t.messages=t.messages.map(e=>({...e,timestamp:new Date(e.timestamp)}))),n({type:"RESTORE_SESSION",payload:t})}}catch(t){d.error("Chat: Fallback rehydration failed",t)}}finally{o(!0)}})()},[r]),e.useEffect(()=>{if(!r)return;const e=setTimeout(async()=>{try{await W.saveMessages(t.messages),await W.setMetadata({isOpen:t.isOpen,sessionId:t.sessionId})}catch(e){d.error("Chat Persistence Error:",e);try{const e={isOpen:t.isOpen,messages:t.messages,sessionId:t.sessionId};localStorage.setItem(V,JSON.stringify(e))}catch(n){d.error("Chat: Fallback persistence failed",n)}}},500);return()=>clearTimeout(e)},[t.isOpen,t.messages,t.sessionId,r]);const s=e.useCallback(e=>{n({type:"ADD_MESSAGE",payload:e})},[]),i=e.useCallback(()=>n({type:"TOGGLE_WINDOW"}),[]),a=e.useCallback(()=>n({type:"OPEN_WINDOW"}),[]),c=e.useCallback(()=>n({type:"CLOSE_WINDOW"}),[]),u=e.useCallback(e=>n({type:"SET_CONNECTED",payload:e}),[]),l=e.useCallback(e=>n({type:"SET_TYPING",payload:e}),[]),p=e.useCallback(e=>n({type:"SET_MESSAGES",payload:e}),[]),f=e.useCallback(e=>n({type:"SET_ERROR",payload:e}),[]),m=e.useCallback(e=>n({type:"SET_SESSION_ID",payload:e}),[]),h=e.useCallback(()=>{localStorage.removeItem(V),n({type:"CLEAR_CHAT"})},[]),g=e.useCallback(()=>{n({type:"SET_MESSAGES",payload:[]})},[]);return{state:t,isHydrated:r,actions:{toggleWindow:i,openWindow:a,closeWindow:c,setConnected:u,setTyping:l,addMessage:s,setMessages:p,setError:f,setSessionId:m,clearChat:h,clearMessages:g}}}(),I=function(t=!1){const n="undefined"!=typeof window?window.location.pathname:"",r=e.useMemo(()=>n,[n]),[o,s]=e.useState({});return e.useEffect(()=>{if(!t)return void s({});const e=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}();s(e)},100);return()=>clearTimeout(e)},[r,t]),t&&Object.keys(o).length>0?o:void 0}(a),$=function(t){const{apiKey:n,apiBaseUrl:r,pageContext:o,userContext:s}=t,i=e.useRef(t);e.useEffect(()=>{i.current=t},[t]);const a=e.useRef(null),[c,u]=e.useState(!1),[l,f]=e.useState(!1),m=e.useRef(function(){try{const e=localStorage.getItem(hs);if(e)return e;const t=gs();return localStorage.setItem(hs,t),t}catch{return d.warn("localStorage not available, using session-only device ID"),gs()}}()),h=e.useRef(o);e.useEffect(()=>{h.current=o},[o]);const g=e.useCallback(e=>{const t=ys.safeParse(e),n=t.success&&t.data.id?t.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,r=t.success&&t.data.sender?t.data.sender:"bot",o=t.success&&t.data.timestamp?new Date(t.data.timestamp):/* @__PURE__ */new Date,s=t.success?t.data:{type:"text"};switch(s.type){case"image":return{id:n,type:"image",sender:r,timestamp:o,imageUrl:s.imageUrl||s.content||"",altText:"Imagen enviada"};case"audio":return{id:n,type:"audio",sender:r,timestamp:o,content:s.audioUrl||s.content||""};case"location":return{id:n,type:"location",sender:r,timestamp:o,latitude:Number(s.latitude||0),longitude:Number(s.longitude||0),name:s.content||"Ubicación compartida"};case"system":return{id:n,type:"system",sender:"system",timestamp:o,content:String(s.content||"")};default:return{id:n,type:"text",sender:r,timestamp:o,content:String(s.content||"Sin contenido"),emotion:s.emotion}}},[]),v=e.useCallback(()=>{if(!n||!r)return;if(a.current?.connected)return;u(!0);const e=y(`${r}/webchat`,{auth:{apiKey:n,deviceId:m.current,token:s?.token,metadata:s?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});e.on("connect",()=>{u(!1),f(!0),i.current.onConnected(`temp-${Date.now()}`,void 0)}),e.on("disconnect",e=>{u(!1),f(!1),i.current.onDisconnected()}),e.on("connect_error",e=>{u(!1),i.current.onError(`Error de conexión: ${e.message}`)}),e.on("connection_ack",e=>{i.current.onConnected(e.sessionId,e.config)}),e.on("bot_message",e=>{try{i.current.onMessage(g(e))}catch(t){d.error("ChatSocket Error processing bot_message:",t)}}),e.on("chat_history",e=>{e.messages&&Array.isArray(e.messages)&&e.messages.forEach(e=>{try{i.current.onMessage(g(e))}catch(t){d.debug("Error processing history message:",t)}}),i.current.onEvent&&i.current.onEvent("history_loaded",e)}),e.on("bot_typing",e=>i.current.onTyping(e)),e.on("auth_success",e=>{i.current.onLogin&&i.current.onLogin(e),e.theme&&i.current.onThemeUpdate&&i.current.onThemeUpdate(e.theme)}),a.current=e},[n,r]),b=e.useCallback(()=>{a.current&&(a.current.disconnect(),a.current=null,f(!1))},[]),_=e.useRef(v);_.current=v,e.useEffect(()=>(_.current(),()=>{a.current&&(a.current.disconnect(),a.current=null)}),[]);const w=e.useRef([]),k=e.useRef([]),z=e.useCallback(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),x=e.useCallback(()=>{if(a.current?.connected)for(;w.current.length>0;){const e=w.current.shift();a.current.emit("user_message",e)}},[]);e.useEffect(()=>{l&&x()},[l,x]),e.useEffect(()=>{if(!l)return;const e=setInterval(()=>{const e=Date.now();k.current=k.current.filter(t=>e<t.nextRetryAt||(t.attempts>=t.maxAttempts?(i.current.onEvent?.("message_failed",{id:t.id,payload:t.payload}),d.error("Message failed after max retries:",t.id),!1):!a.current?.connected||(a.current.emit("user_message",t.payload,e=>{e?.success&&i.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)},[l]);const E=e.useCallback((e,t="text")=>{const n=z(),r={...h.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:m.current},o={id:n,content:e.trim(),type:t,metadata:r};return a.current?.connected?(a.current.emit("user_message",o,e=>{!1!==e?.success&&e?i.current.onEvent?.("message_sent",{id:n}):(k.current.push({id:n,payload:o,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),i.current.onEvent?.("message_retry_queued",{id:n}))}),n):(w.current.push(o),i.current.onEvent?.("queued_message",{id:n,payload:o}),n)},[z]),S=e.useMemo(()=>p(e=>{a.current?.emit("typing",e)},250),[]);return{isConnected:l,isConnecting:c,sendMessage:E,sendTyping:S,requestHistory:e.useCallback(()=>{a.current?.emit("request_history")},[]),reconnect:v,disconnect:b}}({apiKey:r,apiBaseUrl:o,pageContext:e.useMemo(()=>I?{...s||{},seo:{...I||{}}}:s,[s,I]),userContext:u,onMessage:e.useCallback(e=>{const t=Date.now(),n=w.current>0?t-w.current:void 0;w.current=t,O.addMessage(e),z.trackMessageReceived(e.type,n),S.isOpen||"bot"!==e.sender||(_(e=>e+1),x.notifyWithSound(e))},[O,S.isOpen,z,x]),onConnected:e.useCallback((e,t)=>{O.setConnected(!0),O.setSessionId(e),z.trackConnectionStatus(!0),t&&h&&h("backend_config",t)},[O,h,z]),onDisconnected:e.useCallback(()=>{O.setConnected(!1),z.trackConnectionStatus(!1)},[O,z]),onTyping:e.useCallback(e=>O.setTyping(e),[O]),onError:e.useCallback(e=>{O.setError(e),z.trackError(e)},[O,z]),onLogin:l,onNavigate:m,onEvent:h,onThemeUpdate:v}),N=e.useCallback(()=>{d.debug("ChatWidget handleToggle called, current isOpen:",S.isOpen),S.isOpen?(O.closeWindow(),z.trackClose(),g?.(!1),d.debug("ChatWidget Closing window")):(O.openWindow(),_(0),z.trackOpen(),g?.(!0),d.debug("ChatWidget Opening window"))},[S.isOpen,O,g,z]),C=e.useCallback(e=>{if(!E.isAllowed()){const e=E.getTimeUntilReset(),t=Math.ceil(e/1e3);return void O.setError(k("rate_limit_exceeded")+` Espera ${t}s.`)}const t={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:e};O.addMessage(t),z.trackMessageSent("text"),$.sendMessage(e,"text")},[O,$,E,z,k]),T=e.useCallback(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}`},O.addMessage(n);const r=await(e=>new Promise((t,n)=>{const r=new FileReader;r.readAsDataURL(e),r.onload=()=>t(r.result),r.onerror=e=>n(e)}))(e);$.sendMessage(r,t)},[O,$]),A=e.useCallback(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"};O.addMessage(t),$.sendMessage(JSON.stringify(e),"location")},[O,$]);e.useEffect(()=>{const e=()=>{S.isOpen||O.openWindow()},t=()=>{S.isOpen&&O.closeWindow()},n=()=>{S.isOpen?O.closeWindow():O.openWindow()},r=e=>{e.detail?.message&&C(e.detail.message)};return window.addEventListener("botuyo-chat:open",e),window.addEventListener("botuyo-chat:close",t),window.addEventListener("botuyo-chat:toggle",n),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:send-message",r)}},[S.isOpen,O,C]),e.useEffect(()=>()=>{},[C]);const j=e.useCallback(()=>{O.clearMessages(),d.info("Chat history cleared")},[O]);e.useEffect(()=>()=>{},[j]);const Z=e.useMemo(()=>{if(S.isTyping)return"thinking";const e=[...S.messages].reverse().find(e=>"bot"===e.sender&&"text"===e.type);return"text"===e?.type&&e.emotion?e.emotion:"default"},[S.isTyping,S.messages]);return{state:S,actions:O,unreadCount:b,currentBotEmotion:Z,isConnected:$.isConnected,handleToggle:N,handleSendText:C,handleSendAttachment:T,handleSendLocation:A}}function _s(n){const{apiKey:r,apiBaseUrl:o,pageContext:s,includeSEOMetadata:i=!1,theme:c,mediaConfig:u,userContext:d,onLogin:p,onNavigate:f,onEvent:y,onStateChange:z,onVoiceCall:x}=n,E=e.useRef(null),S=m();!function(t){const[n,r]=e.useState(!1);e.useEffect(()=>{let e=null;const n=()=>{if(!t.current)return;const e=!!t.current.parentElement?.closest(".dark"),n=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),o=document.getElementById("botuyo-chat-widget-root"),s=!!o?.parentElement?.closest(".dark"),i=document.documentElement.classList.contains("dark"),a=document.body.classList.contains("dark"),c=window.matchMedia("(prefers-color-scheme: dark)").matches,u=e||n||s||i||a||c;t.current&&(u?t.current.classList.add("dark"):t.current.classList.remove("dark")),r(u)};n();const o=window.matchMedia("(prefers-color-scheme: dark)"),s=()=>n();o.addEventListener("change",s);const i=new MutationObserver(()=>{n()}),a=document.getElementById("botuyo-chat-widget-root");a&&(i.observe(a,{attributes:!0,attributeFilter:["class"]}),a.parentElement&&(i.observe(a.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=a.parentElement)),i.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),i.observe(document.body,{attributes:!0,attributeFilter:["class"]});let c=t.current?.parentElement;for(;c;)i.observe(c,{attributes:!0,attributeFilter:["class"]}),c=c.parentElement;const u=setInterval(()=>{const t=document.getElementById("botuyo-chat-widget-root");t&&t.parentElement!==e&&(e&&t.parentElement&&(i.observe(t.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=t.parentElement),n())},100);return()=>{i.disconnect(),o.removeEventListener("change",s),clearInterval(u)}},[t])}(E);const[O,I]=e.useState(),{mergedTheme:$,mergedStyles:N,getContainerStyle:C}=function(t,n){const r=function(){const[t,n]=e.useState(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return e.useEffect(()=>{const e=window.matchMedia("(prefers-contrast: high)"),t=window.matchMedia("(prefers-contrast: more)"),r=e=>{n(e.matches)};return e.addEventListener("change",r),t.addEventListener("change",r),()=>{e.removeEventListener("change",r),t.removeEventListener("change",r)}},[]),t}(),o=e.useMemo(()=>{const e=l(t,n);return r?{...e,primaryColor:"#000000",cssVariables:{...e.cssVariables,background:"#FFFFFF",foreground:"#000000",card:"#FFFFFF",cardForeground:"#000000",primary:"#000000",primaryForeground:"#FFFFFF",muted:"#F5F5F5",mutedForeground:"#000000",border:"#000000"}}:e},[t,n,r]),s=e.useMemo(()=>({radius:{..._,...t?.bubbleStyles?.radius},bot:{...w,...t?.bubbleStyles?.bot},user:{...k,...t?.bubbleStyles?.user},launcher:{...t?.bubbleStyles?.launcher},mapCard:{...t?.bubbleStyles?.mapCard}}),[t?.bubbleStyles]);return{mergedTheme:o,mergedStyles:s,getContainerStyle:(e,t,n)=>({"--chat-primary":o.primaryColor,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:"100px",width:t&&e?"100%":"auto",height:t&&e?"100%":"auto"})}}(c,O),{state:T,actions:A,unreadCount:j,currentBotEmotion:Z,isConnected:M,handleToggle:P,handleSendText:D,handleSendAttachment:F,handleSendLocation:R}=bs({apiKey:r,apiBaseUrl:o,pageContext:s,includeSEOMetadata:i,theme:c,userContext:d,onLogin:p,onNavigate:f,onEvent:y,onStateChange:z,onThemeUpdate:I}),L=e.useCallback(e=>{e.stopPropagation()},[]),U=C(T.isOpen,S,c?.position),J=e.useMemo(()=>{if(!$.cssVariables)return{};const e={},t=$.cssVariables;return t.background&&(e["--background"]=t.background),t.foreground&&(e["--foreground"]=t.foreground),t.card&&(e["--card"]=t.card),t.cardForeground&&(e["--card-foreground"]=t.cardForeground),t.primary&&(e["--primary"]=t.primary),t.primaryForeground&&(e["--primary-foreground"]=t.primaryForeground),t.muted&&(e["--muted"]=t.muted),t.mutedForeground&&(e["--muted-foreground"]=t.mutedForeground),t.border&&(e["--border"]=t.border),t.destructive&&(e["--destructive"]=t.destructive),t.radius&&(e["--radius"]=t.radius),t.spacing1&&(e["--spacing-1"]=t.spacing1),t.spacing2&&(e["--spacing-2"]=t.spacing2),t.spacing3&&(e["--spacing-3"]=t.spacing3),t.spacing4&&(e["--spacing-4"]=t.spacing4),t.spacing5&&(e["--spacing-5"]=t.spacing5),t.spacing6&&(e["--spacing-6"]=t.spacing6),t.spacing8&&(e["--spacing-8"]=t.spacing8),e},[$.cssVariables]);/* @__PURE__ */
30
+ return t.jsx(h,{animations:c?.animations,effects:c?.effects,children:/* @__PURE__ */t.jsxs("div",{ref:E,id:"botuyo-chat-widget",className:a("botuyo-chat-widget flex flex-col",!S&&("bottom-left"===c?.position?"items-start":"items-end")),style:{...U,...J,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:[
31
+ /* @__PURE__ */t.jsx("div",{className:a("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",S?"bottom-left"===c?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",T.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:T.isOpen?"auto":"none"},onMouseDown:L,onTouchStart:L,children:/* @__PURE__ */t.jsx(b,{children:/* @__PURE__ */t.jsx(g,{isOpen:T.isOpen,isConnected:M,isTyping:T.isTyping,messages:T.messages,onClose:()=>A.closeWindow(),onSendMessage:D,onSendAttachment:F,onSendLocation:R,botName:c?.botName,logoUrl:c?.logoUrl,welcomeMessage:c?.welcomeMessage,inputPlaceholder:c?.inputPlaceholder,primaryColor:c?.primaryColor,position:c?.position,bubbleStyles:N,avatars:c?.avatars,mediaConfig:u,theme:$,onVoiceCall:x})})}),
32
+ /* @__PURE__ */t.jsx("div",{className:a(T.isOpen?"hidden":"block",!S&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:L,onTouchStart:L,children:/* @__PURE__ */t.jsx(v,{isOpen:T.isOpen,onClick:P,unreadCount:j,position:c?.position||"bottom-right",primaryColor:c?.primaryColor,logoUrl:c?.logoUrl,starterPrompt:c?.starterPrompt,avatars:c?.avatars,emotion:Z,styles:N,promptPersistence:c?.promptPersistence,avatarScale:c?.avatarScale})})]})})}e.createContext(null);export{_s as ChatWidget};
33
+ //# sourceMappingURL=ChatWidget-3m1RqH_c.js.map