var Mt=Object.defineProperty;var Ot=(e,t,r)=>t in e?Mt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var H=(e,t,r)=>Ot(e,typeof t!="symbol"?t+"":t,r);import{r as Bt,a as Dt,b as Ut}from"./vendor-CuZOJldH.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const f of i.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&s(f)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();var S=Bt(),jt=Dt(),o=Ut();const nt="Escribe tu teléfono completo a 10 dígitos, incluyendo lada. Puedes agregar +52 al inicio.";function Fe(e){const t=e.trim();if(!/^(?:\+\s*52[\s()-]*|52[\s()-]*)?[0-9\s()-]+$/.test(t))return null;const r=t.replace(/\D/g,"");return t.startsWith("+")&&!/^52\d{10}$/.test(r)?null:/^(?:52)?\d{10}$/.test(r)?r:null}class gt{constructor(t){H(this,"chatbotName");H(this,"startNodeId");H(this,"flowId");H(this,"nodesMap");H(this,"variables");H(this,"history");H(this,"currentBranchId");H(this,"pendingReturnNodeId");H(this,"completed");H(this,"abandoned");H(this,"_currentNodeId");H(this,"_snapshot",null);this.chatbotName=t.chatbot_name,this.startNodeId=t.start_node_id,this.flowId=t.flow_id,this.nodesMap=new Map(t.nodes.map(r=>[r._id,r])),this.variables={},this.history=[],this.currentBranchId=null,this.pendingReturnNodeId=null,this.completed=!1,this.abandoned=!1}start(){const t=this.nodesMap.get(this.startNodeId);if(!t)throw new Error("Nodo inicial no encontrado");return this._autoFlow(t)}_autoAdvanceFrom(t){const r=this._getNext(t.next_node_id??null);if(r)return this._currentNodeId=r._id,this._autoFlow(r);if(this.currentBranchId&&this.pendingReturnNodeId){const s=this.pendingReturnNodeId;this.currentBranchId=null,this.pendingReturnNodeId=null;const a=this.nodesMap.get(s)??null;return a&&(this._currentNodeId=a._id),a?this._autoFlow(a):null}return null}next(t,r){if(this.completed||this.abandoned)return null;const s=this._currentNodeId?this.nodesMap.get(this._currentNodeId):void 0;if(!s)return this.completed=!0,null;const a=this._resolveInput(s,t,r);if(a.validation_error)throw a;const i=a.node;return i?i._id?this._autoFlow(i):(i.end_conversation&&(this.abandoned||(this.completed=!0)),i):(this.completed=!0,null)}getPayload(){return{history:this.history,variables:this.variables,flow_id:this.flowId}}_resolveInput(t,r,s){const a=["question","email","phone","number"],i=["options","policy"];if(a.includes(t.node_type)){const f=this._validateInput(t,r);return f?{node:null,validation_error:!0,message:f,field:t.node_type}:((t.node_type==="phone"||t.variable_key==="phone")&&r.trim()&&(r=Fe(r)??r),this.history.push({node_id:t._id,question:t.content,answer:r,node_type:t.node_type,variable_key:t.variable_key??null}),t.variable_key&&(this.variables[t.variable_key]=r),{node:this._getNext(t.next_node_id??null)})}if(i.includes(t.node_type)){const c=(t.node_type==="options"?t.options:t.policy)?.find(x=>String(x.value).toLowerCase()===String(r).toLowerCase()||String(x.label).toLowerCase()===String(r).toLowerCase());if(!c)return{node:t};const d=s?.trim()?`${c.label}: ${s.trim()}`:c.label;if(this.history.push({node_id:t._id,question:t.content,answer:d,node_type:t.node_type,variable_key:t.variable_key??null}),t.variable_key&&(this.variables[t.variable_key]=d),t.node_type==="policy"){let x=c.value;if(x.toUpperCase()==="SI"&&(x="accepted"),x.toUpperCase()==="NO"&&(x="rejected"),this.variables.data_processing_consent=x,x==="rejected")return this.abandoned=!0,{node:{_id:"",node_type:"text",content:"No podemos continuar sin aceptar nuestras políticas de tratamiento de datos.",typing_time:1,end_conversation:!0}}}return c.next_branch_id?(this.pendingReturnNodeId=String(c.next_node_id??t.next_node_id??"")||null,this.currentBranchId=String(c.next_branch_id),{node:this._getBranchStart(this.currentBranchId)}):(this.currentBranchId=null,this.pendingReturnNodeId=null,{node:this._getNext(c.next_node_id??t.next_node_id??null)})}return{node:this._getNext(t.next_node_id??null)}}_evaluateCondition(t){const s=(t.meta??{}).condition??{},a=String(s.variable_key??"").trim(),i=String(s.operator??"equals"),f=String(s.value??""),c=String(this.variables[a]??"");let d=!1;switch(i){case"not_equals":d=c.toLowerCase()!==f.toLowerCase();break;case"contains":d=c.toLowerCase().includes(f.toLowerCase());break;case"not_contains":d=!c.toLowerCase().includes(f.toLowerCase());break;case"exists":d=c.trim().length>0;break;case"not_exists":d=c.trim().length===0;break;case"gt":d=Number(c)>Number(f);break;case"gte":d=Number(c)>=Number(f);break;case"lt":d=Number(c)d.trim()).filter(Boolean));c.add(f),this.variables.__flow_tags=Array.from(c).join(",")}if(a==="remove_tag"&&f){const c=String(this.variables.__flow_tags??"").split(",").map(d=>d.trim()).filter(Boolean).filter(d=>d!==f);this.variables.__flow_tags=c.join(",")}}}_autoFlow(t){const r=["question","email","phone","number"],s=["options","policy"];let a=0;for(;t&&a++<20;){if(this._currentNodeId=t._id,t.node_type==="condition"){const c=this._evaluateCondition(t),d=this._getNext(c??t.next_node_id??null);if(!d)break;t=d;continue}if(t.node_type==="action"){this._runActions(t);const c=this._getNext(t.next_node_id??null);if(!c)break;t=c;continue}if(r.includes(t.node_type)||s.includes(t.node_type))return t;const i=!!this.currentBranchId&&!!this.pendingReturnNodeId;if(t.end_conversation&&!i)return this.completed=!0,t;if(["text","media","link"].includes(t.node_type))return t;const f=this._getNext(t.next_node_id??null);if(!f)break;t=f}return this.completed=!0,null}_getBranchStart(t){const r=Array.from(this.nodesMap.values()).filter(i=>String(i.branch_id??"")===String(t));if(!r.length)return null;const s=new Set(r.map(i=>i.next_node_id).filter(Boolean).map(i=>String(i))),a=r.find(i=>!s.has(String(i._id)))??r[0];return this._currentNodeId=a._id,a}_getNext(t){if(!t)return null;const r=this.nodesMap.get(String(t));return!r||r.branch_id&&r.branch_id!==this.currentBranchId?null:r}_validateInput(t,r){const s=t.validation,a=Array.isArray(s?.rules)?s.rules.find(d=>d?.type==="required"):null,i=s==null||a!=null;if(r==null||String(r).trim()==="")return i?a?.message||"Este campo es obligatorio.":null;if((t.node_type==="phone"||t.variable_key==="phone")&&!Fe(String(r)))return nt;if(!s)return null;if(t.node_type==="email"){const d=String(r).trim();if(!/^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,10}$/.test(d))return"Correo inválido."}if(!s.rules){if(t.node_type==="number"){const d=Number(r);if(isNaN(d))return s.message||"Debe ser un número.";if(s.min!=null&&ds.max)return s.message||`Máximo ${s.max}.`}return t.node_type==="question"&&s.min_length&&String(r).trim().lengthd.max)return d.message}if(t.node_type==="number"){const x=Number(c);if(isNaN(x)||d.min!==void 0&&xd.max)return d.message}break}}return null}getCurrentNodeId(){return this._currentNodeId}getState(){return{nodeId:this._currentNodeId,variables:this.variables,history:this.history,currentBranchId:this.currentBranchId,pendingReturnNodeId:this.pendingReturnNodeId}}restoreState(t,r,s,a,i){this._currentNodeId=t,r&&(this.variables=r),s&&(this.history=s),this.currentBranchId=a??null,this.pendingReturnNodeId=i??null}getCurrentNode(){if(this._currentNodeId)return this.nodesMap.get(this._currentNodeId)}saveSnapshot(){this._snapshot={nodeId:this._currentNodeId,variables:{...this.variables},history:[...this.history],branchId:this.currentBranchId,pendingReturnNodeId:this.pendingReturnNodeId}}rollback(){this._snapshot&&(this._currentNodeId=this._snapshot.nodeId,this.variables={...this._snapshot.variables},this.history=[...this._snapshot.history],this.currentBranchId=this._snapshot.branchId,this.pendingReturnNodeId=this._snapshot.pendingReturnNodeId,this.completed=!1,this.abandoned=!1,this._snapshot=null)}}const vt=10,Pt=200,Je=(e,t)=>`chatbot_history_${e}_${t}`,ee=(e,t)=>`chatbot_active_session_${e}_${t}`;function at(){return crypto.randomUUID()}function ue(e,t){try{const r=localStorage.getItem(Je(e,t));return r?JSON.parse(r):[]}catch{return[]}}function _e(e,t,r){try{const s=r.slice(-vt);localStorage.setItem(Je(e,t),JSON.stringify(s))}catch{try{const s=r.slice(-Math.floor(vt/2));localStorage.setItem(Je(e,t),JSON.stringify(s))}catch{}}}function Ht(e,t,r="es"){const s={sessionId:at(),publicId:e,visitorId:t,startedAt:Date.now(),lastActivityAt:Date.now(),messages:[],completed:!1,lang:r},a=ue(e,t);return a.push(s),_e(e,t,a),localStorage.setItem(ee(e,t),s.sessionId),s}function X(e,t){const r=localStorage.getItem(ee(e,t));return r?ue(e,t).find(a=>a.sessionId===r)??null:null}function st(e,t,r,s,a){const i=ue(e,t),f=localStorage.getItem(ee(e,t)),c=i.findIndex(_=>_.sessionId===f);if(c===-1)return null;const d=i[c].messages.at(-1);if(d&&d.role===r&&d.text===s&&Date.now()-d.timestamp<500)return d;i[c].messages.length>=Pt&&i[c].messages.shift();const x={id:at(),role:r,text:s,html:a?.html,nodeId:a?.nodeId,timestamp:Date.now()};return i[c].messages.push(x),i[c].lastActivityAt=Date.now(),_e(e,t,i),x}function qt(e,t,r){const s=ue(e,t),a=localStorage.getItem(ee(e,t)),i=s.findIndex(f=>f.sessionId===a);i!==-1&&(s[i].engineState=r,s[i].lastActivityAt=Date.now(),_e(e,t,s))}function Oe(e,t){const r=ue(e,t),s=localStorage.getItem(ee(e,t)),a=r.findIndex(i=>i.sessionId===s);a!==-1&&(r[a].completed=!0,r[a].lastActivityAt=Date.now(),_e(e,t,r))}function Vt(e,t){const r=localStorage.getItem(ee(e,t));if(!r)return;const a=ue(e,t).filter(i=>i.sessionId!==r);_e(e,t,a),localStorage.removeItem(ee(e,t))}function zt(e,t){localStorage.removeItem(Je(e,t)),localStorage.removeItem(ee(e,t))}function Wt(e,t,r="Chatbot"){const s=X(e,t);if(!s)return;const a={chatbot:r,sessionId:s.sessionId,visitorId:s.visitorId,startedAt:new Date(s.startedAt).toISOString(),lastActivityAt:new Date(s.lastActivityAt).toISOString(),lang:s.lang,completed:s.completed,messages:s.messages.map(d=>({id:d.id,role:d.role,text:d.text,timestamp:new Date(d.timestamp).toISOString()}))},i=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),f=URL.createObjectURL(i),c=document.createElement("a");c.href=f,c.download=`chat-${r.replace(/\s+/g,"-")}-${s.sessionId.slice(0,8)}.json`,c.click(),URL.revokeObjectURL(f)}function Ft(e,t,r){try{const s=JSON.parse(r);if(typeof s.sessionId!="string"||!Array.isArray(s.messages))return null;const a={sessionId:s.sessionId,publicId:e,visitorId:t,startedAt:s.startedAt?new Date(s.startedAt).getTime():Date.now(),lastActivityAt:Date.now(),messages:s.messages.map(c=>({id:c.id??at(),role:c.role,text:c.text??"",timestamp:c.timestamp?new Date(c.timestamp).getTime():Date.now()})),completed:!1,lang:s.lang??"es"},i=ue(e,t),f=i.findIndex(c=>c.sessionId===a.sessionId);return f!==-1?i[f]=a:i.push(a),_e(e,t,i),localStorage.setItem(ee(e,t),a.sessionId),a}catch{return null}}function yt(e,t){const r=X(e,t);return!!r&&r.messages.length>0&&!r.completed}const Zt=/^(?:https?:\/\/[^/]+)?(\/avatars\/Avatar[1-3]\.(?:png|webp))(?:[?#].*)?$/i,Jt=/^https?:\/\/[^/]+\.vercel\.app(\/avatars\/[^?#]+)(?:[?#].*)?$/i;function De(e,t=108){if(!e)return"";const r=e.trim();if(!r)return"";const s=r.match(Zt);if(s)return s[1].replace(/\.png$/i,".webp");const a=r.match(Jt);return a?a[1]:/\/avatars\/Avatar\d+\.png(?:[?#]|$)/i.test(r)?r.replace(/(\/avatars\/Avatar\d+)\.png/i,"$1.webp"):r.includes("res.cloudinary.com")&&r.includes("/image/upload/")&&!/\/image\/upload\/[^/]*[wqfc]_[^/]+\//.test(r)?r.replace("/image/upload/",`/image/upload/f_auto,q_auto,w_${t},h_${t},c_fill/`):r}function _t(e){const t=e.currentTarget;t.src.includes(".webp")&&(t.onerror=null,t.src=t.src.replace(/\.webp($|\?)/,".png$1"))}function Be(e,t="msg-avatar",r=32,s=""){const a=document.createElement("img");return a.className=t,a.alt=s,a.width=r,a.height=r,a.loading="lazy",a.decoding="async",a.src=De(e,r*2),a.onerror=()=>{a.src.includes(".webp")&&(a.onerror=null,a.src=a.src.replace(/\.webp($|\?)/,".png$1"))},a}const wt=["question","email","phone","number"],Kt={email:'',whatsapp:'',phone:'',link:''},le=()=>{const e="chat_visitor_id";let t=localStorage.getItem(e);return t||(t=crypto.randomUUID(),localStorage.setItem(e,t)),t},Ze=()=>new Date().toLocaleTimeString("es-MX",{hour:"2-digit",minute:"2-digit"}),Ct=e=>`chatbot_started_at_${e}`,It=e=>{const t=Ct(e),r=sessionStorage.getItem(t);if(r){const a=new Date(r);if(!Number.isNaN(a.getTime()))return a.toISOString()}const s=new Date().toISOString();return sessionStorage.setItem(t,s),s},Xt=e=>/^#[\da-f]{6}$/i.test(e)?`${parseInt(e.slice(1,3),16)},${parseInt(e.slice(3,5),16)},${parseInt(e.slice(5),16)}`:"37,99,235",Nt=(e,t)=>{if(!/^#[\da-f]{6}$/i.test(e))return e;const r=f=>Math.min(255,Math.max(0,f)),s=r(parseInt(e.slice(1,3),16)+t),a=r(parseInt(e.slice(3,5),16)+t),i=r(parseInt(e.slice(5),16)+t);return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`},Gt=(e,t)=>Nt(e,-22),St=e=>{try{const t=document.createElement("div");return t.innerHTML=e,t.textContent??t.innerText??e}catch{return e}},Yt=new Set(["hola","hello","hey","buenas","buenos","dias","día","tardes","noches","cotizacion","cotización","precio","precios","informacion","información","asesoria","asesoría","servicio","servicios","producto","productos","ayuda","contacto","contactar","presupuesto","quiero","quisiera","necesito","busco","buscando","alguien","atender","atienda","mensaje","prueba","test","empresa","negocio"]),Qt=e=>e.trim().replace(/^[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ]+|[^A-Za-zÁÉÍÓÚÜÑáéíóúüñ'-]+$/g,""),er=e=>{if(e==null)return null;const t=String(e).trim().replace(/\s+/g," ");if(!t||t.length<2||t.length>45||/[?¿!¡@]/.test(t)||/https?:\/\/|www\./i.test(t)||/\d{3,}/.test(t)||/^[\d\s()+.-]+$/.test(t))return null;const r=t.split(" ").filter(Boolean);if(r.length>4)return null;const s=r.map(Qt).filter(Boolean);if(!s.length)return null;const a=s.map(c=>c.toLocaleLowerCase("es-MX"));if(a.some(c=>Yt.has(c)))return null;const i=a.join(" ");if(/^(me|mi|yo|soy|quiero|quisiera|necesito|busco|deseo|hola|buenas)\b/.test(i)||/\b(cotiz|inform|precio|servicio|producto|presupuesto|asesor|atender)\w*/.test(i))return null;const f=s[0];return/^[A-Za-zÁÉÍÓÚÜÑáéíóúüñ][A-Za-zÁÉÍÓÚÜÑáéíóúüñ'-]{1,24}$/.test(f)?f.charAt(0).toLocaleUpperCase("es-MX")+f.slice(1):null},tr=e=>e.replace(/\s+,/g,",").replace(/,\s*([!?.])/g,"$1").replace(/,\s{2,}/g,", ").replace(/\s{2,}/g," ").replace(/,\s*(?=[😊🙂😉😁👋])/g," ").replace(/,\s*!/g,"!").trim(),rr=(e,t,r)=>{const s=String(e||"").replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g,(a,i)=>{if(i==="chatbot_name")return r;const f=t[i];return i==="name"?er(f)??"":f!=null&&String(f).trim()?String(f):`{{${i}}}`});return tr(s)},nr=()=>{const e=navigator.userAgent;return/tablet|ipad|playbook|silk/i.test(e)?"tablet":/mobile|android|iphone|ipod|blackberry|iemobile|opera mini/i.test(e)?"mobile":"desktop"},oe=e=>{const t=String(e||"").trim();if(!t)return"";try{const r=new URL(t);if(r.protocol==="http:"||r.protocol==="https:")return r.toString()}catch{}try{return new URL(`https://${t}`).toString()}catch{return""}};function sr(e){const t=o.useRef(null),r=o.useRef(null),s=o.useRef(!1),a=o.useRef(null),i=o.useRef(!1),f=o.useRef(!1),c=o.useRef(Symbol("chatbot-init")),d=o.useRef(null),x=o.useRef(null),_=o.useRef(""),M=o.useRef({originUrl:"",lastPageUrl:"",referrerUrl:typeof document<"u"&&document.referrer||""}),j=e?`chatbot_dom_${e.publicId}`:null,[Xe,Ue]=o.useState(!1),we=o.useRef(!1),ie=o.useRef(!1),[Ge,de]=o.useState("connecting"),[ce,q]=o.useState(()=>{if(!e)return 0;const n=localStorage.getItem(`chatbot_unread_${e.publicId}`);return n?parseInt(n,10):0}),[Z,me]=o.useState(!0),[je,pe]=o.useState(!0),[Ye,te]=o.useState("Conectando..."),[Ie,Se]=o.useState(!1),[Pe,Ee]=o.useState(""),[Ce,Ne]=o.useState(!1),[he,xe]=o.useState(()=>e?sessionStorage.getItem(`chatbot_welcome_${e.publicId}`)==="true":!1),[He,qe]=o.useState(!1),[Qe,V]=o.useState(null),ke=o.useRef(()=>{}),fe=o.useRef(null),E=o.useRef(null),w=o.useRef(null),$=o.useRef(null),P=o.useRef(null),re=o.useRef(null),Re=o.useRef(null),Te=o.useRef(()=>{}),Ae=o.useRef(()=>{}),ne=o.useRef(Promise.resolve()),[ot,et]=o.useState(!1),it=o.useRef(()=>{}),Ve=o.useCallback(()=>{$.current&&(clearInterval($.current),$.current=null)},[]),A=o.useCallback(()=>{requestAnimationFrame(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)})},[]),L=o.useCallback(()=>{me(!0),pe(!0)},[]),z=o.useCallback(()=>{me(!1),pe(!1),setTimeout(()=>r.current?.focus(),50)},[]);o.useEffect(()=>{_.current=le()},[]),o.useEffect(()=>{if(!e?.publicId)return;const n=oe(e.originUrl)||oe(e.originDomain);n&&!M.current.originUrl&&(M.current.originUrl=n,M.current.lastPageUrl=n);const u=v=>{const h=v.data;if(!h||h.type!=="CHATBOT_PAGE_CONTEXT"||h.instanceId&&h.instanceId!==e.publicId)return;const y=oe(String(h.originUrl||"").slice(0,2048)),b=oe(String(h.lastPageUrl||h.originUrl||"").slice(0,2048));!M.current.originUrl&&y&&(M.current.originUrl=y),b&&(M.current.lastPageUrl=b),h.referrerUrl&&!M.current.referrerUrl&&(M.current.referrerUrl=String(h.referrerUrl).slice(0,2048))};window.addEventListener("message",u);const m=()=>{try{window.parent.postMessage({type:"CHATBOT_PAGE_CONTEXT_REQUEST",instanceId:e.publicId},"*")}catch{}};m();const p=window.setTimeout(m,250),l=window.setTimeout(m,1e3);return()=>{window.removeEventListener("message",u),window.clearTimeout(p),window.clearTimeout(l)}},[e?.publicId,e?.originUrl,e?.originDomain]),o.useEffect(()=>{if(!e)return;_.current=le();const n=_.current,u=sessionStorage.getItem(`chatbot_dom_${e.publicId}`);if(u){s.current=!0,te("En línea"),de("connected"),ne.current=new Promise(y=>{it.current=y});const m=document.createElement("div");m.innerHTML=u;const p=m.querySelector('.inline-options[data-active="true"]')!==null;p||(me(!1),pe(!1));const l=X(e.publicId,n);l&&V(l);const v=c.current,h=setTimeout(()=>{fe.current?.(v)?.then(y=>{if(!y||v!==c.current)return;const b=new gt(y),g=X(e.publicId,n),k=sessionStorage.getItem(`chatbot_node_${e.publicId}`);if(g?.engineState)b.restoreState(g.engineState.nodeId,g.engineState.variables,g.engineState.history,g.engineState.currentBranchId,g.engineState.pendingReturnNodeId);else if(k)try{const I=JSON.parse(k);b.restoreState(I.nodeId,I.variables,I.history,I.currentBranchId,I.pendingReturnNodeId)}catch{}d.current=b,it.current(),p||(me(!1),pe(!1))})},0);return()=>clearTimeout(h)}yt(e.publicId,n)},[e?.publicId]),o.useEffect(()=>{if(!e||s.current)return;const n=sessionStorage.getItem(`chatbot_dom_${e.publicId}`),u=sessionStorage.getItem(`chatbot_needs_start_${e.publicId}`);if(n&&!u)return;const m=`chatbot_starting_${e.publicId}`,p=sessionStorage.getItem(m);if(!(p&&Date.now()-parseInt(p)<3e3))return sessionStorage.setItem(m,String(Date.now())),s.current=!0,u&&(sessionStorage.removeItem(`chatbot_needs_start_${e.publicId}`),sessionStorage.removeItem(`chatbot_dom_${e.publicId}`),sessionStorage.removeItem(`chatbot_node_${e.publicId}`),t.current&&(t.current.innerHTML="")),et(!0),()=>{sessionStorage.removeItem(m)}},[e?.publicId]),o.useEffect(()=>{if(!ot)return;et(!1);const n=c.current;setTimeout(()=>{E.current?.(n)?.finally(()=>{e?.publicId&&sessionStorage.removeItem(`chatbot_needs_start_${e.publicId}`)})},0)},[ot,e?.publicId]),o.useEffect(()=>{if(!e)return;const n=e.primaryColor,u=e.secondaryColor;document.documentElement.style.setProperty("--chat-primary",n),document.documentElement.style.setProperty("--chat-primary-light",Nt(n,28)),document.documentElement.style.setProperty("--chat-primary-dark",Gt(n)),document.documentElement.style.setProperty("--chat-primary-rgb",Xt(n)),document.documentElement.style.setProperty("--chat-secondary",u)},[e?.primaryColor,e?.secondaryColor]),o.useEffect(()=>{if(!(!j||!t.current))try{const n=sessionStorage.getItem(j);if(n){t.current.innerHTML=n,a.current=null;const u=t.current.querySelector(".msg.bot.typing");u&&u.remove(),t.current.querySelectorAll(".inline-options").forEach(p=>{const l=p.dataset.active==="true",v=p.querySelectorAll("button");l?v.forEach(h=>{const y=h.cloneNode(!0);y.disabled=!1,y.style.opacity="",y.style.cursor="",y.style.pointerEvents="",h.replaceWith(y),y.addEventListener("click",async()=>{delete p.dataset.active,p.querySelectorAll("button").forEach(k=>{k.disabled=!0,k.style.opacity="0.5",k.style.cursor="not-allowed",k.style.pointerEvents="none"});const b=y.textContent??"",g=y.hasAttribute("data-value")?y.dataset.value:b;Te.current("user",b),Ae.current(),await ne.current,Re.current&&await Re.current(g)})}):v.forEach(h=>{h.disabled=!0,h.style.opacity="0.5",h.style.cursor="not-allowed",h.style.pointerEvents="none"})}),A()}}catch{}},[j,A]),o.useEffect(()=>{if(!j||!t.current)return;const n=new MutationObserver(()=>{if(!(!t.current||!j))try{sessionStorage.setItem(j,t.current.innerHTML)}catch{}});return n.observe(t.current,{childList:!0,subtree:!0,characterData:!0}),()=>n.disconnect()},[j]),o.useEffect(()=>{if(e){if(!we.current){we.current=!0;return}localStorage.setItem(`chatbot_unread_${e.publicId}`,String(ce))}},[ce,e?.publicId]),o.useEffect(()=>{if(e){if(!ie.current){ie.current=!0;return}sessionStorage.setItem(`chatbot_welcome_${e.publicId}`,String(he))}},[he,e?.publicId]),o.useEffect(()=>{if(!e?.welcomeMessage||matchMedia("(max-width:480px)").matches&&e.showWelcomeOnMobile===!1)return;const u=(e.welcomeDelay??2)*1e3,m=l=>{!l.data||l.data.type!=="CHATBOT_WELCOME_PERMISSION"||l.data.instanceId===e.publicId&&l.data.allowed&&!f.current&&xe(!0)};window.addEventListener("message",m);const p=setTimeout(()=>{f.current||window.parent.postMessage({type:"CHATBOT_WELCOME_REQUEST",instanceId:e.publicId},"*")},u);return()=>{clearTimeout(p),window.removeEventListener("message",m)}},[e?.publicId,e?.welcomeMessage,e?.welcomeDelay,e?.showWelcomeOnMobile]);const se=o.useCallback((n,u)=>{r.current&&(r.current.placeholder=e?.inputPlaceholder??"Escribe tu mensaje...",n==="email"&&(r.current.placeholder="correo@ejemplo.com"),n==="phone"&&(r.current.placeholder="Ej. +52 999 123 4567"),u==="date"&&(r.current.placeholder="Selecciona una fecha"),u==="time"&&(r.current.placeholder="Selecciona una hora"),u==="location"&&(r.current.placeholder="Escribe ubicación o dirección"))},[e?.inputPlaceholder]),be=o.useCallback(()=>{if(a.current)return a.current;const n=document.createElement("div");return n.className="msg bot typing",n.innerHTML=`
`,t.current?.appendChild(n),a.current=n,A(),n},[e?.avatar,A]),D=o.useCallback(()=>{a.current?.remove(),a.current=null},[]),Le=o.useCallback(n=>{const u=a.current;if(!e?.publicId)return J(n);if(!u||!t.current?.contains(u))return a.current=null,J(n);u.classList.remove("typing");const m=u.querySelector(".bubble"),p=u.querySelector(".msg-content");m.innerHTML=n;const l=document.createElement("div");return l.className="message-time",l.textContent=Ze(),p.appendChild(l),a.current=null,f.current||q(v=>v+1),A(),e&&(st(e.publicId,_.current,"bot",St(n),{html:n}),V(X(e.publicId,_.current))),m},[A,e]),W=o.useCallback((n,u,m=!1)=>{if(!t.current||!e?.publicId)return;const p=document.createElement("div");if(p.className=`msg ${n}${m?" error":""}`,n==="bot"){const y=Be(e?.avatar,"msg-avatar",32);p.appendChild(y)}const l=document.createElement("div");l.className="msg-content";const v=document.createElement("div");v.className="bubble",v.textContent=u;const h=document.createElement("div");h.className="message-time",h.textContent=Ze(),l.append(v,h),p.appendChild(l),t.current.appendChild(p),n==="bot"&&!f.current&&q(y=>y+1),A(),e&&!m&&(st(e.publicId,_.current,n,u),V(X(e.publicId,_.current)))},[e?.avatar,A,e]),ct=o.useCallback(async(n,u)=>{u===c.current&&(be(),await new Promise(m=>setTimeout(m,2e3)),u===c.current&&(D(),W("bot",n,!0)))},[be,D,W]),J=o.useCallback(n=>{const u=document.createElement("div");if(u.className="msg bot",!e?.publicId)return u;const m=Be(e?.avatar,"msg-avatar",32),p=document.createElement("div");p.className="msg-content";const l=document.createElement("div");l.className="bubble",l.innerHTML=n;const v=document.createElement("div");return v.className="message-time",v.textContent=Ze(),p.append(l,v),u.append(m,p),t.current?.appendChild(u),f.current||q(h=>h+1),A(),e&&n&&(st(e.publicId,_.current,"bot",St(n),{html:n}),V(X(e.publicId,_.current))),l},[e?.avatar,A,e]),lt=o.useCallback(n=>{Ne(!1),Ee(n),Se(!0)},[]),ut=o.useCallback(n=>{Ne(!0),Ee(n),Se(!0)},[]),kt=o.useCallback(()=>{Se(!1),Ee("")},[]),dt=o.useCallback((n,u)=>{const m=document.createElement("div");m.className="link-actions",n.forEach(p=>{const l=document.createElement("a");l.className=`link-action link-${p.type}`;const v=Kt[p.type]??"";switch(l.innerHTML=` ${v} ${p.title||p.value} `,l.target="_blank",l.rel="noopener noreferrer",p.type){case"link":l.href=p.value;break;case"email":{const h=p.value.trim(),y=e?.name||"Chatbot",b=encodeURIComponent(`Contacto desde chatbot: ${y}`),g=encodeURIComponent(`Hola, Estoy contactando desde el chatbot "${y}". Quiero más información. Gracias.`),k=/Android|iPhone|iPad|iPod/i.test(navigator.userAgent);l.href=k?`mailto:${h}?subject=${b}&body=${g}`:`https://mail.google.com/mail/?view=cm&fs=1&to=${h}&su=${b}&body=${g}`;break}case"phone":l.href=`tel:${p.value}`;break;case"whatsapp":{const h=p.value.replace(/\D/g,""),y=h.startsWith("52")?h:`52${h}`;l.href=`https://api.whatsapp.com/send?phone=${y}`;break}default:return}m.appendChild(l)}),u.appendChild(m)},[e]),mt=o.useCallback((n,u)=>{const m=(n||[]).filter(N=>!!(N?.url&&String(N.url).trim()));if(!m.length)return!1;const p=u.closest(".msg.bot");p&&p.classList.add("media-msg");const l=document.createElement("div");l.className="media-carousel-wrapper";const v=4,h=m.length,y=h-v,b={1:"count-1",2:"count-2",3:"count-3",4:"count-4"},g=document.createElement("div");g.className=`media-grid ${b[Math.min(h,4)]??"count-more"}`;const k=N=>String(N||"").match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([^?&/]+)/i)?.[1]||null,I=N=>{try{const O=new URL(N).pathname.toLowerCase();return O.includes(".")&&O.split(".").pop()||""}catch{return String(N).split("?")[0].split("#")[0].split(".").pop()?.toLowerCase()||""}},R=N=>{try{const O=new URL(N);return!/dropbox\.com$/i.test(O.hostname)&&!/\.dropbox\.com$/i.test(O.hostname)?N:(O.searchParams.delete("dl"),O.searchParams.set("raw","1"),O.toString())}catch{return N}},U=N=>{const O=String(N).match(/drive\.google\.com\/file\/d\/([^/]+)/i);return O?.[1]?`https://drive.google.com/file/d/${O[1]}/preview`:null},G=(N,O="Abrir archivo")=>{const C=document.createElement("a");return C.href=N,C.target="_blank",C.rel="noopener noreferrer",C.className="media-preview-open",C.textContent=O,C},Y=(N,O,C)=>{N.classList.add("media-load-error"),N.innerHTML="";const B=document.createElement("a");B.className="media-fallback-link",B.href=C,B.target="_blank",B.rel="noopener noreferrer",B.innerHTML=`${O}Abrir archivo`,N.appendChild(B)},ge=(N,O,C,B,F="media-embed-item")=>{N.classList.add(F);const ve=document.createElement("div");ve.className="media-preview-frame";const Q=document.createElement("iframe");Q.src=O,Q.title=B,Q.loading="lazy",Q.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",Q.allowFullscreen=!0,ve.appendChild(Q);const ye=document.createElement("div");ye.className="media-preview-toolbar";const T=document.createElement("span");T.textContent=B,ye.append(T,G(C)),N.append(ve,ye)};return m.slice(0,v).forEach((N,O)=>{const C=document.createElement("div");if(C.className="media-item",O===v-1&&y>0){C.classList.add("has-more-overlay");const T=document.createElement("span");T.className="more-overlay",T.textContent=`+${y}`,C.appendChild(T)}const B=String(N.url).trim(),F=R(B),ve=I(F),Q=k(F),ye=U(F);if(Q)ge(C,`https://www.youtube.com/embed/${Q}`,B,"Video de YouTube","media-youtube-item");else if(ye)ge(C,ye,B,"Vista previa de Google Drive","media-drive-item");else if(N.type==="image"){const T=document.createElement("img");T.src=F,T.loading="lazy",T.onload=()=>T.classList.add("loaded"),T.onerror=()=>Y(C,"No se pudo cargar la imagen",B),C.onclick=()=>{C.classList.contains("media-load-error")||lt(F)},C.appendChild(T)}else if(N.type==="video"){const T=document.createElement("video");if(T.src=F,T.playsInline=!0,T.muted=!0,T.preload="metadata",T.controls=h===1,C.appendChild(T),h!==1){const Me=document.createElement("div");Me.className="video-play-overlay",Me.innerHTML='',C.style.cursor="pointer",C.onclick=()=>ut(F),C.appendChild(Me)}T.onloadeddata=()=>T.classList.add("loaded"),T.onerror=()=>Y(C,"El enlace no es un video directo o el servidor bloquea la reproducción",B)}else if(N.type==="youtube")Y(C,"Enlace de YouTube no válido",B);else if(N.type==="document"){const T=ve==="pdf",Me=["doc","docx","xls","xlsx","ppt","pptx"].includes(ve);if(T)ge(C,F,B,"Documento PDF","media-document-preview-item");else if(Me){const ae=`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(F)}`;ge(C,ae,B,"Documento","media-document-preview-item")}else{const ae=document.createElement("a");ae.href=B,ae.target="_blank",ae.rel="noopener noreferrer",ae.className="media-document-link",ae.innerHTML='📄Abrir documentoEste tipo de archivo no admite vista previa integrada.',C.classList.add("media-document-item"),C.appendChild(ae)}}else Y(C,"Tipo de archivo no compatible",B);g.appendChild(C)}),l.appendChild(g),u.appendChild(l),A(),!0},[lt,ut,A]),ze=o.useCallback((n,u,m)=>{const p=n.node_type==="policy"?n.policy:n.options,l=d.current,v=document.createElement("div");v.className="inline-options",p.length>=7&&v.classList.add("is-long-list"),v.dataset.active="true",p.forEach(h=>{const y=document.createElement("button");y.textContent=h.label,y.dataset.value=h.value??h.label;const b=async g=>{if(m!==c.current)return;delete v.dataset.active,y.classList.add("selected"),v.querySelectorAll("button").forEach(I=>{I.disabled=!0,I.style.cursor="not-allowed",I.style.pointerEvents="none"}),v.querySelector(".inline-other-form")?.remove();const k=g?.trim()?`${h.label}: ${g.trim()}`:h.label;W("user",k),L();try{const I=l.next(h.value??h.label,g);if(I){re.current?.(I,0,m);return}P.current?.(l,m)}catch(I){I?.validation_error&&(ct(I.message,m),z())}};y.onclick=async()=>{const g=String(h.label||"").trim().toLowerCase().replace(/[.…:]+$/g,"").trim(),k=String(h.value||"").trim().toLowerCase();if(!(["otro","otra","other","__other__"].includes(g)||["otro","otra","other","__other__"].includes(k))){await b();return}v.querySelector(".inline-other-form")?.remove();const R=document.createElement("form");R.className="inline-other-form";const U=document.createElement("input");U.type="text",U.placeholder="Escribe tu opción…",U.maxLength=300,U.setAttribute("aria-label","Escribe otra opción");const G=document.createElement("button");G.type="submit",G.textContent="Continuar";const Y=document.createElement("small");Y.textContent="Escribe una opción para continuar.",Y.hidden=!0,R.append(U,G,Y),R.onsubmit=async ge=>{ge.preventDefault();const N=U.value.trim();if(!N){Y.hidden=!1,U.focus();return}await b(N)},v.appendChild(R),U.focus(),A()},v.appendChild(y)}),u.appendChild(v)},[W,L,z,A]),pt=o.useCallback(()=>{if(!t.current||w.current)return;const n=document.createElement("div");n.className="msg bot error-server";const u=Be(e?.avatar,"msg-avatar",32),m=document.createElement("div");m.className="msg-content";const p=document.createElement("div");p.className="bubble bubble-server-error",p.innerHTML=`

Sin conexión al servidor

Intentando reconectar

`;const l=document.createElement("div");l.className="message-time",l.textContent=Ze(),m.append(p,l),n.append(u,m),t.current.appendChild(n),w.current=n,A();const v=p.querySelector(".retry-dots");let h=0;const y=setInterval(()=>{h=(h+1)%4,v&&(v.textContent=".".repeat(h))},500);return $.current=setInterval(async()=>{try{clearInterval(y),Ve(),w.current?.remove(),w.current=null,t.current&&(t.current.innerHTML=""),te("En línea"),de("connected");const b=Symbol("chatbot-reconnect");c.current=b,i.current=!1,d.current=null,await E.current?.(b)}catch{}},5e3),()=>{clearInterval(y)}},[e,A,Ve]),K=o.useCallback(n=>{const u=d.current;return rr(n||"",u?.variables||{},e?.name||"")},[e?.name]),$e=o.useCallback((n,u,m)=>{if(!n||u>50||!e||m!==c.current)return;const p=d.current;if(!p)return;const l=()=>{const h=p.getState();sessionStorage.setItem(`chatbot_node_${e.publicId}`,JSON.stringify(h)),qt(e.publicId,_.current,h),V(X(e.publicId,_.current))};(async()=>{if(m!==c.current){D();return}const h=n.typing_time&&n.typing_time>0;if(h&&(be(),A(),await new Promise(b=>setTimeout(b,n.typing_time*1e3)),m!==c.current)){D();return}const y=!h&&a.current!==null;if(n.node_type==="link"){const b=h||y?Le(K(n.content)):J(K(n.content));if(n.link_actions?.length&&dt(n.link_actions,b),n.end_conversation){l(),L(),Oe(e.publicId,_.current),P.current?.(p,m);return}const g=p._autoAdvanceFrom(n);g&&$e(g,u+1,m);return}if(n.node_type==="media"){(h||y)&&D();const b=Array.isArray(n.media)?n.media:[],g=!!String(n.content||"").trim(),k=b.some(R=>!!(R?.url&&String(R.url).trim()));if(g||k){const R=J("");if(R.classList.add("media-only"),R.style.minHeight="0",g){const G=document.createElement("div");G.className="media-caption",G.textContent=K(n.content),R.prepend(G),R.classList.remove("media-only")}!mt(b,R)&&!g&&R.closest(".msg.bot")?.remove()}if(n.end_conversation){l(),L(),Oe(e.publicId,_.current),P.current?.(p,m);return}if(l(),L(),await new Promise(R=>setTimeout(R,180)),m!==c.current)return;const I=p._autoAdvanceFrom(n);I?$e(I,u+1,m):p.completed&&P.current?.(p,m);return}if(n.node_type==="text"||n.node_type==="html"){if(n.content?h||y?Le(K(n.content)):J(K(n.content)):h&&D(),n.end_conversation){l(),L(),Oe(e.publicId,_.current),P.current?.(p,m);return}const b=p._autoAdvanceFrom(n);b&&$e(b,u+1,m);return}if(n.node_type==="options"&&n.options?.length||n.node_type==="policy"&&n.policy?.length){const b=n.content?h||y?Le(K(n.content)):J(K(n.content)):(()=>{(h||y)&&D();const g=J("");return g.classList.add("media-only"),g})();ze(n,b,m),l(),L();return}if(wt.includes(n.node_type||"")){let b=null;n.content?b=h||y?Le(K(n.content)):J(K(n.content)):h&&D();const g=Array.isArray(n.validation?.rules)?n.validation.rules:null;if(g!==null&&!g.some(I=>I?.type==="required")){const I=document.createElement("button");I.type="button",I.className="optional-answer-skip",I.textContent="Omitir por ahora",I.onclick=async()=>{if(!(m!==c.current||i.current)){i.current=!0,I.disabled=!0,W("user","Omitir"),L();try{const R=p.next("");R?re.current?.(R,0,m):await P.current?.(p,m)}finally{i.current=!1}}},b||(b=J(""),b.classList.add("media-only")),b.appendChild(I)}se(n.node_type||"question",String(n?.meta?.input_variant||"")),l(),z();return}n.end_conversation&&(l(),L(),Oe(e.publicId,_.current),P.current?.(p,m))})()},[e,be,D,Le,A,J,dt,mt,ze,L,z,se,K]),tt=o.useCallback(async(n,u)=>{if(!e||!d.current)return;const m=u??c.current;if(m!==c.current)return;const p=n??r.current?.value?.trim();if(p&&!i.current){i.current=!0,n===void 0&&(W("user",p),r.current&&(r.current.value="")),L();try{const l=d.current,v=l.next(p);if(v){re.current?.(v,0,m),i.current=!1;return}await P.current?.(l,m)}catch(l){l?.validation_error&&(ct(l.message,m),se(l.field||"question"),z())}i.current=!1}},[e,W,L,z,se]),We=o.useCallback(async n=>{if(!e)return null;const u=n??c.current,m=`chatbot_bundle_${e.publicId}`;try{const p=await fetch(`${e.apiBase}/api/public-chatbot/chatbot-conversation/${e.publicId}/bundle?_=${Date.now()}`,{cache:"no-store"});if(u!==c.current)return null;if(!p.ok)throw new Error("Bundle fetch failed");const l=await p.json(),v={chatbot_name:l.chatbot_name};l.nodes=l.nodes.map(h=>({...h,content:h.content?h.content.replace(/\{\{(\w+)\}\}/g,(y,b)=>v[b]??`{{${b}}}`):h.content})),x.current=l;try{sessionStorage.setItem(m,JSON.stringify(l))}catch{}return l}catch{try{const p=sessionStorage.getItem(m);if(!p)return null;const l=JSON.parse(p);return x.current=l,l}catch{return null}}},[e]),ht=o.useCallback(n=>{t.current&&(n.forEach(u=>{const m=document.createElement("div");if(m.className=`msg ${u.role}`,u.role==="bot"){const h=Be(e?.avatar,"msg-avatar",32);m.appendChild(h)}const p=document.createElement("div");p.className="msg-content";const l=document.createElement("div");l.className="bubble",u.html&&u.role==="bot"?l.innerHTML=u.html:l.textContent=u.text;const v=document.createElement("div");v.className="message-time",v.textContent=new Date(u.timestamp).toLocaleTimeString("es-MX",{hour:"2-digit",minute:"2-digit"}),p.append(l,v),m.appendChild(p),t.current.appendChild(m)}),A())},[e?.avatar,A]),ft=o.useCallback(async n=>{if(!e)return;const u=n??c.current;a.current=null,i.current=!1;const m=_.current||le();_.current=m,It(e.publicId);try{te("Conectando...");const p=await We(u);if(u!==c.current)return;if(!p){ke.current();return}be();const l=new gt(p);if(d.current=l,localStorage.removeItem(`chat_session_${e.publicId}`),te("En línea"),de("connected"),yt(e.publicId,m)){const b=X(e.publicId,m);D(),ht(b.messages),b.engineState&&(l.restoreState(b.engineState.nodeId,b.engineState.variables,b.engineState.history,b.engineState.currentBranchId,b.engineState.pendingReturnNodeId),sessionStorage.setItem(`chatbot_node_${e.publicId}`,JSON.stringify(b.engineState))),V(b);const g=l.getCurrentNode();if(g&&wt.includes(g.node_type||""))se(g.node_type||"question",String(g?.meta?.input_variant||"")),z();else if(g&&(g.node_type==="options"&&g.options?.length||g.node_type==="policy"&&g.policy?.length)){const k=document.createElement("div");k.className="bubble media-only";const I=document.createElement("div");I.className="msg bot";const R=Be(e.avatar,"msg-avatar",32),U=document.createElement("div");U.className="msg-content",U.appendChild(k),I.append(R,U),t.current?.appendChild(I),A(),ze(g,k,u),L()}else!g||l.completed?L():z();return}const h=Ht(e.publicId,m);V(h);const y=l.start();if(!y){D(),L();return}re.current?.(y,0,u)}catch{if(u!==c.current)return;D(),te("Error"),de("error"),ke.current()}},[e,D,L,z,We,be,se,A,ze,ht]),bt=o.useCallback(async(n,u)=>{if(e&&u===c.current){L(),Oe(e.publicId,_.current),V(X(e.publicId,_.current));try{const{history:m,variables:p,flow_id:l}=n.getPayload(),v=It(e.publicId),h=new Date().toISOString(),y=Math.max(0,Math.round((new Date(h).getTime()-new Date(v).getTime())/1e3)),b=await fetch(`${e.apiBase}/api/public-chatbot/chatbot-conversation/${e.publicId}/finish`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({history:m,variables:p,flow_id:l,origin_url:M.current.originUrl||oe(e.originUrl)||oe(e.originDomain),last_page_url:M.current.lastPageUrl||M.current.originUrl||oe(e.originUrl)||oe(e.originDomain),referrer_url:M.current.referrerUrl||typeof document<"u"&&document.referrer||null,visitor_id:le(),device:nr(),started_at:v,ended_at:h,duration_seconds:y})});if(u!==c.current)return;if(b.status===409){const k=await b.json();n.rollback(),W("bot",k.message,!0),se(k.field||"question"),z();return}const g=await b.json().catch(()=>({}));if(!b.ok)throw new Error(g?.message||"No se pudo confirmar el prospecto.");if(g?.conversion_eligible===!0&&g?.session_id){const k=String(g.session_id),I=`weblab_chatbot_lead_${k}`;let R=!1;try{R=sessionStorage.getItem(I)==="1"}catch{}if(!R){window.parent.postMessage({type:"WEBLAB_CHATBOT_LEAD",instanceId:e.publicId,eventId:k,conversationType:g.conversation_type||"General"},"*");try{sessionStorage.setItem(I,"1")}catch{}}}}catch{if(u!==c.current)return}}},[e,L,W,z,se]),Rt=o.useCallback(()=>{e&&Ue(n=>{const u=!n;return f.current=u,u&&(xe(!1),q(0),localStorage.removeItem(`chatbot_unread_${e.publicId}`),sessionStorage.removeItem(`chatbot_welcome_${e.publicId}`),window.parent.postMessage({type:"CHATBOT_WELCOME_SEEN",instanceId:e.publicId},"*")),u})},[e]),Tt=o.useCallback(()=>{f.current=!1,Ue(!1)},[]),rt=o.useCallback(async()=>{if(He)return;qe(!0);const n=Symbol("chatbot-restart");if(c.current=n,i.current=!1,Ve(),w.current?.remove(),w.current=null,D(),a.current=null,e){const u=_.current||le();localStorage.removeItem(`chat_session_${e.publicId}`),sessionStorage.removeItem(`chatbot_dom_${e.publicId}`),sessionStorage.removeItem(`chatbot_node_${e.publicId}`),sessionStorage.removeItem(`chatbot_bundle_${e.publicId}`),sessionStorage.removeItem(j??""),sessionStorage.removeItem(Ct(e.publicId)),Vt(e.publicId,u),sessionStorage.setItem(`chatbot_needs_start_${e.publicId}`,"1")}t.current&&(t.current.innerHTML=""),r.current&&(r.current.value=""),a.current=null,d.current=null,V(null),L(),te("Reiniciando…"),s.current=!1,et(!0),setTimeout(()=>qe(!1),100)},[e,L,Ve,D,j]),At=o.useCallback(()=>{e&&Wt(e.publicId,_.current,e.name)},[e]),Lt=o.useCallback(async n=>{if(!e)return!1;const u=_.current||le();return Ft(e.publicId,u,n)?(await rt(),!0):!1},[e,rt]),$t=o.useCallback(()=>{if(!e)return;const n=_.current||le();zt(e.publicId,n),V(null)},[e]);return o.useEffect(()=>{fe.current=We},[We]),o.useEffect(()=>{E.current=ft},[ft]),o.useEffect(()=>{P.current=bt},[bt]),o.useEffect(()=>{re.current=$e},[$e]),o.useEffect(()=>{Re.current=tt},[tt]),o.useEffect(()=>{ke.current=pt},[pt]),o.useEffect(()=>{Te.current=W},[W]),o.useEffect(()=>{Ae.current=L},[L]),e?{messagesRef:t,inputRef:r,isOpen:Xe,statusText:Ye,inputDisabled:Z,sendDisabled:je,welcomeVisible:he,viewerOpen:Ie,viewerUrl:Pe,viewerIsVideo:Ce,toggle:Rt,close:Tt,send:tt,restart:rt,closeViewer:kt,connectionStatus:Ge,unreadCount:ce,isRestarting:He,currentNodeType:d.current?.getCurrentNode()?.node_type??null,currentInputVariant:String(d.current?.getCurrentNode()?.meta?.input_variant||"")||null,activeSession:Qe,downloadHistory:At,importHistory:Lt,clearHistory:$t}:{messagesRef:t,inputRef:r,isOpen:!1,statusText:"",inputDisabled:!0,sendDisabled:!0,welcomeVisible:!1,viewerOpen:!1,viewerUrl:"",viewerIsVideo:!1,toggle:()=>{},close:()=>{},send:async()=>{},restart:async()=>{},closeViewer:()=>{},connectionStatus:"connecting",unreadCount:0,activeSession:null,downloadHistory:()=>{},importHistory:async()=>!1,clearHistory:()=>{}}}const xt=(...e)=>e.filter((t,r,s)=>!!t&&t.trim()!==""&&s.indexOf(t)===r).join(" ").trim();const ar=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const or=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,s)=>s?s.toUpperCase():r.toLowerCase());const Et=e=>{const t=or(e);return t.charAt(0).toUpperCase()+t.slice(1)};var ir={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const cr=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};const lr=o.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:a="",children:i,iconNode:f,...c},d)=>o.createElement("svg",{ref:d,...ir,width:t,height:t,stroke:e,strokeWidth:s?Number(r)*24/Number(t):r,className:xt("lucide",a),...!i&&!cr(c)&&{"aria-hidden":"true"},...c},[...f.map(([x,_])=>o.createElement(x,_)),...Array.isArray(i)?i:[i]]));const Ke=(e,t)=>{const r=o.forwardRef(({className:s,...a},i)=>o.createElement(lr,{ref:i,iconNode:t,className:xt(`lucide-${ar(Et(e))}`,`lucide-${e}`,s),...a}));return r.displayName=Et(e),r};const ur=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],dr=Ke("message-circle",ur);const mr=[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]],pr=Ke("refresh-ccw",mr);const hr=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],fr=Ke("send",hr);const br=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],gr=Ke("x",br),vr=e=>t=>{window.parent.postMessage({type:"CHATBOT_RESIZE",open:t,instanceId:e},"*")},yr=e=>(t,r)=>{window.parent.postMessage({type:"CHATBOT_WELCOME",visible:t,message:r,instanceId:e},"*")};function _r(e){const t=new TextDecoder().decode(Uint8Array.from(atob(decodeURIComponent(e)),s=>s.charCodeAt(0))),r=JSON.parse(t);if(!r.payload||!r.signature)throw new Error("Config malformada");return r}async function wr(e,t,r){const s=await fetch(`${e}/api/chatbot-integration/config/verify`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",body:JSON.stringify({payload:t,signature:r})});if(!s.ok){const i=(await s.json().catch(()=>({})))?.error??s.statusText;throw s.status===403?new Error(`AUTH_FAILED: ${i}`):s.status===400?new Error(`BAD_REQUEST: ${i}`):new Error(`SERVER_ERROR: ${i}`)}return s.json()}function Ir(e){return e instanceof Error?e.message.startsWith("AUTH_FAILED")?e.message.includes("expirada")||e.message.includes("Nonce")?"expired":"auth":e.message==="Failed to fetch"||e.message.includes("NetworkError")?"network":"unknown":"unknown"}const Sr=()=>/Android|iPhone|iPad|iPod/i.test(navigator.userAgent);function Er(){const[e,t]=o.useState(null),[r,s]=o.useState(null),[a,i]=o.useState(!0),f=o.useRef(!1),c=o.useRef(-1),d=o.useRef(()=>{}),x=o.useRef(()=>{});o.useEffect(()=>{e?.publicId&&(d.current=yr(e.publicId),x.current=vr(e.publicId))},[e?.publicId]),o.useEffect(()=>{if(!e?.publicId)return;const E=e.publicId,w=$=>{$.data?.instanceId&&$.data.instanceId!==E||($.data?.type==="CHATBOT_FAB_FREEZE"&&document.querySelector(".chat-fab")?.classList.add("no-transition"),$.data?.type==="CHATBOT_FAB_UNFREEZE"&&document.querySelector(".chat-fab")?.classList.remove("no-transition"))};return window.addEventListener("message",w),()=>window.removeEventListener("message",w)},[e?.publicId]),o.useEffect(()=>{if(f.current)return;f.current=!0,(async()=>{try{const w=window.location.hash.slice(1),P=new URLSearchParams(w).get("config");if(!P)throw new Error("Missing config");const{payload:re,signature:Re}=_r(P),Te="https://weblab-chatbot-backend-dxxn.onrender.com";try{const ne=JSON.parse(re);ne&&(t(ne),i(!1))}catch{}let Ae;try{Ae=await wr(Te,re,Re)}catch(ne){throw t(null),ne}t(Ae)}catch(w){s(Ir(w))}finally{i(!1)}})()},[]);const _=sr(e),M=o.useCallback(()=>{const E=_.messagesRef?.current;E&&requestAnimationFrame(()=>{E.scrollTop=E.scrollHeight})},[_.messagesRef]);o.useEffect(()=>{e?.publicId&&c.current!==_.unreadCount&&(c.current=_.unreadCount,window.parent.postMessage({type:"CHATBOT_UNREAD",count:_.unreadCount,instanceId:e.publicId},"*"))},[_.unreadCount,e?.publicId]),o.useEffect(()=>{if(e?.welcomeMessage)if(_.welcomeVisible){const E=setTimeout(()=>{d.current(!0,e.welcomeMessage??"")},100);return()=>clearTimeout(E)}else d.current(!1,"")},[_.welcomeVisible,e?.welcomeMessage]);const j=o.useRef(!1);o.useEffect(()=>{j.current=_.isOpen},[_.isOpen]),o.useEffect(()=>{const E=()=>{j.current&&(setTimeout(()=>M(),80),setTimeout(()=>M(),250))};window.visualViewport&&window.visualViewport.addEventListener("resize",E);const w=()=>{j.current&&M()};return window.addEventListener("resize",w),()=>{window.visualViewport&&window.visualViewport.removeEventListener("resize",E),window.removeEventListener("resize",w)}},[]),o.useEffect(()=>{if(!e?.publicId)return;const E=e.publicId,w=$=>{$.data?.instanceId&&$.data.instanceId!==E||$.data?.type==="CHATBOT_SCROLL_BOTTOM"&&(setTimeout(()=>M(),80),setTimeout(()=>M(),200))};return window.addEventListener("message",w),()=>window.removeEventListener("message",w)},[e?.publicId]),o.useEffect(()=>{if(!e?.publicId)return;const E=e.publicId,w=$=>{$.data?.instanceId&&$.data.instanceId!==E||$.data?.type==="CHATBOT_FORCE_CLOSE"&&_.isOpen&&(_.close(),d.current(!1,""))};return window.addEventListener("message",w),()=>window.removeEventListener("message",w)},[e?.publicId,_.isOpen,_.close]);const Xe=o.useCallback(()=>{setTimeout(()=>M(),300)},[M]);if(r||!e)return null;const{messagesRef:Ue,inputRef:we,isOpen:ie,statusText:Ge,inputDisabled:de,sendDisabled:ce,currentNodeType:q,currentInputVariant:Z,viewerOpen:me,viewerUrl:je,viewerIsVideo:pe,toggle:Ye,close:te,send:Ie,restart:Se,closeViewer:Pe,connectionStatus:Ee,isRestarting:Ce}=_,Ne=!!e.avatar,he=e.launcherMode||"avatar",xe=e.launcherImageUrl?.trim()||"",He=e.launcherAnimation||"float",qe=he==="image"&&!!xe,Qe=he==="avatar"&&Ne,V=()=>{x.current(!ie),Ye()},ke=()=>{x.current(!1),te()},fe=()=>{const E=we.current;E&&(E.style.height="auto",E.classList.remove("expanded"),E.classList.remove("multiline"))};return S.jsxs(S.Fragment,{children:[e&&S.jsxs("button",{className:`chat-fab launcher-animation-${He}${ie?" active":""}${a?" no-transition":""}`,onClick:V,"aria-label":"Abrir chat",style:a?{pointerEvents:"none"}:void 0,children:[qe?S.jsx("img",{className:"chat-launcher-custom",src:De(xe,108),alt:"",width:54,height:54,loading:"eager",decoding:"async"}):Qe?S.jsx("img",{className:"chat-avatar-fab",src:De(e.avatar,108),alt:e.name,width:54,height:54,loading:"eager",decoding:"async",onError:_t}):S.jsx(dr,{className:"chat-launcher-icon",size:28,strokeWidth:2.2}),!ie&&S.jsx("span",{className:`fab-connection-dot ${Ee}`})]}),S.jsxs("div",{style:a||!e?{visibility:"hidden",pointerEvents:"none"}:void 0,children:[S.jsx("div",{className:`chat-widget${ie?" open":""}`,children:S.jsxs("div",{className:"chat",children:[S.jsxs("header",{className:"chat-header",children:[Ne?S.jsx("img",{className:"chat-avatar",src:De(e.avatar,88),alt:e.name,width:44,height:44,loading:"lazy",decoding:"async",onError:_t}):S.jsx("span",{className:"chat-avatar-fallback",children:e.name?.charAt(0)??"C"}),S.jsxs("div",{className:"chat-header-info",children:[S.jsx("strong",{children:e.name}),S.jsx("div",{className:"chat-status",children:Ge})]}),S.jsxs("div",{className:"chat-actions",children:[S.jsx("button",{className:"chat-restart",onClick:Se,disabled:Ce,"aria-label":"Reiniciar conversación",style:Ce?{opacity:.4,cursor:"not-allowed"}:void 0,children:S.jsx(pr,{size:18,strokeWidth:2,style:Ce?{animation:"spin 1s linear infinite"}:void 0})}),S.jsx("button",{className:"chat-close",onClick:ke,"aria-label":"Cerrar chat",children:S.jsx(gr,{size:18,strokeWidth:2})})]})]}),S.jsx("main",{ref:Ue}),S.jsx("footer",{children:S.jsxs("div",{className:"input-row",children:[S.jsx("textarea",{id:"messageInput",ref:we,rows:Z==="long"?3:1,maxLength:Z==="short"?160:void 0,autoComplete:"off",inputMode:q==="phone"?"numeric":q==="email"?"email":"text",placeholder:e.inputPlaceholder??"Escribe tu mensaje...",disabled:de,onFocus:Xe,onInput:E=>{const w=E.currentTarget;if(q==="phone"&&(w.value=w.value.replace(/\D/g,"")),w.style.height="auto",w.style.height=Math.min(w.scrollHeight,120)+"px",q==="email"||q==="phone"||Z==="short"||Z==="date"||Z==="time"){w.style.height="auto",w.classList.remove("expanded"),w.classList.remove("multiline");return}else w.classList.remove("expanded");if(!w.value){w.style.height="auto",w.classList.remove("expanded"),w.classList.remove("multiline");return}w.scrollHeight>46||w.value.includes(` `)?w.classList.add("multiline"):w.classList.remove("multiline")},onKeyDown:E=>{const w=q==="email"||q==="phone"||Z==="short"||Z==="date"||Z==="time",$=Sr();if(E.key==="Enter"&&w){E.preventDefault(),ce||(Ie(),setTimeout(fe,0));return}E.key==="Enter"&&$||E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),ce||(Ie(),setTimeout(fe,0)))}}),S.jsx("button",{id:"sendBtn",onClick:()=>{Ie(),setTimeout(fe,0)},disabled:ce,"aria-label":"Enviar",children:S.jsx(fr,{size:18,strokeWidth:2})})]})}),e.showBranding!==!1&&S.jsx("div",{className:"chat-branding",children:S.jsxs("a",{href:"https://weblab.mx",target:"_blank",rel:"noopener noreferrer","aria-label":"Conoce WebLab.mx",children:[S.jsx("span",{children:"Potencia tu negocio con "}),S.jsx("strong",{children:"WEBLAB.mx"})]})})]})}),S.jsxs("div",{className:`chat-image-viewer${me?" open":""}`,onClick:E=>{E.target===E.currentTarget&&Pe()},children:[S.jsx("span",{className:"viewer-close",onClick:Pe,children:"✕"}),pe?S.jsx("video",{className:"viewer-video",src:je,controls:!0,playsInline:!0,autoPlay:!0}):S.jsx("img",{className:"viewer-img",src:je||void 0,alt:"preview"})]})]})]})}function Cr(){return S.jsx(Er,{})}jt.createRoot(document.getElementById("root")).render(S.jsx(Cr,{}));