1import{a as Te,b as O}from"./chunk-QI4LGXPX.js";import{a as Se}from"./chunk-ONCQ7SS3.js";import"./chunk-WB77Z5HL.js";import{a as fe}from"./chunk-6OWU35TE.js";import{o as ne}from"./chunk-7NVEQORR.js";import{$ as Ce,Ac as Ee,Bb as A,Cb as T,Da as L,Gb as I,Hb as p,I as j,Ia as d,N as E,Nb as Me,Ob as ye,Rb as F,S as w,T as z,Ub as m,Va as xe,Vb as P,Wb as Z,da as b,fa as ie,gc as Pe,ib as W,kb as _,l as _e,mb as C,na as oe,nb as pe,pb as N,qb as k,vb as c,vc as he,wb as l,xb as Y,yc as ge,zc as q}from"./chunk-LJUQDJMB.js";import{a as V,b as H}from"./chunk-C6Q5SG76.js";var re=class n{constructor(e,t,i,o,r,a,s){this.meta=e;this.emb=t;this.convs=i;this.fc1w=o;this.fc1b=r;this.fc2w=a;this.fc2b=s}static desdePesos(e,t){let i=e.arquitectura,o=new Float32Array(t),r=0,a=y=>{let D=o.subarray(r,r+y);return r+=y,D},s=a(i.vocab*i.emb),u=i.kernels.map(y=>({k:y,w:a(i.filtros*i.emb*y),b:a(i.filtros)})),f=a(i.oculta*i.filtros*i.kernels.length),h=a(i.oculta),v=a(e.intents.length*i.oculta),M=a(e.intents.length);if(r!==o.length)throw new Error(`Pesos corruptos: esperaba ${r} floats, el archivo trae ${o.length}`);return new n(e,s,u,f,h,v,M)}clasificar(e){let t=this.meta,i=t.arquitectura,o=t.maxLen,r=new Int32Array(o).fill(t.pad);for(let g=0;g<Math.min(e.length,o);g++){let x=t.charset.indexOf(e[g]);r[g]=x>=0?x+t.offset:t.unk}let a=i.emb,s=new Float32Array(o*a);for(let g=0;g<o;g++){let x=r[g]*a;s.set(this.emb.subarray(x,x+a),g*a)}let u=new Float32Array(i.filtros*this.convs.length),f=0;for(let g of this.convs){let x=g.k,G=Math.floor(x/2),$=o+2*G-(x-1);for(let K=0;K<i.filtros;K++){let le=0,De=K*a*x;for(let de=0;de<$;de++){let me=g.b[K];for(let ee=0;ee<x;ee++){let ue=de-G+ee;if(ue<0||ue>=o)continue;let qe=ue*a,$e=De+ee;for(let te=0;te<a;te++)me+=g.w[$e+te*x]*s[qe+te]}me>le&&(le=me)}u[f++]=le}}let h=i.oculta,v=u.length,M=new Float32Array(h);for(let g=0;g<h;g++){let x=this.fc1b[g],G=g*v;for(let $=0;$<v;$++)x+=this.fc1w[G+$]*u[$];M[g]=x>0?x:0}let y=t.intents.length,D=new Float32Array(y),ce=-1/0;for(let g=0;g<y;g++){let x=this.fc2b[g],G=g*h;for(let $=0;$<h;$++)x+=this.fc2w[G+$]*M[$];D[g]=x,x>ce&&(ce=x)}let be=0,J=0;for(let g=0;g<y;g++)D[g]=Math.exp(D[g]-ce),be+=D[g],D[g]>D[J]&&(J=g);return{intent:t.intents[J],confianza:D[J]/be}}};var ve={meta:"/assets/mesero/modelo-meta.10c4022865.json",pesos:"/assets/mesero/modelo-mesero-v1.10c4022865.pesos.bin"};var Oe={bunny:"brownie",browny:"brownie",brawnie:"brownie"},Ne={catalogo:"menu",catalogos:"menu"};function ke(n){return n.split(" ").map(e=>Oe[e]??Ne[e]??e).join(" ")}var we={un:1,una:1,uno:1,dos:2,tres:3,cuatro:4,cinco:5,seis:6,siete:7,ocho:8,nueve:9,diez:10,once:11,doce:12,docena:12,quince:15,veinte:20};function S(n){return n.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9 ]+/g," ").replace(/\s+/g," ").trim()}var R=class n{modelo=null;cargando=null;menu=null;get modeloListo(){return this.modelo!==null}usarMenu(e){this.menu=e}cargarModelo(){if(this.modelo)return Promise.resolve();if(this.cargando)return this.cargando;let e=(async()=>{let[t,i]=await Promise.all([fetch(ve.meta).then(o=>o.json()),fetch(ve.pesos).then(o=>o.arrayBuffer())]);this.modelo=re.desdePesos(t,i)})();return this.cargando=e.catch(t=>{throw this.cargando=null,t}),this.cargando}async entender(e){let t=ke(S(e)),i={intent:"fuera_de_tema",confianza:0,item:null,itemCandidatos:[],categoria:null,cantidad:this.extraerCantidad(t),texto:t};if(!t)return i;let o=this.intentPorRegla(t),r=this.matchearItem(t);if(i.item=r.mejor,i.itemCandidatos=r.candidatos,i.categoria=this.matchearCategoria(t),o)return i.intent=o,i.confianza=1,i;if(this.modelo){let{intent:a,confianza:s}=this.modelo.clasificar(t);i.intent=s>=this.modelo.meta.umbral?a:"fuera_de_tema",i.confianza=s,i.intent==="despedida"&&s<.75&&(i.intent="fuera_de_tema")}else i.intent=i.item?"agregar_item":i.categoria?"leer_categoria":"ayuda",i.confianza=.4;return i}intentPorRegla(e){return/^(si|sisi|si claro|claro|claro que si|dale|de una|ok|okey|vale|correcto|exacto|listo|perfecto|aja|va|simon|de acuerdo|esta bien|asi es|si senor|si senora|si por favor)$/.test(e)?"confirmar":/^(no|nono|no gracias|nel|nop|negativo|mejor no|para nada|no senor|no senora|ese no|asi no)$/.test(e)?"negar":/^(repite|otra vez|como|como dijo|que dijiste|no te escuche|no escuche)$/.test(e)?"repetir":/^(atras|volver|regresa|menu principal|devuelvete)$/.test(e)?"volver":/^(ayuda|no entiendo|que hago)$/.test(e)?"ayuda":/^(gracias|muchas gracias|chao|adios|hasta luego)$/.test(e)?"despedida":null}extraerCantidad(e){let t=e.match(/\b(\d{1,2})\b/);if(t){let i=+t[1];if(i>=1&&i<=50)return i}for(let i of e.split(" "))if(i in we)return we[i];return/media docena/.test(e)?6:null}static singular(e){return e.length>4&&e.endsWith("es")?e.slice(0,-2):e.length>3&&e.endsWith("s")?e.slice(0,-1):e}matchearItem(e){let t=n.singular,i=e.split(" ").filter(s=>s.length>2).map(t);if(!this.menu||i.length===0)return{mejor:null,candidatos:[]};let o=[];for(let s of this.menu.categories??[])for(let u of s.items??[]){let f=S(u.name),h=f.split(" ").filter(
1Boolean).map(t),v=0;for(let M of i)h.some(y=>y===M)||h.some(y=>M.length>=4&&y.startsWith(M))?v+=2:h.some(y=>y.startsWith(M)||M.startsWith(y))&&(v+=1);e.includes(f)&&(v+=4),v>0&&o.push({item:u,score:v})}if(o.length===0)return{mejor:null,candidatos:[]};o.sort((s,u)=>u.score-s.score);let r=o[0];if(r.score<2)return{mejor:null,candidatos:[]};let a=o.filter(s=>s.score===r.score);return a.length>1&&a.length<=4?{mejor:null,candidatos:a.map(s=>s.item)}:{mejor:r.item,candidatos:[]}}matchearCategoria(e){if(!this.menu)return null;let t=null,i=0;for(let o of this.menu.categories??[]){let r=S(o.name);if(!r)continue;let a=0;if(e.includes(r))a=r.length+2;else{let s=n.singular,u=e.split(" ").map(s),f=r.split(" ").filter(v=>v.length>2).map(s),h=0;for(let v of f)u.some(M=>M===v||M.length>3&&(v.startsWith(M)||M.startsWith(v)))&&(a+=v.length,h++);f.length>1&&h<Math.ceil(f.length/2)&&(a=0)}a>i&&(i=a,t=o)}return i>=4?t:null}extraerDigitos(e){let t=S(e),i={cero:"0",uno:"1",una:"1",un:"1",dos:"2",tres:"3",cuatro:"4",cinco:"5",seis:"6",siete:"7",ocho:"8",nueve:"9"},o="";for(let r of t.split(" "))/^\d+$/.test(r)?o+=r:r in i&&(o+=i[r]);return o}static \u0275fac=function(t){return new(t||n)};static \u0275prov=j({token:n,factory:n.\u0275fac})};var B=class n{isBrowser=ne(E(oe));conversationId="";businessId="";businessName="";sourceModule="menu_digital";startedAt="";turnos=[];datosPersonales=[];sttSoportado=!1;modeloCargado=!1;itemsAgregados=0;pedidoEnviado=!1;totalPedido;moneda;intents={};vias={voz:0,chip:0,teclado:0};alOcultar=()=>{document.visibilityState==="hidden"&&this.enviar()};iniciar(e){!this.isBrowser||!fe.meseroVozApiUrl||(this.conversationId=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`conv-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,this.businessId=e.businessId,this.businessName=e.businessName,this.sourceModule=e.sourceModule,this.startedAt=new Date().toISOString(),document.addEventListener("visibilitychange",this.alOcultar))}registrarDatoPersonal(e){let t=(e??"").trim();t.length>=2&&this.datosPersonales.push(t)}turnoMesero(e){this.turnos.push({rol:"mesero",texto:e})}turnoCliente(e,t){this.turnos.push({rol:"cliente",texto:e,via:t}),this.vias[t]++}intentDetectado(e,t){for(let i=this.turnos.length-1;i>=0;i--)if(this.turnos[i].rol==="cliente"){this.turnos[i].intent=e,this.turnos[i].confianza=+t.toFixed(3);break}this.intents[e]=(this.intents[e]??0)+1}marcarResultadoTurno(e){for(let t=this.turnos.length-1;t>=0;t--)if(this.turnos[t].rol==="cliente"){this.turnos[t].resultado=e;break}}marcarStt(e){this.sttSoportado=e}marcarModeloCargado(){this.modeloCargado=!0}marcarItemAgregado(e){this.itemsAgregados+=e}marcarPedidoEnviado(e,t){this.pedidoEnviado=!0,this.totalPedido=e,this.moneda=t,this.enviar()}anonimizar(e){let t=e;for(let i of this.datosPersonales){let o=new Set([i,S(i)]);/^\d+$/.test(i.replace(/\D/g,""))&&i.replace(/\D/g,"").length>=5&&(o.add(i.replace(/\D/g,"").split("").join(", ")),o.add(i.replace(/\D/g,"")));for(let r of o){if(r.length<2)continue;let a,s=()=>t.toLowerCase();for(;(a=s().indexOf(r.toLowerCase()))>=0;)t=t.slice(0,a)+"[dato personal]"+t.slice(a+r.length)}}return t.replace(/\d(?:[\s.,-]?\d){6,}/g,"[###]").slice(0,380)}enviar(){if(!(!this.isBrowser||!this.conversationId||this.turnos.length===0))try{let e=JSON.stringify({conversationId:this.conversationId,businessName:this.businessName,sourceModule:this.sourceModule,startedAt:this.startedAt,endedAt:new Date().toISOString(),turnos:this.turnos.slice(0,150).map(o=>H(V({},o),{texto:this.anonimizar(o.texto)})),resultado:this.pedidoEnviado?"completado":"abandonado",metricas:H(V(V({sttSoportado:this.sttSoportado,turnosVoz:this.vias.voz,turnosChip:this.vias.chip,turnosTeclado:this.vias.teclado,modeloCargado:this.modeloCargado,itemsAgregados:this.itemsAgregados,pedidoEnviado:this.pedidoEnviado},this.totalPedido!=null?{totalPedido:this.totalPedido}:{}),this.moneda?{moneda:this.moneda}:{}),{intents:this.intents,duracionSegundos:Math.max(0,Math.round((Date.now()-Date.parse(this.startedAt))/1e3))})}),t=`${fe.meseroVozApiUrl}/api/modules/${encodeURIComponent(this.businessId)}/mesero-voz/conversaciones`;"sendBeacon"in navigator&&navigator.sendBeacon(t,new Blob([e],{type:"text/plain;charset=UTF-8"}))||fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}
1).catch(()=>{})}catch{}}finalizar(){this.isBrowser&&(document.removeEventListener("visibilitychange",this.alOcultar),this.enviar())}static \u0275fac=function(t){return new(t||n)};static \u0275prov=j({token:n,factory:n.\u0275fac})};var U=class n{platformId=E(oe);zone=E(Ce);isBrowser=ne(this.platformId);sttSoportado=b(!1);ttsSoportado=b(!1);escuchando=b(!1);hablando=b(!1);transcripcionParcial=b("");rate=b(.95);ultimoError=b(null);reconocimiento=null;vozElegida=null;lang="es-419";resolverEscucha=null;desbloqueado=!1;iniciar(e){if(!this.isBrowser)return;let t=window,i=t.SpeechRecognition??t.webkitSpeechRecognition;this.sttSoportado.set(!!i),this.ttsSoportado.set("speechSynthesis"in window),this.lang=this.langPorPais(e),this.ttsSoportado()&&(this.elegirVoz(),window.speechSynthesis.onvoiceschanged=()=>this.elegirVoz())}langPorPais(e){let t=(e??"").toUpperCase();return{CO:"es-CO",VE:"es-VE",MX:"es-MX",AR:"es-AR",CL:"es-CL",PE:"es-PE",EC:"es-EC",US:"es-US",ES:"es-ES",PA:"es-PA",DO:"es-DO",PY:"es-PY",BO:"es-BO",UY:"es-UY",GT:"es-GT",CR:"es-CR",HN:"es-HN",NI:"es-NI",SV:"es-SV",PR:"es-PR"}[t]??"es-419"}elegirVoz(){let e=window.speechSynthesis.getVoices();if(!e.length)return;let t=e.filter(i=>i.lang.toLowerCase().startsWith("es"));this.vozElegida=t.find(i=>i.lang.toLowerCase()===this.lang.toLowerCase())??t.find(i=>i.default)??t[0]??null}desbloquear(){if(!(!this.isBrowser||this.desbloqueado)&&(this.desbloqueado=!0,this.ttsSoportado())){let e=new SpeechSynthesisUtterance(" ");e.volume=0,window.speechSynthesis.speak(e)}}precalentarMotor(){if(!this.isBrowser||!this.ttsSoportado())return;let e=new SpeechSynthesisUtterance(" ");e.volume=0,window.speechSynthesis.speak(e)}precalentarMicrofono(){!this.isBrowser||!this.sttSoportado()||navigator.mediaDevices?.getUserMedia({audio:!0}).then(e=>e.getTracks().forEach(t=>t.stop())).catch(()=>{})}hablar(e){return!this.isBrowser||!this.ttsSoportado()||!e?Promise.resolve():new Promise(t=>{(window.speechSynthesis.speaking||window.speechSynthesis.pending)&&window.speechSynthesis.cancel(),window.speechSynthesis.resume();let i=new SpeechSynthesisUtterance(e);i.lang=this.lang,this.vozElegida&&(i.voice=this.vozElegida),i.rate=this.rate();let o=!1,r=setInterval(()=>{window.speechSynthesis.pause(),window.speechSynthesis.resume()},8e3),a=()=>{o||(o=!0,clearTimeout(s),clearInterval(r),this.zone.run(()=>this.hablando.set(!1)),t())},s=setTimeout(a,Math.min(3e4,(2e3+e.length*110)/this.rate()));i.onend=a,i.onerror=a,this.hablando.set(!0),window.speechSynthesis.speak(i)})}callar(){this.isBrowser&&(this.ttsSoportado()&&window.speechSynthesis.cancel(),this.hablando.set(!1))}masDespacio(){this.rate.set(Math.max(.7,+(this.rate()-.12).toFixed(2)))}escuchar(){if(!this.isBrowser||!this.sttSoportado())return Promise.resolve(null);this.detenerEscucha(),this.callar();let e=window,t=e.SpeechRecognition??e.webkitSpeechRecognition,i=new t;i.lang=this.lang,i.continuous=!0,i.interimResults=!0,i.maxAlternatives=1,this.reconocimiento=i,this.escuchando.set(!0),this.transcripcionParcial.set(""),this.ultimoError.set(null);let o=3500;return new Promise(r=>{let a="",s="";this.resolverEscucha=r;let u=null,f=()=>{u&&clearTimeout(u),u=setTimeout(()=>{try{i.stop()}catch{}},o)},h=setTimeout(()=>{this.ultimoError.set("watchdog-stt");try{i.abort()}catch{}this.terminarEscucha((a+" "+s).trim()||null)},2e4);i.onresult=v=>{this.zone.run(()=>{for(let M=v.resultIndex;M<v.results.length;M++){let y=v.results[M],D=y[0]?.transcript??"";y.isFinal?(a=(a+" "+D).trim(),s=""):s=D}this.transcripcionParcial.set((a+" "+s).trim()),f()})},i.onerror=v=>{this.zone.run(()=>{clearTimeout(h),u&&clearTimeout(u),this.ultimoError.set(v.error),this.terminarEscucha((a+" "+s).trim()||null)})},i.onend=()=>{this.zone.run(()=>{clearTimeout(h),u&&clearTimeout(u),this.terminarEscucha((a+" "+s).trim()||null)})};try{i.start(),f()}catch{clearTimeout(h),this.ultimoError.set("no-arranco"),this.terminarEscucha(null)}})}detenerEscucha(){if(this.reconocimiento){let e=this.reconocimiento;e.onresult=null,e.onend=null,e.onerror=null;try{e.abort()}catch{}this.reconocimiento=null}if(this.resolverEscucha){let e=this.resolverEscucha;this.resolverEscucha=null,e(null)}this.escuchando.set(!1)}terminarEscucha(e){this.reconocimiento=null,this.escuchando.set(!1);let t=this.resolverEscucha;this.resolverEscucha=null,t?.(e?.trim()||null)}destruir(){this.detenerEscucha(),this.callar(),this.isBrowser&&this.ttsSoportado()&&(window.speechSynthesis.onvoiceschanged=null)}static \u0275fac=function(t){return new(t||n)};static \u0275prov=j({token:n,factory:n.\u0275fac})};var Ae={USD:{uno:"d\xF3lar",muchos:"d\xF3lares"},EUR:{uno:"euro",muchos:"euros"},COP:{uno:"peso",muchos:"pesos"},MXN:{uno:"peso",muchos:"pesos"},ARS:{uno:"peso",muchos:"pesos"},CLP:{uno:"peso",muchos:"pesos"},UYU:{uno:"peso",muchos:"pesos"},DOP:{uno:"peso",muchos:"pesos"},CUP:{uno:"peso",muchos:"pesos"},PEN:{uno:"sol",muchos:"soles"},BRL:{uno:"real",muchos:"reales"},VES:{uno:"bol\xEDvar",muchos:"bol\xEDvares"},PYG:{uno:"guaran\xED",muchos:"guaran\xEDes"},BOB:{uno:"boliviano",muchos:"bolivianos"},GTQ:{uno:"quetzal",muchos:"quetzales"},HNL:{uno:"lempira",muchos:"lempiras"},NIO:{uno:"c\xF3rdoba",muchos:"c\xF3rdobas"},CRC:{uno:"col\xF3n",muchos:"colones"},PAB:{uno:"balboa",muchos:"balboas"}};function Q(n){let e=(t,i,o)=>{let r=parseInt(t.replace(/,/g,""),10),a=parseInt(i,10),s=Ae[o]??{uno:o,muchos:o},u=`${r} ${r===1&&a===0?s.uno:s.muchos}`;return a>0&&(u+=` con ${a} centavo${a===1?"":"s"}`),u};return n.replace(/\$([\d,]+)\.(\d{2})\b/g,(t,i,o)=>e(i,o,"USD")).replace(/\b([A-Z]{3}) ([\d,]+)\.(\d{2})\b/g,(t,i,o,r)=>e(o,r,i))}var X=class n{nlu=E(R);voz=E(U);telemetria=E(B);cart=E(Te);cms=E(Se);mensajes=b([]);chips=b([]);ocupado=b(!1);estado=b("inicio");pedidoCreado=b(null);requiereCheckoutVisual=b(!1);modoVoz=b(!0);visual=b(null);silenciado=b(!1);ctx;ultimoDicho="";activo=!0;intentosVaciosSeguidos=0;micBloqueado=!1;categoriaActual=null;offsetLectura=0;candidatos=[];propositoDesambiguacion="agregar";
1cantidadPendiente=1;itemPendiente=null;gruposPendientes=[];variantesElegidas=[];modificadoresElegidos=[];ultimoItemMencionado=null;coTipo="pickup";coNombre="";coTelefono="";coDireccion="";coZonaId=null;coZonaNombre="";coMesa=null;get moneda(){return this.ctx?.ordering?.currency??"USD"}get esTienda(){return this.ctx?.esCatalogo??!1}get agenteNombre(){return this.esTienda?"Asesor Pana":"Mesero Pana"}get agenteSustantivo(){return this.esTienda?"asesor":"mesero"}get cosaGrande(){return this.esTienda?"el cat\xE1logo":"el men\xFA"}get itemSingular(){return this.esTienda?"producto":"plato"}get antojoAlguno(){return this.esTienda?"te interes\xF3 alguno":"te antoj\xF3 alguno"}get antojaAlguno(){return this.esTienda?"te interesa alguno":"te antoja alguno"}iniciar(e){this.ctx=e,this.activo=!0,this.intentosVaciosSeguidos=0,this.micBloqueado=!1,this.visual.set({tipo:"negocio",titulo:e.businessName,items:[]}),this.nlu.usarMenu(e.menu),this.telemetria.iniciar({businessId:e.businessId,businessName:e.businessName,sourceModule:e.sourceModule}),this.nlu.cargarModelo().then(()=>this.telemetria.marcarModeloCargado(),()=>{});let t=`\xA1Hola! Soy el ${this.agenteNombre} de ${e.businessName}. Puedo leerte ${this.cosaGrande}, contarte de cada ${this.itemSingular} y tomarte el pedido. `;e.acceptingOrders||(t+=e.closedLabel?`Ahora mismo el negocio est\xE1 cerrado \u2014 ${e.closedLabel} \u2014 pero con gusto te leo ${this.cosaGrande}. `:`Ahora mismo no estamos recibiendo pedidos, pero con gusto te leo ${this.cosaGrande}. `),t+="\xBFQu\xE9 deseas hacer?",this.estado.set("inicio"),this.decir(t,this.chipsInicio()).then(()=>this.autoescuchar())}detener(){this.activo=!1,this.voz.destruir(),this.telemetria.finalizar()}async procesar(e,t="teclado"){let i=(e??"").trim();if(console.log("[procesar] texto=",i,"ocupado=",this.ocupado(),"estado=",this.estado()),!(!i||this.ocupado())){this.mensajes.update(o=>[...o,{rol:"cliente",texto:i}]),this.telemetria.turnoCliente(i,t),this.ocupado.set(!0);try{await this.responder(i)}finally{this.ocupado.set(!1)}this.autoescuchar()}}async escucharTurno(){if(console.log("[escucharTurno] entrada ocupado=",this.ocupado(),"escuchando=",this.voz.escuchando()),this.ocupado()||this.voz.escuchando()){console.log("[escucharTurno] guard -> detenerEscucha + return"),this.voz.detenerEscucha();return}let e=await this.voz.escuchar();if(console.log("[escucharTurno] texto recibido=",e),e){this.intentosVaciosSeguidos=0,this.micBloqueado=!1,await this.procesar(e,"voz");return}if(!this.modoVoz()||!this.activo)return;let t=this.voz.ultimoError();if(t==="not-allowed"||t==="audio-capture"||t==="service-not-allowed"||t==="no-arranco"){this.micBloqueado=!0,await this.decir("No tengo acceso a tu micr\xF3fono. Revisa los permisos del navegador, o usa los botones para seguir.",this.chips());return}if(this.intentosVaciosSeguidos++,this.intentosVaciosSeguidos>=3){this.intentosVaciosSeguidos=0;let i="Disculpa, no entend\xED. \xBFPodr\xEDas repetir eso?";await this.decir(this.ultimoDicho?`${i} ${this.ultimoDicho}`:i,this.chips())}this.autoescuchar()}establecerModoVoz(e){this.modoVoz.set(e),e&&this.autoescuchar()}alternarSilencio(){this.silenciado.update(e=>!e),this.silenciado()?this.voz.detenerEscucha():this.autoescuchar()}autoescuchar(){!this.activo||!this.modoVoz()||this.micBloqueado||this.silenciado()||this.estado()!=="cerrado"&&this.voz.sttSoportado()&&this.escucharTurno()}async responder(e){let t=this.estado();if(t==="co_nombre")return this.capturarNombre(e);if(t==="co_telefono")return this.capturarTelefono(e);if(t==="co_confirmar_telefono")return this.confirmarTelefono(e);if(t==="co_direccion")return this.capturarDireccion(e);if(t==="co_mesa")return this.capturarMesa(e);let i=await this.nlu.entender(e);switch(i.intent==="fuera_de_tema"&&(i.item?i.intent="describir_plato":i.categoria?i.intent="leer_categoria":i.itemCandidatos.length&&(i.intent="describir_plato")),this.telemetria.intentDetectado(i.intent,i.confianza),this.telemetria.marcarResultadoTurno("resuelto"),i.intent){case"repetir":return this.telemetria.marcarResultadoTurno("corregido"),this.decir(this.ultimoDicho||"\xBFEn qu\xE9 te ayudo?",this.chips());
1case"mas_despacio":return this.voz.masDespacio(),this.decir("Claro, voy m\xE1s despacio. "+this.ultimoDicho,this.chips());case"ayuda":return this.ayudar();case"cancelar":return this.cancelar()}switch(t){case"desambiguar":return this.resolverDesambiguacion(i);case"variantes":return this.resolverVariante(i);case"co_tipo":return this.resolverTipo(i);case"co_zona":return this.resolverZona(i);case"co_confirmar":return this.resolverConfirmacionFinal(i);case"exito":case"cerrado":return i.intent==="despedida"?this.despedir():(this.estado.set("inicio"),this.responder(e));case"ofrecido":if(i.intent==="confirmar"&&this.ultimoItemMencionado)return this.prepararAgregado(this.ultimoItemMencionado,i.cantidad??1);if(i.intent==="negar")return this.estado.set("inicio"),this.decir("Est\xE1 bien. \xBFTe leo algo m\xE1s o quieres ordenar otra cosa?",this.chipsInicio());this.estado.set("inicio");break}switch(i.intent){case"despedida":return this.despedir();case"ver_pedido":return this.leerPedido();case"volver":return this.volverAlInicio();case"conocer_menu":return this.leerCategorias();
1case"recomendacion":return this.recomendar();case"preguntas_dieta":return this.responderDieta(i);case"quitar_item":return this.quitarItem(i)}switch(i.intent){case"saludo":return this.decir(`\xA1Hola! Dime, \xBFte leo ${this.cosaGrande} o quieres pedir algo?`,this.chipsInicio());case"leer_categoria":return this.nombraItemEspecifico(i)?this.describirPlato(i):i.categoria?this.leerCategoria(i.categoria):this.leerCategorias();case"describir_plato":return this.describirPlato(i);case"preguntar_precio":return this.decirPrecio(i);case"agregar_item":return this.agregarItem(i);case"cambiar_cantidad":return this.cambiarCantidad(i);case"terminar_pedido":return this.iniciarCheckout();case"confirmar":return t==="confirmar_agregado"?this.iniciarCheckout():t==="navegando"?this.seguirLeyendo():this.decir("Perfecto. \xBFQu\xE9 deseas?",this.chipsInicio());case"negar":return t==="confirmar_agregado"?(this.estado.set("inicio"),this.decir("Est\xE1 bien. \xBFTe leo algo m\xE1s o seguimos con el pedido?",this.chipsInicio())):this.decir("Est\xE1 bien. \xBFEn qu\xE9 m\xE1s te ayudo?",this.chipsInicio());default:return this.decir(`Disculpa, de eso no s\xE9 \u2014 soy el ${this.agenteSustantivo} y solo manejo ${this.cosaGrande} y tu pedido. \xBFTe leo ${this.cosaGrande} o quieres ordenar algo?`,this.chipsInicio())}}categorias(){return(this.ctx.menu?.categories??[]).filter(e=>(e.items?.length??0)>0)}leerCategorias(){let e=this.categorias();if(e.length===0)return this.decir("Este negocio a\xFAn no tiene productos publicados.",this.chipsInicio());this.estado.set("categorias");let t=e.map(a=>a.name),i=`Tenemos ${e.length===1?"una secci\xF3n":e.length+" secciones"}: `,o="\xBFCu\xE1l te leo?",r=`${i}${this.enumerar(t)}. ${o}`;return this.decirEnumeracion(r,e.slice(0,8).map(a=>({etiqueta:a.name,valor:a.name})),e.map(a=>({texto:a.name,visual:this.visualCategoria(a)})),i,o)}leerCategoria(e){return this.categoriaActual=e,this.offsetLectura=0,this.estado.set("navegando"),this.leerLote()}seguirLeyendo(){return this.categoriaActual?this.leerLote():this.leerCategorias()}leerLote(){let e=this.categoriaActual,t=(e.items??[]).filter(h=>h.available!==!1),i=t.slice(this.offsetLectura,this.offsetLectura+4);if(i.length===0)return this.estado.set("inicio"),this.decir(`Eso es todo en ${e.name}. \xBFTe leo otra secci\xF3n o quieres pedir algo?`,this.chipsInicio());this.offsetLectura+=i.length;let o=t.length-this.offsetLectura,r=i.map(h=>this.itemConPrecio(h)),a=`En ${e.name}: `,s=o>1?`Quedan ${o} m\xE1s. \xBFSigo leyendo, o ${this.antojoAlguno}?`:o===1?`Queda 1 m\xE1s. \xBFSigo leyendo, o ${this.antojoAlguno}?`:`\xBF${this.antojoAlguno}?`,u=`${a}${this.enumerar(r)}. ${s}`,f=i.slice(0,3).map(h=>({etiqueta:`Pedir ${h.name}`,valor:`quiero ${h.name}`}));return o>0&&f.push({etiqueta:"Sigue leyendo",valor:"sigue leyendo"}),f.push({etiqueta:"Otras secciones",valor:"que categorias hay"}),this.decirEnumeracion(u,f,i.map(h=>({texto:this.itemConPrecio(h),visual:this.visualProducto(h)})),a,s)}describirPlato(e){let t=e.item??(this.pareceReferirseAlUltimo(e.texto)?this.ultimoItemMencionado:null);if(!t)return e.itemCandidatos.length?this.desambiguar(e.itemCandidatos,e.cantidad??1,"describir"):e.categoria?this.leerCategoria(e.categoria):this.decir(`\xBFDe cu\xE1l ${this.itemSingular} quieres que te cuente? Dime el nombre.`,this.chips());this.ultimoItemMencionado=t,this.estado.set("ofrecido");let i=t.name+". ";t.description&&(i+=t.description+". "),this.precioOculto(t)||(i+=`Cuesta ${this.precioHablado(t)}. `);let o=[...t.tags??[],...this.badgesHablados(t)];return o.length&&(i+=`Es ${this.enumerar(o)}. `),i+="\xBFTe lo agrego al pedido?",this.decirVisual(i,[{etiqueta:`S\xED, pide ${t.name}`,valor:`quiero ${t.name}`},{etiqueta:"No, gracias",valor:"no"}],this.visualProducto(t))}decirPrecio(e){let t=e.item??(this.pareceReferirseAlUltimo(e.texto)?this.ultimoItemMencionado:null);return t?(this.ultimoItemMencionado=t,this.estado.set("ofrecido"),this.precioOculto(t)?this.decirVisual(`El precio de ${t.name} te lo cotiza el negocio al confirmar el pedido. \xBFTe lo agrego?`,[{etiqueta:`Pedir ${t.name}`,valor:`quiero ${t.name}`}],this.visualProducto(t)):this.decirVisual(`${t.name} cuesta ${this.precioHablado(t)}. \xBFTe lo agrego al pedido?`,[{etiqueta:"S\xED, agr\xE9galo",valor:`quiero ${t.name}`},{etiqueta:"No, gracias",valor:"no"}],this.visualProducto(t))):e.itemCandidatos.length?this.desambiguar(e.itemCandidatos,e.cantidad??1,"precio"):this.decir(`\xBFDe cu\xE1l ${this.itemSingular} quieres saber el precio?`,this.chips())}
1recomendar(){let e=[];for(let s of this.categorias())for(let u of s.items??[])u.available!==!1&&e.push(u);if(!e.length)return this.decir("A\xFAn no hay productos publicados.",this.chipsInicio());let t=e.filter(s=>s.badges?.includes("popular")),i=(t.length?t:e).slice(0,3),o=i.map(s=>this.itemConPrecio(s));this.ultimoItemMencionado=i[0];let r="Te recomiendo ",a=`\xBF${this.antojaAlguno}?`;return this.decirEnumeracion(`${r}${this.enumerar(o)}. ${a}`,i.map(s=>({etiqueta:`Pedir ${s.name}`,valor:`quiero ${s.name}`})),i.map(s=>({texto:this.itemConPrecio(s),visual:this.visualProducto(s)})),r,a)}responderDieta(e){let t=e.texto,i=[];/vegan/.test(t)&&i.push({badge:"vegan",etiqueta:"veganos"}),/vegetarian|sin carne/.test(t)&&i.push({badge:"vegan",etiqueta:"vegetarianos"}),/gluten|celiac/.test(t)&&i.push({badge:"gluten-free",etiqueta:"sin gluten"}),/picante/.test(t)&&i.push({badge:"spicy",etiqueta:"picantes"});let o=[];for(let a of this.categorias())for(let s of a.items??[])s.available!==!1&&o.push(s);let r=o.filter(a=>{let s=(a.tags??[]).map(f=>S(f)),u=a.badges??[];return i.some(f=>u.includes(f.badge)||s.some(h=>h.includes(S(f.etiqueta))))});if(i.length&&r.length){let a=r.slice(0,4),s=a.map(h=>this.itemConPrecio(h)),u="Tenemos ",f="\xBFTe leo m\xE1s o te agrego alguno?";return this.decirEnumeracion(`${u}${this.enumerar(s)}. ${f}`,r.slice(0,3).map(h=>({etiqueta:`Pedir ${h.name}`,valor:`quiero ${h.name}`})),a.map(h=>({texto:this.itemConPrecio(h),visual:this.visualProducto(h)})),u,f)}return this.decir(`No tengo esa informaci\xF3n marcada en ${this.cosaGrande}. Si tienes alguna alergia, te sugiero confirmarla directamente con el negocio al recibir tu pedido. \xBFTe leo ${this.cosaGrande}?`,this.chipsInicio())}agregarItem(e){let t=e.cantidad??1;return e.item?this.prepararAgregado(e.item,t):e.itemCandidatos.length?this.desambiguar(e.itemCandidatos,t,"agregar"):e.categoria?this.ofrecerCategoriaParaAgregar(e.categoria,t):(this.esRepeticion(e.texto)||this.tienePronombreDemostrativo(e.texto))&&this.ultimoItemMencionado?this.prepararAgregado(this.ultimoItemMencionado,t):this.ctx.acceptingOrders?this.decir(`\xBFCu\xE1l ${this.itemSingular} te agrego? Dime el nombre, o te leo ${this.cosaGrande} para escoger.`,this.chipsInicio()):this.decir(this.ctx.closedLabel?`Ahora mismo el negocio est\xE1 cerrado \u2014 ${n.sinPuntoFinal(this.ctx.closedLabel)} \u2014 as\xED que no puedo tomarte pedidos, pero con gusto te leo ${this.cosaGrande} o te recomiendo algo.`:`Ahora mismo no estamos recibiendo pedidos, pero con gusto te leo ${this.cosaGrande} o te recomiendo algo.`,this.chipsInicio())}esRepeticion(e){return/^(otro|otra|otro mas|otra mas|uno mas|una mas|lo mismo|el mismo|la misma|dame otro|dame otra|quiero otro|quiero otra|igual|el de siempre|lo de siempre)$/.test(e)}pareceReferirseAlUltimo(e){return this.tienePronombreDemostrativo(e)?!0:e.split(" ").filter(Boolean).length<=2}tienePronombreDemostrativo(e){return/\b(eso|ese|esa|esos|esas|esto|esta|estos|estas|este)\b/.test(e)}ofrecerCategoriaParaAgregar(e,t){let i=(e.items??[]).filter(o=>o.available!==!1);return i.length?this.desambiguar(i.slice(0,6),t,"agregar",`En ${e.name}
1 tenemos: `):this.decir(`Por ahora no tengo nada disponible en ${e.name}. \xBFTe leo otra secci\xF3n?`,this.chipsInicio())}prepararAgregado(e,t){if(!this.ctx.acceptingOrders){this.ultimoItemMencionado=e;let i=this.ctx.closedLabel?` \u2014 ${n.sinPuntoFinal(this.ctx.closedLabel)} \u2014`:"";return this.decirVisual(`\xA1Buena elecci\xF3n! Pero ahora mismo el negocio est\xE1 cerrado${i} y no puedo tomarte el pedido todav\xEDa. \xBFTe cuento de ${e.name} mientras tanto, o te leo otra secci\xF3n?`,[{etiqueta:`Cu\xE9ntame de ${e.name}`,valor:`que trae ${e.name}`},...this.chipsInicio()],this.visualProducto(e))}return e.available===!1||e.stock?.soldOut?this.decirVisual(`Ay, ${e.name} est\xE1 agotado${this.esTienda?"":" por hoy"}. \xBFTe ofrezco otra cosa?`,this.chipsInicio(),this.visualProducto(e)):(this.ultimoItemMencionado=e,this.itemPendiente=e,this.cantidadPendiente=Math.min(t,e.maxPerOrder??50),this.variantesElegidas=[],this.modificadoresElegidos=[],this.gruposPendientes=[...(e.variants??[]).filter(i=>i.required).map(i=>({tipo:"variante",grupo:i})),...(e.modifiers??[]).filter(i=>i.min>0).map(i=>({tipo:"modificador",grupo:i}))],this.gruposPendientes.length>0?this.preguntarSiguienteGrupo():this.confirmarAgregado())}preguntarSiguienteGrupo(){let e=this.gruposPendientes[0],t=e.grupo.options.filter(o=>o.available!==!1);this.estado.set("variantes");let i=t.map(o=>o.priceDelta>0?`${o.label} por ${O(o.priceDelta,this.moneda)}`:o.label);return this.decirVisual(`Para ${this.itemPendiente.name}, \xBF${e.grupo.name}? Puede ser ${this.enumerar(i,"o")}.`,t.slice(0,6).map(o=>({etiqueta:o.label,valor:o.label})),this.visualProducto(this.itemPendiente))}resolverVariante(e){let t=this.gruposPendientes[0];if(!t||!this.itemPendiente)return this.volverAlInicio();let i=t.grupo.options.filter(s=>s.available!==!1),o=e.texto,r=i.find(s=>o.includes(S(s.label)));if(r||(r=i.find(s=>S(s.label).split(" ").some(u=>u.length>2&&o.split(" ").includes(u)))),!r)return this.telemetria.marcarResultadoTurno("corregido"),this.decir(`No te entend\xED. \xBF${t.grupo.name}: ${this.enumerar(i.map(s=>s.label),"o")}?`,i.slice(0,6).map(s=>({etiqueta:s.label,valor:s.label})));let a={groupId:t.grupo.id,groupName:t.grupo.name,optionId:r.id,optionLabel:r.label,priceDelta:r.priceDelta};return t.tipo==="variante"?this.variantesElegidas.push(a):this.modificadoresElegidos.push(a),this.gruposPendientes.shift(),this.gruposPendientes.length>0?this.preguntarSiguienteGrupo():this.confirmarAgregado()}confirmarAgregado(){let e=this.itemPendiente;this.cart.addLine(e,this.cantidadPendiente,this.variantesElegidas,this.modificadoresElegidos,null),this.telemetria.marcarItemAgregado(this.cantidadPendiente),this.telemetria.marcarResultadoTurno("resuelto");let t=this.cantidadPendiente,i=[...this.variantesElegidas,...this.modificadoresElegidos].map(a=>a.optionLabel);this.itemPendiente=null,this.estado.set("confirmar_agregado");let o=O(this.cart.subtotal(),this.moneda),r=`\xA1Listo! Agregu\xE9 ${t>1?t+" ":""}${e.name}`;return i.length&&(r+=` (${i.join(", ")})`),r+=`. Tu pedido va en ${o}. \xBFDeseas algo m\xE1s, o cerramos el pedido?`,this.decirVisual(r,[{etiqueta:"Cerrar el pedido",valor:"eso es todo"},{etiqueta:"Pedir algo m\xE1s",valor:"que categorias hay"},{etiqueta:"Ver mi pedido",valor:"que llevo en el pedido"}],this.visualProducto(e))}desambiguar(e,t,i,o){this.candidatos=e,this.cantidadPendiente=t,this.propositoDesambiguacion=i,this.estado.set("desambiguar");let r=e.map(u=>i==="agregar"?this.itemConPrecio(u):u.name),a=o??"Tenemos varios parecidos: ",s="\xBFCu\xE1l dices?";return this.decirEnumeracion(`${a}${this.enumerar(r,"o")}. ${s}`,e.map(u=>({etiqueta:u.name,valor:u.name})),e.map((u,f)=>({texto:r[f],visual:this.visualProducto(u)})),a,s)}resolverDesambiguacion(e){let t=e.item&&this.candidatos.some(i=>i.id===e.item.id)?e.item:null;if(t||(t=this.candidatos.find(i=>e.texto.includes(S(i.name)))??null),!t&&e.intent==="negar")return this.telemetria.marcarResultadoTurno("corregido"),this.estado.set("inicio"),this.decir("Est\xE1 bien. \xBFQu\xE9 m\xE1s te provoca?",this.chipsInicio());if(!t)return this.telemetria.marcarResultadoTurno("corregido"),this.decir(`\xBFCu\xE1l de estos: ${this.enumerar(this.candidatos.map(i=>i.name),"o")}?`,this.candidatos.map(i=>({etiqueta:i.name,valor:i.name})));if(this.candidatos=[],e.intent!=="agregar_item"&&this.propositoDesambiguacion!=="agregar"){let i=H(V({},e),{item:t,itemCandidatos:[]});return this.propositoDesambiguacion==="precio"?this.decirPrecio(i):this.describirPlato(i)}return this.prepararAgregado(t,e.cantidad??this.cantidadPendiente)}cambiarCantidad(e){let t=this.cart.lines();if(!t.length)return this.decir(`Tu pedido est\xE1 vac\xEDo todav\xEDa. \xBFTe leo ${this.cosaGrande}?`,this.chipsInicio());let i=e.item?t.find(o=>o.itemId===e.item.id):t.length===1?t[0]:null;if(!i)return this.decir("\xBFDe cu\xE1l producto cambio la cantidad? Dime el nombre.",this.chips());if(e.cantidad==null)if(/mas\b/.test(e.texto))this.cart.updateQuantity(i.lineId,i.quantity+1);else if(/menos\b/.test(e.texto)&&i.quantity>1)this.cart.updateQuantity(i.lineId,i.quantity-1);else return this.decir(`\xBFCu\xE1ntos ${i.itemName} te dejo?`,this.chips());else this.cart.updateQuantity(i.lineId,e.cantidad);return this.leerPedido()}quitarItem(e){let t=this.cart.lines();if(!t.length)return this.decir(`Tu pedido est\xE1 vac\xEDo. \xBFTe leo ${this.cosaGrande}?`,this.chipsInicio());let i=e.item?t.find(r=>r.itemId===e.item.id):null;if(!i&&/ultimo/.test(e.texto)&&(i=t[t.length-1]),!i&&t.length===1&&(i=t[0]),!i)return this.decir("\xBFCu\xE1l te quito? "+this.enumerar(t.map(r=>r.itemName),"o")+".",t.slice(0,6).map(r=>({etiqueta:`Quitar ${r.itemName}`,valor:`quita ${r.itemName}`})));this.cart.removeLine(i.lineId);let o=this.cart.lines().length;return this.decir(`Listo, quit\xE9 ${i.itemName}. ${o?"Tu pedido queda en "+O(this.cart.subtotal(),this.moneda)+".":"Tu pedido qued\xF3 vac\xEDo."} \xBFAlgo m\xE1s?`,this.chipsInicio())}leerPedido(){let e=this.cart.lines();if(!e.length)return this.decir(`Tu pedido est\xE1 vac\xEDo todav\xEDa. \xBFTe leo ${this.cosaGrande} para escoger?`,this.chipsInicio());let t=e.map(o=>`${o.quantity} ${o.itemName}${o.variants.length?" "+o.variants.map(r=>r.optionLabel).join(" "):""}`),i=`Llevas ${this.enumerar(t)}. Van ${O(this.cart.subtotal(),this.moneda)}. \xBFCerramos el pedido o deseas algo m\xE1s?`;return this.decirVisual(i,[{etiqueta:"Cerrar el pedido",valor:"eso es todo"},{etiqueta:"Pedir algo m\xE1s",valor:"que categorias hay"},{etiqueta:"Quitar algo",valor:"quita lo ultimo"}],this.visualPedido())}tiposDisponibles(){let e=this.ctx.ordering?.orderTypes;if(!e)return[];let t=[];return e.table&&!this.ctx.esCatalogo&&t.push("table"),e.pickup&&t.push("pickup"),e.delivery&&t.pu
1sh("delivery"),e.quote&&t.push("quote"),t}etiquetaTipo(e){return e==="table"?"para la mesa":e==="pickup"?"para recoger":e==="delivery"?"a domicilio":"para cotizar"}iniciarCheckout(){if(!this.cart.lines().length)return this.decir(`A\xFAn no has pedido nada. \xBFTe leo ${this.cosaGrande} para escoger?`,this.chipsInicio());if(this.visual.set(this.visualPedido()),!this.ctx.acceptingOrders||!this.ctx.ordering?.enabled){let i=this.ctx.closedLabel?` El negocio est\xE1 cerrado \u2014 ${n.sinPuntoFinal(this.ctx.closedLabel)}.`:"";return this.decir(`Ahora mismo no puedo enviar tu pedido.${i} Lo que llevas queda guardado en el carrito para que lo env\xEDes apenas abran. \xBFTe leo algo m\xE1s mientras tanto?`,this.chipsInicio())}let e=this.ctx.ordering.checkout.minOrderAmount;if(e!=null&&this.cart.subtotal()<e)return this.decir(`El pedido m\xEDnimo es ${O(e,this.moneda)} y llevas ${O(this.cart.subtotal(),this.moneda)}. \xBFTe agrego algo m\xE1s?`,this.chipsInicio());let t=this.tiposDisponibles();return t.length===0?this.decir("El negocio no tiene tipos de pedido habilitados en este momento.",this.chipsInicio()):this.ctx.preselectedTable!=null&&t.includes("table")?(this.coTipo="table",this.coMesa=this.ctx.preselectedTable,this.pedirNombre()):t.length===1?(this.coTipo=t[0],this.despuesDeTipo()):(this.estado.set("co_tipo"),this.decir(`Perfecto. \xBFC\xF3mo quieres tu pedido: ${this.enumerar(t.map(i=>this.etiquetaTipo(i)),"o")}?`,t.map(i=>({etiqueta:this.etiquetaTipo(i),valor:this.etiquetaTipo(i)}))))}resolverTipo(e){let t=e.texto,i=this.tiposDisponibles(),o=null;return/mesa/.test(t)&&i.includes("table")?o="table":/(recoger|recojo|paso|llevar|pickup)/.test(t)&&i.includes("pickup")?o="pickup":/(domicilio|casa|entrega|enviar|envio|delivery)/.test(t)&&i.includes("delivery")?o="delivery":/(cotiza|cotizar)/.test(t)&&i.includes("quote")&&(o="quote"),o?(this.coTipo=o,this.despuesDeTipo()):this.decir(`No te entend\xED. \xBF${this.enumerar(i.map(r=>this.etiquetaTipo(r)),"o")}?`,i.map(r=>({etiqueta:this.etiquetaTipo(r),valor:this.etiquetaTipo(r)})))}despuesDeTipo(){if(this.coTipo==="table"){if(this.ctx.preselectedTable!=null)return this.coMesa=this.ctx.preselectedTable,this.pedirNombre();if(this.ctx.ordering?.table.allowSelfSelect)return this.estado.set("co_mesa"),this.decir("\xBFEn qu\xE9 n\xFAmero de mesa est\xE1s?",[])}return this.pedirNombre()}capturarMesa(e){let t=this.nlu.extraerDigitos(e),i=t?+t:NaN;return Number.isNaN(i)||i<1||i>500?this.decir("No te entend\xED el n\xFAmero de mesa. D\xEDmelo otra vez, por favor.",[]):(this.coMesa=i,this.pedirNombre())}pedirNombre(){return this.estado.set("co_nombre"),this.decir("\xBFA nombre de qui\xE9n hago el pedido?",[])}capturarNombre(e){let t=e.trim().slice(0,80);return t.length<2?this.decir("No te escuch\xE9 bien. \xBFMe repites tu nombre?",[]):(this.coNombre=t,this.telemetria.registrarDatoPersonal(t),this.estado.set("co_telefono"),this.decir(`Gracias, ${t}. Ahora dime tu n\xFAmero de tel\xE9fono, d\xEDgito por d\xEDgito.`,[]))}capturarTelefono(e){let t=this.nlu.extraerDigitos(e);return t.length<7||t.length>15?(this.telemetria.marcarResultadoTurno("corregido"),this.decir("Necesito el n\xFAmero completo. D\xEDmelo d\xEDgito por d\xEDgito, o escr\xEDbelo con el teclado.",[])):(this.coTelefono=t,this.telemetria.registrarDatoPersonal(t),this.telemetria.registrarDatoPersonal(e.trim()),this.estado.set("co_confirmar_telefono"),this.decir(`Te anot\xE9 el ${this.deletrear(t)}. \xBFEst\xE1 correcto?`,[{etiqueta:"S\xED, correcto",valor:"si"},{etiqueta:"No, lo repito",valor:"no"}]))}async confirmarTelefono(e){let t=await this.nlu.entender(e);return t.intent==="confirmar"?this.coTipo==="delivery"?(this.estado.set("co_direccion"),this.decir("\xBFA qu\xE9 direcci\xF3n te lo enviamos? D\xEDmela completa.",[])):this.resumenFinal():t.intent==="negar"?(this.estado.set("co_telefono"),this.decir("Est\xE1 bien, dime el n\xFAmero otra vez, d\xEDgito por d\xEDgito.",[])):this.nlu.extraerDigitos(e).length>=7?this.capturarTelefono(e):(this.telemetria.marcarResultadoTurno("corregido"),this.decir(`\xBFEl n\xFAmero ${this.deletrear(this.coTelefono)} est\xE1 correcto?`,[{etiqueta:"S\xED, correcto",valor:"si"},{etiqueta:"No, lo repito",valor:"no"}]))}capturarDireccion(e){let t=e.trim().slice(0,200);if(t.length<5)return this.telemetria.marcarResultadoTurno("corregido"),this.decir("No te escuch\xE9 bien la direcci\xF3n. \xBFMe la repites?",[]);this.coDireccion=t,this.telemetria.registrarDatoPersonal(t);let i=this.ctx.ordering?.delivery.zones??[];return this.ctx.ordering?.delivery.requireZone!==!1&&i.length>0?(this.estado.set("co_zona"),this.decir(`\xBFEn cu\xE1l zona queda: ${this.enumerar(i.map(r=>r.name),"o")}?`,i.slice(0,8).map(r=>({etiqueta:r.name,valor:r.name})))):this.resumenFinal()}resolverZona(e){let t=this.ctx.ordering?.delivery.zones??[],i=t.find(o=>e.texto.includes(S(o.name)))??t.find(o=>S(o.name).split(" ").some(r=>r.length>3&&e.texto.split(" ").includes(r)));return i?(this.coZonaId=i.id,this.coZonaNombre=i.name,this.resumenFinal()):(this.telemetria.marcarResultadoTurno("corregido"),this.decir(`No encontr\xE9 esa zona. \xBF${this.enumerar(t.map(o=>o.name),"o")}?`,t.slice(0,8).map(o=>({etiqueta:o.name,valor:o.name}))))}resumenFinal(){this.estado.set("co_confirmar");let t=this.cart.lines().map(s=>`${s.quantity} ${s.itemName}`),o=this.cart.subtotal(),r=`Te confirmo: ${this.enumerar(t)}, ${this.etiquetaTipo(this.coTipo)}`;
1if(this.coTipo==="table"&&this.coMesa!=null&&(r+=`, mesa ${this.coMesa}`),this.coTipo==="delivery"){let s=this.cart.computeDeliveryFee(this.ctx.ordering,this.coZonaId);o+=s,r+=`, a ${this.coDireccion}`,this.coZonaNombre&&(r+=` en ${this.coZonaNombre}`),s>0&&(r+=`, con env\xEDo de ${O(s,this.moneda)}`)}let a=this.ctx.ordering?this.cart.computeTax(this.ctx.ordering):0;return o+=a,r+=`, a nombre de ${this.coNombre}. `,r+=this.coTipo==="quote"?"El negocio te confirmar\xE1 el precio. ":`El total es ${O(+o.toFixed(2),this.moneda)}. `,r+="Al confirmar aceptas los t\xE9rminos del negocio. \xBFEnv\xEDo tu pedido?",this.decir(r,[{etiqueta:"\u2705 S\xED, env\xEDalo",valor:"si confirmo"},{etiqueta:"Todav\xEDa no",valor:"no"}])}resolverConfirmacionFinal(e){return e.intent==="confirmar"||e.intent==="terminar_pedido"?this.enviarPedido():e.intent==="negar"||e.intent==="cancelar"?(this.telemetria.marcarResultadoTurno("corregido"),this.estado.set("inicio"),this.decir("Est\xE1 bien, no lo env\xEDo todav\xEDa. Tu pedido queda guardado. \xBFCambio algo?",this.chipsInicio())):this.decir("\xBFTe env\xEDo el pedido? Dime s\xED o no.",[{etiqueta:"\u2705 S\xED, env\xEDalo",valor:"si confirmo"},{etiqueta:"Todav\xEDa no",valor:"no"}])}async enviarPedido(){let e=this.ctx.ordering?.checkout.paymentMode??"offline_only";if(e==="online_only"&&this.coTipo!=="quote")return this.activo=!1,this.requiereCheckoutVisual.set(!0),this.decir("Este negocio cobra con pago en l\xEDnea, as\xED que te abro la pantalla de pago con tu pedido ya armado. Solo te falta pagar. \xA1Gracias!",[]);await this.decir("Enviando tu pedido\u2026",[]);let t=H(V({type:this.coTipo,items:this.cart.lines().map(a=>({itemId:a.itemId,quantity:a.quantity,variants:a.variants.map(s=>({groupId:s.groupId,optionId:s.optionId})),modifiers:a.modifiers.map(s=>({groupId:s.groupId,optionId:s.optionId})),notes:a.notes})),customer:V({name:this.coNombre,phone:this.coTelefono},this.coTipo==="delivery"?{address:this.coDireccion,zone:this.coZonaNombre||void 0}:{}),tableNumber:this.coTipo==="table"?this.coMesa:null,deliveryZoneId:this.coTipo==="delivery"?this.coZonaId:null,honeypot:"",legalNoticeShown:!0},e==="both"?{paymentChoice:"offline"}:{}),{sourceModule:this.ctx.sourceModule,origin:"voz"}),i=await _e(this.cms.submitMenuOrder(this.ctx.businessId,t));if(i.ok===!1){let a=i;return this.estado.set("inicio"),this.decir(`No pude enviar el pedido: ${a.message} \xBFIntentamos de nuevo?`,[{etiqueta:"Reintentar",valor:"si confirmo"},{etiqueta:`Volver ${this.esTienda?"al cat\xE1logo":"al men\xFA"}`,valor:"volver"}])}let o=i;this.telemetria.marcarResultadoTurno("resuelto"),this.telemetria.marcarPedidoEnviado(o.total,this.moneda),this.pedidoCreado.set(o),this.cart.clear(),this.estado.set("exito");let r=`\xA1Pedido enviado, ${this.coNombre}! `;return this.coTipo!=="quote"&&(r+=`El total fue ${O(o.total,this.moneda)}. `),r+=this.coTipo==="table"?"Ya lo tiene el negocio \u2014 en un momento te atienden en la mesa. ":"El negocio ya lo recibi\xF3 y se pondr\xE1 en contacto contigo. ",o.whatsappUrl&&(r+="Si quieres, tambi\xE9n puedes enviarlo por WhatsApp con el bot\xF3n que te dejo aqu\xED. "),r+="\xA1Gracias por tu pedido!",this.decir(r,[])}ayudar(){return this.decir(`Es muy f\xE1cil: puedes decirme cosas como "l\xE9eme ${this.cosaGrande}", "qu\xE9 me recomiendas", "cu\xE1nto cuesta" un ${this.itemSingular}, "quiero" el ${this.itemSingular} que te guste, y al final "eso es todo" para cerrar tu pedido. Tambi\xE9n puedes tocar los botones que te muestro. \xBFEmpezamos?`,this.chipsInicio())}cancelar(){return this.cart.clear(),this.estado.set("inicio"),this.decir("Listo, cancel\xE9 el pedido y vaciamos todo. \xBFEmpezamos de nuevo o necesitas algo m\xE1s?",this.chipsInicio())}despedir(){return this.estado.set("cerrado"),this.decir("\xA1Con mucho gusto! Que lo disfrutes. Aqu\xED estar\xE9 si me necesitas.",[])}volverAlInicio(){return this.estado.set("inicio"),this.categoriaActual=null,this.decir("Listo, volvamos. \xBFQu\xE9 deseas hacer?",this.chipsInicio())}chipsInicio(){let e=[{etiqueta:`\u{1F4D6} L\xE9eme ${this.cosaGrande}`,valor:"que categorias hay"},{etiqueta:"\u2B50 Recomi\xE9ndame algo",valor:"que me recomiendas"}];return this.cart.lines().length&&(e.push({etiqueta:"\u{1F9FE} Ver mi pedido",valor:"que llevo en el pedido"}),e.push({etiqueta:"\u2705 Cerrar el pedido",valor:"eso es todo"})),e}decir(e,t){return this.registrarTurnoMesero(e,t),this.modoVoz()&&this.activo?this.voz.hablar(Q(e)):(this.voz.hablar(Q(e)),Promise.resolve())}decirVisual(e,t,i){return this.visual.set(i),this.decir(e,t)}async decirEnumeracion(e,t,i,o,r){if(this.registrarTurnoMesero(e,t),!this.modoVoz()||!this.activo){i[0]&&this.visual.set(i[0].visual),this.voz.hablar(Q(e));return}o&&await this.voz.hablar(Q(o));for(let a of i){if(!this.activo)return;this.visual.set(a.visual),await this.voz.hablar(Q(a.texto))}r&&this.activo&&await this.voz.hablar(Q(r))}registrarTurnoMesero(e,t){this.ultimoDicho=e,this.mensajes.update(i=>[...i,{rol:"mesero",texto:e}]),this.telemetria.turnoMesero(e),this.chips.set(t)}visualCategoria(e){let t=(e.items??[]).filter(i=>i.available!==!1&&i.image).slice(0,6).map(i=>({nombre:i.name,imagen:i.image}));
1return{tipo:"categoria",titulo:e.name,items:t}}visualProducto(e){return{tipo:"producto",titulo:e.name,items:[{nombre:e.name,imagen:e.image,precio:this.precioOculto(e)?null:this.precioHablado(e)}]}}visualPedido(){return{tipo:"pedido",titulo:"Tu pedido",items:this.cart.lines().map(e=>({nombre:`${e.quantity} \xD7 ${e.itemName}`,imagen:e.itemImage}))}}enumerar(e,t="y"){return e.length===0?"":e.length===1?e[0]:e.slice(0,-1).join(", ")+` ${t} `+e[e.length-1]}precioOculto(e){return e.price==null||this.ctx.ordering?.quote.hidePrices===!0&&this.ctx.ordering?.orderTypes.quote===!0}precioHablado(e){let t=e.price??0;return e.discount?.type==="amount"?t=e.discount.value:e.discount?.type==="percentage"&&(t=+(t*(1-e.discount.value/100)).toFixed(2)),O(t,this.moneda)}itemConPrecio(e){return this.precioOculto(e)?e.name:`${e.name} por ${this.precioHablado(e)}`}badgesHablados(e){let t={new:"nuevo",popular:"de los m\xE1s pedidos",spicy:"picante",vegan:"vegano","gluten-free":"sin gluten"};return(e.badges??[]).map(i=>t[i]).filter(Boolean)}deletrear(e){return e.split("").join(", ")}nombraItemEspecifico(e){if(!e.item)return!1;let t=new Set(S(e.categoria?.name??"").split(" ")),i=new Set(S(e.item.name).split(" "));return e.texto.split(" ").some(o=>o.length>2&&i.has(o)&&!t.has(o))}static sinPuntoFinal(e){return e.replace(/[.\s]+$/,"")}static \u0275fac=function(t){return new(t||n)};static \u0275prov=j({token:n,factory:n.\u0275fac})};var Ve=["scroller"],se=(n,e)=>e.nombre,Ie=(n,e)=>e.valor;function je(n,e){if(n&1){let t=A();c(0,"header",2)(1,"div",5)(2,"span",6),m(3,"\u{1F935}"),l(),c(4,"div")(5,"p",7),m(6),l(),c(7,"p",8),m(8),l()()(),c(9,"div",9)(10,"button",10),I("click",function(){w(t);let o=p();return z(o.cerrar())}),m(11," \u2715 "),c(12,"span",11),m(13,"Cerrar"),l()()()()}if(n&2){let t=p();d(6),P(t.agenteNombre()),d(2),P(t.businessName()),d(2),W("aria-label","Cerrar el "+t.agenteNombre())}}function Le(n,e){if(n&1&&(c(0,"div",13),m(1),l()),n&2){let t=e.$implicit;F("mesero-burbuja--cliente",t.rol==="cliente"),d(),P(t.texto)}}function Fe(n,e){if(n&1&&(c(0,"div",3),N(1,Le,2,3,"div",12,pe),l()),n&2){let t=p();d(),k(t.dialogo.mensajes())}}function Re(n,e){if(n&1){let t=A();c(0,"div",4)(1,"div",14),m(2,"\u{1F935}"),l(),c(3,"p",15),m(4),l(),c(5,"p",16),m(6),l(),c(7,"div",17)(8,"button",18),I("click",function(){w(t);let o=p();return z(o.cerrar())}),c(9,"span",19),m(10,"\u2715"),l(),c(11,"span",20),m(12,"Cancelar"),l()(),c(13,"button",21),I("click",function(){w(t);let o=p();return z(o.contestar())}),c(14,"span",19),m(15,"\u{1F4DE}"),l(),c(16,"span",20),m(17,"Contestar"),l()()()()}if(n&2){let t=p();d(4),P(t.agenteNombre()),d(2),Z("",t.businessName()," \xB7 llamando\u2026")}}function Be(n,e){if(n&1&&(c(0,"div",24)(1,"div",37),m(2,"\u{1F399}\uFE0F"),l(),c(3,"p",38),m(4),l()()),n&2){let t=p(2);d(4),P(t.voz.transcripcionParcial()||"Te escucho\u2026")}}function Ue(n,e){if(n&1&&(c(0,"div",39)(1,"span",42),m(2,"\u{1F935}"),l(),c(3,"p",43),m(4),l()()),n&2){let t=p();d(4),P(t.titulo)}}function Ge(n,e){if(n&1&&Y(0,"img",45),n&2){let t=p().$implicit;T("src",t.imagen,L)("alt",t.nombre)}}function He(n,e){n&1&&(c(0,"div",46),m(1,"\u{1F37D}\uFE0F"),l())}function Ze(n,e){if(n&1&&(c(0,"p",48),m(1),l()),n&2){let t=p().$implicit;d(),P(t.precio)}}function Qe(n,e){if(n&1&&(c(0,"figure",44),_(1,Ge,1,2,"img",45)(2,He,2,0,"div",46),c(3,"figcaption")(4,"p",47),m(5),l(),_(6,Ze,2,1,"p",48),l()()),n&2){let t=e.$implicit;d(),C(t.imagen?1:2),d(4),P(t.nombre),d(),C(t.precio?6:-1)}}function We(n,e){if(n&1&&N(0,Qe,7,3,"figure",44,se),n&2){let t=p();k(t.items)}}function Ye(n,e){if(n&1&&Y(0,"img",52),n&2){let t=e.$implicit;T("src",t.imagen,L)("alt",t.nombre)}}function Xe(n,e){if(n&1&&(c(0,"div",51),N(1,Ye,1,2,"img",52,se),l()),n&2){let t=p(2);F("mesero-voz-collage--uno",t.items.length===1),d(),k(t.items)}}function Je(n,e){if(n&1&&(c(0,"div",40)(1,"p",49),m(2),l(),_(3,Xe,3,2,"div",50),l()),n&2){let t=p();d(2),P(t.titulo),d(),C(t.items.length?3:-1)}}function Ke(n,e){if(n&1&&(c(0,"p",53),m(1),l()),n&2){let t=p(2);d(),P(t.titulo)}}function et(n,e){if(n&1&&Y(0,"img",56),n&2){let t=p().$implicit;T("src",t.imagen,L)("alt",t.nombre)}}function tt(n,e){n&1&&(c(0,"div",57),m(1,"\u{1F37D}\uFE0F"),l())}function it(n,e){if(n&1&&(c(0,"div",55),_(1,et,1,2,"img",56)(2,tt,2,0,"div",57),c(3,"p"),m(4),l()()),n&2){let t=e.$implicit;d(),C(t.imagen?1:2),d(3),P(t.nombre)}}function ot(n,e){if(n&1&&(c(0,"div",41),_(1,Ke,2,1,"p",53),c(2,"div",54),N(3,it,5,2,"div",55,se),l()()),n&2){let t=p();d(),C(t.titulo?1:-1),d(2),k(t.items)}}function nt(n,e){if(n&1&&Y(0,"img",56),n&2){let t=p().$implicit;T("src",t.imagen,L)("alt",t.nombre)}}function rt(n,e){n&1&&(c(0,"div",57),m(1,"\u{1F37D}\uFE0F"),l())}
1function at(n,e){if(n&1&&(c(0,"div",55),_(1,nt,1,2,"img",56)(2,rt,2,0,"div",57),c(3,"p"),m(4),l()()),n&2){let t=e.$implicit;d(),C(t.imagen?1:2),d(3),P(t.nombre)}}function st(n,e){if(n&1&&(c(0,"div",41)(1,"p",53),m(2),l(),c(3,"div",54),N(4,at,5,2,"div",55,se),l()()),n&2){let t=p();d(2),P(t.titulo),d(2),k(t.items)}}function ct(n,e){if(n&1&&_(0,Ue,5,1,"div",39)(1,We,2,0)(2,Je,4,2,"div",40)(3,ot,5,1,"div",41)(4,st,6,1,"div",41),n&2){let t;C((t=e.tipo)==="negocio"?0:t==="producto"?1:t==="categoria"?2:t==="productos"?3:t==="pedido"?4:-1)}}function lt(n,e){if(n&1&&(c(0,"a",58),m(1," Enviar mi pedido por WhatsApp "),l()),n&2){let t=p();T("href",t.whatsappUrl,L)}}function dt(n,e){n&1&&_(0,lt,2,1,"a",58),n&2&&C(e.whatsappUrl?0:-1)}function mt(n,e){if(n&1){let t=A();c(0,"button",59),I("click",function(){w(t);let o=p(2);return z(o.alternarSilencio())}),c(1,"span",19),m(2),l(),c(3,"span",20),m(4),l()()}if(n&2){let t=p(2);F("mesero-btn-redondo--activo",t.dialogo.silenciado()),W("aria-pressed",t.dialogo.silenciado())("aria-label",t.dialogo.silenciado()?"Activar micr\xF3fono":"Silenciar micr\xF3fono"),d(2),P(t.dialogo.silenciado()?"\u{1F507}":"\u{1F399}\uFE0F"),d(2),P(t.dialogo.silenciado()?"Silenciado":"Silenciar")}}function ut(n,e){if(n&1){let t=A();c(0,"button",61),I("click",function(){let o=w(t).$implicit,r=p(3);return z(r.tocarChip(o.valor))}),m(1),l()}if(n&2){let t=e.$implicit,i=p(3);T("disabled",i.dialogo.ocupado()),d(),Z(" ",t.etiqueta," ")}}function pt(n,e){if(n&1&&(c(0,"div",33),N(1,ut,2,2,"button",60,Ie),l()),n&2){let t=p(2);d(),k(t.dialogo.chips())}}function ht(n,e){if(n&1){let t=A();c(0,"div",22)(1,"div",23),_(2,Be,5,1,"div",24)(3,ct,5,1),l(),c(4,"div",25)(5,"span",26),m(6,"\u{1F935}"),l(),c(7,"span",27),m(8),l()()(),c(9,"p",28),m(10),l(),_(11,dt,1,1),c(12,"footer",29),_(13,mt,5,6,"button",30),c(14,"button",31),I("click",function(){w(t);let o=p();return z(o.cerrar())}),c(15,"span",19),m(16,"\u{1F4DE}"),l(),c(17,"span",20),m(18,"Colgar"),l()()(),c(19,"div",32),_(20,pt,3,0,"div",33),c(21,"form",34),I("submit",function(o){return w(t),p().enviarTexto(),z(o.preventDefault())}),c(22,"input",35),I("input",function(o){w(t);let r=p();return z(r.textoEscrito.set(o.target.value))}),l(),c(23,"button",36),m(24,"\u27A4"),l()()()}if(n&2){let t,i,o=p();d(2),C(o.voz.escuchando()?2:(t=o.dialogo.visual())?3:-1,t),d(6),P(o.agenteNombre()),d(2),P(o.duracion()),d(),C((i=o.dialogo.pedidoCreado())?11:-1,i),d(2),C(o.voz.sttSoportado()?13:-1),d(7),C(o.dialogo.chips().length>0?20:-1),d(2),T("value",o.textoEscrito())("disabled",o.dialogo.ocupado()),d(),T("disabled",o.dialogo.ocupado())}}function gt(n,e){if(n&1&&(c(0,"div",13),m(1),l()),n&2){let t=e.$implicit;F("mesero-burbuja--cliente",t.rol==="cliente"),d(),Z(" ",t.texto," ")}}function ft(n,e){if(n&1&&(c(0,"div",63),m(1),l()),n&2){let t=p(2);d(),Z(" ",t.voz.transcripcionParcial()||"Te escucho\u2026"," ")}}function vt(n,e){if(n&1&&(c(0,"a",58),m(1," Enviar mi pedido por WhatsApp "),l()),n&2){let t=p();T("href",t.whatsappUrl,L)}}function bt(n,e){n&1&&_(0,vt,2,1,"a",58),n&2&&C(e.whatsappUrl?0:-1)}function _t(n,e){if(n&1){let t=A();c(0,"button",61),I("click",function(){let o=w(t).$implicit,r=p(3);return z(r.tocarChip(o.valor))}),m(1),l()}if(n&2){let t=e.$implicit,i=p(3);T("disabled",i.dialogo.ocupado()),d(),Z(" ",t.etiqueta," ")}}function Ct(n,e){if(n&1&&(c(0,"div",33),N(1,_t,2,2,"button",60,Ie),l()),n&2){let t=p(2);d(),k(t.dialogo.chips())}}function xt(n,e){if(n&1){let t=A();c(0,"button",68),I("click",function(){w(t);let o=p(2);return z(o.tocarMic())}),c(1,"span",69),m(2,"\u{1F399}\uFE0F"),l(),c(3,"span",70),m(4),l()()}if(n&2){let t=p(2);F("mesero-mic--escuchando",t.voz.escuchando()),T("disabled",t.dialogo.ocupado()&&!t.voz.escuchando()),W("aria-label",t.voz.escuchando()?"Dejar de escuchar":"Hablar con el mesero"),d(4),P(t.voz.escuchando()?"Te escucho\u2026 toca para parar":"Toca y habla")}}function Mt(n,e){if(n&1){let t=A();c(0,"div",62,0),N(2,gt,2,3,"div",12,pe),_(4,ft,2,1,"div",63),_(5,bt,1,1),l(),_(6,Ct,3,0,"div",33),c(7,"footer",64),_(8,xt,5,5,"button",65),c(9,"form",66),I("submit",function(o){return w(t),p().enviarTexto(),z(o.preventDefault())}),c(10,"input",67),I("input",function(o){w(t);let r=p();return z(r.textoEscrito.set(o.target.value))}),l(),c(11,"button",36),m(12,"\u27A4"),l()()()}if(n&2){let t,i=p();d(2),k(i.dialogo.mensajes()),d(2),C(i.voz.escuchando()?4:-1),d(),C((t=i.dialogo.pedidoCreado())?5:-1,t),d(),C(i.dialogo.chips().length>0?6:-1),d(2),C(i.voz.sttSoportado()?8:-1),d(2),T("value",i.textoEscrito())("disabled",i.dialogo.ocupado()),d(),T("disabled",i.dialogo.ocupado())}}var ze=class n{dialogo=E(X);voz=E(U);nlu=E(R);telemetria=E(B);businessId=q.required();businessSlug=q("");businessName=q("");countryCode=q(null);menu=q.required();ordering=q(null);acceptingOrders=q(!1);closedLabel=q(null);preselectedTable=q(null);sourceModule=q("menu_digital");esCatalogo=q(!1);closed=ge();abrirCheckout=ge();agenteNombre=he(()=>this.esCatalogo()?"Asesor Pana":"Mesero Pana");textoEscrito=b("");scroller=Ee("scroller");llamando=b(!0);segundos=b(0);cronometro=null;calentamiento=null;duracion=he(()=>{let e=this.segundos(),t=Math.floor(e/60),i=e%60;return`${String(t).padStart(2,"0")}
1:${String(i).padStart(2,"0")}`});constructor(){ie(()=>{this.dialogo.mensajes();let e=this.scroller()?.nativeElement;e&&setTimeout(()=>e.scrollTo({top:e.scrollHeight,behavior:"smooth"}))}),ie(()=>{this.dialogo.requiereCheckoutVisual()&&(this.dialogo.requiereCheckoutVisual.set(!1),this.closed.emit(),this.abrirCheckout.emit())}),ie(()=>this.nlu.usarMenu(this.menu()))}ngOnInit(){this.voz.iniciar(this.countryCode()),this.telemetria.marcarStt(this.voz.sttSoportado()),this.voz.precalentarMotor(),this.calentamiento=setInterval(()=>{this.llamando()&&this.voz.precalentarMotor()},4e3)}ngOnDestroy(){this.cronometro&&clearInterval(this.cronometro),this.calentamiento&&clearInterval(this.calentamiento),this.dialogo.detener()}contestar(){this.llamando()&&(this.calentamiento&&(clearInterval(this.calentamiento),this.calentamiento=null),this.voz.precalentarMicrofono(),this.llamando.set(!1),this.cronometro=setInterval(()=>this.segundos.update(e=>e+1),1e3),this.dialogo.iniciar({businessId:this.businessId(),businessSlug:this.businessSlug(),businessName:this.businessName()||"este negocio",countryCode:this.countryCode(),menu:this.menu(),ordering:this.ordering(),acceptingOrders:this.acceptingOrders(),closedLabel:this.closedLabel(),preselectedTable:this.preselectedTable(),sourceModule:this.sourceModule(),esCatalogo:this.esCatalogo()}))}cerrar(){this.dialogo.detener(),this.closed.emit()}tocarMic(){this.voz.desbloquear(),this.dialogo.escucharTurno()}tocarChip(e){this.voz.desbloquear(),this.dialogo.procesar(e,"chip")}enviarTexto(){let e=this.textoEscrito().trim();e&&(this.voz.desbloquear(),this.textoEscrito.set(""),this.dialogo.procesar(e,"teclado"))}cambiarModo(e){this.voz.desbloquear(),this.dialogo.establecerModoVoz(e)}alternarSilencio(){this.voz.desbloquear(),this.dialogo.alternarSilencio()}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=xe({type:n,selectors:[["mesero-panel"]],viewQuery:function(t,i){t&1&&Me(i.scroller,Ve,5),t&2&&ye()},inputs:{businessId:[1,"businessId"],businessSlug:[1,"businessSlug"],businessName:[1,"businessName"],countryCode:[1,"countryCode"],menu:[1,"menu"],ordering:[1,"ordering"],acceptingOrders:[1,"acceptingOrders"],closedLabel:[1,"closedLabel"],preselectedTable:[1,"preselectedTable"],sourceModule:[1,"sourceModule"],esCatalogo:[1,"esCatalogo"]},outputs:{closed:"closed",abrirCheckout:"abrirCheckout"},features:[Pe([X,R,U,B])],decls:6,vars:6,consts:[["scroller",""],["role","dialog","aria-modal","true",1,"mesero-overlay"],[1,"mesero-header"],["aria-live","polite",1,"mesero-sr-only"],[1,"mesero-llamando"],[1,"mesero-header-info"],["aria-hidden","true",1,"mesero-avatar"],[1,"mesero-titulo"],[1,"mesero-subtitulo"],[1,"mesero-header-acciones"],["type","button",1,"mesero-cerrar",3,"click"],[1,"mesero-cerrar-texto"],[1,"mesero-burbuja",3,"mesero-burbuja--cliente"],[1,"mesero-burbuja"],["aria-hidden","true",1,"mesero-llamando-avatar"],[1,"mesero-llamando-nombre"],[1,"mesero-llamando-sub"],[1,"mesero-llamando-acciones"],["type","button","aria-label","Cancelar la llamada",1,"mesero-btn-redondo","mesero-btn-redondo--rechazar",3,"click"],["aria-hidden","true"],[1,"mesero-btn-redondo-texto"],["type","button","aria-label","Contestar la llamada",1,"mesero-btn-redondo","mesero-btn-redondo--contestar",3,"click"],[1,"mesero-voz-tarjeta"],["aria-live","polite",1,"mesero-voz-escenario"],[1,"mesero-voz-escuchando"],[1,"mesero-voz-insignia"],["aria-hidden","true",1,"mesero-voz-insignia-avatar"],[1,"mesero-voz-insignia-nombre"],["aria-live","off",1,"mesero-duracion"],[1,"mesero-llamada-controles"],["type","button",1,"mesero-btn-redondo","mesero-btn-redondo--mute",3,"mesero-btn-redondo--activo"],["type","button","aria-label","Terminar la llamada",1,"mesero-btn-redondo","mesero-btn-redondo--colgar",3,"click"],[1,"mesero-sr-only"],[1,"mesero-chips"],[3,"submit"],["type","text","placeholder","\u2026o escr\xEDbele aqu\xED","aria-label","Escr\xEDbele al mesero",1,"mesero-input",3,"input","value","disabled"],["type","submit","aria-label","Enviar mensaje",1,"mesero-enviar",3,"disabled"],["aria-hidden","true",1,"mesero-voz-pulso"],[1,"mesero-voz-transcripcion"],[1,"mesero-voz-negocio"],[1,"mesero-voz-categoria"],[1,"mesero-voz-lista"],["aria-hidden","true",1,"mesero-voz-negocio-avatar"],[1,"mesero-voz-negocio-nombre"],[1,"mesero-voz-producto"],[1,"mesero-voz-producto-img",3,"src","alt"],["aria-hidden","true",1,"mesero-voz-producto-sinfoto"],[1,"mesero-voz-producto-nombre"],[1,"mesero-voz-producto-precio"],[1,"mesero-voz-categoria-nombre"],[1,"mesero-voz-collage",3,"mesero-voz-collage--uno"],[1,"mesero-voz-collage"],[1,"mesero-voz-collage-img",3,"src","alt"],[1,"mesero-voz-lista-titulo"],[1,"mesero-voz-grid"],[1,"mesero-voz-grid-item"],[3,"src","alt"],["aria-hidden","true",1,"mesero-voz-grid-sinfoto"],["target","_blank","rel","noopener",1,"mesero-whatsapp",3,"href"],["type","button",1,"mesero-btn-redondo","mesero-btn-redondo--mute",3,"click"],["type","button",1,"mesero-chip",3,"disabled"],["type","button",1,"mesero-chip",3,"click","disabled"],["aria-live","polite",1,"mesero-mensajes"],[1,"mesero-burbuja","mesero-burbuja--cliente","mesero-burbuja--parcial"],[1,"mesero-pie"],["type","button",1,"mesero-mic",3,"mesero-mic--escuchando","disabled"],[1,"mesero-teclado",3,"submit"],["type","text","placeholder","\u2026o escribe aqu\xED","aria-label","Escr\xEDbele al mesero",1,"mesero-input",3,"input","value","disabled"],["type","button",1,"mesero-mic",3,"click","disabled"],["aria-hidden","true",1,"mesero-mic-icono"],[1,"mesero-mic-texto"]],template:function(t,i){t&1&&(c(0,"div",1),_(1,je,14,3,"header",2),_(2,Fe,3,0,"div",3),_(3,Re,18,2,"div",4)(4,ht,25,9)(5,Mt,13,7),l()),t&2&&(F("mesero-overlay--voz",i.dialogo.modoVoz()),W("aria-label","Llamada con el "+i.agenteNombre()+" de "+i.businessName()),d(),C(i.dialogo.modoVoz()?-1:1),d(),C(i.dialogo.modoVoz()?2:-1),d(),C(i.dialogo.modoVoz()&&i.llamando()?3:i.dialogo.modoVoz()?4:5)
1)},styles:['@charset "UTF-8";.mesero-overlay[_ngcontent-%COMP%]{position:fixed;inset:0;z-index:10000;display:flex;flex-direction:column;background:#f7f5f0;color:#1c1917;font-size:1.15rem;line-height:1.5}.mesero-header[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:space-between;gap:.75rem;padding:max(.85rem,env(safe-area-inset-top)) 1rem .85rem;background:#14532d;color:#fff}.mesero-header-info[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.65rem;min-width:0}.mesero-header-acciones[_ngcontent-%COMP%]{flex-shrink:0;display:flex;align-items:center;gap:.5rem}.mesero-avatar[_ngcontent-%COMP%]{font-size:2rem;line-height:1}.mesero-titulo[_ngcontent-%COMP%]{margin:0;font-size:1.15rem;font-weight:700}.mesero-subtitulo[_ngcontent-%COMP%]{margin:0;font-size:.9rem;opacity:.85;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.mesero-cerrar[_ngcontent-%COMP%]{flex-shrink:0;display:inline-flex;align-items:center;gap:.4rem;border:2px solid rgba(255,255,255,.55);border-radius:9999px;background:#ffffff1f;color:#fff;font-size:1.05rem;font-weight:700;padding:.55rem 1rem;cursor:pointer;min-height:48px}.mesero-sr-only[_ngcontent-%COMP%]{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.mesero-mensajes[_ngcontent-%COMP%]{flex:1;overflow-y:auto;padding:1rem;display:flex;flex-direction:column;gap:.75rem}.mesero-burbuja[_ngcontent-%COMP%]{max-width:88%;padding:.85rem 1.1rem;background:#fff;border:1px solid #e7e5e4;box-shadow:0 1px 2px #0000000f;border-radius:1.25rem 1.25rem 1.25rem .35rem;white-space:pre-line}.mesero-burbuja--cliente[_ngcontent-%COMP%]{align-self:flex-end;background:#dcfce7;border-color:#bbf7d0;border-bottom-left-radius:1.25rem;border-bottom-right-radius:.35rem}.mesero-burbuja--parcial[_ngcontent-%COMP%]{opacity:.7;font-style:italic}.mesero-whatsapp[_ngcontent-%COMP%]{align-self:center;margin-top:.25rem;display:inline-block;background:#16a34a;color:#fff;font-weight:700;font-size:1.1rem;border-radius:9999px;padding:.9rem 1.5rem;text-decoration:none;min-height:48px}.mesero-chips[_ngcontent-%COMP%]{display:flex;flex-wrap:wrap;gap:.6rem;padding:.5rem 1rem}.mesero-chip[_ngcontent-%COMP%]{border:2px solid #14532d;border-radius:9999px;background:#fff;color:#14532d;font-size:1.05rem;font-weight:600;padding:.7rem 1.15rem;cursor:pointer;min-height:48px}.mesero-chip[_ngcontent-%COMP%]:disabled{opacity:.5;cursor:default}.mesero-pie[_ngcontent-%COMP%]{padding:.75rem 1rem calc(.9rem + env(safe-area-inset-bottom));background:#fff;border-top:1px solid #e7e5e4;display:flex;flex-direction:column;gap:.6rem}.mesero-mic[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:center;gap:.6rem;width:100%;min-height:64px;border:none;border-radius:1rem;background:#14532d;color:#fff;font-size:1.25rem;font-weight:700;cursor:pointer}.mesero-mic--escuchando[_ngcontent-%COMP%]{background:#b91c1c;animation:mesero-pulso 1.2s ease-in-out infinite}.mesero-mic[_ngcontent-%COMP%]:disabled{opacity:.55;cursor:default}.mesero-mic-icono[_ngcontent-%COMP%]{font-size:1.6rem}.mesero-teclado[_ngcontent-%COMP%]{display:flex;gap:.5rem}.mesero-input[_ngcontent-%COMP%]{flex:1;min-height:48px;border:2px solid #d6d3d1;border-radius:.85rem;padding:.5rem .9rem;font-size:1.05rem;background:#fafaf9;color:#1c1917}.mesero-input[_ngcontent-%COMP%]:focus{outline:3px solid #14532d;outline-offset:1px}.mesero-input[_ngcontent-%COMP%]:disabled, .mesero-enviar[_ngcontent-%COMP%]:disabled{opacity:.55;cursor:default}.mesero-enviar[_ngcontent-%COMP%]{min-width:56px;min-height:48px;border:none;border-radius:.85rem;background:#14532d;color:#fff;font-size:1.3rem;cursor:pointer}.mesero-overlay--voz[_ngcontent-%COMP%]{background:#0c0a09;color:#fff}.mesero-llamando[_ngcontent-%COMP%]{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.25rem;padding:2rem 1.5rem calc(3rem + env(safe-area-inset-bottom));text-align:center}.mesero-llamando-avatar[_ngcontent-%COMP%]{width:132px;height:132px;border-radius:9999px;display:flex;align-items:center;justify-content:center;font-size:4.5rem;background:#ffffff14;border:2px solid rgba(255,255,255,.15);animation:_ngcontent-%COMP%_mesero-anillo 1.6s ease-in-out infinite;margin-bottom:1.25rem}
1.mesero-llamando-nombre[_ngcontent-%COMP%]{margin:0;font-size:1.6rem;font-weight:800}.mesero-llamando-sub[_ngcontent-%COMP%]{margin:.35rem 0 0;opacity:.65;font-size:1.05rem}.mesero-llamando-acciones[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:center;gap:3rem;margin-top:3rem}@keyframes _ngcontent-%COMP%_mesero-anillo{0%,to{box-shadow:0 0 #ffffff2e}50%{box-shadow:0 0 0 18px #fff0}}.mesero-voz-tarjeta[_ngcontent-%COMP%]{position:relative;flex:1;min-height:0;margin:1rem 1rem 0;border-radius:1.5rem;overflow:hidden;background:#17140f}.mesero-voz-escenario[_ngcontent-%COMP%]{width:100%;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.75rem;padding:1.25rem;overflow:hidden}.mesero-voz-insignia[_ngcontent-%COMP%]{position:absolute;right:.75rem;bottom:.75rem;display:flex;align-items:center;gap:.4rem;padding:.35rem .85rem .35rem .35rem;border-radius:9999px;background:#0000008c;border:1px solid rgba(255,255,255,.12)}.mesero-voz-insignia-avatar[_ngcontent-%COMP%]{width:26px;height:26px;display:flex;align-items:center;justify-content:center;border-radius:9999px;background:#ffffff24;font-size:1rem}.mesero-voz-insignia-nombre[_ngcontent-%COMP%]{font-size:.82rem;font-weight:700;color:#fff}.mesero-duracion[_ngcontent-%COMP%]{margin:.65rem 0 0;text-align:center;font-size:.95rem;font-weight:600;color:#ffffffa6;font-variant-numeric:tabular-nums}.mesero-llamada-controles[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:center;gap:2rem;padding:.6rem 1rem .2rem}.mesero-btn-redondo[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;gap:.4rem;border:none;background:transparent;color:#fff;cursor:pointer;padding:0}.mesero-btn-redondo[_ngcontent-%COMP%] > span[_ngcontent-%COMP%]:first-child{width:60px;height:60px;border-radius:9999px;display:flex;align-items:center;justify-content:center;font-size:1.6rem;background:#ffffff1f}.mesero-btn-redondo-texto[_ngcontent-%COMP%]{font-size:.85rem;font-weight:600;color:#fffc}.mesero-btn-redondo--activo[_ngcontent-%COMP%] > span[_ngcontent-%COMP%]:first-child{background:#fff;color:#0c0a09}.mesero-btn-redondo--colgar[_ngcontent-%COMP%] > span[_ngcontent-%COMP%]:first-child, .mesero-btn-redondo--rechazar[_ngcontent-%COMP%] > span[_ngcontent-%COMP%]:first-child{background:#dc2626;color:#fff}.mesero-btn-redondo--contestar[_ngcontent-%COMP%] > span[_ngcontent-%COMP%]:first-child{background:#16a34a;color:#fff;animation:mesero-pulso 1.2s ease-in-out infinite}.mesero-btn-redondo[_ngcontent-%COMP%]:disabled{opacity:.5;cursor:default}.mesero-voz-escuchando[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;gap:1.25rem;color:#fff;text-align:center}.mesero-voz-pulso[_ngcontent-%COMP%]{font-size:4.5rem;line-height:1;animation:mesero-pulso 1.2s ease-in-out infinite}.mesero-voz-transcripcion[_ngcontent-%COMP%]{margin:0;font-size:1.4rem;font-weight:600;max-width:90%}.mesero-voz-negocio[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;gap:1rem;color:#fff;text-align:center}.mesero-voz-negocio-avatar[_ngcontent-%COMP%]{font-size:5rem;line-height:1}.mesero-voz-negocio-nombre[_ngcontent-%COMP%]{margin:0;font-size:1.6rem;font-weight:800}.mesero-voz-producto[_ngcontent-%COMP%]{margin:0;width:100%;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.75rem}.mesero-voz-producto-img[_ngcontent-%COMP%]{max-width:100%;max-height:70%;width:auto;height:auto;object-fit:contain;border-radius:1.25rem;box-shadow:0 12px 40px #00000073}.mesero-voz-producto-sinfoto[_ngcontent-%COMP%]{font-size:6rem;line-height:1}.mesero-voz-producto[_ngcontent-%COMP%] figcaption[_ngcontent-%COMP%]{text-align:center}.mesero-voz-producto-nombre[_ngcontent-%COMP%]{margin:0;color:#fff;font-size:1.6rem;font-weight:800}.mesero-voz-producto-precio[_ngcontent-%COMP%]{margin:.15rem 0 0;color:#fbbf24;font-size:1.25rem;font-weight:700}.mesero-voz-categoria[_ngcontent-%COMP%]{width:100%;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1rem}
1.mesero-voz-categoria-nombre[_ngcontent-%COMP%]{margin:0;color:#fff;font-size:2rem;font-weight:800;text-align:center}.mesero-voz-collage[_ngcontent-%COMP%]{display:grid;grid-template-columns:repeat(3,1fr);gap:.5rem;width:100%;max-width:480px}.mesero-voz-collage--uno[_ngcontent-%COMP%]{grid-template-columns:1fr;max-width:320px}.mesero-voz-collage-img[_ngcontent-%COMP%]{width:100%;aspect-ratio:1/1;object-fit:cover;border-radius:.85rem;box-shadow:0 6px 18px #0006}.mesero-voz-lista[_ngcontent-%COMP%]{width:100%;height:100%;overflow-y:auto;display:flex;flex-direction:column;gap:.85rem;padding:.25rem}.mesero-voz-lista-titulo[_ngcontent-%COMP%]{margin:0;color:#fff;font-size:1.3rem;font-weight:800;text-align:center}.mesero-voz-grid[_ngcontent-%COMP%]{display:grid;grid-template-columns:repeat(2,1fr);gap:.75rem}.mesero-voz-grid-item[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;gap:.4rem;background:#ffffff0f;border-radius:.85rem;padding:.6rem}.mesero-voz-grid-item[_ngcontent-%COMP%] img[_ngcontent-%COMP%]{width:100%;aspect-ratio:1/1;object-fit:cover;border-radius:.65rem}.mesero-voz-grid-sinfoto[_ngcontent-%COMP%]{width:100%;aspect-ratio:1/1;display:flex;align-items:center;justify-content:center;font-size:2.25rem;background:#ffffff14;border-radius:.65rem}.mesero-voz-grid-item[_ngcontent-%COMP%] p[_ngcontent-%COMP%]{margin:0;color:#fff;font-size:.95rem;font-weight:700;text-align:center}@media(prefers-reduced-motion:reduce){.mesero-mic--escuchando[_ngcontent-%COMP%]{animation:none}}'],changeDetection:0})};export{ze as MeseroPanelComponent};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.