@kavchat/widget 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ "use strict";(()=>{var P={"live.talk":"Talk to a representative","live.intro":"A representative will join shortly. Leave an email or a phone number in case we need to get back to you.","live.department":"Department","live.message":"Your message (optional)","live.start":"Start chat","live.connecting":"Connecting...","live.waiting":"Waiting for a representative","live.waitingLeft":"Waiting for a representative ({time})","live.leave":"Leave a message instead","live.end":"End chat","live.joined":"{name} joined the chat","live.with":"Chatting with {name}","live.agent":"Representative","live.typing":"Typing a reply...","live.ended":"The chat has ended","live.ticket":"We got your message and will get back to you soon.","live.timeout":"No representative was free in time, so we saved your chat as a request.","live.number":"Request #{number}","live.closed":"Our representatives are not available right now. Leave a message and we will get back to you.","live.closedUntil":"Our representatives are not available right now and will be back at {time}. Leave a message and we will get back to you.","live.busy":"All our representatives are busy right now. Leave a message and we will get back to you.","live.failed":"Message not sent. Tap to try again.","live.back":"Back to the bot","live.reconnecting":"Reconnecting...","live.tooLong":"Messages are limited to 2000 characters.","live.elsewhere":"You already have an open chat in another window.","live.replaced":"This chat continues in another window.","live.placeholder":"Type a message..."};var ye={"live.talk":"שיחה עם נציג","live.intro":"נציג יצטרף בעוד רגע. השאירו אימייל או טלפון למקרה שנצטרך לחזור אליכם.","live.department":"מחלקה","live.message":"ההודעה שלכם (לא חובה)","live.start":"התחלת שיחה","live.connecting":"מתחברים...","live.waiting":"ממתינים לנציג","live.waitingLeft":"ממתינים לנציג ({time})","live.leave":"להשאיר הודעה במקום","live.end":"סיום השיחה","live.joined":"עכשיו בשיחה: {name}","live.with":"בשיחה עם {name}","live.agent":"נציג","live.typing":"מקלידים תשובה...","live.ended":"השיחה הסתיימה","live.ticket":"קיבלנו את ההודעה ונחזור אליכם בהקדם.","live.timeout":"אף נציג לא התפנה בזמן, אז שמרנו את השיחה כפנייה.","live.number":"פנייה מספר {number}","live.closed":"הנציגים לא זמינים כרגע. השאירו הודעה ונחזור אליכם.","live.closedUntil":"הנציגים לא זמינים כרגע ויחזרו ב-{time}. השאירו הודעה ונחזור אליכם.","live.busy":"כל הנציגים עסוקים כרגע. השאירו הודעה ונחזור אליכם.","live.failed":"ההודעה לא נשלחה. הקישו כדי לנסות שוב.","live.back":"חזרה לבוט","live.reconnecting":"מתחברים מחדש...","live.tooLong":"אפשר לשלוח עד 2000 תווים בהודעה.","live.elsewhere":"כבר יש לכם שיחה פתוחה בחלון אחר.","live.replaced":"השיחה ממשיכה בחלון אחר.","live.placeholder":"כתבו הודעה..."};var ke={"live.talk":"التحدث مع ممثل","live.intro":"سينضم ممثل بعد لحظات. اترك بريدًا إلكترونيًا أو رقم هاتف في حال احتجنا إلى العودة إليك.","live.department":"القسم","live.message":"رسالتك (اختياري)","live.start":"بدء المحادثة","live.connecting":"جارٍ الاتصال...","live.waiting":"في انتظار ممثل","live.waitingLeft":"في انتظار ممثل ({time})","live.leave":"اترك رسالة بدلًا من ذلك","live.end":"إنهاء المحادثة","live.joined":"انضم {name} إلى المحادثة","live.with":"تتحدث مع {name}","live.agent":"ممثل","live.typing":"يكتب ردًا...","live.ended":"انتهت المحادثة","live.ticket":"وصلتنا رسالتك وسنعود إليك قريبًا.","live.timeout":"لم يتفرغ أي ممثل في الوقت المناسب، لذلك حفظنا المحادثة كطلب.","live.number":"طلب رقم {number}","live.closed":"ممثلونا غير متاحين الآن. اترك رسالة وسنعود إليك.","live.closedUntil":"ممثلونا غير متاحين الآن وسيعودون في {time}. اترك رسالة وسنعود إليك.","live.busy":"جميع ممثلينا مشغولون الآن. اترك رسالة وسنعود إليك.","live.failed":"لم تُرسل الرسالة. اضغط للمحاولة مرة أخرى.","live.back":"العودة إلى البوت","live.reconnecting":"جارٍ إعادة الاتصال...","live.tooLong":"الحد الأقصى للرسالة 2000 حرف.","live.elsewhere":"لديك محادثة مفتوحة بالفعل في نافذة أخرى.","live.replaced":"تستمر هذه المحادثة في نافذة أخرى.","live.placeholder":"اكتب رسالة..."};var xe={"live.talk":"Связаться с оператором","live.intro":"Оператор скоро подключится. Оставьте email или телефон на случай, если нам нужно будет с вами связаться.","live.department":"Отдел","live.message":"Ваше сообщение (необязательно)","live.start":"Начать чат","live.connecting":"Подключение...","live.waiting":"Ожидание оператора","live.waitingLeft":"Ожидание оператора ({time})","live.leave":"Оставить сообщение","live.end":"Завершить чат","live.joined":"{name} присоединяется к чату","live.with":"Чат с: {name}","live.agent":"Оператор","live.typing":"Печатает ответ...","live.ended":"Чат завершён","live.ticket":"Мы получили ваше сообщение и скоро с вами свяжемся.","live.timeout":"Ни один оператор не освободился вовремя, поэтому мы сохранили чат как обращение.","live.number":"Обращение №{number}","live.closed":"Сейчас операторы недоступны. Оставьте сообщение, и мы с вами свяжемся.","live.closedUntil":"Сейчас операторы недоступны и вернутся в {time}. Оставьте сообщение, и мы с вами свяжемся.","live.busy":"Все операторы сейчас заняты. Оставьте сообщение, и мы с вами свяжемся.","live.failed":"Сообщение не отправлено. Нажмите, чтобы повторить.","live.back":"Вернуться к боту","live.reconnecting":"Переподключение...","live.tooLong":"Длина сообщения не более 2000 символов.","live.elsewhere":"У вас уже есть открытый чат в другом окне.","live.replaced":"Этот чат продолжается в другом окне.","live.placeholder":"Введите сообщение..."};var Le={"live.talk":"Hablar con un agente","live.intro":"Un agente se unirá en breve. Deja un email o un teléfono por si necesitamos contactarte.","live.department":"Departamento","live.message":"Tu mensaje (opcional)","live.start":"Iniciar chat","live.connecting":"Conectando...","live.waiting":"Esperando a un agente","live.waitingLeft":"Esperando a un agente ({time})","live.leave":"Dejar un mensaje","live.end":"Terminar chat","live.joined":"{name} se unió al chat","live.with":"Hablando con {name}","live.agent":"Agente","live.typing":"Escribiendo una respuesta...","live.ended":"El chat ha terminado","live.ticket":"Recibimos tu mensaje y te responderemos pronto.","live.timeout":"Ningún agente quedó libre a tiempo, así que guardamos tu chat como una solicitud.","live.number":"Solicitud n.º {number}","live.closed":"Nuestros agentes no están disponibles ahora. Deja un mensaje y te responderemos.","live.closedUntil":"Nuestros agentes no están disponibles ahora y volverán a las {time}. Deja un mensaje y te responderemos.","live.busy":"Todos nuestros agentes están ocupados ahora. Deja un mensaje y te responderemos.","live.failed":"Mensaje no enviado. Toca para intentarlo de nuevo.","live.back":"Volver al bot","live.reconnecting":"Reconectando...","live.tooLong":"Los mensajes tienen un máximo de 2000 caracteres.","live.elsewhere":"Ya tienes un chat abierto en otra ventana.","live.replaced":"Este chat continúa en otra ventana.","live.placeholder":"Escribe un mensaje..."};var we={"live.talk":"Parler à un conseiller","live.intro":"Un conseiller va vous rejoindre. Laissez un email ou un numéro de téléphone au cas où nous devrions vous recontacter.","live.department":"Service","live.message":"Votre message (facultatif)","live.start":"Démarrer le chat","live.connecting":"Connexion...","live.waiting":"En attente d’un conseiller","live.waitingLeft":"En attente d’un conseiller ({time})","live.leave":"Laisser un message à la place","live.end":"Terminer le chat","live.joined":"{name} a rejoint le chat","live.with":"En conversation avec {name}","live.agent":"Conseiller","live.typing":"Rédige une réponse...","live.ended":"Le chat est terminé","live.ticket":"Nous avons bien reçu votre message et revenons vers vous rapidement.","live.timeout":"Aucun conseiller ne s’est libéré à temps, nous avons donc enregistré votre chat comme demande.","live.number":"Demande n° {number}","live.closed":"Nos conseillers ne sont pas disponibles pour le moment. Laissez un message et nous reviendrons vers vous.","live.closedUntil":"Nos conseillers ne sont pas disponibles pour le moment et reviennent à {time}. Laissez un message et nous reviendrons vers vous.","live.busy":"Tous nos conseillers sont occupés. Laissez un message et nous reviendrons vers vous.","live.failed":"Message non envoyé. Touchez pour réessayer.","live.back":"Retour au bot","live.reconnecting":"Reconnexion...","live.tooLong":"Les messages sont limités à 2000 caractères.","live.elsewhere":"Vous avez déjà un chat ouvert dans une autre fenêtre.","live.replaced":"Ce chat continue dans une autre fenêtre.","live.placeholder":"Écrivez un message..."};var Se={"live.talk":"Mit einem Mitarbeiter sprechen","live.intro":"Gleich ist jemand für Sie da. Hinterlassen Sie eine E-Mail-Adresse oder Telefonnummer, falls wir uns bei Ihnen melden müssen.","live.department":"Abteilung","live.message":"Ihre Nachricht (optional)","live.start":"Chat starten","live.connecting":"Verbinden...","live.waiting":"Warten auf einen Mitarbeiter","live.waitingLeft":"Warten auf einen Mitarbeiter ({time})","live.leave":"Stattdessen eine Nachricht hinterlassen","live.end":"Chat beenden","live.joined":"{name} ist dem Chat beigetreten","live.with":"Im Chat mit {name}","live.agent":"Mitarbeiter","live.typing":"Schreibt eine Antwort...","live.ended":"Der Chat wurde beendet","live.ticket":"Wir haben Ihre Nachricht erhalten und melden uns bald bei Ihnen.","live.timeout":"Es wurde rechtzeitig niemand frei, deshalb haben wir Ihren Chat als Anfrage gespeichert.","live.number":"Anfrage Nr. {number}","live.closed":"Unsere Mitarbeiter sind gerade nicht erreichbar. Hinterlassen Sie eine Nachricht, wir melden uns bei Ihnen.","live.closedUntil":"Unsere Mitarbeiter sind gerade nicht erreichbar und ab {time} wieder da. Hinterlassen Sie eine Nachricht, wir melden uns bei Ihnen.","live.busy":"Alle Mitarbeiter sind gerade beschäftigt. Hinterlassen Sie eine Nachricht, wir melden uns bei Ihnen.","live.failed":"Nachricht nicht gesendet. Tippen Sie, um es erneut zu versuchen.","live.back":"Zurück zum Bot","live.reconnecting":"Neu verbinden...","live.tooLong":"Nachrichten sind auf 2000 Zeichen begrenzt.","live.elsewhere":"Sie haben bereits einen offenen Chat in einem anderen Fenster.","live.replaced":"Dieser Chat geht in einem anderen Fenster weiter.","live.placeholder":"Nachricht eingeben..."};var Te={"live.talk":"Falar com um atendente","live.intro":"Um atendente vai entrar em instantes. Deixe um email ou telefone caso precisemos retornar o contato.","live.department":"Departamento","live.message":"Sua mensagem (opcional)","live.start":"Iniciar chat","live.connecting":"Conectando...","live.waiting":"Aguardando um atendente","live.waitingLeft":"Aguardando um atendente ({time})","live.leave":"Deixar uma mensagem","live.end":"Encerrar chat","live.joined":"{name} entrou no chat","live.with":"Conversando com {name}","live.agent":"Atendente","live.typing":"Digitando uma resposta...","live.ended":"O chat foi encerrado","live.ticket":"Recebemos sua mensagem e retornaremos em breve.","live.timeout":"Nenhum atendente ficou livre a tempo, então salvamos seu chat como uma solicitação.","live.number":"Solicitação nº {number}","live.closed":"Nossos atendentes não estão disponíveis agora. Deixe uma mensagem e retornaremos.","live.closedUntil":"Nossos atendentes não estão disponíveis agora e voltam às {time}. Deixe uma mensagem e retornaremos.","live.busy":"Todos os nossos atendentes estão ocupados agora. Deixe uma mensagem e retornaremos.","live.failed":"Mensagem não enviada. Toque para tentar de novo.","live.back":"Voltar ao bot","live.reconnecting":"Reconectando...","live.tooLong":"As mensagens têm no máximo 2000 caracteres.","live.elsewhere":"Você já tem um chat aberto em outra janela.","live.replaced":"Este chat continua em outra janela.","live.placeholder":"Digite uma mensagem..."};var Ce={"live.talk":"Parla con un operatore","live.intro":"Un operatore arriverà a breve. Lascia un’email o un numero di telefono nel caso dovessimo ricontattarti.","live.department":"Reparto","live.message":"Il tuo messaggio (facoltativo)","live.start":"Avvia la chat","live.connecting":"Connessione...","live.waiting":"In attesa di un operatore","live.waitingLeft":"In attesa di un operatore ({time})","live.leave":"Lascia invece un messaggio","live.end":"Termina la chat","live.joined":"{name} è entrato nella chat","live.with":"In chat con {name}","live.agent":"Operatore","live.typing":"Sta scrivendo una risposta...","live.ended":"La chat è terminata","live.ticket":"Abbiamo ricevuto il tuo messaggio e ti risponderemo presto.","live.timeout":"Nessun operatore si è liberato in tempo, quindi abbiamo salvato la chat come richiesta.","live.number":"Richiesta n. {number}","live.closed":"I nostri operatori non sono disponibili ora. Lascia un messaggio e ti ricontatteremo.","live.closedUntil":"I nostri operatori non sono disponibili ora e tornano alle {time}. Lascia un messaggio e ti ricontatteremo.","live.busy":"Tutti i nostri operatori sono occupati. Lascia un messaggio e ti ricontatteremo.","live.failed":"Messaggio non inviato. Tocca per riprovare.","live.back":"Torna al bot","live.reconnecting":"Riconnessione...","live.tooLong":"I messaggi possono avere al massimo 2000 caratteri.","live.elsewhere":"Hai già una chat aperta in un’altra finestra.","live.replaced":"Questa chat continua in un’altra finestra.","live.placeholder":"Scrivi un messaggio..."};var Ee={"live.talk":"Bir temsilciyle konuş","live.intro":"Birazdan bir temsilci katılacak. Size dönmemiz gerekirse diye bir e-posta veya telefon numarası bırakın.","live.department":"Departman","live.message":"Mesajınız (isteğe bağlı)","live.start":"Sohbeti başlat","live.connecting":"Bağlanıyor...","live.waiting":"Temsilci bekleniyor","live.waitingLeft":"Temsilci bekleniyor ({time})","live.leave":"Bunun yerine mesaj bırak","live.end":"Sohbeti bitir","live.joined":"{name} sohbete katıldı","live.with":"Görüştüğünüz kişi: {name}","live.agent":"Temsilci","live.typing":"Yanıt yazıyor...","live.ended":"Sohbet sona erdi","live.ticket":"Mesajınızı aldık, en kısa sürede size döneceğiz.","live.timeout":"Zamanında müsait temsilci olmadı, bu yüzden sohbetinizi talep olarak kaydettik.","live.number":"Talep no. {number}","live.closed":"Temsilcilerimiz şu anda müsait değil. Mesaj bırakın, size dönelim.","live.closedUntil":"Temsilcilerimiz şu anda müsait değil, {time} itibarıyla dönecekler. Mesaj bırakın, size dönelim.","live.busy":"Tüm temsilcilerimiz şu anda meşgul. Mesaj bırakın, size dönelim.","live.failed":"Mesaj gönderilemedi. Tekrar denemek için dokunun.","live.back":"Bota dön","live.reconnecting":"Yeniden bağlanıyor...","live.tooLong":"Mesajlar en fazla 2000 karakter olabilir.","live.elsewhere":"Başka bir pencerede zaten açık bir sohbetiniz var.","live.replaced":"Bu sohbet başka bir pencerede devam ediyor.","live.placeholder":"Bir mesaj yazın..."};var Ie={"live.talk":"คุยกับเจ้าหน้าที่","live.intro":"เจ้าหน้าที่จะเข้ามาในอีกสักครู่ กรุณาฝากอีเมลหรือเบอร์โทรไว้ เผื่อเราต้องติดต่อกลับ","live.department":"แผนก","live.message":"ข้อความของคุณ (ไม่บังคับ)","live.start":"เริ่มแชท","live.connecting":"กำลังเชื่อมต่อ...","live.waiting":"กำลังรอเจ้าหน้าที่","live.waitingLeft":"กำลังรอเจ้าหน้าที่ ({time})","live.leave":"ฝากข้อความแทน","live.end":"จบการแชท","live.joined":"{name} เข้าร่วมแชทแล้ว","live.with":"กำลังคุยกับ {name}","live.agent":"เจ้าหน้าที่","live.typing":"กำลังพิมพ์คำตอบ...","live.ended":"การแชทสิ้นสุดแล้ว","live.ticket":"เราได้รับข้อความของคุณแล้ว และจะติดต่อกลับโดยเร็ว","live.timeout":"ไม่มีเจ้าหน้าที่ว่างทันเวลา เราจึงบันทึกแชทของคุณเป็นคำขอ","live.number":"คำขอหมายเลข {number}","live.closed":"ขณะนี้เจ้าหน้าที่ไม่พร้อมให้บริการ ฝากข้อความไว้ แล้วเราจะติดต่อกลับ","live.closedUntil":"ขณะนี้เจ้าหน้าที่ไม่พร้อมให้บริการ และจะกลับมาเวลา {time} ฝากข้อความไว้ แล้วเราจะติดต่อกลับ","live.busy":"เจ้าหน้าที่ทุกคนไม่ว่างในขณะนี้ ฝากข้อความไว้ แล้วเราจะติดต่อกลับ","live.failed":"ส่งข้อความไม่สำเร็จ แตะเพื่อลองอีกครั้ง","live.back":"กลับไปที่บอท","live.reconnecting":"กำลังเชื่อมต่อใหม่...","live.tooLong":"ข้อความยาวได้ไม่เกิน 2000 ตัวอักษร","live.elsewhere":"คุณมีแชทที่เปิดอยู่แล้วในหน้าต่างอื่น","live.replaced":"แชทนี้ดำเนินต่อในหน้าต่างอื่น","live.placeholder":"พิมพ์ข้อความ..."};var Ae={en:P,he:ye,ar:ke,ru:xe,es:Le,fr:we,de:Se,pt:Te,it:Ce,tr:Ee,th:Ie};var ot=i=>String(i||"en").toLowerCase().split(/[-_]/)[0].replace(/^iw$/,"he");function ie(i,e){var n;let t=(n=Ae[ot(i)])!=null?n:P;return{...P,...t,...e!=null?e:{}}}var E=(i,e)=>i.replace(/\{(\w+)\}/g,(t,n)=>e[n]!==void 0?String(e[n]):t);var U=2e3,Re=3e3,De=6e3,_e=3e4,Me=[1,2,4,8,16,30];var C=i=>i==="closed"||i==="ticket";function M(i,e=Math.random){let t=Me[Math.min(Math.max(0,Math.floor(i)||0),Me.length-1)]*1e3;return Math.round(t*(.7+.6*e()))}function Ne(i){return{conversation:i,events:[],lastSeq:0,pending:[]}}function I(i,e){if(!e||e.id!==i.conversation.id)return i;let t=i.conversation;if(C(t.state)&&!C(e.state))return i;let n=e.ticket||t.ticket,a=n&&t.ticket&&t.ticket.number!=null&&(!e.ticket||e.ticket.number==null)?{...n,number:t.ticket.number}:n;return{...i,conversation:{...e,ticket:a!=null?a:null}}}function $(i,e){if(!e||typeof e.seq!="number"||!(e.seq>0)||Math.floor(e.seq)!==e.seq)return i;let t=e.seq,n=i.events;if(n.some(p=>p.seq===t))return i;let a=n.length;for(;a>0&&n[a-1].seq>t;)a--;let r=[...n.slice(0,a),e,...n.slice(a)],x=e.clientId?i.pending.filter(p=>p.clientId!==e.clientId):i.pending,s=i.conversation,v=e.data||{};if(C(s.state))e.type==="conversation.ticket"&&s.ticket&&s.ticket.number==null&&typeof v.ticketNumber=="number"&&(s={...s,ticket:{...s.ticket,number:v.ticketNumber}});else if(e.type==="agent.joined"){let p=v.agent||{};s={...s,state:"active",agent:{name:p.name}}}else if(e.type==="conversation.closed")s={...s,state:"closed",closeReason:v.reason||null};else if(e.type==="conversation.ticket"){let p=typeof v.ticketNumber=="number"?v.ticketNumber:null;s={...s,state:"ticket",ticket:{number:p,reason:v.reason}}}return{conversation:s,events:r,lastSeq:Math.max(i.lastSeq,t),pending:x}}function ne(i,e){let t=I(i,e.conversation);for(let n of e.events||[])t=$(t,n);return t}function Ue(i,e,t,n){return i.pending.some(a=>a.clientId===e)||i.events.some(a=>a.clientId===e)?i:{...i,pending:[...i.pending,{clientId:e,text:t,at:n,status:"sending"}]}}function ae(i,e,t){if(!i.pending.some(a=>a.clientId===e))return i;let n=t?i.pending.map(a=>a.clientId===e?{...a,status:t}:a):i.pending.filter(a=>a.clientId!==e);return{...i,pending:n}}function se(i,e){var n;let t=[];for(let a of i.events){let r=`e${a.seq}`,x=a.data||{};if(a.type==="message"){let s=a.author&&(a.author.kind==="visitor"||a.author.kind==="agent")?a.author.kind:"system",v={key:r,kind:s,text:String((n=a.text)!=null?n:"")};s==="agent"&&(v.name=a.author.name||e["live.agent"]),t.push(v)}else if(a.type==="agent.joined"){let s=x.agent||{};t.push({key:r,kind:"system",text:E(e["live.joined"],{name:s.name||e["live.agent"]})})}else if(a.type==="conversation.closed")t.push({key:r,kind:"system",text:e["live.ended"]});else if(a.type==="conversation.ticket"){let s=x.ticketNumber;t.push({key:r,kind:"system",text:typeof s=="number"?`${e["live.ticket"]} ${E(e["live.number"],{number:s})}`:e["live.ticket"]})}}for(let a of i.pending)t.push({key:`p${a.clientId}`,kind:"visitor",text:a.text,status:a.status,clientId:a.clientId});return t}function re(i,e){if(i.state!=="queued"||!i.queueDeadline)return null;let t=Date.parse(i.queueDeadline);return isFinite(t)?Math.max(0,Math.ceil((t-e)/1e3)):null}var lt=i=>`${Math.floor(i/60)}:${String(i%60).padStart(2,"0")}`;function je(i,e,t){switch(i.state){case"queued":{let n=re(i,t);return n===null?e["live.waiting"]:E(e["live.waitingLeft"],{time:lt(n)})}case"active":return E(e["live.with"],{name:i.agent&&i.agent.name||e["live.agent"]});case"ticket":{let n=i.ticket?i.ticket.number:null;return[i.ticket&&i.ticket.reason==="timeout"?e["live.timeout"]:"",e["live.ticket"],n!=null?E(e["live.number"],{number:n}):""].filter(Boolean).join(" ")}default:return e["live.ended"]}}function oe(i,e,t){return i==="closed"?t?E(e["live.closedUntil"],{time:t}):e["live.closed"]:i==="no_agents"?e["live.busy"]:""}function qe(i,e){let t=i.findIndex(r=>r.kind==="contact");if(t<0||i.some(r=>r.kind==="live"))return i;let n=i[t],a={id:"live",label:e,kind:"live",...n.prefill?{prefill:n.prefill}:{}};return[...i.slice(0,t),a,...i.slice(t)]}function d(i,e,...t){let n=document.createElement(i);if(e)for(let[a,r]of Object.entries(e))r==null||r===!1||n.setAttribute(a,r===!0?"":r);return ct(n,t),n}function ct(i,e){for(let t of e)t==null||t===!1||i.appendChild(typeof t=="string"?document.createTextNode(t):t)}var ze="http://www.w3.org/2000/svg";function Oe(i){let e=document.createElementNS(ze,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","24"),e.setAttribute("height","24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let t=document.createElementNS(ze,"path");return t.setAttribute("d",i),t.setAttribute("fill","currentColor"),e.appendChild(t),e}var Be={chat:"M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z",close:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z",send:"M2.01 21 23 12 2.01 3 2 10l15 2-15 2z"};var dt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";function j(i=22){let e=new Uint8Array(i);if(typeof crypto!="undefined"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let n=0;n<i;n++)e[n]=Math.floor(Math.random()*256);let t="";for(let n=0;n<i;n++)t+=dt[e[n]&63];return t}var Ve=(i,e)=>`${i.apiBase.replace(/\/+$/,"")}/v1/client/${encodeURIComponent(i.publicKey)}/live/${e}`;async function He(i,e,t){try{let n=await fetch(Ve(i,e),{method:t===void 0?"GET":"POST",cache:"no-store",credentials:"omit",...t===void 0?{}:{body:JSON.stringify(t)}}),a=await n.json().catch(()=>null);return{status:n.status,ok:n.ok&&!!a&&a.success===!0,data:a&&a.data,code:String(a&&a.code||""),message:String(a&&a.message||"")}}catch(n){return{status:0,ok:!1,data:null,code:"network",message:""}}}var w=(i,e,t)=>He(i,e,t),Pe=(i,e)=>He(i,e),F=i=>i.status===0||i.status===429||i.status>=500,q=i=>new Promise(e=>setTimeout(e,i)),ut=9e4,vt=12e4,G=class{constructor(e,t,n,a){this.api=e;this.credential=t;this.cb=a;this.stopped=!1;this.random=Math.random;this.es=null;this.attempt=0;this.blocked=0;this.pollUntil=0;this.polling=!1;this.typingOn=!1;this.typingAt=0;this.numberTried=!1;this.onOnline=()=>{!this.es&&!this.polling&&this.schedule(0)};this.chat=Ne(n),window.addEventListener("online",this.onOnline)}get final(){return C(this.chat.conversation.state)}body(e){return{credential:this.credential,...e}}set(e){if(e===this.chat)return;let t=this.chat;this.chat=e,e.events.length>t.events.length&&e.events.some(n=>n.type==="message"&&n.author.kind==="agent"&&!t.events.includes(n))&&this.cb.typing(!1),this.cb.change(e),this.final&&this.finish()}async sync(){for(let e=0;e<50;e++){let t=await w(this.api,"sync",this.body({after:this.chat.lastSeq}));if(this.stopped)return!1;if(!t.ok)return this.fail(t),!1;if(this.set(ne(this.chat,t.data)),!t.data.hasMore)return!0}return!0}fail(e){return e.code==="live_credential_invalid"?(this.final?this.finish():this.set(I(this.chat,{...this.chat.conversation,state:"closed",closeReason:this.chat.conversation.closeReason||"expired"})),!0):e.code==="live_conversation_closed"?(this.sync(),!0):!1}connect(){this.stopped||this.final||(clearTimeout(this.timer),navigator.onLine!==!1&&(typeof EventSource!="function"||Date.now()<this.pollUntil?this.poll():this.openStream()))}async openStream(){let e=await w(this.api,"stream-ticket",this.body());if(this.stopped||this.final)return;if(!e.ok)return this.fail(e)?void 0:(e.code==="live_busy"&&(this.pollUntil=Date.now()+vt),this.retry());let t=new EventSource(`${Ve(this.api,"stream")}?ticket=${encodeURIComponent(String(e.data.ticket))}&after=${this.chat.lastSeq}`);this.es=t;let n=!1,a=(r,x)=>t.addEventListener(r,s=>{if(this.es!==t)return;this.touch();let v;try{v=JSON.parse(s.data)}catch(p){return}v&&typeof v=="object"&&x(v)});a("ready",r=>{n=!0,this.blocked=0,this.attempt=0,this.cb.notice(null),this.set(I(this.chat,r.conversation))}),a("event",r=>this.set($(this.chat,r))),a("state",r=>this.set(I(this.chat,r))),a("typing",r=>this.showTyping(r.on!==!1)),a("bye",r=>{this.closeStream(),this.bye(r.reason)}),t.onerror=()=>{this.es===t&&(this.closeStream(),!n&&++this.blocked>=3&&(this.pollUntil=1/0),this.cb.notice("reconnecting"),this.retry())},this.touch()}touch(){clearTimeout(this.idle),this.idle=setTimeout(()=>{this.es&&(this.closeStream(),this.schedule(0))},ut)}closeStream(){clearTimeout(this.idle),this.es&&this.es.close(),this.es=null}bye(e){e==="replaced"?(this.stop(),this.cb.notice("replaced")):e==="expired"||e==="deleted"?this.set(I(this.chat,{...this.chat.conversation,state:"closed",closeReason:"expired"})):this.retry()}retry(){this.schedule(M(this.attempt++,this.random))}schedule(e){clearTimeout(this.timer),!(this.stopped||this.final)&&(this.timer=setTimeout(async()=>{this.stopped||navigator.onLine===!1||(await this.sync()?this.connect():!this.stopped&&!this.final&&this.retry())},e))}async poll(){if(!this.polling){for(this.polling=!0;!this.stopped&&!this.final&&!(typeof EventSource=="function"&&Date.now()>=this.pollUntil);){let e=Date.now(),t=this.chat,n=await w(this.api,"sync",this.body({after:this.chat.lastSeq,wait:25}));if(this.stopped)break;if(!n.ok){this.polling=!1,this.fail(n)||this.retry();return}this.attempt=0,this.set(ne(this.chat,n.data));let a=this.chat.lastSeq===t.lastSeq&&this.chat.conversation.state===t.conversation.state;!(n.data&&n.data.hasMore)&&a&&Date.now()-e<1e3&&await q(1e3)}this.polling=!1,!this.stopped&&!this.final&&this.connect()}}showTyping(e){clearTimeout(this.typingTimer),this.cb.typing(e),e&&(this.typingTimer=setTimeout(()=>this.cb.typing(!1),De))}send(e){let t=e.trim();if(!t)return"empty";if(t.length>U)return"too_long";if(this.final||this.stopped)return"closed";let n=j(22);return this.set(Ue(this.chat,n,t,new Date().toISOString())),this.typing(!1),this.deliver(n,t,0),"ok"}retrySend(e){let t=this.chat.pending.find(n=>n.clientId===e);!t||t.status!=="failed"||this.final||this.stopped||(this.set(ae(this.chat,e,"sending")),this.deliver(e,t.text,0))}async deliver(e,t,n){let a=await w(this.api,"messages",this.body({clientId:e,text:t}));if(!this.stopped){if(a.ok){this.set($(this.chat,a.data.event));return}if(F(a)&&n<5)return await q(M(n,this.random)),this.deliver(e,t,n+1);this.set(ae(this.chat,e,"failed")),this.fail(a)}}typing(e){if(this.chat.conversation.state!=="active"||this.stopped)return;let t=Date.now();(e?this.typingOn&&t-this.typingAt<Re:!this.typingOn)||(this.typingOn=e,this.typingAt=t,w(this.api,"typing",this.body({on:e})))}async command(e){for(let t=0;t<4&&!this.stopped;t++){let n=await w(this.api,e,this.body());if(n.ok)return this.set(I(this.chat,n.data&&n.data.conversation)),!0;if(!F(n))return this.fail(n);await q(M(t,this.random))}return!1}finish(){if(this.stopped)return;this.closeStream(),clearTimeout(this.timer);let e=this.chat.conversation.ticket;if(this.chat.conversation.state==="ticket"&&(!e||e.number==null)&&!this.numberTried){this.numberTried=!0,this.timer=setTimeout(()=>{this.sync().then(()=>this.end())},2e3);return}this.end()}end(){this.stopped||(this.stop(),this.cb.ended())}stop(){this.stopped=!0,this.closeStream(),clearTimeout(this.timer),clearTimeout(this.typingTimer),window.removeEventListener("online",this.onOnline)}};var $e=`
2
+ .lstatus{flex:none;padding:8px 14px;font-size:13px;line-height:1.6;color:#374151;background:#fff;border-block-end:1px solid #e3e6ea}
3
+ .lsys{align-self:center;max-width:90%;text-align:center;font-size:12px;color:#6b7280;padding:2px 8px}
4
+ .lsep{margin-block:6px;border-block-start:1px solid #e3e6ea;padding-block-start:8px;align-self:stretch;max-width:none}
5
+ .lname{display:block;font-size:11px;font-weight:600;color:#6b7280}
6
+ .lp-sending{opacity:.65}
7
+ .lp-failed{opacity:.85;outline:1px solid #b42318}
8
+ .lp-failed .btn{display:block;margin-block-start:6px;padding:3px 8px;font-size:12px;color:#b42318;background:#fff;border-color:#b42318}
9
+ .ltyping{flex:none;padding:0 14px 4px;font-size:12px;color:#6b7280}
10
+ .lerror{flex:none;padding:0 14px}
11
+ .lerror:empty{display:none}
12
+ .lactions{flex:none;display:flex;flex-wrap:wrap;gap:6px;padding:4px 14px 8px}
13
+ .lactions:empty{display:none}
14
+ .lactions .btn{padding:6px 12px;font-size:14px}
15
+ .note{margin:0;font-size:14px;color:#4b5563}
16
+ .composer input:disabled{opacity:.5}
17
+ .send:disabled{opacity:.5;cursor:default}
18
+ .launcher.kc-unread::after{content:"";position:absolute;inset-block-start:4px;inset-inline-end:4px;width:12px;height:12px;border-radius:50%;background:#e11d48;border:2px solid #fff}
19
+ `;var Y=i=>`kavchat:live:${i}`,W=(i,e)=>`kavchat:live:${i}:${e}`;function pt(i){try{let e=localStorage.getItem(Y(i)),t=e&&localStorage.getItem(W(i,e)),n=t?JSON.parse(t):null;if(n&&n.id===e&&/^lvc_/.test(n.credential)&&Date.parse(n.expiresAt)>Date.now())return n;e&&K(i,e)}catch(e){}return null}function mt(i,e){try{localStorage.setItem(W(i,e.id),JSON.stringify(e)),localStorage.setItem(Y(i),e.id)}catch(t){}}function K(i,e,t){try{let n=localStorage.getItem(W(i,e));if(t&&n&&JSON.parse(n).credential!==t)return;localStorage.removeItem(W(i,e)),localStorage.getItem(Y(i))===e&&localStorage.removeItem(Y(i))}catch(n){}}var gt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,ht=()=>typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches;function Fe(i){let e=i.api.publicKey,t={...i.t,...ie(i.locale)},n=i.ui,a=d("style",null,$e);n.root.appendChild(a);let r=null,x=null,s=null,v=null,p=null,J=!1,R=null,z=new Set,le="",S,ce=0,D=!1,X=!1,l={};function de(){var o;if(r&&Date.now()-r.at<_e)return Promise.resolve();if(!x){let c=!!((o=r==null?void 0:r.data)!=null&&o.open);x=Pe(i.api,"availability").then(u=>{var g;x=null,r={at:Date.now(),data:u.ok?u.data:null},!D&&c!==!!((g=r.data)!=null&&g.open)&&i.renderChips()})}return x}function ue(o){var y;let c=(y=o==null?void 0:o.departments.find(h=>h.nextOpenAt))==null?void 0:y.nextOpenAt,u=c?new Date(c):null;if(!u||isNaN(u.getTime()))return null;let g=u.toDateString()===new Date().toDateString();try{return new Intl.DateTimeFormat(i.locale,{...g?{}:{weekday:"short"},hour:"2-digit",minute:"2-digit"}).format(u)}catch(h){return null}}let ve=()=>{let o=r==null?void 0:r.data;return o&&o.enabled&&!o.open?oe(o.reason,t,o.reason==="closed"?ue(o):null):""};function Ge(o,c){let u=!i.opts.userToken,g=j(22),y=j(22),h=(T,k,H)=>d("div",{class:"field"},d("label",{for:T},k),H),m=d("input",{id:"kl-name",type:"text",autocomplete:"name",maxlength:"100",dir:"auto"});m.value=i.opts.userName||"";let L=d("input",{id:"kl-email",type:"email",autocomplete:"email",dir:"auto"}),B=d("input",{id:"kl-phone",type:"tel",autocomplete:"tel",dir:"auto"}),Z=c.departments.filter(T=>T.open),A=null;if(Z.length>1){A=d("select",{id:"kl-dept"});for(let T of Z)A.appendChild(d("option",{value:T.id},T.name))}let Q=d("textarea",{id:"kl-message",maxlength:String(U),dir:"auto"});Q.value=o.prefill||"";let V=d("div",{class:"error",role:"alert"}),N=d("button",{type:"submit",class:"btn btn-primary"},t["live.start"]),he=d("button",{type:"button",class:"btn"},t["form.cancel"]);he.addEventListener("click",()=>i.showChat());let ee=d("form",{class:"form",novalidate:!0},d("h2",null,t["live.talk"]),u?d("p",{class:"note"},t["live.intro"]):null,u?h("kl-name",t["form.name"],m):null,u?h("kl-email",t["form.email"],L):null,u?h("kl-phone",t["form.phone"],B):null,A?h("kl-dept",t["live.department"],A):null,h("kl-message",t["live.message"],Q),V,d("div",{class:"actions"},N,he));ee.addEventListener("submit",async T=>{var fe,be;T.preventDefault();let k={name:m.value.trim(),email:L.value.trim(),phone:B.value.trim(),message:Q.value.trim()},H=u&&!k.email&&!k.phone?t["form.contactRequired"]:u&&k.email&&!gt.test(k.email)?t["form.emailInvalid"]:"";if(H){V.textContent=H;return}V.textContent="",N.disabled=!0,N.textContent=t["live.connecting"];let te={requestId:g,sessionId:(fe=i.session)==null?void 0:fe.id,identityToken:i.opts.userToken,...u?{name:k.name||void 0,email:k.email||void 0,phone:k.phone||void 0}:{},departmentId:A?A.value:(be=Z[0])==null?void 0:be.id,topicId:o.contactTopicId||void 0,...k.message?{message:k.message,messageClientId:y}:{},page:location.href.split(/[?#]/)[0],transcript:o.transcript.slice(-200).map(b=>({...b,text:b.text.slice(0,1e3)}))},f=await w(i.api,"requests",te);for(let b=0;b<2&&F(f);b++)await q(M(b)),f=await w(i.api,"requests",te);if(!D)if(N.disabled=!1,N.textContent=t["live.start"],f.ok&&f.data.accepted){let b=f.data;v={id:b.conversation.id,credential:b.credential,expiresAt:b.credentialExpiresAt,transcript:te.transcript},mt(e,v),pe(b.conversation,!1)}else if(f.ok){let b=r==null?void 0:r.data;r=null,i.showForm(o,{...k,note:oe(f.data.reason,t,f.data.reason==="closed"?ue(b):null)})}else V.textContent=f.code==="ticket_contact_required"?t["form.contactRequired"]:f.code==="email_invalid"?t["form.emailInvalid"]:f.code==="live_conversation_open"?t["live.elsewhere"]:f.code==="network"?t["form.error"]:f.message||t["form.error"]}),n.formView.replaceChildren(ee),n.chatView.hidden=!0,n.formView.hidden=!1,i.isOpen&&(ee.querySelector("input,select,textarea")||n.panel).focus()}function pe(o,c){let u=v;s==null||s.stop(),z=new Set,R=null,J=!1;let g=new G(i.api,u.credential,o,{change:()=>_(),typing:y=>{J=y,me()},notice:y=>{R=y,_()},ended:()=>{K(e,u.id,u.credential),_()}});return s=g,Ke(),c||(_(),g.connect()),g}function Ke(){if(p)return;l.status=d("div",{class:"lstatus"}),l.msgs=d("div",{class:"messages"}),l.typing=d("div",{class:"ltyping","aria-hidden":"true"},t["live.typing"]),l.actions=d("div",{class:"lactions"}),l.error=d("div",{class:"error lerror",role:"alert"}),l.input=d("input",{type:"text",dir:"auto",maxlength:String(U),autocomplete:"off",placeholder:t["live.placeholder"],"aria-label":t["live.placeholder"],enterkeyhint:"send"}),l.send=d("button",{type:"submit",class:"send","aria-label":t["widget.send"]},Oe(Be.send));let o=d("form",{class:"composer"},l.input,l.send);o.addEventListener("submit",c=>{if(c.preventDefault(),!s)return;let u=s.send(l.input.value);u==="ok"?(l.input.value="",l.error.textContent=""):u==="too_long"&&(l.error.textContent=t["live.tooLong"])}),l.input.addEventListener("input",()=>s==null?void 0:s.typing(l.input.value.trim()!=="")),p=d("div",{class:"view lv"},l.status,l.msgs,l.typing,l.error,l.actions,o),n.panel.insertBefore(p,n.live)}function O(o,c,u=!1){let g=d("button",{type:"button",class:u?"btn btn-primary":"btn"},o);return g.addEventListener("click",c),g}function Ye(){s&&(s.stop(),v&&K(e,v.id,v.credential)),s=null,v=null,clearInterval(S),S=void 0,p==null||p.remove(),p=null,i.showChat()}function me(){!p||!s||(l.typing.hidden=!(J&&s.chat.conversation.state==="active"))}function _(){if(X||!p||!s||!v)return;let o=s.chat,c=o.conversation,g=C(c.state)||R==="replaced";n.chatView.hidden=!0,n.formView.hidden=!0,p.hidden=!1,ge();let y=l.msgs.scrollHeight-l.msgs.scrollTop-l.msgs.clientHeight<40;l.msgs.textContent="";for(let m of v.transcript)l.msgs.appendChild(d("div",{class:`msg msg-${m.from==="user"?"user":"bot"}`,dir:"auto"},m.text));v.transcript.length&&l.msgs.appendChild(d("div",{class:"lsys lsep"},t["live.talk"]));let h=[];for(let m of se(o,t)){let L;if(m.kind==="system")L=d("div",{class:"lsys"},m.text);else if(m.kind==="agent")L=d("div",{class:"msg msg-bot",dir:"auto"},d("span",{class:"lname"},m.name||""),m.text);else if(L=d("div",{class:`msg msg-user${m.status?` lp-${m.status}`:""}`,dir:"auto"},m.text),m.status==="failed"){let B=m.clientId;L.appendChild(O(t["live.failed"],()=>s==null?void 0:s.retrySend(B)))}else m.status==="sending"&&L.setAttribute("aria-busy","true");l.msgs.appendChild(L),z.has(m.key)||(z.add(m.key),m.kind!=="visitor"&&h.push(m.kind==="agent"?`${m.name}: ${m.text}`:m.text))}h.length&&(n.live.textContent=h.join(`
20
+ `),i.isOpen||n.launcher.classList.add("kc-unread")),(y||h.length)&&(l.msgs.scrollTop=l.msgs.scrollHeight),me(),l.actions.textContent="",g?l.actions.appendChild(O(t["live.back"],Ye,!0)):(c.state==="queued"&&l.actions.appendChild(O(t["live.leave"],()=>{s==null?void 0:s.command("leave-message")})),l.actions.appendChild(O(t["live.end"],()=>{s==null?void 0:s.command("end")}))),l.input.disabled=g,l.send.disabled=g,c.state!==le&&(le=c.state,i.emit({type:"live",state:c.state,id:c.id})),c.state==="queued"&&c.queueDeadline&&!S&&(S=setInterval(We,1e3)),c.state!=="queued"&&S&&(clearInterval(S),S=void 0)}function ge(){if(!s)return;let o=s.chat.conversation;l.status.textContent=R==="replaced"?t["live.replaced"]:`${je(o,t,Date.now())}${R==="reconnecting"&&!C(o.state)?` · ${t["live.reconnecting"]}`:""}`}function We(){if(!s)return;ge(),re(s.chat.conversation,Date.now())===0&&Date.now()-ce>1e4&&(ce=Date.now(),s.sync())}return{chips(o){var c,u,g;return!((u=(c=i.release)==null?void 0:c.liveChat)!=null&&u.enabled)||!o.some(y=>y.kind==="contact")?o:(de(),(g=r==null?void 0:r.data)!=null&&g.open?qe(o,t["live.talk"]):o)},note:ve,async start(o){if(await de(),D)return;let c=r==null?void 0:r.data;c&&c.open?Ge(o,c):i.showForm(o,{note:ve()})},async restore(){let o=pt(e);if(!o)return;v=o,X=!0;let c=pe({id:o.id,state:"queued",lastSeq:0,credentialExpiresAt:o.expiresAt},!0),u=await c.sync();if(X=!1,!(D||s!==c)){if(!u&&c.final&&c.chat.events.length===0){c.stop(),K(e,o.id,o.credential),s=null,v=null,p==null||p.remove(),p=null;return}for(let g of se(c.chat,t))z.add(g.key);_(),c.connect()}},focus(){return!p||p.hidden?!1:(n.launcher.classList.remove("kc-unread"),ht()||l.input.disabled?n.panel.focus():l.input.focus(),!0)},destroy(){D=!0,s==null||s.stop(),clearInterval(S),p==null||p.remove(),a.remove()}}}window.KavchatLive={createLive:Fe};})();
package/dist/kavchat.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";(()=>{var Yu=["he","en","ar","ru","es","fr","de","pt","it","tr","th"],Wu={ך:"כ",ם:"מ",ן:"נ",ף:"פ",ץ:"צ",أ:"ا",إ:"ا",آ:"ا",ٱ:"ا",ة:"ه",ى:"ي",ؤ:"و",ئ:"ي",ё:"е",ß:"ss",ı:"i"};function Ju(e){return e>=768&&e<=879||e>=1425&&e<=1479||e>=1552&&e<=1562||e>=1611&&e<=1631||e===1648||e>=1750&&e<=1773}function au(e){return e>=3585&&e<=3630||e>=3632&&e<=3642||e>=3648&&e<=3653||e>=3655&&e<=3662||e>=3713&&e<=3758||e>=3760&&e<=3781||e>=3784&&e<=3790||e>=3804&&e<=3807||e>=4096&&e<=4169||e>=4176&&e<=4253||e>=6016&&e<=6099||e===6108||e===6109||e===12293||e>=12353&&e<=12438||e>=12441&&e<=12442||e>=12445&&e<=12447||e>=12449&&e<=12538||e>=12540&&e<=12543||e>=13312&&e<=19903||e>=19968&&e<=40959}function U(e){for(let u=0;u<e.length;u++)if(au(e.charCodeAt(u)))return!0;return!1}function Xu(e){let u=e.charCodeAt(0);return u>=48&&u<=57||u>=1632&&u<=1641||u>=1488&&u<=1514||u>=1568&&u<=1610||u>=1649&&u<=1747||au(u)?!0:e.toLowerCase()!==e.toUpperCase()}var Zu=e=>e>=8203&&e<=8205||e===8288||e===65279,ue=[3664,3792,4160,6112];function ee(e){for(let u of ue)if(e>=u&&e<=u+9)return String.fromCharCode(48+e-u)}var q={3640:103,3641:103,3642:9,3656:107,3657:107,3658:107,3659:107,3768:118,3769:118,3770:9,3784:122,3785:122,3786:122,3787:122,4151:7,4153:9,4154:9,4237:220,6098:9,6109:230,12441:8,12442:8},ou=e=>e>=3656&&e<=3659;function te(e){if(!/[\u0e33\u0e38-\u0e3a\u0e48-\u0e4b\u0e4d\u0eb8-\u0eba\u0ec8-\u0ecb\u1037\u1039\u103a\u108d\u17d2\u17dd\u3099\u309a]/.test(e))return e;let u=[];for(let t=0;t<e.length;t++)u.push(e.charCodeAt(t));for(let t=0;t<u.length;t++){if(!q[u[t]])continue;let i=t;for(;i<u.length&&q[u[i]];)i++;for(let o=t+1;o<i;o++){let r=u[o],a=o-1;for(;a>=t&&q[u[a]]>q[r];)u[a+1]=u[a],a--;u[a+1]=r}t=i-1}let n="";for(let t=0;t<u.length;t++){let i=u[t];i===3661&&u[t+1]===3634?(n+="ำ",t++):i===3661&&ou(u[t+1])&&u[t+2]===3634?(n+=String.fromCharCode(u[t+1],3635),t+=2):i===3635&&ou(u[t+1])?(n+=String.fromCharCode(u[t+1],3635),t++):n+=String.fromCharCode(i)}return n}var ne=e=>{try{return e.normalize("NFD")}catch(u){return e}};function $(e){var u,n;let t=ne(String(e!=null?e:"").toLowerCase()),i="";for(let r of t){let a=r.charCodeAt(0);if(Ju(a)||Zu(a))continue;let c=(n=(u=Wu[r])!=null?u:ee(a))!=null?n:r;i+=c.length===1&&!Xu(c)?" ":c}let o=te(i).replace(/\s+/g," ").trim();return o?o.split(" "):[]}var ie={he:["איך","מה","אני","של","עם","את","זה","יש","אפשר","לי","על","או","גם","רוצה","צריך","האם","למה","מתי","איפה","כמה","אתם","שלי","לכם","אין","לא"],en:["how","what","i","my","me","the","a","an","is","are","do","does","can","to","of","in","on","for","with","and","or","it","you","your","want","need","please","when","where","why","which","there","this","that","be","get","not","no"],ar:["كيف","ماذا","ما","انا","في","على","من","الى","عن","هل","هذا","هذه","او","و","لي","متى","اين","لماذا","كم","اريد","ممكن","لا"],ru:["как","что","я","мне","мой","моя","в","на","с","и","или","не","это","где","когда","почему","сколько","можно","хочу","нужно","у","по","для","ли","есть"],es:["como","que","yo","mi","me","el","la","los","las","un","una","de","del","en","con","por","para","y","o","es","se","puedo","quiero","cuando","donde","cual","hay","no"],fr:["comment","que","quoi","je","mon","ma","mes","le","la","les","un","une","de","des","du","en","avec","pour","et","ou","est","il","elle","puis","veux","quand","ou","pourquoi","combien","ne","pas","j","l","d","qu"],de:["wie","was","ich","mein","meine","mir","der","die","das","ein","eine","und","oder","in","mit","fur","von","zu","ist","kann","mochte","wann","wo","warum","nicht","es","den","dem"],pt:["como","que","eu","meu","minha","o","a","os","as","um","uma","de","do","da","em","no","na","com","para","por","e","ou","posso","quero","quando","onde","porque","nao"],it:["come","che","cosa","io","mio","mia","il","lo","la","i","gli","le","un","una","di","del","della","in","con","per","e","o","posso","voglio","quando","dove","perche","non","l"],tr:["nasil","ne","ben","benim","bir","ve","veya","ile","icin","bu","su","mi","mu","nerede","ne zaman","neden","kac","istiyorum","var","yok","de","da"],th:["ฉัน","ผม","ดิฉัน","คุณ","ครับ","ค่ะ","คะ","นะ","ไหม","มั้ย","อะไร","อย่างไร","ยังไง","ที่","และ","หรือ","ของ","ได้","จะ","ใน","กับ","เป็น","มี","ไม่","ให้","ว่า","อยาก","ต้องการ","เมื่อไหร่","ที่ไหน","ทำไม","เท่าไหร่"]},L={};for(let e of Yu)L[e]=new Set(ie[e].flatMap(u=>$(u)));var oe=["ו","ה","ב","ל","מ","ש","כ"],re=["وال","بال","لل","كال","فال","ال","و","ب","ل","ف"],ae=e=>e>=97&&e<=122||e>=224&&e<=591;function se(e){let u=e,n=u.charCodeAt(0);if(ae(n))return u.length>3&&u.endsWith("s")&&!/(ss|us|is)$/.test(u)?u.slice(0,-1):u;if(n>=1488&&n<=1514){for(let t=0;t<2&&(u.length>3&&oe.includes(u[0]));t++)u=u.slice(1);return u}if(n>=1568&&n<=1610){for(let t of re)if(u.startsWith(t)&&u.length-t.length>=3)return u.slice(t.length)}return u}function ru(e,u="en"){var n;let t=(n=L[u])!=null?n:L.en,i=L.en;return $(e).filter(o=>o.length>1&&!t.has(o)&&!i.has(o)).map(se)}function ce(e,u){if(e===u)return!0;if(Math.abs(e.length-u.length)>1||Math.min(e.length,u.length)<4)return!1;if(e.length===u.length){let o=[];for(let r=0;r<e.length&&o.length<=2;r++)e[r]!==u[r]&&o.push(r);if(o.length===2&&o[1]===o[0]+1&&e[o[0]]===u[o[1]]&&e[o[1]]===u[o[0]])return!0}let n=0,t=0,i=0;for(;n<e.length&&t<u.length;){if(e[n]===u[t]){n++,t++;continue}if(++i>1)return!1;e.length>u.length?n++:(u.length>e.length||n++,t++)}return i+(e.length-n)+(u.length-t)<=1}var le=e=>String(e!=null?e:"").split(/\n\s*\n/).map(u=>u.trim()).filter(Boolean);function su(e,u,n="en"){var t,i;let o=Array.from(new Set(ru(u,n)));if(o.length===0)return{kind:"none",matches:[]};let r=p=>p.flatMap(E=>ru(E,n)),a=o.filter(p=>!U(p)),c=$(u).join(""),f=[];for(let p of e){if(p.kind==="opening")continue;let E=p.content,A=new Map;for(let b of E.steps)for(let d of b.buttons){let l=d.action;l&&(l.type==="step"||l.type==="goto"&&!l.scriptId)&&A.set(l.stepId,[...(t=A.get(l.stepId))!=null?t:[],d.label])}for(let b of E.steps){let d=b.id===E.rootStepId,l=r([...b.keywords,...d?E.keywords:[]]),w=r([...d?[E.name]:[],...(i=A.get(b.id))!=null?i:[]]),v=[...l,...w].filter(h=>!U(h)),x=0,y=[];for(let h of a)l.includes(h)?(x+=3,y.push({kind:"keyword",term:h})):w.includes(h)?(x+=2,y.push({kind:"title",term:h})):v.some(F=>ce(h,F))&&(x+=.5,y.push({kind:"typo",term:h}));for(let h of Ee(l,w,c))x+=h.weight,y.push({kind:h.weight===3?"keyword":"title",term:h.term});x>0&&f.push({scriptId:p.id,stepId:b.id,score:x,reasons:y})}}if(f.sort((p,E)=>E.score-p.score),f.length===0)return{kind:"none",matches:[]};let[m,k]=f;return!k||m.score>=k.score*2?{kind:"single",matches:[m]}:{kind:"multi",matches:f.filter(p=>p.score>=m.score/2).slice(0,3)}}function Ee(e,u,n){let t=[],i=new Set;for(let[o,r]of[[e,3],[u,2]])for(let a of o)i.has(a)||!U(a)||(i.add(a),n.includes(a)&&t.push({term:a,weight:r}));return t.filter(o=>!t.some(r=>r.term!==o.term&&r.weight>=o.weight&&r.term.includes(o.term)))}var j={"chat.askAnswered":"Did that answer your question?","chat.yes":"Yes, thanks","chat.no":"No, I need help","chat.thanks":"Glad I could help!","chat.newQuestion":"New question","chat.back":"Back","chat.home":"Main menu","chat.didYouMean":"What did you mean?","chat.notFound":"I could not find an answer to that. Pick a topic from the menu, or talk to our team.","chat.notFoundTwice":"I could not find an answer. Our team will be happy to help, and your question is already in the form.","chat.contactChip":"Talk to our team","chat.openingContact":"Opening the contact form. This conversation will be attached to your request.","chat.chooseTopic":"How can I help?","chat.aiLabel":"AI answer","widget.open":"Open chat","widget.close":"Close chat","widget.placeholder":"Type your question...","widget.send":"Send","widget.poweredBy":"Powered by Kavchat","widget.offline":"You are offline. Showing saved answers.","widget.loading":"Loading...","widget.unavailable":"The assistant is not available right now.","form.title":"Contact us","form.name":"Name","form.email":"Email","form.phone":"Phone","form.topic":"Topic","form.message":"Message","form.submit":"Send","form.cancel":"Cancel","form.sending":"Sending...","form.sent":"Thanks! Your request #{number} was received. We will get back to you soon.","form.error":"Something went wrong. Please try again.","form.required":"Required","form.contactRequired":"Leave an email or a phone number so we can get back to you","form.emailInvalid":"Invalid email address","form.backToChat":"Back to chat"},de={"chat.askAnswered":"קיבלת מענה?","chat.yes":"כן, תודה","chat.no":"לא, אני צריך עזרה","chat.thanks":"שמחתי לעזור!","chat.newQuestion":"שאלה חדשה","chat.back":"חזרה","chat.home":"תפריט ראשי","chat.didYouMean":"למה התכוונת?","chat.notFound":"לא מצאתי תשובה לשאלה הזו. אפשר לבחור נושא מהתפריט, או לפנות לצוות.","chat.notFoundTwice":"לא הצלחתי למצוא תשובה. הצוות ישמח לעזור, והשאלה שלך כבר תהיה כתובה בטופס.","chat.contactChip":"פנייה לצוות","chat.openingContact":"פותח את טופס הפנייה. מסלול השיחה יצורף לפנייה.","chat.chooseTopic":"במה אפשר לעזור?","chat.aiLabel":"תשובת AI","widget.open":"פתיחת הצ'אט","widget.close":"סגירת הצ'אט","widget.placeholder":"כתבו את השאלה...","widget.send":"שליחה","widget.poweredBy":"מופעל על ידי Kavchat","widget.offline":"אין חיבור לאינטרנט. מוצגות תשובות שמורות.","widget.loading":"טוען...","widget.unavailable":"העוזר לא זמין כרגע.","form.title":"פנייה לצוות","form.name":"שם","form.email":"אימייל","form.phone":"טלפון","form.topic":"נושא","form.message":"הודעה","form.submit":"שליחה","form.cancel":"ביטול","form.sending":"שולח...","form.sent":"תודה! פנייה מספר {number} התקבלה. נחזור אליכם בקרוב.","form.error":"משהו השתבש. נסו שוב.","form.required":"שדה חובה","form.contactRequired":"השאירו אימייל או טלפון כדי שנוכל לחזור אליכם","form.emailInvalid":"כתובת אימייל לא תקינה","form.backToChat":"חזרה לצ'אט"},pe={"chat.askAnswered":"هل أجبت عن سؤالك؟","chat.yes":"نعم، شكرًا","chat.no":"لا، أحتاج مساعدة","chat.thanks":"سعدت بمساعدتك!","chat.newQuestion":"سؤال جديد","chat.back":"رجوع","chat.home":"القائمة الرئيسية","chat.didYouMean":"ماذا تقصد؟","chat.notFound":"لم أجد إجابة عن هذا السؤال. اختر موضوعًا من القائمة، أو تواصل مع فريقنا.","chat.notFoundTwice":"لم أتمكن من العثور على إجابة. يسعد فريقنا مساعدتك، وسؤالك مكتوب بالفعل في النموذج.","chat.contactChip":"تواصل مع الفريق","chat.openingContact":"جارٍ فتح نموذج التواصل. ستُرفق هذه المحادثة بطلبك.","chat.chooseTopic":"كيف يمكنني مساعدتك؟","chat.aiLabel":"إجابة من الذكاء الاصطناعي","widget.open":"فتح المحادثة","widget.close":"إغلاق المحادثة","widget.placeholder":"اكتب سؤالك...","widget.send":"إرسال","widget.poweredBy":"بدعم من Kavchat","widget.offline":"أنت غير متصل بالإنترنت. نعرض الإجابات المحفوظة.","widget.loading":"جارٍ التحميل...","widget.unavailable":"المساعد غير متاح حاليًا.","form.title":"تواصل معنا","form.name":"الاسم","form.email":"البريد الإلكتروني","form.phone":"الهاتف","form.topic":"الموضوع","form.message":"الرسالة","form.submit":"إرسال","form.cancel":"إلغاء","form.sending":"جارٍ الإرسال...","form.sent":"شكرًا! تم استلام طلبك رقم {number}. سنعود إليك قريبًا.","form.error":"حدث خطأ ما. يرجى المحاولة مرة أخرى.","form.required":"مطلوب","form.contactRequired":"اترك بريدًا إلكترونيًا أو رقم هاتف لنتمكن من الرد عليك","form.emailInvalid":"عنوان البريد الإلكتروني غير صالح","form.backToChat":"العودة إلى المحادثة"},he={"chat.askAnswered":"Это ответило на ваш вопрос?","chat.yes":"Да, спасибо","chat.no":"Нет, нужна помощь","chat.thanks":"Рад помочь!","chat.newQuestion":"Новый вопрос","chat.back":"Назад","chat.home":"Главное меню","chat.didYouMean":"Что вы имели в виду?","chat.notFound":"Я не нашёл ответа на этот вопрос. Выберите тему в меню или напишите нашей команде.","chat.notFoundTwice":"Не удалось найти ответ. Наша команда с радостью поможет, а ваш вопрос уже добавлен в форму.","chat.contactChip":"Связаться с нами","chat.openingContact":"Открываю форму обращения. Этот диалог будет приложен к вашему запросу.","chat.chooseTopic":"Чем могу помочь?","chat.aiLabel":"Ответ ИИ","widget.open":"Открыть чат","widget.close":"Закрыть чат","widget.placeholder":"Введите ваш вопрос...","widget.send":"Отправить","widget.poweredBy":"Работает на Kavchat","widget.offline":"Нет подключения к интернету. Показываем сохранённые ответы.","widget.loading":"Загрузка...","widget.unavailable":"Ассистент сейчас недоступен.","form.title":"Связаться с нами","form.name":"Имя","form.email":"Email","form.phone":"Телефон","form.topic":"Тема","form.message":"Сообщение","form.submit":"Отправить","form.cancel":"Отмена","form.sending":"Отправка...","form.sent":"Спасибо! Ваше обращение №{number} получено. Мы скоро с вами свяжемся.","form.error":"Что-то пошло не так. Попробуйте ещё раз.","form.required":"Обязательное поле","form.contactRequired":"Укажите email или номер телефона, чтобы мы могли с вами связаться","form.emailInvalid":"Неверный адрес email","form.backToChat":"Вернуться в чат"},fe={"chat.askAnswered":"¿Resolvimos tu duda?","chat.yes":"Sí, gracias","chat.no":"No, necesito ayuda","chat.thanks":"¡Me alegra haberte ayudado!","chat.newQuestion":"Nueva pregunta","chat.back":"Atrás","chat.home":"Menú principal","chat.didYouMean":"¿Qué quisiste decir?","chat.notFound":"No encontré una respuesta para eso. Elige un tema del menú o habla con nuestro equipo.","chat.notFoundTwice":"No pude encontrar una respuesta. Nuestro equipo te ayudará con gusto, y tu pregunta ya está en el formulario.","chat.contactChip":"Hablar con el equipo","chat.openingContact":"Abriendo el formulario de contacto. Esta conversación se adjuntará a tu solicitud.","chat.chooseTopic":"¿En qué te puedo ayudar?","chat.aiLabel":"Respuesta de IA","widget.open":"Abrir chat","widget.close":"Cerrar chat","widget.placeholder":"Escribe tu pregunta...","widget.send":"Enviar","widget.poweredBy":"Con la tecnología de Kavchat","widget.offline":"Estás sin conexión. Mostrando respuestas guardadas.","widget.loading":"Cargando...","widget.unavailable":"El asistente no está disponible en este momento.","form.title":"Contáctanos","form.name":"Nombre","form.email":"Correo electrónico","form.phone":"Teléfono","form.topic":"Tema","form.message":"Mensaje","form.submit":"Enviar","form.cancel":"Cancelar","form.sending":"Enviando...","form.sent":"¡Gracias! Recibimos tu solicitud n.º {number}. Te responderemos pronto.","form.error":"Algo salió mal. Inténtalo de nuevo.","form.required":"Obligatorio","form.contactRequired":"Deja un correo o un teléfono para que podamos responderte","form.emailInvalid":"Correo electrónico no válido","form.backToChat":"Volver al chat"},me={"chat.askAnswered":"Avez-vous trouvé votre réponse ?","chat.yes":"Oui, merci","chat.no":"Non, aidez-moi","chat.thanks":"Ravi d'avoir pu vous aider !","chat.newQuestion":"Nouvelle question","chat.back":"Retour","chat.home":"Menu principal","chat.didYouMean":"Que vouliez-vous dire ?","chat.notFound":"Je n'ai pas trouvé de réponse à cette question. Choisissez un sujet dans le menu ou contactez notre équipe.","chat.notFoundTwice":"Je n'ai pas trouvé de réponse. Notre équipe se fera un plaisir de vous aider, et votre question figure déjà dans le formulaire.","chat.contactChip":"Contacter l'équipe","chat.openingContact":"Ouverture du formulaire de contact. Cette conversation sera jointe à votre demande.","chat.chooseTopic":"Comment puis-je vous aider ?","chat.aiLabel":"Réponse de l'IA","widget.open":"Ouvrir le chat","widget.close":"Fermer le chat","widget.placeholder":"Écrivez votre question...","widget.send":"Envoyer","widget.poweredBy":"Propulsé par Kavchat","widget.offline":"Vous êtes hors ligne. Affichage des réponses enregistrées.","widget.loading":"Chargement...","widget.unavailable":"L'assistant n'est pas disponible pour le moment.","form.title":"Nous contacter","form.name":"Nom","form.email":"E-mail","form.phone":"Téléphone","form.topic":"Sujet","form.message":"Message","form.submit":"Envoyer","form.cancel":"Annuler","form.sending":"Envoi en cours...","form.sent":"Merci ! Votre demande n° {number} a bien été reçue. Nous vous répondrons rapidement.","form.error":"Une erreur s'est produite. Veuillez réessayer.","form.required":"Obligatoire","form.contactRequired":"Indiquez un e-mail ou un numéro de téléphone pour que nous puissions vous répondre","form.emailInvalid":"Adresse e-mail invalide","form.backToChat":"Retour au chat"},ge={"chat.askAnswered":"Hat Ihnen das weitergeholfen?","chat.yes":"Ja, danke","chat.no":"Nein, Hilfe bitte","chat.thanks":"Freut mich, dass ich helfen konnte!","chat.newQuestion":"Neue Frage","chat.back":"Zurück","chat.home":"Hauptmenü","chat.didYouMean":"Was meinten Sie?","chat.notFound":"Dazu habe ich leider keine Antwort gefunden. Wählen Sie ein Thema aus dem Menü oder wenden Sie sich an unser Team.","chat.notFoundTwice":"Ich konnte keine Antwort finden. Unser Team hilft Ihnen gerne weiter, und Ihre Frage steht bereits im Formular.","chat.contactChip":"Team kontaktieren","chat.openingContact":"Das Kontaktformular wird geöffnet. Dieser Chatverlauf wird Ihrer Anfrage beigefügt.","chat.chooseTopic":"Wie kann ich helfen?","chat.aiLabel":"KI-Antwort","widget.open":"Chat öffnen","widget.close":"Chat schließen","widget.placeholder":"Ihre Frage eingeben...","widget.send":"Senden","widget.poweredBy":"Bereitgestellt von Kavchat","widget.offline":"Sie sind offline. Gespeicherte Antworten werden angezeigt.","widget.loading":"Wird geladen...","widget.unavailable":"Der Assistent ist gerade nicht verfügbar.","form.title":"Kontakt","form.name":"Name","form.email":"E-Mail","form.phone":"Telefon","form.topic":"Thema","form.message":"Nachricht","form.submit":"Senden","form.cancel":"Abbrechen","form.sending":"Wird gesendet...","form.sent":"Vielen Dank! Ihre Anfrage Nr. {number} ist eingegangen. Wir melden uns in Kürze bei Ihnen.","form.error":"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.","form.required":"Pflichtfeld","form.contactRequired":"Bitte geben Sie eine E-Mail-Adresse oder Telefonnummer an, damit wir uns melden können","form.emailInvalid":"Ungültige E-Mail-Adresse","form.backToChat":"Zurück zum Chat"},De={"chat.askAnswered":"Isso respondeu à sua pergunta?","chat.yes":"Sim, obrigado","chat.no":"Não, preciso de ajuda","chat.thanks":"Que bom que pude ajudar!","chat.newQuestion":"Nova pergunta","chat.back":"Voltar","chat.home":"Menu principal","chat.didYouMean":"O que você quis dizer?","chat.notFound":"Não encontrei uma resposta para isso. Escolha um assunto no menu ou fale com a nossa equipe.","chat.notFoundTwice":"Não consegui encontrar uma resposta. Nossa equipe vai ajudar com prazer, e sua pergunta já está no formulário.","chat.contactChip":"Falar com a equipe","chat.openingContact":"Abrindo o formulário de contato. Esta conversa será anexada à sua solicitação.","chat.chooseTopic":"Como posso ajudar?","chat.aiLabel":"Resposta de IA","widget.open":"Abrir chat","widget.close":"Fechar chat","widget.placeholder":"Digite sua pergunta...","widget.send":"Enviar","widget.poweredBy":"Desenvolvido por Kavchat","widget.offline":"Você está offline. Mostrando respostas salvas.","widget.loading":"Carregando...","widget.unavailable":"O assistente não está disponível no momento.","form.title":"Fale conosco","form.name":"Nome","form.email":"E-mail","form.phone":"Telefone","form.topic":"Assunto","form.message":"Mensagem","form.submit":"Enviar","form.cancel":"Cancelar","form.sending":"Enviando...","form.sent":"Obrigado! Sua solicitação nº {number} foi recebida. Retornaremos em breve.","form.error":"Algo deu errado. Tente novamente.","form.required":"Obrigatório","form.contactRequired":"Informe um e-mail ou telefone para que possamos retornar","form.emailInvalid":"Endereço de e-mail inválido","form.backToChat":"Voltar ao chat"},be={"chat.askAnswered":"Hai trovato la risposta?","chat.yes":"Sì, grazie","chat.no":"No, mi serve aiuto","chat.thanks":"Felice di esserti stato utile!","chat.newQuestion":"Nuova domanda","chat.back":"Indietro","chat.home":"Menu principale","chat.didYouMean":"Cosa intendevi?","chat.notFound":"Non ho trovato una risposta. Scegli un argomento dal menu o parla con il nostro team.","chat.notFoundTwice":"Non sono riuscito a trovare una risposta. Il nostro team sarà felice di aiutarti, e la tua domanda è già nel modulo.","chat.contactChip":"Parla con il team","chat.openingContact":"Apro il modulo di contatto. Questa conversazione sarà allegata alla tua richiesta.","chat.chooseTopic":"Come posso aiutarti?","chat.aiLabel":"Risposta dell'IA","widget.open":"Apri la chat","widget.close":"Chiudi la chat","widget.placeholder":"Scrivi la tua domanda...","widget.send":"Invia","widget.poweredBy":"Powered by Kavchat","widget.offline":"Sei offline. Mostro le risposte salvate.","widget.loading":"Caricamento...","widget.unavailable":"L'assistente non è disponibile al momento.","form.title":"Contattaci","form.name":"Nome","form.email":"Email","form.phone":"Telefono","form.topic":"Argomento","form.message":"Messaggio","form.submit":"Invia","form.cancel":"Annulla","form.sending":"Invio in corso...","form.sent":"Grazie! La tua richiesta n. {number} è stata ricevuta. Ti risponderemo presto.","form.error":"Qualcosa è andato storto. Riprova.","form.required":"Obbligatorio","form.contactRequired":"Lascia un'email o un numero di telefono per poterti ricontattare","form.emailInvalid":"Indirizzo email non valido","form.backToChat":"Torna alla chat"},ve={"chat.askAnswered":"Sorunuza yanıt bulabildiniz mi?","chat.yes":"Evet, teşekkürler","chat.no":"Hayır, yardım lazım","chat.thanks":"Yardımcı olabildiğime sevindim!","chat.newQuestion":"Yeni soru","chat.back":"Geri","chat.home":"Ana menü","chat.didYouMean":"Ne demek istediniz?","chat.notFound":"Bununla ilgili bir yanıt bulamadım. Menüden bir konu seçin veya ekibimizle görüşün.","chat.notFoundTwice":"Bir yanıt bulamadım. Ekibimiz size memnuniyetle yardımcı olur, sorunuz forma zaten eklendi.","chat.contactChip":"Ekibe ulaşın","chat.openingContact":"İletişim formu açılıyor. Bu konuşma talebinize eklenecek.","chat.chooseTopic":"Size nasıl yardımcı olabilirim?","chat.aiLabel":"Yapay zekâ yanıtı","widget.open":"Sohbeti aç","widget.close":"Sohbeti kapat","widget.placeholder":"Sorunuzu yazın...","widget.send":"Gönder","widget.poweredBy":"Kavchat ile desteklenmektedir","widget.offline":"Çevrimdışısınız. Kayıtlı yanıtlar gösteriliyor.","widget.loading":"Yükleniyor...","widget.unavailable":"Asistan şu anda kullanılamıyor.","form.title":"Bize ulaşın","form.name":"Ad","form.email":"E-posta","form.phone":"Telefon","form.topic":"Konu","form.message":"Mesaj","form.submit":"Gönder","form.cancel":"İptal","form.sending":"Gönderiliyor...","form.sent":"Teşekkürler! {number} numaralı talebiniz alındı. En kısa sürede size dönüş yapacağız.","form.error":"Bir sorun oluştu. Lütfen tekrar deneyin.","form.required":"Zorunlu","form.contactRequired":"Size dönüş yapabilmemiz için bir e-posta veya telefon numarası bırakın","form.emailInvalid":"Geçersiz e-posta adresi","form.backToChat":"Sohbete dön"},xe={"chat.askAnswered":"คำตอบนี้ช่วยตอบคำถามของคุณหรือไม่","chat.yes":"ใช่ ขอบคุณ","chat.no":"ไม่ใช่ ต้องการความช่วยเหลือ","chat.thanks":"ยินดีที่ได้ช่วยเหลือ","chat.newQuestion":"ถามคำถามใหม่","chat.back":"ย้อนกลับ","chat.home":"เมนูหลัก","chat.didYouMean":"คุณหมายถึงข้อใด","chat.notFound":"ขออภัย ไม่พบคำตอบสำหรับคำถามนี้ กรุณาเลือกหัวข้อจากเมนู หรือติดต่อทีมงานของเรา","chat.notFoundTwice":"ขออภัย ไม่พบคำตอบ ทีมงานของเรายินดีช่วยเหลือ และได้ใส่คำถามของคุณไว้ในแบบฟอร์มแล้ว","chat.contactChip":"ติดต่อทีมงาน","chat.openingContact":"กำลังเปิดแบบฟอร์มติดต่อ บทสนทนานี้จะแนบไปกับคำขอของคุณ","chat.chooseTopic":"มีอะไรให้ช่วยไหม","chat.aiLabel":"คำตอบจาก AI","widget.open":"เปิดแชต","widget.close":"ปิดแชต","widget.placeholder":"พิมพ์คำถามของคุณ...","widget.send":"ส่ง","widget.poweredBy":"ขับเคลื่อนโดย Kavchat","widget.offline":"คุณออฟไลน์อยู่ กำลังแสดงคำตอบที่บันทึกไว้","widget.loading":"กำลังโหลด...","widget.unavailable":"ผู้ช่วยไม่พร้อมให้บริการในขณะนี้","form.title":"ติดต่อเรา","form.name":"ชื่อ","form.email":"อีเมล","form.phone":"โทรศัพท์","form.topic":"หัวข้อ","form.message":"ข้อความ","form.submit":"ส่ง","form.cancel":"ยกเลิก","form.sending":"กำลังส่ง...","form.sent":"ขอบคุณ เราได้รับคำขอหมายเลข {number} ของคุณแล้ว และจะติดต่อกลับโดยเร็ว","form.error":"เกิดข้อผิดพลาด กรุณาลองอีกครั้ง","form.required":"จำเป็นต้องกรอก","form.contactRequired":"กรุณาระบุอีเมลหรือหมายเลขโทรศัพท์ เพื่อให้เราติดต่อกลับได้","form.emailInvalid":"อีเมลไม่ถูกต้อง","form.backToChat":"กลับไปที่แชต"},O={en:j,he:de,ar:pe,ru:he,es:fe,fr:me,de:ge,pt:De,it:be,tr:ve,th:xe},we=["he","ar"],cu=e=>we.includes(lu(e)),lu=e=>String(e||"en").toLowerCase().split(/[-_]/)[0].replace(/^iw$/,"he");function z(e,u){var n;let t=(n=O[lu(e)])!=null?n:j;return{...j,...t,...u!=null?u:{}}}var Eu=(e,u)=>e.replace(/\{(\w+)\}/g,(n,t)=>u[t]!==void 0?String(u[t]):n),T={now:()=>Date.now()};function V(e){T={...T,...e}}var g=e=>z(e.locale,T.texts),G=()=>new Date(T.now()).toISOString();function du(e,u,n){let t=e.scripts[u],i=t==null?void 0:t.content.steps.find(o=>o.id===n);return t&&i?{script:t,step:i}:null}var Y=e=>Object.values(e.scripts).filter(u=>u.kind!=="opening").sort((u,n)=>u.sortOrder-n.sortOrder),pu=e=>Y(e).map(u=>({id:`script:${u.id}`,label:u.content.name,kind:"button",action:{type:"script",scriptId:u.id}})),R=e=>({id:"home",label:g(e)["chat.home"],kind:"home"}),Q=e=>{let u=[];return e.history.length>0&&u.push({id:"back",label:g(e)["chat.back"],kind:"back"}),u.push(R(e)),u},N=(e,u)=>({id:"contact",label:g(e)["chat.contactChip"],kind:"contact",...u?{prefill:u}:{}});function D(e,u,n,t={}){return(u==="bot"?le(n):[n]).reduce((o,r)=>({...o,seq:o.seq+1,messages:[...o.messages,{id:`m${o.seq+1}`,from:u,text:r,at:T.now(),...t}]}),e)}var hu=(e,u,n,t)=>({...e,path:[...e.path,{scriptId:u,stepId:n,via:t,at:G()}]});function C(e,u){let n=e.scripts[e.openingId],t=n==null?void 0:n.content.steps.find(r=>r.id===n.content.rootStepId),i=e.userName?`, ${e.userName}`:"",o={...e,position:null,history:[],outcome:"open"};if(u==="start"){let r=((t==null?void 0:t.text)||g(e)["chat.chooseTopic"]).replace(/\{name\}/g,i);o=D(o,"bot",r,t!=null&&t.imageUrl?{imageUrl:t.imageUrl}:{})}else o=D(o,"bot",g(e)["chat.chooseTopic"]);return o=hu(o,e.openingId,(t==null?void 0:t.id)||"welcome",u),{...o,chips:[...pu(o),N(o)]}}function S(e,u,n,t,i=!0){let o=du(e,u,n);if(!o)return C(e,"home");let{step:r}=o,a={...e,history:i&&e.position?[...e.history,e.position]:e.history,position:{scriptId:u,stepId:n},lastScriptId:u};if(a=D(a,"bot",r.text,{stepId:n,scriptId:u,...r.imageUrl?{imageUrl:r.imageUrl}:{}}),a=hu(a,u,n,t),r.buttons.length>0){let c=r.buttons.map(f=>({id:`btn:${f.id}`,label:f.label,kind:"button",action:f.action}));return{...a,chips:[...c,...Q(a)]}}return a=D(a,"bot",g(a)["chat.askAnswered"]),{...a,chips:[{id:"yes",label:g(a)["chat.yes"],kind:"yes"},{id:"no",label:g(a)["chat.no"],kind:"no"},...Q(a)]}}function ye(e){return e.messages.map(u=>({from:u.from,text:u.text,...u.stepId?{stepId:u.stepId}:{},at:new Date(u.at).toISOString()}))}function fu(e,u){let n=e.lastScriptId?e.scripts[e.lastScriptId]:null,t={type:"contact",contactTopicId:(n==null?void 0:n.content.contactTopicId)||null,scriptId:e.lastScriptId,prefill:u||"",transcript:ye(e)},i=D({...e,outcome:"contact"},"bot",g(e)["chat.openingContact"]);return{state:{...i,chips:[R(i)]},effect:t}}function mu(e){let u={scripts:Object.fromEntries(e.scripts.map(n=>[n.id,n])),openingId:e.openingScriptId,locale:e.locale||"en",userName:e.userName||"",messages:[],chips:[],position:null,history:[],path:[],unmatched:[],misses:0,outcome:"open",lastScriptId:null,lastMatch:null,seq:0};return C(u,"start")}function ke(e,u,n){var t;let i=(t=e.position)==null?void 0:t.scriptId;if(!u)return{state:C(e,"home")};switch(u.type){case"script":{let o=e.scripts[u.scriptId];return o?{state:S(e,o.id,o.content.rootStepId,"button")}:{state:C(e,"home")}}case"step":return{state:S(e,i||"",u.stepId,"button")};case"goto":return{state:S(e,u.scriptId||i||"",u.stepId,"button")};case"contact":return fu(e);case"screen":case"link":return{state:{...e,chips:n.length?n:Q(e)},effect:u};default:return{state:C(e,"home")}}}function gu(e,u){let n={...D(e,"user",u.label),chips:[],lastMatch:null};switch(u.kind){case"home":return{state:C(n,"home")};case"back":{let t=n.history[n.history.length-1];return t?(n={...n,history:n.history.slice(0,-1),position:null},{state:S(n,t.scriptId,t.stepId,"back",!1)}):{state:C(n,"home")}}case"yes":return n=D({...n,outcome:"answered"},"bot",g(n)["chat.thanks"]),{state:{...n,chips:[{id:"new",label:g(n)["chat.newQuestion"],kind:"home"}]}};case"no":case"contact":return fu(n,u.prefill);case"pick":return u.target?{state:S(n,u.target.scriptId,u.target.stepId,"text")}:{state:C(n,"home")};default:return ke(n,u.action,e.chips)}}function Ae(e,u){let n=du(e,u.scriptId,u.stepId);if(!n)return"";let{script:t,step:i}=n;if(i.id===t.content.rootStepId)return t.content.name;for(let o of t.content.steps){let r=o.buttons.find(a=>a.action&&"stepId"in a.action&&a.action.stepId===i.id);if(r)return r.label}return i.text.slice(0,25)}function W(e,u){let n=String(u!=null?u:"").trim().slice(0,500);if(!n)return{state:e};let t={...D(e,"user",n),chips:[]},i=su(Y(t),n,t.locale);if(t={...t,lastMatch:i},i.kind==="single"){let o=i.matches[0];return{state:{...S(t,o.scriptId,o.stepId,"text"),misses:0,lastMatch:i}}}if(i.kind==="multi"){t=D({...t,misses:0},"bot",g(t)["chat.didYouMean"]);let o=i.matches.map(r=>({id:`pick:${r.scriptId}:${r.stepId}`,label:Ae(t,r),kind:"pick",target:{scriptId:r.scriptId,stepId:r.stepId}}));return{state:{...t,chips:[...o,R(t)]}}}return t={...t,misses:t.misses+1,unmatched:[...t.unmatched,{text:n,at:G()}]},t.misses>=2?(t=D(t,"bot",g(t)["chat.notFoundTwice"]),{state:{...t,chips:[N(t,n),R(t)]}}):(t=D(t,"bot",g(t)["chat.notFound"]),{state:{...t,chips:[...pu(t),N(t,n)]}})}var Ce=300,Fe=600;function Du(e,u){let n=String(u!=null?u:"").trim().slice(0,500);return!n||su(Y(e),n,e.locale).kind!=="none"?null:n.slice(0,Ce)}function bu(e,u){let n=String(u!=null?u:"").trim().slice(0,500);return n?{...D(e,"user",n),chips:[]}:e}function vu(e,u,n,t){let i=String(u!=null?u:"").trim().slice(0,500),o=String(n!=null?n:"").trim().slice(0,Fe);if(!i||!o)return W(e,u);let r={...D(e,"user",i),chips:[],lastMatch:{kind:"none",matches:[]},misses:0,unmatched:[...e.unmatched,{text:i,at:G()}]};r={...r,seq:r.seq+1,messages:[...r.messages,{id:`m${r.seq+1}`,from:"bot",text:o,at:T.now(),ai:!0}]};let a=t?r.scripts[t]:void 0,c=[];return a&&a.kind!=="opening"&&c.push({id:`script:${a.id}`,label:a.content.name,kind:"button",action:{type:"script",scriptId:a.id}}),{state:{...r,chips:[...c,N(r,i),R(r)]}}}function xu(e,u,n,t){return{sessionId:u,releaseVersion:n,startedAt:t,outcome:e.outcome,path:e.path.slice(-200),unmatched:e.unmatched.slice(-20)}}var wu=(e,u)=>`${e.apiBase.replace(/\/+$/,"")}/v1/client/${encodeURIComponent(e.publicKey)}/${u}`;function yu(e,u={}){let n=e.getToken();return n?{...u,Authorization:`Bearer ${n}`}:u}async function ku(e,u){let n;try{n=await fetch(wu(e,"release"),{method:"GET",cache:"no-store",credentials:"omit",headers:yu(e,u?{"If-None-Match":u}:{})})}catch(i){return{kind:"offline"}}if(n.status===304)return{kind:"not-modified"};if(n.status>=500||n.status===429)return{kind:"offline"};if(!n.ok)return{kind:"denied",status:n.status};let t=await n.json().catch(()=>null);return!t||t.success!==!0||!t.data||typeof t.data.enabled!="boolean"?{kind:"offline"}:{kind:"ok",release:t.data,etag:n.headers.get("ETag")||""}}function K(e,u,n,t=!1,i){return fetch(wu(e,u),{method:"POST",cache:"no-store",credentials:"omit",keepalive:t,signal:i,headers:yu(e,{"Content-Type":"application/json"}),body:JSON.stringify(n)})}var Se=2e4;async function Au(e,u,n){let t=new AbortController,i=setTimeout(()=>t.abort(),Se);try{let o=await K(e,"ai/answer",{sessionId:u,question:n},!1,t.signal),r=o.ok&&(await o.json()).data;return r&&typeof r.answer=="string"&&r.answer.trim()?{answer:r.answer,scriptId:r.scriptId||null}:null}catch(o){return null}finally{clearTimeout(i)}}async function Cu(e,u,n=!1){try{return(await K(e,"events",u,n)).ok}catch(t){return!1}}async function Fu(e,u){try{return(await K(e,"screens",{platform:"web",screens:u})).ok}catch(n){return!1}}async function Su(e,u){try{let n=await K(e,"tickets",u),t=await n.json().catch(()=>null);return n.ok&&t&&t.success&&t.data?{ok:!0,id:String(t.data.id),number:Number(t.data.number)}:{ok:!1,code:String((t==null?void 0:t.code)||`http_${n.status}`),message:String((t==null?void 0:t.message)||"")}}catch(n){return{ok:!1,code:"network",message:""}}}var Te="#2563eb",J="#111827",X="#ffffff";function uu(e){let u=/^#([0-9a-f]{6})$/i.exec(String(e||"").trim());if(!u)return null;let n=parseInt(u[1],16);return[n>>16&255,n>>8&255,n&255]}function Tu(e){let[u,n,t]=e.map(i=>{let o=i/255;return o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4)});return .2126*u+.7152*n+.0722*t}function Z(e,u){var i,o;let n=Tu((i=uu(e))!=null?i:[0,0,0]),t=Tu((o=uu(u))!=null?o:[0,0,0]);return(Math.max(n,t)+.05)/(Math.min(n,t)+.05)}function Bu(e){let u=uu(e)?e.toLowerCase():Te,n=Z(u,X)>=Z(u,J)?X:J,t=Z(u,X)>=3?u:J;return{primary:u,onPrimary:n,accent:t}}function s(e,u,...n){let t=document.createElement(e);if(u)for(let[i,o]of Object.entries(u))o==null||o===!1||t.setAttribute(i,o===!0?"":o);return _(t,n),t}function _(e,u){for(let n of u)n==null||n===!1||e.appendChild(typeof n=="string"?document.createTextNode(n):n)}var Iu="http://www.w3.org/2000/svg";function B(e){let u=document.createElementNS(Iu,"svg");u.setAttribute("viewBox","0 0 24 24"),u.setAttribute("width","24"),u.setAttribute("height","24"),u.setAttribute("aria-hidden","true"),u.setAttribute("focusable","false");let n=document.createElementNS(Iu,"path");return n.setAttribute("d",e),n.setAttribute("fill","currentColor"),u.appendChild(n),u}var I={chat:"M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z",close:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z",send:"M2.01 21 23 12 2.01 3 2 10l15 2-15 2z"};function M(e,u){try{let n=new URL(String(e||"").trim());return u.includes(n.protocol)?n.href:null}catch(n){return null}}var eu=/https:\/\/[^\s<>"'`]+/g,Be=/[.,;:!?)\]}'"»]+$/;function Ru(e){let u=document.createDocumentFragment(),n=0;eu.lastIndex=0;let t;for(;t=eu.exec(e);){let i=t[0].replace(Be,""),o=M(i,["https:"]);if(!o||!i)continue;t.index>n&&u.appendChild(document.createTextNode(e.slice(n,t.index)));let r=s("a",{href:o,target:"_blank",rel:"noopener noreferrer"},i);u.appendChild(r),n=t.index+i.length,eu.lastIndex=n}return n<e.length&&u.appendChild(document.createTextNode(e.slice(n))),u}var Mu=e=>`kavchat:release:${e}`,qu=e=>`kavchat:session:${e}`,Lu=e=>`kavchat:screens:${e}`;function tu(e,u){try{let n=e().getItem(u);return n?JSON.parse(n):null}catch(n){return null}}function nu(e,u,n){try{e().setItem(u,JSON.stringify(n))}catch(t){}}var P=()=>window.localStorage,Nu=()=>window.sessionStorage,Ou=e=>tu(P,Mu(e)),zu=(e,u)=>nu(P,Mu(e),u),Ku=e=>tu(P,Lu(e)),_u=(e,u)=>nu(P,Lu(e),u),Pu=e=>tu(Nu,qu(e)),Hu=(e,u)=>nu(Nu,qu(e),u),Ie="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";function Uu(e=22){let u=new Uint8Array(e);if(typeof crypto!="undefined"&&crypto.getRandomValues)crypto.getRandomValues(u);else for(let t=0;t<e;t++)u[t]=Math.floor(Math.random()*256);let n="";for(let t=0;t<e;t++)n+=Ie[u[t]&63];return n}var ju=`
1
+ "use strict";(()=>{var ht=["he","en","ar","ru","es","fr","de","pt","it","tr","th"],mt={ך:"כ",ם:"מ",ן:"נ",ף:"פ",ץ:"צ",أ:"ا",إ:"ا",آ:"ا",ٱ:"ا",ة:"ه",ى:"ي",ؤ:"و",ئ:"ي",ё:"е",ß:"ss",ı:"i"};function ft(t){return t>=768&&t<=879||t>=1425&&t<=1479||t>=1552&&t<=1562||t>=1611&&t<=1631||t===1648||t>=1750&&t<=1773}function pe(t){return t>=3585&&t<=3630||t>=3632&&t<=3642||t>=3648&&t<=3653||t>=3655&&t<=3662||t>=3713&&t<=3758||t>=3760&&t<=3781||t>=3784&&t<=3790||t>=3804&&t<=3807||t>=4096&&t<=4169||t>=4176&&t<=4253||t>=6016&&t<=6099||t===6108||t===6109||t===12293||t>=12353&&t<=12438||t>=12441&&t<=12442||t>=12445&&t<=12447||t>=12449&&t<=12538||t>=12540&&t<=12543||t>=13312&&t<=19903||t>=19968&&t<=40959}function P(t){for(let e=0;e<t.length;e++)if(pe(t.charCodeAt(e)))return!0;return!1}function gt(t){let e=t.charCodeAt(0);return e>=48&&e<=57||e>=1632&&e<=1641||e>=1488&&e<=1514||e>=1568&&e<=1610||e>=1649&&e<=1747||pe(e)?!0:t.toLowerCase()!==t.toUpperCase()}var bt=t=>t>=8203&&t<=8205||t===8288||t===65279,vt=[3664,3792,4160,6112];function xt(t){for(let e of vt)if(t>=e&&t<=e+9)return String.fromCharCode(48+t-e)}var K={3640:103,3641:103,3642:9,3656:107,3657:107,3658:107,3659:107,3768:118,3769:118,3770:9,3784:122,3785:122,3786:122,3787:122,4151:7,4153:9,4154:9,4237:220,6098:9,6109:230,12441:8,12442:8},ue=t=>t>=3656&&t<=3659;function wt(t){if(!/[\u0e33\u0e38-\u0e3a\u0e48-\u0e4b\u0e4d\u0eb8-\u0eba\u0ec8-\u0ecb\u1037\u1039\u103a\u108d\u17d2\u17dd\u3099\u309a]/.test(t))return t;let e=[];for(let n=0;n<t.length;n++)e.push(t.charCodeAt(n));for(let n=0;n<e.length;n++){if(!K[e[n]])continue;let o=n;for(;o<e.length&&K[e[o]];)o++;for(let r=n+1;r<o;r++){let s=e[r],a=r-1;for(;a>=n&&K[e[a]]>K[s];)e[a+1]=e[a],a--;e[a+1]=s}n=o-1}let i="";for(let n=0;n<e.length;n++){let o=e[n];o===3661&&e[n+1]===3634?(i+="ำ",n++):o===3661&&ue(e[n+1])&&e[n+2]===3634?(i+=String.fromCharCode(e[n+1],3635),n+=2):o===3635&&ue(e[n+1])?(i+=String.fromCharCode(e[n+1],3635),n++):i+=String.fromCharCode(o)}return i}var yt=t=>{try{return t.normalize("NFD")}catch(e){return t}};function F(t){var o,r;let e=yt(String(t!=null?t:"").toLowerCase()),i="";for(let s of e){let a=s.charCodeAt(0);if(ft(a)||bt(a))continue;let l=(r=(o=mt[s])!=null?o:xt(a))!=null?r:s;i+=l.length===1&&!gt(l)?" ":l}let n=wt(i).replace(/\s+/g," ").trim();return n?n.split(" "):[]}var kt={he:["איך","מה","אני","של","עם","את","זה","יש","אפשר","לי","על","או","גם","רוצה","צריך","האם","למה","מתי","איפה","כמה","אתם","שלי","לכם","אין","לא"],en:["how","what","i","my","me","the","a","an","is","are","do","does","can","to","of","in","on","for","with","and","or","it","you","your","want","need","please","when","where","why","which","there","this","that","be","get","not","no"],ar:["كيف","ماذا","ما","انا","في","على","من","الى","عن","هل","هذا","هذه","او","و","لي","متى","اين","لماذا","كم","اريد","ممكن","لا"],ru:["как","что","я","мне","мой","моя","в","на","с","и","или","не","это","где","когда","почему","сколько","можно","хочу","нужно","у","по","для","ли","есть"],es:["como","que","yo","mi","me","el","la","los","las","un","una","de","del","en","con","por","para","y","o","es","se","puedo","quiero","cuando","donde","cual","hay","no"],fr:["comment","que","quoi","je","mon","ma","mes","le","la","les","un","une","de","des","du","en","avec","pour","et","ou","est","il","elle","puis","veux","quand","ou","pourquoi","combien","ne","pas","j","l","d","qu"],de:["wie","was","ich","mein","meine","mir","der","die","das","ein","eine","und","oder","in","mit","fur","von","zu","ist","kann","mochte","wann","wo","warum","nicht","es","den","dem"],pt:["como","que","eu","meu","minha","o","a","os","as","um","uma","de","do","da","em","no","na","com","para","por","e","ou","posso","quero","quando","onde","porque","nao"],it:["come","che","cosa","io","mio","mia","il","lo","la","i","gli","le","un","una","di","del","della","in","con","per","e","o","posso","voglio","quando","dove","perche","non","l"],tr:["nasil","ne","ben","benim","bir","ve","veya","ile","icin","bu","su","mi","mu","nerede","ne zaman","neden","kac","istiyorum","var","yok","de","da"],th:["ฉัน","ผม","ดิฉัน","คุณ","ครับ","ค่ะ","คะ","นะ","ไหม","มั้ย","อะไร","อย่างไร","ยังไง","ที่","และ","หรือ","ของ","ได้","จะ","ใน","กับ","เป็น","มี","ไม่","ให้","ว่า","อยาก","ต้องการ","เมื่อไหร่","ที่ไหน","ทำไม","เท่าไหร่"]},z={};for(let t of ht)z[t]=new Set(kt[t].flatMap(e=>F(e)));var St=["ו","ה","ב","ל","מ","ש","כ"],Ct=["وال","بال","لل","كال","فال","ال","و","ب","ل","ف"],Tt=t=>t>=97&&t<=122||t>=224&&t<=591;function It(t){let e=t,i=e.charCodeAt(0);if(Tt(i))return e.length>3&&e.endsWith("s")&&!/(ss|us|is)$/.test(e)?e.slice(0,-1):e;if(i>=1488&&i<=1514){for(let n=0;n<2&&(e.length>3&&St.includes(e[0]));n++)e=e.slice(1);return e}if(i>=1568&&i<=1610){for(let n of Ct)if(e.startsWith(n)&&e.length-n.length>=3)return e.slice(n.length)}return e}function Q(t,e="en"){var o;let i=(o=z[e])!=null?o:z.en,n=z.en;return F(t).filter(r=>r.length>1&&!i.has(r)&&!n.has(r)).map(It)}function he(t,e){if(t===e)return!0;if(Math.abs(t.length-e.length)>1||Math.min(t.length,e.length)<4)return!1;if(t.length===e.length){let r=[];for(let s=0;s<t.length&&r.length<=2;s++)t[s]!==e[s]&&r.push(s);if(r.length===2&&r[1]===r[0]+1&&t[r[0]]===e[r[1]]&&t[r[1]]===e[r[0]])return!0}let i=0,n=0,o=0;for(;i<t.length&&n<e.length;){if(t[i]===e[n]){i++,n++;continue}if(++o>1)return!1;t.length>e.length?i++:(e.length>t.length||i++,n++)}return o+(t.length-i)+(e.length-n)<=1}var me=t=>String(t!=null?t:"").split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean);function V(t,e,i="en"){var T,I;let n=Array.from(new Set(Q(e,i)));if(n.length===0)return{kind:"none",matches:[]};let o=d=>d.flatMap(p=>Q(p,i)),r=n.filter(d=>!P(d)),s=F(e).join(""),a=[];for(let d of t){if(d.kind==="opening")continue;let p=d.content,S=new Map;for(let m of p.steps)for(let y of m.buttons){let h=y.action;h&&(h.type==="step"||h.type==="goto"&&!h.scriptId)&&S.set(h.stepId,[...(T=S.get(h.stepId))!=null?T:[],y.label])}for(let m of p.steps){let y=m.id===p.rootStepId,h=o([...m.keywords,...y?p.keywords:[]]),f=o([...y?[p.name]:[],...(I=S.get(m.id))!=null?I:[]]),g=[...h,...f].filter(u=>!P(u)),b=0,v=[];for(let u of r)h.includes(u)?(b+=3,v.push({kind:"keyword",term:u})):f.includes(u)?(b+=2,v.push({kind:"title",term:u})):g.some(C=>he(u,C))&&(b+=.5,v.push({kind:"typo",term:u}));for(let u of Et(h,f,s))b+=u.weight,v.push({kind:u.weight===3?"keyword":"title",term:u.term});b>0&&a.push({scriptId:d.id,stepId:m.id,score:b,reasons:v})}}if(a.sort((d,p)=>p.score-d.score),a.length===0)return{kind:"none",matches:[]};let[l,w]=a;return!w||l.score>=w.score*2?{kind:"single",matches:[l]}:{kind:"multi",matches:a.filter(d=>d.score>=l.score/2).slice(0,3)}}function Et(t,e,i){let n=[],o=new Set;for(let[r,s]of[[t,3],[e,2]])for(let a of r)o.has(a)||!P(a)||(o.add(a),i.includes(a)&&n.push({term:a,weight:s}));return n.filter(r=>!n.some(s=>s.term!==r.term&&s.weight>=r.weight&&s.term.includes(r.term)))}var D={"chat.askAnswered":"Did that answer your question?","chat.yes":"Yes, thanks","chat.no":"No, I need help","chat.thanks":"Glad I could help!","chat.newQuestion":"New question","chat.back":"Back","chat.home":"Main menu","chat.didYouMean":"What did you mean?","chat.notFound":"I could not find an answer to that. Pick a topic from the menu, or talk to our team.","chat.notFoundTwice":"I could not find an answer. Our team will be happy to help, and your question is already in the form.","chat.contactChip":"Talk to our team","chat.openingContact":"Opening the contact form. This conversation will be attached to your request.","chat.chooseTopic":"How can I help?","chat.aiLabel":"AI answer","widget.open":"Open chat","widget.close":"Close chat","widget.placeholder":"Type your question...","widget.send":"Send","widget.poweredBy":"Powered by Kavchat","widget.offline":"You are offline. Showing saved answers.","widget.loading":"Loading...","widget.unavailable":"The assistant is not available right now.","form.title":"Contact us","form.name":"Name","form.email":"Email","form.phone":"Phone","form.topic":"Topic","form.message":"Message","form.submit":"Send","form.cancel":"Cancel","form.sending":"Sending...","form.sent":"Thanks! Your request #{number} was received. We will get back to you soon.","form.error":"Something went wrong. Please try again.","form.required":"Required","form.contactRequired":"Leave an email or a phone number so we can get back to you","form.emailInvalid":"Invalid email address","form.backToChat":"Back to chat"};var fe={"chat.askAnswered":"קיבלת מענה?","chat.yes":"כן, תודה","chat.no":"לא, אני צריך עזרה","chat.thanks":"שמחתי לעזור!","chat.newQuestion":"שאלה חדשה","chat.back":"חזרה","chat.home":"תפריט ראשי","chat.didYouMean":"למה התכוונת?","chat.notFound":"לא מצאתי תשובה לשאלה הזו. אפשר לבחור נושא מהתפריט, או לפנות לצוות.","chat.notFoundTwice":"לא הצלחתי למצוא תשובה. הצוות ישמח לעזור, והשאלה שלך כבר תהיה כתובה בטופס.","chat.contactChip":"פנייה לצוות","chat.openingContact":"פותח את טופס הפנייה. מסלול השיחה יצורף לפנייה.","chat.chooseTopic":"במה אפשר לעזור?","chat.aiLabel":"תשובת AI","widget.open":"פתיחת הצ'אט","widget.close":"סגירת הצ'אט","widget.placeholder":"כתבו את השאלה...","widget.send":"שליחה","widget.poweredBy":"מופעל על ידי Kavchat","widget.offline":"אין חיבור לאינטרנט. מוצגות תשובות שמורות.","widget.loading":"טוען...","widget.unavailable":"העוזר לא זמין כרגע.","form.title":"פנייה לצוות","form.name":"שם","form.email":"אימייל","form.phone":"טלפון","form.topic":"נושא","form.message":"הודעה","form.submit":"שליחה","form.cancel":"ביטול","form.sending":"שולח...","form.sent":"תודה! פנייה מספר {number} התקבלה. נחזור אליכם בקרוב.","form.error":"משהו השתבש. נסו שוב.","form.required":"שדה חובה","form.contactRequired":"השאירו אימייל או טלפון כדי שנוכל לחזור אליכם","form.emailInvalid":"כתובת אימייל לא תקינה","form.backToChat":"חזרה לצ'אט"};var ge={"chat.askAnswered":"هل أجبت عن سؤالك؟","chat.yes":"نعم، شكرًا","chat.no":"لا، أحتاج مساعدة","chat.thanks":"سعدت بمساعدتك!","chat.newQuestion":"سؤال جديد","chat.back":"رجوع","chat.home":"القائمة الرئيسية","chat.didYouMean":"ماذا تقصد؟","chat.notFound":"لم أجد إجابة عن هذا السؤال. اختر موضوعًا من القائمة، أو تواصل مع فريقنا.","chat.notFoundTwice":"لم أتمكن من العثور على إجابة. يسعد فريقنا مساعدتك، وسؤالك مكتوب بالفعل في النموذج.","chat.contactChip":"تواصل مع الفريق","chat.openingContact":"جارٍ فتح نموذج التواصل. ستُرفق هذه المحادثة بطلبك.","chat.chooseTopic":"كيف يمكنني مساعدتك؟","chat.aiLabel":"إجابة من الذكاء الاصطناعي","widget.open":"فتح المحادثة","widget.close":"إغلاق المحادثة","widget.placeholder":"اكتب سؤالك...","widget.send":"إرسال","widget.poweredBy":"بدعم من Kavchat","widget.offline":"أنت غير متصل بالإنترنت. نعرض الإجابات المحفوظة.","widget.loading":"جارٍ التحميل...","widget.unavailable":"المساعد غير متاح حاليًا.","form.title":"تواصل معنا","form.name":"الاسم","form.email":"البريد الإلكتروني","form.phone":"الهاتف","form.topic":"الموضوع","form.message":"الرسالة","form.submit":"إرسال","form.cancel":"إلغاء","form.sending":"جارٍ الإرسال...","form.sent":"شكرًا! تم استلام طلبك رقم {number}. سنعود إليك قريبًا.","form.error":"حدث خطأ ما. يرجى المحاولة مرة أخرى.","form.required":"مطلوب","form.contactRequired":"اترك بريدًا إلكترونيًا أو رقم هاتف لنتمكن من الرد عليك","form.emailInvalid":"عنوان البريد الإلكتروني غير صالح","form.backToChat":"العودة إلى المحادثة"};var be={"chat.askAnswered":"Это ответило на ваш вопрос?","chat.yes":"Да, спасибо","chat.no":"Нет, нужна помощь","chat.thanks":"Рад помочь!","chat.newQuestion":"Новый вопрос","chat.back":"Назад","chat.home":"Главное меню","chat.didYouMean":"Что вы имели в виду?","chat.notFound":"Я не нашёл ответа на этот вопрос. Выберите тему в меню или напишите нашей команде.","chat.notFoundTwice":"Не удалось найти ответ. Наша команда с радостью поможет, а ваш вопрос уже добавлен в форму.","chat.contactChip":"Связаться с нами","chat.openingContact":"Открываю форму обращения. Этот диалог будет приложен к вашему запросу.","chat.chooseTopic":"Чем могу помочь?","chat.aiLabel":"Ответ ИИ","widget.open":"Открыть чат","widget.close":"Закрыть чат","widget.placeholder":"Введите ваш вопрос...","widget.send":"Отправить","widget.poweredBy":"Работает на Kavchat","widget.offline":"Нет подключения к интернету. Показываем сохранённые ответы.","widget.loading":"Загрузка...","widget.unavailable":"Ассистент сейчас недоступен.","form.title":"Связаться с нами","form.name":"Имя","form.email":"Email","form.phone":"Телефон","form.topic":"Тема","form.message":"Сообщение","form.submit":"Отправить","form.cancel":"Отмена","form.sending":"Отправка...","form.sent":"Спасибо! Ваше обращение №{number} получено. Мы скоро с вами свяжемся.","form.error":"Что-то пошло не так. Попробуйте ещё раз.","form.required":"Обязательное поле","form.contactRequired":"Укажите email или номер телефона, чтобы мы могли с вами связаться","form.emailInvalid":"Неверный адрес email","form.backToChat":"Вернуться в чат"};var ve={"chat.askAnswered":"¿Resolvimos tu duda?","chat.yes":"Sí, gracias","chat.no":"No, necesito ayuda","chat.thanks":"¡Me alegra haberte ayudado!","chat.newQuestion":"Nueva pregunta","chat.back":"Atrás","chat.home":"Menú principal","chat.didYouMean":"¿Qué quisiste decir?","chat.notFound":"No encontré una respuesta para eso. Elige un tema del menú o habla con nuestro equipo.","chat.notFoundTwice":"No pude encontrar una respuesta. Nuestro equipo te ayudará con gusto, y tu pregunta ya está en el formulario.","chat.contactChip":"Hablar con el equipo","chat.openingContact":"Abriendo el formulario de contacto. Esta conversación se adjuntará a tu solicitud.","chat.chooseTopic":"¿En qué te puedo ayudar?","chat.aiLabel":"Respuesta de IA","widget.open":"Abrir chat","widget.close":"Cerrar chat","widget.placeholder":"Escribe tu pregunta...","widget.send":"Enviar","widget.poweredBy":"Con la tecnología de Kavchat","widget.offline":"Estás sin conexión. Mostrando respuestas guardadas.","widget.loading":"Cargando...","widget.unavailable":"El asistente no está disponible en este momento.","form.title":"Contáctanos","form.name":"Nombre","form.email":"Correo electrónico","form.phone":"Teléfono","form.topic":"Tema","form.message":"Mensaje","form.submit":"Enviar","form.cancel":"Cancelar","form.sending":"Enviando...","form.sent":"¡Gracias! Recibimos tu solicitud n.º {number}. Te responderemos pronto.","form.error":"Algo salió mal. Inténtalo de nuevo.","form.required":"Obligatorio","form.contactRequired":"Deja un correo o un teléfono para que podamos responderte","form.emailInvalid":"Correo electrónico no válido","form.backToChat":"Volver al chat"};var xe={"chat.askAnswered":"Avez-vous trouvé votre réponse ?","chat.yes":"Oui, merci","chat.no":"Non, aidez-moi","chat.thanks":"Ravi d'avoir pu vous aider !","chat.newQuestion":"Nouvelle question","chat.back":"Retour","chat.home":"Menu principal","chat.didYouMean":"Que vouliez-vous dire ?","chat.notFound":"Je n'ai pas trouvé de réponse à cette question. Choisissez un sujet dans le menu ou contactez notre équipe.","chat.notFoundTwice":"Je n'ai pas trouvé de réponse. Notre équipe se fera un plaisir de vous aider, et votre question figure déjà dans le formulaire.","chat.contactChip":"Contacter l'équipe","chat.openingContact":"Ouverture du formulaire de contact. Cette conversation sera jointe à votre demande.","chat.chooseTopic":"Comment puis-je vous aider ?","chat.aiLabel":"Réponse de l'IA","widget.open":"Ouvrir le chat","widget.close":"Fermer le chat","widget.placeholder":"Écrivez votre question...","widget.send":"Envoyer","widget.poweredBy":"Propulsé par Kavchat","widget.offline":"Vous êtes hors ligne. Affichage des réponses enregistrées.","widget.loading":"Chargement...","widget.unavailable":"L'assistant n'est pas disponible pour le moment.","form.title":"Nous contacter","form.name":"Nom","form.email":"E-mail","form.phone":"Téléphone","form.topic":"Sujet","form.message":"Message","form.submit":"Envoyer","form.cancel":"Annuler","form.sending":"Envoi en cours...","form.sent":"Merci ! Votre demande n° {number} a bien été reçue. Nous vous répondrons rapidement.","form.error":"Une erreur s'est produite. Veuillez réessayer.","form.required":"Obligatoire","form.contactRequired":"Indiquez un e-mail ou un numéro de téléphone pour que nous puissions vous répondre","form.emailInvalid":"Adresse e-mail invalide","form.backToChat":"Retour au chat"};var we={"chat.askAnswered":"Hat Ihnen das weitergeholfen?","chat.yes":"Ja, danke","chat.no":"Nein, Hilfe bitte","chat.thanks":"Freut mich, dass ich helfen konnte!","chat.newQuestion":"Neue Frage","chat.back":"Zurück","chat.home":"Hauptmenü","chat.didYouMean":"Was meinten Sie?","chat.notFound":"Dazu habe ich leider keine Antwort gefunden. Wählen Sie ein Thema aus dem Menü oder wenden Sie sich an unser Team.","chat.notFoundTwice":"Ich konnte keine Antwort finden. Unser Team hilft Ihnen gerne weiter, und Ihre Frage steht bereits im Formular.","chat.contactChip":"Team kontaktieren","chat.openingContact":"Das Kontaktformular wird geöffnet. Dieser Chatverlauf wird Ihrer Anfrage beigefügt.","chat.chooseTopic":"Wie kann ich helfen?","chat.aiLabel":"KI-Antwort","widget.open":"Chat öffnen","widget.close":"Chat schließen","widget.placeholder":"Ihre Frage eingeben...","widget.send":"Senden","widget.poweredBy":"Bereitgestellt von Kavchat","widget.offline":"Sie sind offline. Gespeicherte Antworten werden angezeigt.","widget.loading":"Wird geladen...","widget.unavailable":"Der Assistent ist gerade nicht verfügbar.","form.title":"Kontakt","form.name":"Name","form.email":"E-Mail","form.phone":"Telefon","form.topic":"Thema","form.message":"Nachricht","form.submit":"Senden","form.cancel":"Abbrechen","form.sending":"Wird gesendet...","form.sent":"Vielen Dank! Ihre Anfrage Nr. {number} ist eingegangen. Wir melden uns in Kürze bei Ihnen.","form.error":"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.","form.required":"Pflichtfeld","form.contactRequired":"Bitte geben Sie eine E-Mail-Adresse oder Telefonnummer an, damit wir uns melden können","form.emailInvalid":"Ungültige E-Mail-Adresse","form.backToChat":"Zurück zum Chat"};var ye={"chat.askAnswered":"Isso respondeu à sua pergunta?","chat.yes":"Sim, obrigado","chat.no":"Não, preciso de ajuda","chat.thanks":"Que bom que pude ajudar!","chat.newQuestion":"Nova pergunta","chat.back":"Voltar","chat.home":"Menu principal","chat.didYouMean":"O que você quis dizer?","chat.notFound":"Não encontrei uma resposta para isso. Escolha um assunto no menu ou fale com a nossa equipe.","chat.notFoundTwice":"Não consegui encontrar uma resposta. Nossa equipe vai ajudar com prazer, e sua pergunta já está no formulário.","chat.contactChip":"Falar com a equipe","chat.openingContact":"Abrindo o formulário de contato. Esta conversa será anexada à sua solicitação.","chat.chooseTopic":"Como posso ajudar?","chat.aiLabel":"Resposta de IA","widget.open":"Abrir chat","widget.close":"Fechar chat","widget.placeholder":"Digite sua pergunta...","widget.send":"Enviar","widget.poweredBy":"Desenvolvido por Kavchat","widget.offline":"Você está offline. Mostrando respostas salvas.","widget.loading":"Carregando...","widget.unavailable":"O assistente não está disponível no momento.","form.title":"Fale conosco","form.name":"Nome","form.email":"E-mail","form.phone":"Telefone","form.topic":"Assunto","form.message":"Mensagem","form.submit":"Enviar","form.cancel":"Cancelar","form.sending":"Enviando...","form.sent":"Obrigado! Sua solicitação nº {number} foi recebida. Retornaremos em breve.","form.error":"Algo deu errado. Tente novamente.","form.required":"Obrigatório","form.contactRequired":"Informe um e-mail ou telefone para que possamos retornar","form.emailInvalid":"Endereço de e-mail inválido","form.backToChat":"Voltar ao chat"};var ke={"chat.askAnswered":"Hai trovato la risposta?","chat.yes":"Sì, grazie","chat.no":"No, mi serve aiuto","chat.thanks":"Felice di esserti stato utile!","chat.newQuestion":"Nuova domanda","chat.back":"Indietro","chat.home":"Menu principale","chat.didYouMean":"Cosa intendevi?","chat.notFound":"Non ho trovato una risposta. Scegli un argomento dal menu o parla con il nostro team.","chat.notFoundTwice":"Non sono riuscito a trovare una risposta. Il nostro team sarà felice di aiutarti, e la tua domanda è già nel modulo.","chat.contactChip":"Parla con il team","chat.openingContact":"Apro il modulo di contatto. Questa conversazione sarà allegata alla tua richiesta.","chat.chooseTopic":"Come posso aiutarti?","chat.aiLabel":"Risposta dell'IA","widget.open":"Apri la chat","widget.close":"Chiudi la chat","widget.placeholder":"Scrivi la tua domanda...","widget.send":"Invia","widget.poweredBy":"Powered by Kavchat","widget.offline":"Sei offline. Mostro le risposte salvate.","widget.loading":"Caricamento...","widget.unavailable":"L'assistente non è disponibile al momento.","form.title":"Contattaci","form.name":"Nome","form.email":"Email","form.phone":"Telefono","form.topic":"Argomento","form.message":"Messaggio","form.submit":"Invia","form.cancel":"Annulla","form.sending":"Invio in corso...","form.sent":"Grazie! La tua richiesta n. {number} è stata ricevuta. Ti risponderemo presto.","form.error":"Qualcosa è andato storto. Riprova.","form.required":"Obbligatorio","form.contactRequired":"Lascia un'email o un numero di telefono per poterti ricontattare","form.emailInvalid":"Indirizzo email non valido","form.backToChat":"Torna alla chat"};var Se={"chat.askAnswered":"Sorunuza yanıt bulabildiniz mi?","chat.yes":"Evet, teşekkürler","chat.no":"Hayır, yardım lazım","chat.thanks":"Yardımcı olabildiğime sevindim!","chat.newQuestion":"Yeni soru","chat.back":"Geri","chat.home":"Ana menü","chat.didYouMean":"Ne demek istediniz?","chat.notFound":"Bununla ilgili bir yanıt bulamadım. Menüden bir konu seçin veya ekibimizle görüşün.","chat.notFoundTwice":"Bir yanıt bulamadım. Ekibimiz size memnuniyetle yardımcı olur, sorunuz forma zaten eklendi.","chat.contactChip":"Ekibe ulaşın","chat.openingContact":"İletişim formu açılıyor. Bu konuşma talebinize eklenecek.","chat.chooseTopic":"Size nasıl yardımcı olabilirim?","chat.aiLabel":"Yapay zekâ yanıtı","widget.open":"Sohbeti aç","widget.close":"Sohbeti kapat","widget.placeholder":"Sorunuzu yazın...","widget.send":"Gönder","widget.poweredBy":"Kavchat ile desteklenmektedir","widget.offline":"Çevrimdışısınız. Kayıtlı yanıtlar gösteriliyor.","widget.loading":"Yükleniyor...","widget.unavailable":"Asistan şu anda kullanılamıyor.","form.title":"Bize ulaşın","form.name":"Ad","form.email":"E-posta","form.phone":"Telefon","form.topic":"Konu","form.message":"Mesaj","form.submit":"Gönder","form.cancel":"İptal","form.sending":"Gönderiliyor...","form.sent":"Teşekkürler! {number} numaralı talebiniz alındı. En kısa sürede size dönüş yapacağız.","form.error":"Bir sorun oluştu. Lütfen tekrar deneyin.","form.required":"Zorunlu","form.contactRequired":"Size dönüş yapabilmemiz için bir e-posta veya telefon numarası bırakın","form.emailInvalid":"Geçersiz e-posta adresi","form.backToChat":"Sohbete dön"};var Ce={"chat.askAnswered":"คำตอบนี้ช่วยตอบคำถามของคุณหรือไม่","chat.yes":"ใช่ ขอบคุณ","chat.no":"ไม่ใช่ ต้องการความช่วยเหลือ","chat.thanks":"ยินดีที่ได้ช่วยเหลือ","chat.newQuestion":"ถามคำถามใหม่","chat.back":"ย้อนกลับ","chat.home":"เมนูหลัก","chat.didYouMean":"คุณหมายถึงข้อใด","chat.notFound":"ขออภัย ไม่พบคำตอบสำหรับคำถามนี้ กรุณาเลือกหัวข้อจากเมนู หรือติดต่อทีมงานของเรา","chat.notFoundTwice":"ขออภัย ไม่พบคำตอบ ทีมงานของเรายินดีช่วยเหลือ และได้ใส่คำถามของคุณไว้ในแบบฟอร์มแล้ว","chat.contactChip":"ติดต่อทีมงาน","chat.openingContact":"กำลังเปิดแบบฟอร์มติดต่อ บทสนทนานี้จะแนบไปกับคำขอของคุณ","chat.chooseTopic":"มีอะไรให้ช่วยไหม","chat.aiLabel":"คำตอบจาก AI","widget.open":"เปิดแชต","widget.close":"ปิดแชต","widget.placeholder":"พิมพ์คำถามของคุณ...","widget.send":"ส่ง","widget.poweredBy":"ขับเคลื่อนโดย Kavchat","widget.offline":"คุณออฟไลน์อยู่ กำลังแสดงคำตอบที่บันทึกไว้","widget.loading":"กำลังโหลด...","widget.unavailable":"ผู้ช่วยไม่พร้อมให้บริการในขณะนี้","form.title":"ติดต่อเรา","form.name":"ชื่อ","form.email":"อีเมล","form.phone":"โทรศัพท์","form.topic":"หัวข้อ","form.message":"ข้อความ","form.submit":"ส่ง","form.cancel":"ยกเลิก","form.sending":"กำลังส่ง...","form.sent":"ขอบคุณ เราได้รับคำขอหมายเลข {number} ของคุณแล้ว และจะติดต่อกลับโดยเร็ว","form.error":"เกิดข้อผิดพลาด กรุณาลองอีกครั้ง","form.required":"จำเป็นต้องกรอก","form.contactRequired":"กรุณาระบุอีเมลหรือหมายเลขโทรศัพท์ เพื่อให้เราติดต่อกลับได้","form.emailInvalid":"อีเมลไม่ถูกต้อง","form.backToChat":"กลับไปที่แชต"};var O={en:D,he:fe,ar:ge,ru:be,es:ve,fr:xe,de:we,pt:ye,it:ke,tr:Se,th:Ce},Te=["he","ar"],G=t=>Te.includes(Ie(t)),Ie=t=>String(t||"en").toLowerCase().split(/[-_]/)[0].replace(/^iw$/,"he");function A(t,e){var n;let i=(n=O[Ie(t)])!=null?n:D;return{...D,...i,...e!=null?e:{}}}var Y=(t,e)=>t.replace(/\{(\w+)\}/g,(i,n)=>e[n]!==void 0?String(e[n]):i);var R={now:()=>Date.now()};function J(t){R={...R,...t}}var x=t=>A(t.locale,R.texts),Z=()=>new Date(R.now()).toISOString();function Ee(t,e,i){let n=t.scripts[e],o=n==null?void 0:n.content.steps.find(r=>r.id===i);return n&&o?{script:n,step:o}:null}var ee=t=>Object.values(t.scripts).filter(e=>e.kind!=="opening").sort((e,i)=>e.sortOrder-i.sortOrder),Ae=t=>ee(t).map(e=>({id:`script:${e.id}`,label:e.content.name,kind:"button",action:{type:"script",scriptId:e.id}})),M=t=>({id:"home",label:x(t)["chat.home"],kind:"home"}),W=t=>{let e=[];return t.history.length>0&&e.push({id:"back",label:x(t)["chat.back"],kind:"back"}),e.push(M(t)),e},U=(t,e)=>({id:"contact",label:x(t)["chat.contactChip"],kind:"contact",...e?{prefill:e}:{}});function k(t,e,i,n={}){return(e==="bot"?me(i):[i]).reduce((r,s)=>({...r,seq:r.seq+1,messages:[...r.messages,{id:`m${r.seq+1}`,from:e,text:s,at:R.now(),...n}]}),t)}var Be=(t,e,i,n)=>({...t,path:[...t.path,{scriptId:e,stepId:i,via:n,at:Z()}]});function E(t,e){let i=t.scripts[t.openingId],n=i==null?void 0:i.content.steps.find(s=>s.id===i.content.rootStepId),o=t.userName?`, ${t.userName}`:"",r={...t,position:null,history:[],outcome:"open"};if(e==="start"){let s=((n==null?void 0:n.text)||x(t)["chat.chooseTopic"]).replace(/\{name\}/g,o);r=k(r,"bot",s,n!=null&&n.imageUrl?{imageUrl:n.imageUrl}:{})}else r=k(r,"bot",x(t)["chat.chooseTopic"]);return r=Be(r,t.openingId,(n==null?void 0:n.id)||"welcome",e),{...r,chips:[...Ae(r),U(r)]}}function B(t,e,i,n,o=!0){let r=Ee(t,e,i);if(!r)return E(t,"home");let{step:s}=r,a={...t,history:o&&t.position?[...t.history,t.position]:t.history,position:{scriptId:e,stepId:i},lastScriptId:e};if(a=k(a,"bot",s.text,{stepId:i,scriptId:e,...s.imageUrl?{imageUrl:s.imageUrl}:{}}),a=Be(a,e,i,n),s.buttons.length>0){let l=s.buttons.map(w=>({id:`btn:${w.id}`,label:w.label,kind:"button",action:w.action}));return{...a,chips:[...l,...W(a)]}}return a=k(a,"bot",x(a)["chat.askAnswered"]),{...a,chips:[{id:"yes",label:x(a)["chat.yes"],kind:"yes"},{id:"no",label:x(a)["chat.no"],kind:"no"},...W(a)]}}function Ft(t){return t.messages.map(e=>({from:e.from,text:e.text,...e.stepId?{stepId:e.stepId}:{},at:new Date(e.at).toISOString()}))}function X(t,e,i){let n=t.lastScriptId?t.scripts[t.lastScriptId]:null,o={type:i?"live":"contact",contactTopicId:(n==null?void 0:n.content.contactTopicId)||null,scriptId:t.lastScriptId,prefill:e||"",transcript:Ft(t)};if(i)return{state:{...t,outcome:"contact",chips:[M(t)]},effect:o};let r=k({...t,outcome:"contact"},"bot",x(t)["chat.openingContact"]);return{state:{...r,chips:[M(r)]},effect:o}}function Re(t){let e={scripts:Object.fromEntries(t.scripts.map(i=>[i.id,i])),openingId:t.openingScriptId,locale:t.locale||"en",userName:t.userName||"",messages:[],chips:[],position:null,history:[],path:[],unmatched:[],misses:0,outcome:"open",lastScriptId:null,lastMatch:null,seq:0};return E(e,"start")}function Dt(t,e,i){var o;let n=(o=t.position)==null?void 0:o.scriptId;if(!e)return{state:E(t,"home")};switch(e.type){case"script":{let r=t.scripts[e.scriptId];return r?{state:B(t,r.id,r.content.rootStepId,"button")}:{state:E(t,"home")}}case"step":return{state:B(t,n||"",e.stepId,"button")};case"goto":return{state:B(t,e.scriptId||n||"",e.stepId,"button")};case"contact":return X(t);case"screen":case"link":return{state:{...t,chips:i.length?i:W(t)},effect:e};default:return{state:E(t,"home")}}}function Me(t,e){let i={...k(t,"user",e.label),chips:[],lastMatch:null};switch(e.kind){case"home":return{state:E(i,"home")};case"back":{let n=i.history[i.history.length-1];return n?(i={...i,history:i.history.slice(0,-1),position:null},{state:B(i,n.scriptId,n.stepId,"back",!1)}):{state:E(i,"home")}}case"yes":return i=k({...i,outcome:"answered"},"bot",x(i)["chat.thanks"]),{state:{...i,chips:[{id:"new",label:x(i)["chat.newQuestion"],kind:"home"}]}};case"no":case"contact":return X(i,e.prefill);case"live":return X(i,e.prefill,!0);case"pick":return e.target?{state:B(i,e.target.scriptId,e.target.stepId,"text")}:{state:E(i,"home")};default:return Dt(i,e.action,t.chips)}}function Ut(t,e){let i=Ee(t,e.scriptId,e.stepId);if(!i)return"";let{script:n,step:o}=i;if(o.id===n.content.rootStepId)return n.content.name;for(let r of n.content.steps){let s=r.buttons.find(a=>a.action&&"stepId"in a.action&&a.action.stepId===o.id);if(s)return s.label}return o.text.slice(0,25)}function te(t,e){let i=String(e!=null?e:"").trim().slice(0,500);if(!i)return{state:t};let n={...k(t,"user",i),chips:[]},o=V(ee(n),i,n.locale);if(n={...n,lastMatch:o},o.kind==="single"){let r=o.matches[0];return{state:{...B(n,r.scriptId,r.stepId,"text"),misses:0,lastMatch:o}}}if(o.kind==="multi"){n=k({...n,misses:0},"bot",x(n)["chat.didYouMean"]);let r=o.matches.map(s=>({id:`pick:${s.scriptId}:${s.stepId}`,label:Ut(n,s),kind:"pick",target:{scriptId:s.scriptId,stepId:s.stepId}}));return{state:{...n,chips:[...r,M(n)]}}}return n={...n,misses:n.misses+1,unmatched:[...n.unmatched,{text:i,at:Z()}]},n.misses>=2?(n=k(n,"bot",x(n)["chat.notFoundTwice"]),{state:{...n,chips:[U(n,i),M(n)]}}):(n=k(n,"bot",x(n)["chat.notFound"]),{state:{...n,chips:[...Ae(n),U(n,i)]}})}var _t=300,Ht=600;function Le(t,e){let i=String(e!=null?e:"").trim().slice(0,500);return!i||V(ee(t),i,t.locale).kind!=="none"?null:i.slice(0,_t)}function qe(t,e){let i=String(e!=null?e:"").trim().slice(0,500);return i?{...k(t,"user",i),chips:[]}:t}function Oe(t,e,i,n){let o=String(e!=null?e:"").trim().slice(0,500),r=String(i!=null?i:"").trim().slice(0,Ht);if(!o||!r)return te(t,e);let s={...k(t,"user",o),chips:[],lastMatch:{kind:"none",matches:[]},misses:0,unmatched:[...t.unmatched,{text:o,at:Z()}]};s={...s,seq:s.seq+1,messages:[...s.messages,{id:`m${s.seq+1}`,from:"bot",text:r,at:R.now(),ai:!0}]};let a=n?s.scripts[n]:void 0,l=[];return a&&a.kind!=="opening"&&l.push({id:`script:${a.id}`,label:a.content.name,kind:"button",action:{type:"script",scriptId:a.id}}),{state:{...s,chips:[...l,U(s,o),M(s)]}}}function Ne(t,e,i,n){return{sessionId:e,releaseVersion:i,startedAt:n,outcome:t.outcome,path:t.path.slice(-200),unmatched:t.unmatched.slice(-20)}}var Ke=(t,e)=>`${t.apiBase.replace(/\/+$/,"")}/v1/client/${encodeURIComponent(t.publicKey)}/${e}`;function ze(t,e={}){let i=t.getToken();return i?{...e,Authorization:`Bearer ${i}`}:e}async function Pe(t,e){let i;try{i=await fetch(Ke(t,"release"),{method:"GET",cache:"no-store",credentials:"omit",headers:ze(t,e?{"If-None-Match":e}:{})})}catch(o){return{kind:"offline"}}if(i.status===304)return{kind:"not-modified"};if(i.status>=500||i.status===429)return{kind:"offline"};if(!i.ok)return{kind:"denied",status:i.status};let n=await i.json().catch(()=>null);return!n||n.success!==!0||!n.data||typeof n.data.enabled!="boolean"?{kind:"offline"}:{kind:"ok",release:n.data,etag:i.headers.get("ETag")||""}}function _(t,e,i,n=!1,o){return fetch(Ke(t,e),{method:"POST",cache:"no-store",credentials:"omit",keepalive:n,signal:o,headers:ze(t,{"Content-Type":"application/json"}),body:JSON.stringify(i)})}var jt=2e4;async function Fe(t,e,i){let n=new AbortController,o=setTimeout(()=>n.abort(),jt);try{let r=await _(t,"ai/answer",{sessionId:e,question:i},!1,n.signal),s=r.ok&&(await r.json()).data;return s&&typeof s.answer=="string"&&s.answer.trim()?{answer:s.answer,scriptId:s.scriptId||null}:null}catch(r){return null}finally{clearTimeout(o)}}async function De(t,e,i=!1){try{return(await _(t,"events",e,i)).ok}catch(n){return!1}}async function Ue(t,e){try{return(await _(t,"screens",{platform:"web",screens:e})).ok}catch(i){return!1}}async function _e(t,e){try{let i=await _(t,"tickets",e),n=await i.json().catch(()=>null);return i.ok&&n&&n.success&&n.data?{ok:!0,id:String(n.data.id),number:Number(n.data.number)}:{ok:!1,code:String((n==null?void 0:n.code)||`http_${i.status}`),message:String((n==null?void 0:n.message)||"")}}catch(i){return{ok:!1,code:"network",message:""}}}var $t="#2563eb",ne="#111827",ie="#ffffff";function re(t){let e=/^#([0-9a-f]{6})$/i.exec(String(t||"").trim());if(!e)return null;let i=parseInt(e[1],16);return[i>>16&255,i>>8&255,i&255]}function He(t){let[e,i,n]=t.map(o=>{let r=o/255;return r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)});return .2126*e+.7152*i+.0722*n}function oe(t,e){var o,r;let i=He((o=re(t))!=null?o:[0,0,0]),n=He((r=re(e))!=null?r:[0,0,0]);return(Math.max(i,n)+.05)/(Math.min(i,n)+.05)}function je(t){let e=re(t)?t.toLowerCase():$t,i=oe(e,ie)>=oe(e,ne)?ie:ne,n=oe(e,ie)>=3?e:ne;return{primary:e,onPrimary:i,accent:n}}function c(t,e,...i){let n=document.createElement(t);if(e)for(let[o,r]of Object.entries(e))r==null||r===!1||n.setAttribute(o,r===!0?"":r);return H(n,i),n}function H(t,e){for(let i of e)i==null||i===!1||t.appendChild(typeof i=="string"?document.createTextNode(i):i)}var $e="http://www.w3.org/2000/svg";function L(t){let e=document.createElementNS($e,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","24"),e.setAttribute("height","24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let i=document.createElementNS($e,"path");return i.setAttribute("d",t),i.setAttribute("fill","currentColor"),e.appendChild(i),e}var q={chat:"M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z",close:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z",send:"M2.01 21 23 12 2.01 3 2 10l15 2-15 2z"};function N(t,e){try{let i=new URL(String(t||"").trim());return e.includes(i.protocol)?i.href:null}catch(i){return null}}var se=/https:\/\/[^\s<>"'`]+/g,Qt=/[.,;:!?)\]}'"»]+$/;function Qe(t){let e=document.createDocumentFragment(),i=0;se.lastIndex=0;let n;for(;n=se.exec(t);){let o=n[0].replace(Qt,""),r=N(o,["https:"]);if(!r||!o)continue;n.index>i&&e.appendChild(document.createTextNode(t.slice(i,n.index)));let s=c("a",{href:r,target:"_blank",rel:"noopener noreferrer"},o);e.appendChild(s),i=n.index+o.length,se.lastIndex=i}return i<t.length&&e.appendChild(document.createTextNode(t.slice(i))),e}var Ve=t=>`kavchat:release:${t}`,Ge=t=>`kavchat:session:${t}`,Ye=t=>`kavchat:screens:${t}`;function ae(t,e){try{let i=t().getItem(e);return i?JSON.parse(i):null}catch(i){return null}}function ce(t,e,i){try{t().setItem(e,JSON.stringify(i))}catch(n){}}var j=()=>window.localStorage,We=()=>window.sessionStorage,Xe=t=>ae(j,Ve(t)),Je=(t,e)=>ce(j,Ve(t),e),Ze=t=>ae(j,Ye(t)),et=(t,e)=>ce(j,Ye(t),e),tt=t=>ae(We,Ge(t)),nt=(t,e)=>ce(We,Ge(t),e),Vt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";function it(t=22){let e=new Uint8Array(t);if(typeof crypto!="undefined"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let n=0;n<t;n++)e[n]=Math.floor(Math.random()*256);let i="";for(let n=0;n<t;n++)i+=Vt[e[n]&63];return i}var ot=`
2
2
  :host{all:initial}
3
3
  .kc{font-family:system-ui,-apple-system,"Segoe UI",Roboto,"Noto Sans Hebrew","Noto Sans Arabic","Noto Sans Thai",Arial,sans-serif;font-size:15px;line-height:1.45;color:#1f2328;-webkit-font-smoothing:antialiased}
4
4
  .kc *,.kc *::before,.kc *::after{box-sizing:border-box}
@@ -60,6 +60,6 @@
60
60
  .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
61
61
  @media (max-width:480px){.panel,.kc[data-pos=start] .panel{inset:0;width:100%;max-width:none;height:100%;max-height:none;border-radius:0}}
62
62
  @media (prefers-reduced-motion:reduce){.kc *{animation:none!important;transition:none!important}}
63
- `;var Re="https://api.kavchat.com",Me="https://kavchat.com",qe=2e3,Le=/^[A-Za-z0-9_.-]{1,40}$/,Ne=10080*60*1e3;function Oe(e){let u=new Set,n=[];for(let t of e!=null?e:[]){let i=typeof(t==null?void 0:t.id)=="string"?t.id:"",o=typeof(t==null?void 0:t.label)=="string"?t.label.trim().slice(0,60):"";if(!(!Le.test(i)||!o||u.has(i))&&(u.add(i),n.push({id:i,label:o,needsTarget:t.needsTarget===!0}),n.length===100))break}return n}function ze(e){let u=[...e].sort((t,i)=>t.id<i.id?-1:t.id>i.id?1:0).map(t=>`${t.id}|${t.label}|${t.needsTarget?1:0}`).join(`
64
- `),n=2166136261;for(let t=0;t<u.length;t++)n^=u.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16)}var Qu=e=>String(e||"").toLowerCase().split(/[-_]/)[0].replace(/^iw$/,"he");function Ke(e,u){let n=Qu(e||(typeof navigator!="undefined"?navigator.language:"")||"");if(O[n])return n;let t=Qu(u);return O[t]?t:"en"}var _e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,H=class{constructor(u){this.release=null;this.offline=!1;this.ui=null;this.state=null;this.session=null;this.t=z("en");this.locale="en";this.isOpen=!1;this.prevFocus=null;this.reportTimer=null;this.dirty=!1;this.destroyed=!1;this.waiting=!1;this.onPageHide=()=>this.flush(!0);this.onVisibility=()=>{document.visibilityState==="hidden"&&this.flush(!0)};if(!u||!u.publicKey)throw new Error("Kavchat: publicKey is required");this.opts={...u},this.wantOpen=!!u.open,this.api={apiBase:u.apiBase||Re,publicKey:u.publicKey,getToken:()=>this.opts.userToken||void 0},window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibility),this.ready=this.load()}get shadowRoot(){return this.ui?this.ui.root:null}get opened(){return this.isOpen}open(){this.wantOpen=!0;let u=this.ui;!u||this.isOpen||(this.isOpen=!0,this.prevFocus=document.activeElement,this.state||this.startFresh(),u.panel.hidden=!1,u.launcher.setAttribute("aria-expanded","true"),u.launcher.setAttribute("aria-label",this.t["widget.close"]),u.launcher.replaceChildren(B(I.close)),this.render(),this.focusInside(),this.emit({type:"open"}))}close(){this.wantOpen=!1;let u=this.ui;if(!u||!this.isOpen)return;this.isOpen=!1,u.panel.hidden=!0,u.launcher.setAttribute("aria-expanded","false"),u.launcher.setAttribute("aria-label",this.t["widget.open"]),u.launcher.replaceChildren(B(I.chat));let n=this.prevFocus;n&&n!==u.host&&n.isConnected&&typeof n.focus=="function"?n.focus():u.launcher.focus(),this.emit({type:"close"})}toggle(){this.isOpen?this.close():this.open()}setUser(u){return this.opts.userToken=(u==null?void 0:u.token)||void 0,this.opts.userName=(u==null?void 0:u.name)||void 0,this.ready=this.load(),this.ready}destroy(){this.destroyed||(this.flush(!0),this.destroyed=!0,this.reportTimer&&clearTimeout(this.reportTimer),window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibility),this.unmount())}async load(){var r,a;let u=this.opts.publicKey,n=Ou(u),t=await ku(this.api,(n==null?void 0:n.etag)||void 0);if(this.destroyed)return;let i=null,o=!1;t.kind==="ok"?(zu(u,{etag:t.etag,release:t.release}),i=t.release):t.kind==="not-modified"?i=(r=n==null?void 0:n.release)!=null?r:null:t.kind==="offline"&&(i=(a=n==null?void 0:n.release)!=null?a:null,o=!!i),this.apply(i,o),this.registerScreens()}async registerScreens(){let u=Oe(this.opts.screens);if(u.length===0)return;let n=this.opts.publicKey,t=ze(u),i=Ku(n);i&&i.fp===t&&Date.now()-i.at<Ne||await Fu(this.api,u)&&_u(n,{fp:t,at:Date.now()})}apply(u,n){if(!u||!u.enabled){this.release=null,this.state=null,this.isOpen=!1,this.unmount(),this.emit({type:"unavailable",reason:u&&"reason"in u?u.reason:void 0});return}this.offline=n;let t=!this.release||this.release.version!==u.version;this.release=u,this.locale=Ke(this.opts.locale,u.locale),this.t=z(this.locale),(t||!this.ui)&&(this.state=null,this.restoreSession(),this.mount()),this.ui&&(this.ui.banner.hidden=!this.offline),this.emit({type:"ready",version:u.version,offline:n}),this.wantOpen&&this.open()}restoreSession(){let u=this.release;if(!u)return;let n=Pu(this.opts.publicKey);if(n&&n.version===u.version&&n.state){let t={};for(let i of u.scripts)t[i.id]=i;this.session=n,this.state={...n.state,scripts:t}}else this.session=null}run(u){return V({texts:this.t}),u()}startFresh(){let u=this.release;u&&(V({texts:this.t}),this.session={id:Uu(),startedAt:new Date().toISOString(),version:u.version,state:null},this.setState(mu({scripts:u.scripts,openingScriptId:u.openingScriptId,locale:u.locale,userName:this.opts.userName})))}setState(u){if(this.state=u,this.session){let{scripts:n,...t}=u;this.session.state=t,Hu(this.opts.publicKey,this.session)}this.render()}onChip(u){if(!this.state||this.waiting)return;let n=this.state,t=this.run(()=>gu(n,u));this.afterAction(t)}async onSend(u){var a;if(!this.state||!u.trim()||this.waiting)return;let n=this.state,t=this.session,i=(a=this.release)!=null&&a.settings.aiAnswers&&t?Du(n,u):null;if(!i||!t)return this.afterAction(this.run(()=>W(n,u)));let o=bu(n,u);this.state=o,this.waiting=!0,this.render();let r=await Au(this.api,t.id,i);if(this.waiting=!1,this.destroyed||this.state!==o)return this.render();this.afterAction(this.run(()=>vu(n,u,r&&r.answer,r&&r.scriptId)))}afterAction(u){this.setState(u.state),this.scheduleReport(),u.effect&&this.handleEffect(u.effect)}handleEffect(u){var n,t,i;if(this.emit({type:"effect",effect:u}),u.type==="contact")this.showForm(u);else if(u.type==="link")Ue(u.url,(n=this.ui)==null?void 0:n.root);else if(u.type==="screen")try{(i=(t=this.opts).onScreen)==null||i.call(t,u.screen,u.targetId)}catch(o){console.error("Kavchat: onScreen failed",o)}}scheduleReport(){this.dirty=!0,this.reportTimer&&clearTimeout(this.reportTimer),this.reportTimer=setTimeout(()=>this.flush(!1),qe)}flush(u){if(this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=null),!this.dirty||!this.state||!this.release||!this.session||this.destroyed)return;this.dirty=!1;let n=xu(this.state,this.session.id,this.release.version,this.session.startedAt);Cu(this.api,n,u).then(t=>{t||(this.dirty=!0)})}emit(u){var n,t;try{(t=(n=this.opts).onEvent)==null||t.call(n,u)}catch(i){console.error("Kavchat: onEvent failed",i)}}unmount(){this.ui&&this.ui.host.remove(),this.ui=null,this.isOpen=!1}mount(){let u=this.release;if(!u)return;this.unmount();let n=this.t,t=u.settings,i=Bu(t.primaryColor),o=s("div",{"data-kavchat":""}),r=o.attachShadow({mode:"open"}),a=s("div",{class:"kc",dir:cu(this.locale)?"rtl":"ltr",lang:this.locale,"data-pos":t.position==="start"?"start":"end"});a.style.setProperty("--kc-primary",i.primary),a.style.setProperty("--kc-on-primary",i.onPrimary),a.style.setProperty("--kc-accent",i.accent);let c=s("button",{type:"button",class:"launcher","aria-label":n["widget.open"],"aria-expanded":"false","aria-controls":"kc-panel"},B(I.chat));c.addEventListener("click",()=>this.toggle());let f=t.avatarImageUrl?M(t.avatarImageUrl,["https:"]):null,m=s("div",{class:"avatar","aria-hidden":"true"},f?s("img",{src:f,alt:""}):(t.avatarText||t.botName||"").slice(0,2)),k=s("button",{type:"button",class:"close","aria-label":n["widget.close"]},B(I.close));k.addEventListener("click",()=>this.close());let p=s("div",{class:"header"},m,s("div",{class:"titles"},s("h2",{class:"name",id:"kc-title"},t.botName||""),t.subtitle?s("div",{class:"subtitle"},t.subtitle):null),k),E=s("div",{class:"banner",role:"status"},n["widget.offline"]);E.hidden=!this.offline;let A=s("div",{class:"messages"}),b=s("div",{class:"chips",role:"group"}),d=s("input",{type:"text",dir:"auto",maxlength:"500",autocomplete:"off",placeholder:n["widget.placeholder"],"aria-label":n["widget.placeholder"],enterkeyhint:"send"}),l=s("form",{class:"composer"},d,s("button",{type:"submit",class:"send","aria-label":n["widget.send"]},B(I.send)));l.addEventListener("submit",F=>{F.preventDefault();let Gu=d.value;d.value="",this.onSend(Gu)});let w=s("div",{class:"view"},A,b,l),v=s("div",{class:"view"});v.hidden=!0;let x=s("div",{class:"sr-only","aria-live":"polite","aria-atomic":"false"}),y=s("div",{class:"msg msg-bot typing","aria-hidden":"true"},"..."),h=s("div",{class:"panel",id:"kc-panel",role:"dialog","aria-labelledby":"kc-title",tabindex:"-1"},p,E,w,v,x);t.removeBranding||h.appendChild(s("a",{class:"badge",href:Me,target:"_blank",rel:"noopener noreferrer"},n["widget.poweredBy"])),h.hidden=!0,h.addEventListener("keydown",F=>{F.key==="Escape"&&(F.stopPropagation(),this.close())}),_(a,[c,h]),_(r,[s("style",null,ju),a]),(this.opts.container||document.body).appendChild(o),this.ui={host:o,root:r,wrap:a,launcher:c,panel:h,banner:E,chatView:w,messages:A,chips:b,input:d,formView:v,live:x,typing:y,rendered:0},this.state&&this.renderMessages(!1)}focusInside(){let u=this.ui;if(!u)return;let n=typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches;u.formView.hidden?n?u.panel.focus():u.input.focus():(u.formView.querySelector("input,select,textarea")||u.panel).focus()}render(){!this.ui||!this.state||(this.renderMessages(!0),this.renderChips())}renderMessages(u){let n=this.ui,t=this.state;if(!n||!t)return;n.rendered>t.messages.length&&(n.messages.textContent="",n.rendered=0);let i=[];for(let o=n.rendered;o<t.messages.length;o++){let r=t.messages[o];n.messages.appendChild(He(r,this.t)),r.from==="bot"&&i.push(r.ai?`${this.t["chat.aiLabel"]}: ${r.text}`:r.text)}n.rendered=t.messages.length,this.waiting?n.messages.appendChild(n.typing):n.typing.remove(),u&&i.length&&(n.live.textContent=i.join(`
65
- `)),n.messages.scrollTop=n.messages.scrollHeight}renderChips(){let u=this.ui,n=this.state;if(!(!u||!n)){u.chips.textContent="";for(let t of n.chips){let i=s("button",{type:"button",class:`chip chip-${t.kind}`},t.label);i.addEventListener("click",()=>this.onChip(t)),u.chips.appendChild(i)}u.chips.hidden=n.chips.length===0}}showChat(){let u=this.ui;u&&(u.formView.hidden=!0,u.formView.textContent="",u.chatView.hidden=!1,this.render(),this.isOpen&&this.focusInside())}showForm(u){let n=this.ui,t=this.release;if(!n||!t)return;let i=this.t,o=t.settings.contactTopics||[],r=(d,l,w)=>s("div",{class:"field"},s("label",{for:d},l),w),a=s("input",{id:"kc-name",type:"text",autocomplete:"name",maxlength:"100",dir:"auto"});a.value=this.opts.userName||"";let c=s("input",{id:"kc-email",type:"email",autocomplete:"email",dir:"auto"}),f=s("input",{id:"kc-phone",type:"tel",autocomplete:"tel",dir:"auto"}),m=null;if(o.length){m=s("select",{id:"kc-topic"},s("option",{value:""},""));for(let d of o)m.appendChild(s("option",{value:d.id},d.name));u.contactTopicId&&o.some(d=>d.id===u.contactTopicId)&&(m.value=u.contactTopicId)}let k=s("textarea",{id:"kc-message",required:!0,maxlength:"2000",dir:"auto"});k.value=u.prefill||"";let p=s("div",{class:"error",role:"alert"}),E=s("button",{type:"submit",class:"btn btn-primary"},i["form.submit"]),A=s("button",{type:"button",class:"btn"},i["form.cancel"]);A.addEventListener("click",()=>this.showChat());let b=s("form",{class:"form",novalidate:!0},s("h2",null,i["form.title"]),r("kc-name",i["form.name"],a),r("kc-email",i["form.email"],c),r("kc-phone",i["form.phone"],f),m?r("kc-topic",i["form.topic"],m):null,r("kc-message",i["form.message"],k),p,s("div",{class:"actions"},E,A));b.addEventListener("submit",async d=>{var x;d.preventDefault();let l={message:k.value.trim(),name:a.value.trim()||void 0,email:c.value.trim()||void 0,phone:f.value.trim()||void 0,topicId:(m==null?void 0:m.value)||void 0,scriptId:u.scriptId||void 0,sessionId:(x=this.session)==null?void 0:x.id,transcript:u.transcript.slice(-200).map(y=>({...y,text:y.text.slice(0,1e3)}))},w=l.message?!l.email&&!l.phone&&!this.opts.userToken?i["form.contactRequired"]:l.email&&!_e.test(l.email)?i["form.emailInvalid"]:"":i["form.required"];if(w){p.textContent=w;return}p.textContent="",E.disabled=!0,E.textContent=i["form.sending"];let v=await Su(this.api,l);this.destroyed||(E.disabled=!1,E.textContent=i["form.submit"],v.ok?(this.flush(!1),this.emit({type:"ticket",id:v.id,number:v.number}),this.showSent(v.number)):p.textContent=Pe(v.code,v.message,i))}),n.formView.replaceChildren(b),n.chatView.hidden=!0,n.formView.hidden=!1,this.isOpen&&this.focusInside()}showSent(u){let n=this.ui;if(!n)return;let t=this.t,i=s("button",{type:"button",class:"btn btn-primary"},t["form.backToChat"]);i.addEventListener("click",()=>this.showChat());let o=s("p",{role:"status"},Eu(t["form.sent"],{number:u}));n.formView.replaceChildren(s("div",{class:"sent"},o,i)),i.focus()}};function Pe(e,u,n){return e==="ticket_contact_required"?n["form.contactRequired"]:e==="email_invalid"?n["form.emailInvalid"]:e==="network"?n["form.error"]:u||n["form.error"]}function He(e,u){let n=s("div",{class:`msg msg-${e.from}`,dir:"auto"});e.ai&&n.appendChild(s("span",{class:"ai"},u["chat.aiLabel"]));let t=e.from==="bot"&&e.imageUrl?M(e.imageUrl,["https:"]):null;return t&&n.appendChild(s("img",{src:t,alt:"",loading:"lazy"})),n.appendChild(e.from==="bot"&&!e.ai?Ru(e.text):document.createTextNode(e.text)),n}function Ue(e,u){let n=M(e,["https:","tel:"]);if(!n)return!1;let t=s("a",{href:n,target:"_blank",rel:"noopener noreferrer"});return t.style.display="none",(u||document.body).appendChild(t),t.click(),t.remove(),!0}var je=["init","open","close","toggle","setUser","destroy"];function $u(e=window){let u=e.Kavchat;if(u&&u.loaded)return{api:u,queue:[]};let n=Array.isArray(u==null?void 0:u.q)?u.q.filter(Array.isArray):[],t=null,i,o,r={loaded:!0,init(a){t&&t.destroy();let c={...a};return o!==void 0&&(c.open=o),i!==void 0&&(c.userToken=(i==null?void 0:i.token)||void 0,c.userName=(i==null?void 0:i.name)||void 0),o=i=void 0,t=new H(c),t.ready},open(){t?t.open():o=!0},close(){t?t.close():o=!1},toggle(){t?t.toggle():o=!o},setUser(a){t?t.setUser(a):i=a},destroy(){t&&t.destroy(),t=null},q:{push:(...a)=>(a.forEach(c=>iu(r,c)),0)},get widget(){return t}};return e.Kavchat=r,{api:r,queue:n}}function iu(e,u){let[n,...t]=u;if(!je.includes(n)){console.warn(`Kavchat: unknown method ${n}`);return}try{let i=e[n](...t);i&&typeof i.catch=="function"&&i.catch(o=>console.error("Kavchat:",o))}catch(i){console.error("Kavchat:",i)}}function Qe(e){if(!e)return null;let u=i=>e.getAttribute(i)||void 0,n=u("data-key");if(!n)return null;let t={publicKey:n};return u("data-api")&&(t.apiBase=u("data-api")),u("data-locale")&&(t.locale=u("data-locale")),u("data-user-token")&&(t.userToken=u("data-user-token")),u("data-user-name")&&(t.userName=u("data-user-name")),u("data-open")==="true"&&(t.open=!0),t}function $e(){return document.currentScript||document.querySelector('script[data-key][src*="kavchat"]')||document.querySelector("script[data-key]")}function Vu(e=$e()){let{api:u,queue:n}=$u(),t=Qe(e),i=n.findIndex(r=>r[0]==="init"),o=n.filter((r,a)=>a!==i);return i>=0?o.unshift(["init",{...t,...n[i][1]}]):t&&o.unshift(["init",t]),o.forEach(r=>iu(u,r)),u}try{Vu()}catch(e){console.error("Kavchat:",e)}})();
63
+ `;var st,at=((st=document.currentScript)==null?void 0:st.src)||"",rt=at.replace(/\/kavchat(\.[\w-]+)?\.js(\?.*)?$/,"/kavchat-live$1.js"),le,ct=()=>le||(le=new Promise((t,e)=>{let i=document.createElement("script");i.src=rt!==at?rt:"https://cdn.kavchat.com/v1/kavchat-live.js",i.onload=()=>{let n=window.KavchatLive;n?t(n):e()},i.onerror=()=>{le=void 0,e()},document.head.appendChild(i)}));var Gt="https://api.kavchat.com",Yt="https://kavchat.com",Wt=2e3,Xt=/^[A-Za-z0-9_.-]{1,40}$/,Jt=10080*60*1e3;function Zt(t){let e=new Set,i=[];for(let n of t!=null?t:[]){let o=typeof(n==null?void 0:n.id)=="string"?n.id:"",r=typeof(n==null?void 0:n.label)=="string"?n.label.trim().slice(0,60):"";if(!(!Xt.test(o)||!r||e.has(o))&&(e.add(o),i.push({id:o,label:r,needsTarget:n.needsTarget===!0}),i.length===100))break}return i}function en(t){let e=[...t].sort((n,o)=>n.id<o.id?-1:n.id>o.id?1:0).map(n=>`${n.id}|${n.label}|${n.needsTarget?1:0}`).join(`
64
+ `),i=2166136261;for(let n=0;n<e.length;n++)i^=e.charCodeAt(n),i=Math.imul(i,16777619)>>>0;return i.toString(16)}var lt=t=>String(t||"").toLowerCase().split(/[-_]/)[0].replace(/^iw$/,"he");function tn(t,e){let i=lt(t||(typeof navigator!="undefined"?navigator.language:"")||"");if(O[i])return i;let n=lt(e);return O[n]?n:"en"}var nn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,$=class{constructor(e){this.release=null;this.offline=!1;this.ui=null;this.state=null;this.session=null;this.t=A("en");this.locale="en";this.isOpen=!1;this.prevFocus=null;this.reportTimer=null;this.dirty=!1;this.destroyed=!1;this.waiting=!1;this.live=null;this.onPageHide=()=>this.flush(!0);this.onVisibility=()=>{document.visibilityState==="hidden"&&this.flush(!0)};if(!e||!e.publicKey)throw new Error("Kavchat: publicKey is required");this.opts={...e},this.wantOpen=!!e.open,this.api={apiBase:e.apiBase||Gt,publicKey:e.publicKey,getToken:()=>this.opts.userToken||void 0},window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibility),this.ready=this.load()}get shadowRoot(){return this.ui?this.ui.root:null}get opened(){return this.isOpen}open(){this.wantOpen=!0;let e=this.ui;!e||this.isOpen||(this.isOpen=!0,this.prevFocus=document.activeElement,this.state||this.startFresh(),e.panel.hidden=!1,e.launcher.setAttribute("aria-expanded","true"),e.launcher.setAttribute("aria-label",this.t["widget.close"]),e.launcher.replaceChildren(L(q.close)),this.render(),this.focusInside(),this.emit({type:"open"}))}close(){this.wantOpen=!1;let e=this.ui;if(!e||!this.isOpen)return;this.isOpen=!1,e.panel.hidden=!0,e.launcher.setAttribute("aria-expanded","false"),e.launcher.setAttribute("aria-label",this.t["widget.open"]),e.launcher.replaceChildren(L(q.chat));let i=this.prevFocus;i&&i!==e.host&&i.isConnected&&typeof i.focus=="function"?i.focus():e.launcher.focus(),this.emit({type:"close"})}toggle(){this.isOpen?this.close():this.open()}setUser(e){return this.opts.userToken=(e==null?void 0:e.token)||void 0,this.opts.userName=(e==null?void 0:e.name)||void 0,this.ready=this.load(),this.ready}destroy(){this.destroyed||(this.flush(!0),this.destroyed=!0,this.reportTimer&&clearTimeout(this.reportTimer),window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibility),this.setupLive(),this.unmount())}async load(){var s,a;let e=this.opts.publicKey,i=Xe(e),n=await Pe(this.api,(i==null?void 0:i.etag)||void 0);if(this.destroyed)return;let o=null,r=!1;n.kind==="ok"?(Je(e,{etag:n.etag,release:n.release}),o=n.release):n.kind==="not-modified"?o=(s=i==null?void 0:i.release)!=null?s:null:n.kind==="offline"&&(o=(a=i==null?void 0:i.release)!=null?a:null,r=!!o),this.apply(o,r),this.registerScreens()}async registerScreens(){let e=Zt(this.opts.screens);if(e.length===0)return;let i=this.opts.publicKey,n=en(e),o=Ze(i);o&&o.fp===n&&Date.now()-o.at<Jt||await Ue(this.api,e)&&et(i,{fp:n,at:Date.now()})}apply(e,i){if(!e||!e.enabled){this.release=null,this.state=null,this.isOpen=!1,this.unmount(),this.emit({type:"unavailable",reason:e&&"reason"in e?e.reason:void 0});return}this.offline=i;let n=!this.release||this.release.version!==e.version;this.release=e,this.locale=tn(this.opts.locale,e.locale),this.t=A(this.locale),(n||!this.ui)&&(this.state=null,this.restoreSession(),this.mount(),this.setupLive()),this.ui&&(this.ui.banner.hidden=!this.offline),this.emit({type:"ready",version:e.version,offline:i}),this.wantOpen&&this.open()}setupLive(){this.live&&this.live.destroy(),this.live=null;let e=this.ui,i=this.release&&this.release.liveChat,n;try{n=localStorage.getItem(`kavchat:live:${this.opts.publicKey}`)}catch(o){}this.destroyed||!e||!(i&&i.enabled||n)||ct().then(o=>{this.ui!==e||this.destroyed||(this.live=o.createLive(this),this.live.restore(),this.renderChips())},()=>{})}restoreSession(){let e=this.release;if(!e)return;let i=tt(this.opts.publicKey);if(i&&i.version===e.version&&i.state){let n={};for(let o of e.scripts)n[o.id]=o;this.session=i,this.state={...i.state,scripts:n}}else this.session=null}run(e){return J({texts:this.t}),e()}startFresh(){let e=this.release;e&&(J({texts:this.t}),this.session={id:it(),startedAt:new Date().toISOString(),version:e.version,state:null},this.setState(Re({scripts:e.scripts,openingScriptId:e.openingScriptId,locale:e.locale,userName:this.opts.userName})))}setState(e){if(this.state=e,this.session){let{scripts:i,...n}=e;this.session.state=n,nt(this.opts.publicKey,this.session)}this.render()}onChip(e){if(!this.state||this.waiting)return;let i=this.state,n=this.run(()=>Me(i,e));this.afterAction(n)}async onSend(e){var a;if(!this.state||!e.trim()||this.waiting)return;let i=this.state,n=this.session,o=(a=this.release)!=null&&a.settings.aiAnswers&&n?Le(i,e):null;if(!o||!n)return this.afterAction(this.run(()=>te(i,e)));let r=qe(i,e);this.state=r,this.waiting=!0,this.render();let s=await Fe(this.api,n.id,o);if(this.waiting=!1,this.destroyed||this.state!==r)return this.render();this.afterAction(this.run(()=>Oe(i,e,s&&s.answer,s&&s.scriptId)))}afterAction(e){this.setState(e.state),this.scheduleReport(),e.effect&&this.handleEffect(e.effect)}handleEffect(e){var i,n,o;if(this.emit({type:"effect",effect:e}),e.type==="live"&&this.live)this.live.start(e);else if(e.type==="contact"||e.type==="live")this.showForm(e);else if(e.type==="link")sn(e.url,(i=this.ui)==null?void 0:i.root);else if(e.type==="screen")try{(o=(n=this.opts).onScreen)==null||o.call(n,e.screen,e.targetId)}catch(r){console.error("Kavchat: onScreen failed",r)}}scheduleReport(){this.dirty=!0,this.reportTimer&&clearTimeout(this.reportTimer),this.reportTimer=setTimeout(()=>this.flush(!1),Wt)}flush(e){if(this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=null),!this.dirty||!this.state||!this.release||!this.session||this.destroyed)return;this.dirty=!1;let i=Ne(this.state,this.session.id,this.release.version,this.session.startedAt);De(this.api,i,e).then(n=>{n||(this.dirty=!0)})}emit(e){var i,n;try{(n=(i=this.opts).onEvent)==null||n.call(i,e)}catch(o){console.error("Kavchat: onEvent failed",o)}}unmount(){this.ui&&this.ui.host.remove(),this.ui=null,this.isOpen=!1}mount(){let e=this.release;if(!e)return;this.unmount();let i=this.t,n=e.settings,o=je(n.primaryColor),r=c("div",{"data-kavchat":""}),s=r.attachShadow({mode:"open"}),a=c("div",{class:"kc",dir:G(this.locale)?"rtl":"ltr",lang:this.locale,"data-pos":n.position==="start"?"start":"end"});a.style.setProperty("--kc-primary",o.primary),a.style.setProperty("--kc-on-primary",o.onPrimary),a.style.setProperty("--kc-accent",o.accent);let l=c("button",{type:"button",class:"launcher","aria-label":i["widget.open"],"aria-expanded":"false","aria-controls":"kc-panel"},L(q.chat));l.addEventListener("click",()=>this.toggle());let w=n.avatarImageUrl?N(n.avatarImageUrl,["https:"]):null,T=c("div",{class:"avatar","aria-hidden":"true"},w?c("img",{src:w,alt:""}):(n.avatarText||n.botName||"").slice(0,2)),I=c("button",{type:"button",class:"close","aria-label":i["widget.close"]},L(q.close));I.addEventListener("click",()=>this.close());let d=c("div",{class:"header"},T,c("div",{class:"titles"},c("h2",{class:"name",id:"kc-title"},n.botName||""),n.subtitle?c("div",{class:"subtitle"},n.subtitle):null),I),p=c("div",{class:"banner",role:"status"},i["widget.offline"]);p.hidden=!this.offline;let S=c("div",{class:"messages"}),m=c("div",{class:"chips",role:"group"}),y=c("input",{type:"text",dir:"auto",maxlength:"500",autocomplete:"off",placeholder:i["widget.placeholder"],"aria-label":i["widget.placeholder"],enterkeyhint:"send"}),h=c("form",{class:"composer"},y,c("button",{type:"submit",class:"send","aria-label":i["widget.send"]},L(q.send)));h.addEventListener("submit",C=>{C.preventDefault();let pt=y.value;y.value="",this.onSend(pt)});let f=c("div",{class:"view"},S,m,h),g=c("div",{class:"view"});g.hidden=!0;let b=c("div",{class:"sr-only","aria-live":"polite","aria-atomic":"false"}),v=c("div",{class:"msg msg-bot typing","aria-hidden":"true"},"..."),u=c("div",{class:"panel",id:"kc-panel",role:"dialog","aria-labelledby":"kc-title",tabindex:"-1"},d,p,f,g,b);n.removeBranding||u.appendChild(c("a",{class:"badge",href:Yt,target:"_blank",rel:"noopener noreferrer"},i["widget.poweredBy"])),u.hidden=!0,u.addEventListener("keydown",C=>{C.key==="Escape"&&(C.stopPropagation(),this.close())}),H(a,[l,u]),H(s,[c("style",null,ot),a]),(this.opts.container||document.body).appendChild(r),this.ui={host:r,root:s,wrap:a,launcher:l,panel:u,banner:p,chatView:f,messages:S,chips:m,input:y,formView:g,live:b,typing:v,rendered:0},this.state&&this.renderMessages(!1)}focusInside(){let e=this.ui;if(!e||this.live&&this.live.focus())return;let i=typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches;e.formView.hidden?i?e.panel.focus():e.input.focus():(e.formView.querySelector("input,select,textarea")||e.panel).focus()}render(){!this.ui||!this.state||(this.renderMessages(!0),this.renderChips())}renderMessages(e){let i=this.ui,n=this.state;if(!i||!n)return;i.rendered>n.messages.length&&(i.messages.textContent="",i.rendered=0);let o=[];for(let r=i.rendered;r<n.messages.length;r++){let s=n.messages[r];i.messages.appendChild(rn(s,this.t)),s.from==="bot"&&o.push(s.ai?`${this.t["chat.aiLabel"]}: ${s.text}`:s.text)}i.rendered=n.messages.length,this.waiting?i.messages.appendChild(i.typing):i.typing.remove(),e&&o.length&&(i.live.textContent=o.join(`
65
+ `)),i.messages.scrollTop=i.messages.scrollHeight}renderChips(){let e=this.ui,i=this.state;if(!e||!i)return;e.chips.textContent="";let n=this.live?this.live.chips(i.chips):i.chips;for(let o of n){let r=c("button",{type:"button",class:`chip chip-${o.kind}`},o.label);r.addEventListener("click",()=>this.onChip(o)),e.chips.appendChild(r)}e.chips.hidden=n.length===0}showChat(){let e=this.ui;e&&(e.formView.hidden=!0,e.formView.textContent="",e.chatView.hidden=!1,this.render(),this.isOpen&&this.focusInside())}showForm(e,i={}){let n=this.ui,o=this.release;if(!n||!o)return;let r=this.t,s=o.settings.contactTopics||[],a=(f,g,b)=>c("div",{class:"field"},c("label",{for:f},g),b),l=c("input",{id:"kc-name",type:"text",autocomplete:"name",maxlength:"100",dir:"auto"});l.value=i.name||this.opts.userName||"";let w=c("input",{id:"kc-email",type:"email",autocomplete:"email",dir:"auto"});w.value=i.email||"";let T=c("input",{id:"kc-phone",type:"tel",autocomplete:"tel",dir:"auto"});T.value=i.phone||"";let I="note"in i?i.note:this.live&&this.live.note(),d=null;if(s.length){d=c("select",{id:"kc-topic"},c("option",{value:""},""));for(let f of s)d.appendChild(c("option",{value:f.id},f.name));e.contactTopicId&&s.some(f=>f.id===e.contactTopicId)&&(d.value=e.contactTopicId)}let p=c("textarea",{id:"kc-message",required:!0,maxlength:"2000",dir:"auto"});p.value=i.message||e.prefill||"";let S=c("div",{class:"error",role:"alert"}),m=c("button",{type:"submit",class:"btn btn-primary"},r["form.submit"]),y=c("button",{type:"button",class:"btn"},r["form.cancel"]);y.addEventListener("click",()=>this.showChat());let h=c("form",{class:"form",novalidate:!0},c("h2",null,r["form.title"]),I?c("p",{class:"note",role:"status"},I):null,a("kc-name",r["form.name"],l),a("kc-email",r["form.email"],w),a("kc-phone",r["form.phone"],T),d?a("kc-topic",r["form.topic"],d):null,a("kc-message",r["form.message"],p),S,c("div",{class:"actions"},m,y));h.addEventListener("submit",async f=>{var u;f.preventDefault();let g={message:p.value.trim(),name:l.value.trim()||void 0,email:w.value.trim()||void 0,phone:T.value.trim()||void 0,topicId:(d==null?void 0:d.value)||void 0,scriptId:e.scriptId||void 0,sessionId:(u=this.session)==null?void 0:u.id,transcript:e.transcript.slice(-200).map(C=>({...C,text:C.text.slice(0,1e3)}))},b=g.message?!g.email&&!g.phone&&!this.opts.userToken?r["form.contactRequired"]:g.email&&!nn.test(g.email)?r["form.emailInvalid"]:"":r["form.required"];if(b){S.textContent=b;return}S.textContent="",m.disabled=!0,m.textContent=r["form.sending"];let v=await _e(this.api,g);this.destroyed||(m.disabled=!1,m.textContent=r["form.submit"],v.ok?(this.flush(!1),this.emit({type:"ticket",id:v.id,number:v.number}),this.showSent(v.number)):S.textContent=on(v.code,v.message,r))}),n.formView.replaceChildren(h),n.chatView.hidden=!0,n.formView.hidden=!1,this.isOpen&&this.focusInside()}showSent(e){let i=this.ui;if(!i)return;let n=this.t,o=c("button",{type:"button",class:"btn btn-primary"},n["form.backToChat"]);o.addEventListener("click",()=>this.showChat());let r=c("p",{role:"status"},Y(n["form.sent"],{number:e}));i.formView.replaceChildren(c("div",{class:"sent"},r,o)),o.focus()}};function on(t,e,i){return t==="ticket_contact_required"?i["form.contactRequired"]:t==="email_invalid"?i["form.emailInvalid"]:t==="network"?i["form.error"]:e||i["form.error"]}function rn(t,e){let i=c("div",{class:`msg msg-${t.from}`,dir:"auto"});t.ai&&i.appendChild(c("span",{class:"ai"},e["chat.aiLabel"]));let n=t.from==="bot"&&t.imageUrl?N(t.imageUrl,["https:"]):null;return n&&i.appendChild(c("img",{src:n,alt:"",loading:"lazy"})),i.appendChild(t.from==="bot"&&!t.ai?Qe(t.text):document.createTextNode(t.text)),i}function sn(t,e){let i=N(t,["https:","tel:"]);if(!i)return!1;let n=c("a",{href:i,target:"_blank",rel:"noopener noreferrer"});return n.style.display="none",(e||document.body).appendChild(n),n.click(),n.remove(),!0}var an=["init","open","close","toggle","setUser","destroy"];function dt(t=window){let e=t.Kavchat;if(e&&e.loaded)return{api:e,queue:[]};let i=Array.isArray(e==null?void 0:e.q)?e.q.filter(Array.isArray):[],n=null,o,r,s={loaded:!0,init(a){n&&n.destroy();let l={...a};return r!==void 0&&(l.open=r),o!==void 0&&(l.userToken=(o==null?void 0:o.token)||void 0,l.userName=(o==null?void 0:o.name)||void 0),r=o=void 0,n=new $(l),n.ready},open(){n?n.open():r=!0},close(){n?n.close():r=!1},toggle(){n?n.toggle():r=!r},setUser(a){n?n.setUser(a):o=a},destroy(){n&&n.destroy(),n=null},q:{push:(...a)=>(a.forEach(l=>de(s,l)),0)},get widget(){return n}};return t.Kavchat=s,{api:s,queue:i}}function de(t,e){let[i,...n]=e;if(!an.includes(i)){console.warn(`Kavchat: unknown method ${i}`);return}try{let o=t[i](...n);o&&typeof o.catch=="function"&&o.catch(r=>console.error("Kavchat:",r))}catch(o){console.error("Kavchat:",o)}}function cn(t){if(!t)return null;let e=o=>t.getAttribute(o)||void 0,i=e("data-key");if(!i)return null;let n={publicKey:i};return e("data-api")&&(n.apiBase=e("data-api")),e("data-locale")&&(n.locale=e("data-locale")),e("data-user-token")&&(n.userToken=e("data-user-token")),e("data-user-name")&&(n.userName=e("data-user-name")),e("data-open")==="true"&&(n.open=!0),n}function ln(){return document.currentScript||document.querySelector('script[data-key][src*="kavchat"]')||document.querySelector("script[data-key]")}function ut(t=ln()){let{api:e,queue:i}=dt(),n=cn(t),o=i.findIndex(s=>s[0]==="init"),r=i.filter((s,a)=>a!==o);return o>=0?r.unshift(["init",{...n,...i[o][1]}]):n&&r.unshift(["init",n]),r.forEach(s=>de(e,s)),e}try{ut()}catch(t){console.error("Kavchat:",t)}})();