@nexlylab/widget 1.32.18 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/INSTALL.txt +1 -1
  2. package/dist/runtime/{1.32.18/chunks/ClickToLoadEmbed-BLIUFZOn-BwY-LAJ8.js → 1.33.0/chunks/ClickToLoadEmbed-DdH19Upf-CnpjmfE1.js} +2 -2
  3. package/dist/runtime/{1.32.18/chunks/PanelInfoVideo-BNVzih9J-BrU-Qlul.js → 1.33.0/chunks/PanelInfoVideo-XFcVoL2c-qpxDXdLm.js} +2 -2
  4. package/dist/runtime/{1.32.18/chunks/allowed-elements-BXnLJV1S-C-_lr2zm.js → 1.33.0/chunks/allowed-elements-C0OfX2zF-DIBV8lKu.js} +2 -2
  5. package/dist/runtime/{1.32.18/chunks/assistant-link-components-DUrLEPUB-DKaQavIJ.js → 1.33.0/chunks/assistant-link-components-gMuMhmaU-rHpeX4O6.js} +2 -2
  6. package/dist/runtime/{1.32.18/chunks/assistant-link-policy-DHB-k1Aa-Cc-yj-a-.js → 1.33.0/chunks/assistant-link-policy-DlGAtyk7-By6jpR50.js} +2 -2
  7. package/dist/runtime/{1.32.18/chunks/block-rating-D7hR2gTc-CoiP5C2K.js → 1.33.0/chunks/block-rating-CAVRRYuG-CQMNokIy.js} +2 -2
  8. package/dist/runtime/{1.32.18/chunks/external-url-qbs1SznX-CJQjg_od.js → 1.33.0/chunks/external-url-JbUnX7Da-rLiy7c9v.js} +2 -2
  9. package/dist/runtime/{1.32.18/chunks/index--xfG4CIn-DbuSZfeK.js → 1.33.0/chunks/index--H6hRpBJ-F9_TzvkO.js} +2 -2
  10. package/dist/runtime/{1.32.18/chunks/index-BIGVEl9--CSQQTbsg.js → 1.33.0/chunks/index--pcCOJWb-BzpgdoE8.js} +2 -2
  11. package/dist/runtime/{1.32.18/chunks/index-7N5M1HdS-DAdxCQyi.js → 1.33.0/chunks/index-7yhyghzH-BlFXtfQb.js} +2 -2
  12. package/dist/runtime/{1.32.18/chunks/index-CF37rhgu-BcW8HKb8.js → 1.33.0/chunks/index-BCxeWwto-B9PuY2Gx.js} +2 -2
  13. package/dist/runtime/{1.32.18/chunks/index-BKZyJMr2-oy07dUaV.js → 1.33.0/chunks/index-BO0vI80C-qK4w7DnX.js} +4 -4
  14. package/dist/runtime/{1.32.18/chunks/index-99heIIoH-QeFj7CR9.js → 1.33.0/chunks/index-BP1Q45X4-f3F4IxQ5.js} +2 -2
  15. package/dist/runtime/{1.32.18/chunks/index-DAICBUgn-DBhSkJ7i.js → 1.33.0/chunks/index-BPfUysTZ-CV5ZiVsD.js} +2 -2
  16. package/dist/runtime/{1.32.18/chunks/index-Ce9TuEzb-C3bBvEcm.js → 1.33.0/chunks/index-BWY1nqf0-DX50C5MZ.js} +2 -2
  17. package/dist/runtime/{1.32.18/chunks/index-COfQIa8G-D6wzHiS0.js → 1.33.0/chunks/index-BblCrrAW-bh6F7tw3.js} +2 -2
  18. package/dist/runtime/{1.32.18/chunks/index-BX6ig9BJ-Dsa9X9U7.js → 1.33.0/chunks/index-Bd_8PmPr-CgO1smBF.js} +2 -2
  19. package/dist/runtime/{1.32.18/chunks/index-D96sEJQ6-Dp5AxBD4.js → 1.33.0/chunks/index-BjHXOMPQ-Bt7j8evJ.js} +2 -2
  20. package/dist/runtime/{1.32.18/chunks/index-BKrM_uoq-CABL-0v-.js → 1.33.0/chunks/index-BwnCq3yC-LScXPMbE.js} +2 -2
  21. package/dist/runtime/{1.32.18/chunks/index-kAGaGinD-Dm9kbc85.js → 1.33.0/chunks/index-BzVJMW3i-Bhh8_8Oh.js} +2 -2
  22. package/dist/runtime/{1.32.18/chunks/index-B3DeMFo7-BbdAbuAw.js → 1.33.0/chunks/index-CDlumsdH-BgpZz7kC.js} +3 -3
  23. package/dist/runtime/{1.32.18/chunks/index-CYeJYTiB-BLxOZxZv.js → 1.33.0/chunks/index-CH-C6uk_-B-pT4hKt.js} +2 -2
  24. package/dist/runtime/{1.32.18/chunks/index-CV2tGt-4-C9wFr7fa.js → 1.33.0/chunks/index-CNP-4dFm-BlRhWcs1.js} +2 -2
  25. package/dist/runtime/{1.32.18/chunks/index-E59S8-Gw-CovGUxIZ.js → 1.33.0/chunks/index-CNbQ508J-BPOHZMXu.js} +4 -4
  26. package/dist/runtime/{1.32.18/chunks/index-BtkNePSj-CiRb-0NX.js → 1.33.0/chunks/index-CPGSyaZ4-BoVmvEOm.js} +2 -2
  27. package/dist/runtime/{1.32.18/chunks/index-Dw7QeZq3-Dr1V6OGz.js → 1.33.0/chunks/index-CVtuVQCx-Dtq7n928.js} +2 -2
  28. package/dist/runtime/{1.32.18/chunks/index-CCEWGjHV-BTsOZg4v.js → 1.33.0/chunks/index-CYP-tLa5-DLVDVk-F.js} +4 -4
  29. package/dist/runtime/{1.32.18/chunks/index-COTfVuju-DQBGsPwB.js → 1.33.0/chunks/index-CZCcZigQ-qH_mrcVT.js} +2 -2
  30. package/dist/runtime/{1.32.18/chunks/index-Cd1-jHFp-Za3SKEQp.js → 1.33.0/chunks/index-CZSW9eXg-BwcGrX1b.js} +2 -2
  31. package/dist/runtime/{1.32.18/chunks/index-OcrS6o5Y-bdo5pwX-.js → 1.33.0/chunks/index-Cfy6Ocqe-CzwqZYRk.js} +2 -2
  32. package/dist/runtime/1.33.0/chunks/index-Ci7P37Ya-W5nof5Mx.js +6 -0
  33. package/dist/runtime/{1.32.18/chunks/index-l8Oxwea3-Aqz1AnQ5.js → 1.33.0/chunks/index-CmM1q2bg-D6H0juMn.js} +2 -2
  34. package/dist/runtime/{1.32.18/chunks/index-CSRoJRaW-CoI3p0S7.js → 1.33.0/chunks/index-CnknkPUN-Yl3jEGAx.js} +2 -2
  35. package/dist/runtime/{1.32.18/chunks/index-qN6oEHVu-C_0Ll4qr.js → 1.33.0/chunks/index-D9fi5TQ9-k8zxZkfU.js} +2 -2
  36. package/dist/runtime/1.33.0/chunks/index-DG6McKPZ-CqZ9_vG_.js +2 -0
  37. package/dist/runtime/{1.32.18/chunks/index-PxSB6BA6-DFxY6dqO.js → 1.33.0/chunks/index-DOJHU9qy-Bil-vDLm.js} +2 -2
  38. package/dist/runtime/{1.32.18/chunks/index-DiZcd1hz-H31PHMqm.js → 1.33.0/chunks/index-DTa1aDGz-Deg8QEW2.js} +2 -2
  39. package/dist/runtime/{1.32.18/chunks/index-DATkkw3P-VhJcCfAC.js → 1.33.0/chunks/index-DUV1wU5j-ErDxRmJu.js} +2 -2
  40. package/dist/runtime/{1.32.18/chunks/index-oxM4Cgtc-R_xuAEQV.js → 1.33.0/chunks/index-DZNxd978-BmIQ-NmU.js} +2 -2
  41. package/dist/runtime/{1.32.18/chunks/index-BZO9Qaiw-DP0QKkgf.js → 1.33.0/chunks/index-DsyaMk1k-DpMzyqHN.js} +2 -2
  42. package/dist/runtime/{1.32.18/chunks/index-DuPFNKhZ-_M0CWPEY.js → 1.33.0/chunks/index-HIu_g6Cr-CEIHlemy.js} +2 -2
  43. package/dist/runtime/{1.32.18/chunks/index-cCAzBYyN-W1lJrIDD.js → 1.33.0/chunks/index-NPLN6oCC-VW9D8cgC.js} +2 -2
  44. package/dist/runtime/{1.32.18/chunks/index-C5RVj6y1-DUgMllqN.js → 1.33.0/chunks/index-S2W2KqpV-PMvqlUvO.js} +2 -2
  45. package/dist/runtime/{1.32.18/chunks/index-D1YmJ3gf-3B-eE3K7.js → 1.33.0/chunks/index-SV2KdT0_-BZw4n83V.js} +2 -2
  46. package/dist/runtime/{1.32.18/chunks/index-Bf_npmqm-C1BzRUwZ.js → 1.33.0/chunks/index-qzvjftnO-CDVtcfdt.js} +2 -2
  47. package/dist/runtime/{1.32.18/chunks/index-DaW9uf4--pkywvGDF.js → 1.33.0/chunks/index-s0zHGN1t-DWm0RYZF.js} +2 -2
  48. package/dist/runtime/{1.32.18/chunks/index-C1Fa-E3e-ZRnEJoQe.js → 1.33.0/chunks/index-uYSCRIpT-qsVnaLmo.js} +2 -2
  49. package/dist/runtime/{1.32.18/chunks/index-BauMKr5c-BpgnWlB8.js → 1.33.0/chunks/index-v9CNsbwM-CavFmRiD.js} +2 -2
  50. package/dist/runtime/{1.32.18/chunks/index-CZ-JrY2X-TEMHje2B.js → 1.33.0/chunks/index-xQDKGkvA-pCzSL4DD.js} +2 -2
  51. package/dist/runtime/{1.32.18/chunks/index.modern-CioVZ357-BA5NTOmY.js → 1.33.0/chunks/index.modern-CioVZ357-nfRNslCS.js} +2 -2
  52. package/dist/runtime/1.33.0/nexly.js +61 -0
  53. package/dist/v1.js +1 -1
  54. package/package.json +1 -1
  55. package/dist/runtime/1.32.18/chunks/index-rblri-2U-I68tb-d3.js +0 -2
  56. package/dist/runtime/1.32.18/chunks/index-xx1GG5d1-CW29F9vY.js +0 -6
  57. package/dist/runtime/1.32.18/nexly.js +0 -61
  58. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/PanelVideoOverlay-BY__oBYV-B8OPC1xh.js +0 -0
  59. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/_commonjsHelpers-C6fGbg64-BC8KDfbh.js +0 -0
  60. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/accent-legibility-BJF2VO5n-CDPQ7suO.js +0 -0
  61. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/block-helpers-Cg_zAqG6-DnN2COvk.js +0 -0
  62. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/index-BPDIV1BN-DINkyYvc.js +0 -0
  63. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/index-BcsmWDTX-Dw9WA5Ac.js +0 -0
  64. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/index-C262wwK4-DpyhuXqd.js +0 -0
  65. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/index-DMQkz1bV-BuMYksln.js +0 -0
  66. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/index-DZADUAKv-DPfvWVuj.js +0 -0
  67. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/inert-assistant-components-B6Cx9pG5-DWb6n3Yq.js +0 -0
  68. /package/dist/runtime/{1.32.18 → 1.33.0}/chunks/use-deferred-rating-XlgCUwcY-DDVOwURi.js +0 -0
@@ -0,0 +1,6 @@
1
+ import{r as n,j as t,L as wt,K as Ae,e as ts,m as Zs,c as Ys,n as Gs,b as en,x as tn,S as sn,J as nn,i as an,d as rn,X as on,g as cn,f as ln,h as un,s as dn,_ as fn,Z as pn}from"../nexly.js";import{H as hn,P as mn}from"./use-deferred-rating-XlgCUwcY-DDVOwURi.js";import{j as gn}from"./PanelInfoVideo-XFcVoL2c-qpxDXdLm.js";import{x as _n,s as fs,f as ss,c as bn,a as vn}from"./allowed-elements-C0OfX2zF-DIBV8lKu.js";import{f as xn}from"./assistant-link-components-gMuMhmaU-rHpeX4O6.js";import{j as yn,X as kn}from"./ClickToLoadEmbed-DdH19Upf-CnpjmfE1.js";import"./_commonjsHelpers-C6fGbg64-BC8KDfbh.js";import"./assistant-link-policy-DlGAtyk7-By6jpR50.js";const wn=new Set(["table","thead","tbody","tfoot","tr"]);function jn(s){return/^[ \t\r\n\f]*$/.test(s)}function ns(s){return typeof s?.offset=="number"?s.offset:null}function Cn(s){return typeof s=="object"&&s!==null&&"type"in s}function Nn(s={}){const a=s.allowedElements?new Set(s.allowedElements):null,o=s.skipHtml??!1;let r=null;function c(d,p){const m=d.children;if(!m)return;const b=d.type==="element"&&typeof d.tagName=="string"&&wn.has(d.tagName);for(const h of m){if(h.type==="element"){if(a&&typeof h.tagName=="string"&&!a.has(h.tagName))continue;c(h,p);continue}if(h.type!=="text"&&h.type!=="raw"||h.type==="raw"&&o)continue;const i=typeof h.value=="string"?h.value:"";i&&(h.type==="text"&&b&&jn(i)||p.push({value:i,sourceStart:ns(h.position?.start),sourceEnd:ns(h.position?.end)}))}}return{plugin:()=>d=>{r=Cn(d)?d:null},segments:()=>{if(!r)return[];const d=[];return c(r,d),d}}}function Sn(s,a){const o=s.ownerDocument??s;if(typeof o?.createTreeWalker!="function")return null;const r=o.createTreeWalker(s,4),c=[];for(let p=r.nextNode();p;p=r.nextNode())c.push(p);if(c.length!==a.length)return null;const d=[];for(let p=0;p<c.length;p+=1){const m=c[p],b=a[p];if(!m||!b||m.data!==b.value)return null;d.push({...b,node:m})}return d}function as(s,a,o){return Math.min(Math.max(s,a),o)}function Rn(s,a,o){if(!(o>a))return null;let r=null,c=null;for(const d of s){const{sourceStart:p,sourceEnd:m}=d;if(p===null||m===null||m<=a||p>=o)continue;const b=m-p===d.value.length,h=b?as(a-p,0,d.value.length):0,i=b?as(o-p,0,d.value.length):d.value.length;i<=h||(r||(r={node:d.node,offset:h}),c={node:d.node,offset:i})}return r&&c?{startNode:r.node,startOffset:r.offset,endNode:c.node,endOffset:c.offset}:null}const Aa={slug:"support-chat",name:"Support Chat",version:"1.0.0",category:"interactive",requiredService:"support-chat",configSchema:{properties:{voiceEnabled:{type:"boolean",default:!0},voiceConversationEnabled:{type:"boolean",default:!1},voiceReadAloudEnabled:{type:"boolean",default:!1},welcomeMessage:{type:"string",default:""},headerTitle:{type:"string",default:""},placeholder:{type:"string",default:""},showSuggestedQuestions:{type:"boolean",default:!0},suggestedQuestions:{type:"array",items:{type:"string"},default:[]},escalationLabel:{type:"string",default:""},humanHandoffButton:{type:"boolean",default:!1}}},defaultConfig:{voiceEnabled:!0,voiceConversationEnabled:!1,voiceReadAloudEnabled:!1,welcomeMessage:"",headerTitle:"",placeholder:"",showSuggestedQuestions:!0,suggestedQuestions:[],escalationLabel:"",humanHandoffButton:!1},dataContract:{serviceSlug:"support-chat",inputSchema:{type:"object",properties:{answer:{type:"string",description:"AI response text"},confidence:{type:"number",description:"Confidence score 0-1"},sources:{type:"array",items:{type:"object",properties:{title:{type:"string"},url:{type:"string"},excerpt:{type:"string"}}},description:"Source citations for the answer"}},required:["answer"]},previewDataOverride:{answer:"Our return policy allows returns within 30 days of purchase. Items must be in original condition with tags attached.",confidence:.85,sources:[{title:"Return Policy",url:"/policies/returns",excerpt:"Returns accepted within 30 days."}]}},fields:[{id:"voiceConversationEnabled",type:"toggle",label:"Voice conversation (live)",default:!1,group:"Voice"},{id:"voiceReadAloudEnabled",type:"toggle",label:"Read messages aloud",default:!1,group:"Voice"},{id:"headerTitle",type:"localized-text",label:"Header title",default:"",placeholder:'Leave empty to use translated default (e.g. "Support")',group:"Content"},{id:"welcomeMessage",type:"localized-text",label:"Welcome message",default:"",placeholder:'Leave empty to use translated default (e.g. "Hi! How can I help you today?")',group:"Content"},{id:"placeholder",type:"localized-text",label:"Input placeholder",default:"",placeholder:'Leave empty to use translated default (e.g. "Ask a question...")',group:"Content"},{id:"escalationLabel",type:"text",label:"Escalation button label",default:"",placeholder:'Leave empty to use translated default (e.g. "Contact Support")',group:"Content"},{id:"humanHandoffButton",type:"toggle",label:'Show "Human" button',default:!1,group:"Behavior"},{id:"showSuggestedQuestions",type:"toggle",label:"Show suggested questions",default:!0,group:"Behavior"},{id:"suggestedQuestions",type:"json",label:"Suggested questions",default:[],placeholder:'["What is your return policy?", "Do you ship internationally?"]',group:"Behavior"}],events:{emits:[{name:"support-chat:messageSent",description:"User sent a message"},{name:"support-chat:escalated",description:"User requested escalation to human support"},{name:"support-chat:feedbackSubmitted",description:"User rated helpfulness of answer"}],listens:[{name:"support-chat:clearHistory",description:"Clear chat history"}]},sizing:{minWidth:280,preferredHeight:"fill",scrollable:!0},supportedPlacements:["main","sidebar","fullscreen"]};function ps({text:s,allowedLinkHosts:a,sourceCollector:o,containerRef:r}){return t.jsx("div",{ref:r,className:"es-sc__bubble-text es-sc__bubble-text--md",children:t.jsx(_n,{remarkPlugins:[...bn],rehypePlugins:o?[...ss,o.plugin]:[...ss],allowedElements:[...fs],transformLinkUri:c=>vn(c)??"",transformImageUri:()=>"",components:{input:({node:c,type:d,checked:p,...m})=>d==="checkbox"?t.jsx("input",{...m,type:"checkbox",checked:!!p,disabled:!0,readOnly:!0,className:"es-sc__md-task"}):null,...xn({allowedHosts:a})},children:s})})}function Tn({text:s,allowedLinkHosts:a,cursor:o}){const r=n.useRef(null),c=!!o,d=n.useMemo(()=>c?Nn({allowedElements:fs,skipHtml:!1}):void 0,[c]);return n.useEffect(()=>{const p=r.current;if(!o||!d||!p)return;const m=tn({container:p}),b=p.ownerDocument,h=sn({currentTime:o.currentTime,words:o.words,onWord:i=>{if(i===null){m.paint(null);return}const g=Sn(p,d.segments()),v=g&&Rn(g,i.sourceStart,i.sourceEnd);if(!v){m.paint(null);return}const x=b.createRange();x.setStart(v.startNode,v.startOffset),x.setEnd(v.endNode,v.endOffset),m.paint(x)}});return h.start(),()=>{h.stop(),m.destroy()}},[o,d]),t.jsx(ps,{text:s,allowedLinkHosts:a,sourceCollector:d,containerRef:r})}function En({media:s,t:a}){const{embeds:o,images:r}=s;return o.length===0&&r.length===0?null:t.jsxs("div",{className:"es-sc__media","data-testid":"support-chat-media",children:[o.map(c=>t.jsx(kn,{embed:c,t:a,classPrefix:"es-sc"},`${c.provider}:${c.id}`)),r.map(c=>t.jsx("img",{className:"es-sc__media-img",src:c.src,alt:c.alt||a("support_chat.media_image_alt"),loading:"lazy",decoding:"async",referrerPolicy:"no-referrer"},c.src))]})}function jt(s){return s?s.join(","):""}const In=n.memo(function({text:s,allowEmbeds:a,allowedImageHosts:o,t:r}){const c=jt(o),d=n.useMemo(()=>yn(s,{allowEmbeds:a,allowedImageHosts:o}),[s,a,c]);return t.jsx(En,{media:d,t:r})},(s,a)=>s.text===a.text&&s.allowEmbeds===a.allowEmbeds&&s.t===a.t&&jt(s.allowedImageHosts)===jt(a.allowedImageHosts));function Mn(s,a){const o=Math.round((Date.now()-s.getTime())/1e3);if(o<60)return a("time.just_now");const r=Math.round(o/60);if(r<60)return a("time.minutes_ago",{count:r});const c=Math.round(r/60);if(c<24)return a("time.hours_ago",{count:c});const d=Math.round(c/24);return a("time.days_ago",{count:d})}function hs({card:s,t:a,onSelect:o}){const r=t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"es-sc__ticket-card-head",children:[t.jsxs("span",{className:"es-sc__ticket-card-number",children:["#",s.externalNumber]}),t.jsx("span",{className:`es-sc__ticket-card-status es-sc__ticket-card-status--${s.status}`,children:a(`escalation.status_${s.status}`)})]}),s.summary&&t.jsx("p",{className:"es-sc__ticket-card-summary",title:s.summary,children:s.summary}),t.jsxs("p",{className:"es-sc__ticket-card-meta",children:[Mn(new Date(s.createdAt),a),s.priority?` · ${a(`support_chat.priority_${s.priority}`)}`:""]})]});if(o&&s.sessionId){const c=s.sessionId;return t.jsx("button",{type:"button",className:"es-sc__ticket-card es-sc__ticket-card--clickable",onClick:()=>o(c),"aria-label":a("support_chat.open_ticket_conversation"),title:a("support_chat.open_ticket_conversation"),children:r})}return t.jsx("div",{className:"es-sc__ticket-card",children:r})}const An=[{value:"open",key:"support_chat.filter_open"},{value:"closed",key:"support_chat.filter_closed"},{value:"all",key:"support_chat.filter_all"}];function $n(s){const{status:a,loading:o,tickets:r,onSelectStatus:c,onSelectSession:d,t:p}=s;return t.jsxs("div",{className:"es-sc__tickets-view",children:[t.jsx("div",{className:"es-sc__tickets-filters",children:An.map(m=>t.jsx("button",{type:"button",className:`es-sc__tickets-chip${a===m.value?" es-sc__tickets-chip--active":""}`,onClick:()=>c(m.value),children:p(m.key)},m.value))}),t.jsx("div",{className:"es-sc__tickets-view-list",children:o?t.jsx("p",{className:"es-sc__tickets-empty",role:"status","aria-live":"polite",children:"…"}):r.length===0?t.jsx("p",{className:"es-sc__tickets-empty",children:p("support_chat.tickets_empty")}):r.map(m=>t.jsx(hs,{card:m,t:p,onSelect:d},m.externalNumber))})]})}const Ln=["audio/webm;codecs=opus","audio/webm","audio/mp4"];function Pn(){return typeof navigator>"u"||typeof window>"u"?!1:typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof window.MediaRecorder<"u"}function Un(){if(typeof window>"u"||typeof window.MediaRecorder>"u")return;const s=typeof window.MediaRecorder.isTypeSupported=="function";for(const a of Ln)if(!s||window.MediaRecorder.isTypeSupported(a))return a}function On({baseUrl:s,apiKey:a,jwt:o,language:r,onTranscript:c,t:d,disabled:p=!1,streaming:m,voiceStream:b,baseText:h,onText:i}){const[g]=n.useState(Pn),[v,x]=n.useState("idle"),[N,A]=n.useState(null),[O,X]=n.useState("idle"),M=!!(m&&b&&h&&i),k=n.useRef(null),$=n.useRef(null),F=n.useRef([]),V=n.useRef(!0);n.useEffect(()=>()=>{V.current=!1},[]);const me=n.useRef({baseUrl:s,apiKey:a,jwt:o,language:r,onTranscript:c});n.useEffect(()=>{me.current={baseUrl:s,apiKey:a,jwt:o,language:r,onTranscript:c}},[s,a,o,r,c]);const oe=n.useCallback(()=>{$.current?.getTracks().forEach(R=>R.stop()),$.current=null,k.current=null,F.current=[]},[]);n.useEffect(()=>oe,[oe]);const K=n.useRef(()=>{});K.current=()=>{M&&(O==="connecting"||O==="listening")&&b?.stop()},n.useEffect(()=>()=>K.current(),[]);const $e=n.useCallback(async R=>{const{baseUrl:L,apiKey:D,jwt:W,language:E,onTranscript:I}=me.current,se=new FormData;se.append("audio",R,"recording.webm"),se.append("language",E);const ne={};D&&(ne["X-API-Key"]=D),W&&(ne.Authorization=`Bearer ${W}`);const ee=await fetch(`${L}/api/widget/transcribe`,{method:"POST",headers:ne,credentials:"include",body:se});if(!ee.ok){const Z=new Error(`HTTP ${ee.status}`);throw Z.status=ee.status,Z}const ue=await ee.json();I(ue.text??"")},[]),Le=n.useCallback(async()=>{A(null);let R;try{R=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{x("error"),A("voice.permission_denied");return}const L=Un();let D;try{D=L?new MediaRecorder(R,{mimeType:L}):new MediaRecorder(R)}catch{R.getTracks().forEach(W=>W.stop()),x("error"),A("voice.error_generic");return}$.current=R,k.current=D,F.current=[],D.ondataavailable=W=>{W.data&&W.data.size>0&&F.current.push(W.data)},D.onstop=async()=>{const W=D.mimeType||L||"audio/webm",E=new Blob(F.current,{type:W});if(oe(),E.size===0){x("idle");return}x("transcribing");try{if(await $e(E),!V.current)return;x("idle"),A(null)}catch(I){if(!V.current)return;const se=I.status;x("error"),A(se===413?"voice.error_too_large":"voice.error_generic")}},D.start(),x("recording")},[oe,$e]),Te=n.useCallback(()=>{const R=k.current;R&&R.state!=="inactive"?R.stop():(oe(),x("idle"))},[oe]),Ee=n.useCallback(()=>{g&&(M?O==="connecting"||O==="listening"?(b.stop(),X("idle")):(A(null),b.start({language:r,baseText:h,onText:i,onState:R=>X(R),onError:R=>{A(R),X("error")}})):v==="recording"?Te():(v==="idle"||v==="error")&&Le())},[g,M,O,v,r,h,i,b,Le,Te]);if(!g)return null;const _e=M?O==="connecting"||O==="listening":v==="recording",we=!M&&v==="transcribing",Fe=M?O==="error":v==="error",T=d(_e?"voice.stop":"voice.start"),z=N?d(N):we?d("voice.transcribing"):T,ie=["es-sc__mic",_e&&"es-sc__mic--recording",we&&"es-sc__mic--transcribing",Fe&&"es-sc__mic--error"].filter(Boolean).join(" ");return t.jsx("button",{type:"button",className:ie,onClick:Ee,disabled:we||p,"aria-label":T,"aria-pressed":_e,title:z,children:we?t.jsx("svg",{width:18,height:18,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",className:"es-sc__mic-spinner","aria-hidden":"true",children:t.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}):_e?t.jsx("svg",{width:18,height:18,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})}):t.jsxs("svg",{width:18,height:18,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),t.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]})})}function Dn(){return t.jsx("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none","aria-hidden":"true",children:t.jsx("path",{d:"M8 5.14v13.72a1 1 0 0 0 1.5.86l11-6.86a1 1 0 0 0 0-1.72l-11-6.86A1 1 0 0 0 8 5.14Z"})})}function Bn(){return t.jsxs("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none","aria-hidden":"true",children:[t.jsx("rect",{x:"6",y:"5",width:"4",height:"14",rx:"1"}),t.jsx("rect",{x:"14",y:"5",width:"4",height:"14",rx:"1"})]})}function qn(){return t.jsx("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none","aria-hidden":"true",children:t.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})}function Hn(){return t.jsx("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",className:"es-sc__readaloud-spinner","aria-hidden":"true",children:t.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}const Fn=n.memo(function({id:s,session:a,onActivate:o,t:r}){const c=a.activeId===s?a.status:"idle",d=n.useCallback(()=>{if(c==="idle"||c==="error"){o();return}c!=="loading"&&a.togglePause()},[c,o,a]),p=n.useCallback(()=>a.stop(),[a]),m=r(c==="playing"?"voice_output.pause":"voice_output.play"),b=c==="error"?r("voice_output.error"):m;return t.jsxs("span",{className:"es-sc__readaloud-group",children:[t.jsx("button",{type:"button",className:["es-sc__readaloud-btn",c==="playing"&&"es-sc__readaloud-btn--playing",c==="paused"&&"es-sc__readaloud-btn--paused",c==="error"&&"es-sc__readaloud-btn--error"].filter(Boolean).join(" "),onClick:d,disabled:c==="loading","aria-label":m,"aria-pressed":c==="playing",title:b,children:c==="loading"?t.jsx(Hn,{}):c==="playing"?t.jsx(Bn,{}):t.jsx(Dn,{})}),(c==="playing"||c==="paused")&&t.jsx("button",{type:"button",className:"es-sc__readaloud-btn es-sc__readaloud-btn--stop",onClick:p,"aria-label":r("voice_output.stop"),title:r("voice_output.stop"),children:t.jsx(qn,{})})]})});function zn(s){let a=null,o=0,r=null,c=null;const d=new Set,p={ended:new Set},m=h=>{for(const i of[...p[h]])i()},b=h=>{h.onended=null,pn(()=>h.stop())};return{push(h){const i=new Uint8Array(h);let g;r&&r.length>0?(g=new Uint8Array(r.length+i.length),g.set(r,0),g.set(i,r.length),r=null):g=i;const v=g.length-g.length%2;if(v<g.length&&(r=g.slice(v)),v===0)return;const x=new Int16Array(g.buffer,g.byteOffset,v/2);if(x.length===0)return;a??(a=new AudioContext({sampleRate:s}));const N=a.createBuffer(1,x.length,s);N.getChannelData(0).set(Float32Array.from(x,X=>X/32768));const A=a.createBufferSource();A.buffer=N,A.connect(a.destination),A.onended=()=>{d.delete(A),d.size===0&&m("ended")},d.add(A);const O=Math.max(a.currentTime,o);A.start(O),c??(c=O),o=O+N.duration},reset(){for(const h of[...d])b(h);d.clear(),o=0,c=null,r=null},pause(){a?.suspend()},resume(){a?.resume()},currentTime(){return!a||c===null?0:Math.min(Math.max(a.currentTime-c,0),o-c)},nextStartTime(){return!a||c===null?0:Math.max(a.currentTime,o)-c},on(h,i){return p[h].add(i),()=>{p[h].delete(i)}},close(){for(const h of[...d])b(h);d.clear(),a?.close(),a=null,o=0,c=null,p.ended.clear()}}}const Kn=" ";function Wn({baseUrl:s,apiKey:a,getJwt:o}){const[r,c]=n.useState(null),[d,p]=n.useState("idle"),m=n.useRef(null),b=n.useRef(null),h=n.useRef([]),i=n.useRef(!1),g=n.useRef("en"),v=n.useRef(null),x=n.useRef([]),N=n.useRef(""),A=n.useRef(null),O=n.useCallback(()=>{v.current=null,x.current=[],N.current="",A.current=null},[]),X=n.useCallback(()=>{const T=v.current,z=x.current;if(!T||z.length===0){A.current=null;return}A.current=Zs({sanitizedText:N.current,locale:g.current,charTimes:T.charTimes(),toSourceRange:(ie,R)=>{const L=z.find(E=>ie>=E.sanitizedBase&&ie<E.sanitizedBase+E.sanitizedLength);if(!L||L.spans===null||L.sourceBase===null)return null;const D=Math.min(R,L.sanitizedBase+L.sanitizedLength),W=Ys(L.spans,ie-L.sanitizedBase,D-L.sanitizedBase);return W===null?null:{start:W.start+L.sourceBase,end:W.end+L.sourceBase}}})},[]),M=n.useRef(!1),k=n.useRef(!1),$=n.useRef(0),F=n.useRef(null),V=n.useRef(null),me=n.useCallback(()=>{V.current&&(clearTimeout(V.current),V.current=null)},[]),oe=n.useCallback(()=>{F.current?.abort(),F.current=null,V.current&&(clearTimeout(V.current),V.current=null),b.current?.close(),b.current=null,h.current=[],i.current=!1,M.current=!1,k.current=!1,O()},[O]),K=n.useCallback(()=>{$.current+=1,oe(),m.current=null,c(null),p("idle")},[oe]),$e=n.useCallback(()=>{const T=b.current;T&&p(z=>z==="playing"?(T.pause(),"paused"):z==="paused"?(T.resume(),"playing"):z)},[]),Le=n.useCallback(T=>{if(m.current===T)return;oe(),$.current+=1,F.current=new AbortController,m.current=T,c(T),p("loading");const z=$.current;V.current=setTimeout(()=>{z===$.current&&(F.current?.abort(),p("error"))},12e3)},[oe]),Te=n.useCallback(async T=>{if(!T)return;const z=o?.();await Ae(fetch(`${s}/api/widget/read-aloud-play`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"X-API-Key":a}:{},...z?{Authorization:`Bearer ${z}`}:{}},body:JSON.stringify({messageId:T})}))},[s,a,o]),Ee=n.useCallback((T,z)=>{i.current||(i.current=!0,(async()=>{for(;h.current.length>0;){if(T!==$.current){i.current=!1;return}const ie=h.current.shift();if(!ie)continue;const R=ie.text,L=o?.(),[D,W]=await Ae(fetch(`${s}/api/widget/read-aloud`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"X-API-Key":a}:{},...L?{Authorization:`Bearer ${L}`}:{}},body:JSON.stringify({text:R,language:z,messageId:m.current??void 0,alignment:!0}),signal:F.current?.signal}));if(T!==$.current){i.current=!1;return}if(W||!D||!D.ok||!D.body){p("error"),i.current=!1;return}const E=D.headers.get("X-Audio-Encoding");if(E&&E!=="pcm16"){p("error"),i.current=!1;return}if(!b.current){const B=Number(D.headers.get("X-Audio-Sample-Rate"))||24e3,q=zn(B);b.current=q,q.on("ended",()=>{T===$.current&&(!M.current||h.current.length>0||i.current||K())})}const I=b.current,se=B=>{I.push(B),!k.current&&(k.current=!0,me(),p("playing"),Te(m.current))},ne=Gs(D.headers.get("Content-Type"))?en():null;let ee=null,ue=null;const Z=[],je=B=>{const q=v.current;!q||!ee||ue===null||q.addUtterance({charOffset:B.charOffset,characters:B.characters,startTimes:B.startTimes,endTimes:B.endTimes,textBase:ee.sanitizedBase,timeBase:ue})},et=B=>{switch(B.type){case un:{ue===null&&(ue=I.nextStartTime()),se(B.payload.slice().buffer);let q=!1;for(;Z.length>0;){const J=Z.shift();J&&(je(J),q=!0)}return q}case on:{if(ee!==null)return!1;const q=cn(B.payload);return N.current.length>0&&(N.current+=Kn),ee={sanitizedBase:N.current.length,sanitizedLength:q.length,sourceBase:ie.sourceStart??null,spans:null},N.current+=q,x.current.push(ee),v.current??(v.current=ln()),!1}case rn:return ee!==null&&(ee.spans=dn(B.payload)),!1;case nn:{const q=an(B.payload);return q===null?!1:ue===null?(Z.push(q),!1):(je(q),!0)}default:return!1}},Pe=D.body.getReader();for(;;){const[B,q]=await Ae(Pe.read());if(T!==$.current){i.current=!1;return}if(q){p("error"),i.current=!1;return}const{done:J,value:ae}=B;if(J)break;if(!ae||ae.byteLength===0)continue;if(ne===null){se(ae.buffer.slice(ae.byteOffset,ae.byteOffset+ae.byteLength));continue}let be=!1;for(const ze of ne.push(ae))et(ze)&&(be=!0);be&&X()}ne!==null&&X()}i.current=!1,M.current&&!k.current&&T===$.current&&K()})())},[s,a,o,K,Te,X]),_e=n.useCallback((T,z,ie,R)=>{if(m.current!==T)return;const L=z.trim();L&&(g.current=ie,h.current.push({text:L,sourceStart:R}),Ee($.current,ie))},[Ee]),we=n.useCallback(T=>{m.current===T&&(M.current=!0,h.current.length===0&&!i.current&&!k.current&&K())},[K]);n.useEffect(()=>()=>K(),[K]);const Fe=n.useMemo(()=>({words:()=>A.current,currentTime:()=>b.current?.currentTime()??0}),[]);return{activeId:r,status:d,activate:Le,feed:_e,finish:we,togglePause:$e,stop:K,cursor:Fe}}const Jn=1200;function Qn(s={language:"en"}){const{voiceStream:a,language:o,silenceMs:r=Jn}=s;let c=null,d=null,p="",m=!1;const b=()=>{d&&clearTimeout(d),d=null},h=()=>{!a||!m||(p="",a.start({language:o,baseText:()=>"",onText:i=>{const g=i.trim();!g||g===p||(p=g,c?.({type:"user_partial",text:g}),b(),d=setTimeout(()=>{const v=p;v&&(p="",c?.({type:"user_final",text:v}),a.stop(),h())},r))},onError:i=>c?.({type:"error",message:i})}))};return{get available(){return!!a},async start({onEvent:i}){if(!a)throw new Error("conversation transport unavailable");c=i,m=!0,h()},stop(){m=!1,b(),p="",a&&a.stop(),c=null}}}function Xn(s){let a=null,o=null;return{get available(){return s.enabled&&typeof RTCPeerConnection<"u"},async start({onEvent:r}){o=r;const c={"Content-Type":"application/json","X-API-Key":s.apiKey},d=s.getJwt?.()??s.jwt;d&&(c.Authorization=`Bearer ${d}`);const p=s.getSessionId?.()??null,m=await fetch(`${s.baseUrl}/api/widget/realtime-voice`,{method:"POST",headers:c,body:JSON.stringify({language:s.language,...p?{sessionId:p}:{}})});if(!m.ok)throw new Error("eleven token refused");const b=await m.json(),h=b.data?.token;if(b.data?.provider!=="elevenlabs"||!h)throw new Error("not an elevenlabs session");b.data?.sessionId&&s.onSessionId?.(b.data.sessionId);const i=b.data?.endUserToken??"",{Conversation:g}=await fn(async()=>{const{Conversation:k}=await import("./index-DMQkz1bV-BuMYksln.js");return{Conversation:k}},[]);let v=!1,x=null;const N=.6,A=.35,O=k=>{k!==v&&(v=k,o?.({type:"user_speaking",active:k}))};let X="";const M=k=>{const $=k?.trim();$&&(O(!1),o?.({type:"thinking"}),$!==X&&(X=$,s.onUserTurnEnd?.()))};a=await g.startSession({conversationToken:h,connectionType:"webrtc",customLlmExtraBody:{end_user_token:i},onModeChange:({mode:k})=>{o?.(k==="speaking"?{type:"agent_delta",text:""}:{type:"agent_done"})},onVadScore:({vadScore:k})=>{k>=N?(x&&(clearTimeout(x),x=null),O(!0)):k<=A&&v&&!x&&(x=setTimeout(()=>{x=null,O(!1)},600))},onMessage:({message:k,role:$})=>{const F=k?.trim();F&&($==="user"?M(F):(s.onTranscript({role:"assistant",text:F,streaming:!1}),X=""))},onIncomingEvent:k=>{k?.type==="user_transcript"&&M(k.user_transcription_event?.user_transcript)},onAgentTyping:()=>o?.({type:"thinking"}),onAgentChatResponsePart:k=>{const $=k?.text??"";$&&s.onTranscript({role:"assistant",text:$,streaming:!0})},onInterruption:()=>o?.({type:"interrupted"}),onError:k=>{console.warn("[voice] eleven blad:",k),o?.({type:"error",message:"voice_conv.error"})}})},setMuted(r){a?.setMicMuted?.(r)},sendUserMessage(r){const c=r.trim();return!c||!a||(a.sendUserActivity?.(),!a.sendUserMessage)?!1:(a.sendUserMessage(c),!0)},stop(){o=null;const r=a;a=null,r?.endSession()}}}function rs({followUps:s,isNewest:a,isPending:o,hasQuickReplies:r,isSending:c,onSelect:d,t:p}){return!a||o||r||!s||s.length===0?null:t.jsx("div",{className:"es-sc__followups",role:"list","aria-label":p("support_chat.followups_aria"),"data-es-no-read":!0,children:s.map(m=>t.jsx("button",{type:"button",role:"listitem",disabled:c,className:"es-sc__suggestion es-sc__suggestion--followup",onClick:()=>d(m.message),children:m.label},m.message))})}function Vn(s){switch(s){case"OUT_OF_HOURS":return"support_chat.handoff.out_of_hours";case"QUEUE_FULL":return"support_chat.handoff.queue_full";default:return"support_chat.handoff.no_operator_title"}}const Ct={email:254,phone:32,note:2e3},Zn={email:"",phone:"",note:""};function Yn(s){const[a,o]=n.useState(()=>Date.now());return n.useEffect(()=>{if(s===null)return;const r=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(r)},[s]),s===null?null:Math.max(0,Math.ceil((s-a)/1e3))}function Gn({status:s,onSubmitContact:a,onDismissContact:o,t:r}){const[c,d]=n.useState(Zn),[p,m]=n.useState(!1),[b,h]=n.useState(null),i=n.useRef(null),g=Yn(s.kind==="waiting"?s.until:null);return n.useEffect(()=>{s.kind==="unavailable"&&i.current?.focus()},[s.kind]),s.kind==="idle"?null:s.kind==="waiting"?t.jsxs("div",{className:"es-sc__handoff es-sc__handoff--waiting",role:"status","aria-live":"polite",children:[t.jsx("span",{className:"es-sc__handoff-dot","aria-hidden":"true"}),t.jsx("span",{className:"es-sc__handoff-text",children:g===null?r("support_chat.handoff.queued"):r("support_chat.handoff.waiting",{seconds:g})})]}):s.kind==="human"?t.jsx("div",{className:"es-sc__handoff es-sc__handoff--human",role:"status","aria-live":"polite",children:t.jsx("span",{className:"es-sc__handoff-text",children:s.displayName?r("support_chat.handoff.human_joined",{name:s.displayName}):r("support_chat.handoff.human_joined_unnamed")})}):s.kind==="contact_left"?t.jsx("div",{className:"es-sc__handoff es-sc__handoff--done",role:"status","aria-live":"polite",children:t.jsx("span",{className:"es-sc__handoff-text",children:r("support_chat.handoff.contact_success")})}):t.jsxs("form",{className:"es-sc__handoff es-sc__handoff--form",onSubmit:async v=>{if(v.preventDefault(),p)return;if(c.email.trim().length===0&&c.phone.trim().length===0){h(r("support_chat.handoff.contact_validation")),i.current?.focus();return}m(!0),h(null);const x=await a({email:c.email.trim(),phone:c.phone.trim(),note:c.note.trim()});m(!1),x||h(r("support_chat.handoff.contact_error"))},noValidate:!0,children:[t.jsx("p",{className:"es-sc__handoff-title",children:r(Vn(s.reason))}),t.jsx("p",{className:"es-sc__handoff-text",children:r("support_chat.handoff.contact_prompt")}),t.jsx("label",{className:"es-sc__handoff-label",htmlFor:"es-sc-handoff-email",children:r("support_chat.handoff.contact_email_label")}),t.jsx("input",{id:"es-sc-handoff-email",ref:i,className:"es-sc__handoff-input",type:"email",autoComplete:"email",maxLength:Ct.email,value:c.email,"aria-invalid":b!==null,"aria-describedby":b?"es-sc-handoff-error":void 0,onChange:v=>d(x=>({...x,email:v.target.value}))}),t.jsx("label",{className:"es-sc__handoff-label",htmlFor:"es-sc-handoff-phone",children:r("support_chat.handoff.contact_phone_label")}),t.jsx("input",{id:"es-sc-handoff-phone",className:"es-sc__handoff-input",type:"tel",autoComplete:"tel",maxLength:Ct.phone,value:c.phone,onChange:v=>d(x=>({...x,phone:v.target.value}))}),t.jsx("label",{className:"es-sc__handoff-label",htmlFor:"es-sc-handoff-note",children:r("support_chat.handoff.contact_note_label")}),t.jsx("textarea",{id:"es-sc-handoff-note",className:"es-sc__handoff-input es-sc__handoff-textarea",rows:3,maxLength:Ct.note,value:c.note,onChange:v=>d(x=>({...x,note:v.target.value}))}),b&&t.jsx("p",{className:"es-sc__handoff-error",id:"es-sc-handoff-error",role:"alert",children:b}),t.jsxs("div",{className:"es-sc__handoff-actions",children:[t.jsx("button",{className:"es-sc__handoff-submit",type:"submit",disabled:p,children:r("support_chat.handoff.contact_submit")}),t.jsx("button",{className:"es-sc__handoff-dismiss",type:"button",onClick:o,children:r("support_chat.handoff.contact_dismiss")})]})]})}const ms="live:";function He(s){return s.id.startsWith(ms)}function ea(s,a){return s.text!==a.text?!0:JSON.stringify(s.metadata??null)!==JSON.stringify(a.metadata??null)}function ta(s,a){if(a.length===0)return s;const o=new Map;s.forEach((h,i)=>o.set(h.id,i));let r=null;const c=[];let d=!1;for(const h of a){const i=o.get(h.id);if(i===void 0){c.push(h),h.role==="assistant"&&(d=!0);continue}const g=s[i];ea(g,h)&&(r??(r=[...s]),r[i]={...g,...h})}if(c.length===0)return r??s;const p=r??[...s],m=d?p.filter(h=>!He(h)):p,b=m.filter(He);return[...m.filter(h=>!He(h)),...c,...b]}function sa({transport:s,agentId:a,onUserMessage:o,onStopPlayback:r}){const[c,d]=n.useState("idle"),[p,m]=n.useState(null),[b,h]=n.useState(!1),[i,g]=n.useState(null),v=n.useRef(o);v.current=o;const x=n.useRef(r);x.current=r;const N=n.useCallback(M=>{switch(M.type){case"user_partial":x.current(),m(M.text),d("listening");return;case"user_final":m(null),h(!1),d("listening"),M.text.trim()&&v.current(M.text);return;case"user_speaking":h(M.active),M.active&&(x.current(),d("listening"));return;case"thinking":m(null),h(!1),d("thinking");return;case"agent_delta":d("speaking");return;case"agent_done":d("listening");return;case"interrupted":x.current(),d("listening");return;case"error":g(M.message),d("error");return}},[]),A=n.useCallback(async()=>{if(!s.available){g("voice_conv.error"),d("error");return}g(null),d("connecting"),x.current();const[,M]=await Ae(s.start({agentId:a,onEvent:N}));if(M){g("voice_conv.error"),d("error");return}d("listening")},[s,a,N]),O=n.useCallback(()=>{s.stop(),m(null),h(!1),d("idle")},[s]),X=n.useRef(s);return X.current=s,n.useEffect(()=>()=>X.current.stop(),[]),{state:c,draft:p,userSpeaking:b,error:i,start:A,stop:O}}const na=()=>t.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:[t.jsx("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),t.jsx("path",{d:"M5 11a7 7 0 0 0 14 0M12 18v3"})]}),is=()=>t.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:[t.jsx("path",{d:"M4 4l16 16"}),t.jsx("path",{d:"M9 5a3 3 0 0 1 6 0v5m-6 1.5V11"}),t.jsx("path",{d:"M5 11a7 7 0 0 0 10.9 5.8M19 11a7 7 0 0 1-.4 2.3M12 18v3"})]}),aa=()=>t.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:t.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});function ra({running:s}){const[a,o]=n.useState(0);return n.useEffect(()=>{if(!s)return;const r=setInterval(()=>o(c=>c+1),1e3);return()=>clearInterval(r)},[s]),t.jsx("span",{className:"es-vm__elapsed","data-testid":"voice-mode-elapsed",children:ia(a)})}function ia(s){const a=Math.floor(s/60),o=s%60;return`${a}:${String(o).padStart(2,"0")}`}function oa({state:s,draft:a,error:o,muted:r,listening:c,hasTranscript:d,transcript:p,onToggleMute:m,onEnd:b,onRetry:h,t:i}){const g=n.useRef(null);if(n.useEffect(()=>{const N=g.current;N&&(N.scrollTop=N.scrollHeight)},[p]),s==="error")return t.jsxs("div",{className:"es-vm","data-testid":"voice-mode",children:[t.jsxs("div",{className:"es-vm__top",children:[t.jsx("span",{className:"es-vm__dot es-vm__dot--error"}),t.jsx("span",{className:"es-vm__label",children:i("voice_conv.title")})]}),t.jsxs("div",{className:"es-vm__denied",children:[t.jsx("div",{className:"es-vm__denied-icon",children:t.jsx(is,{})}),t.jsxs("div",{children:[t.jsx("div",{className:"es-vm__denied-title",children:i("voice_conv.denied_title")}),t.jsx("div",{className:"es-vm__denied-body",children:i(o||"voice_conv.denied_body")})]}),t.jsxs("div",{className:"es-vm__denied-actions",children:[t.jsx("button",{type:"button",className:"es-vm__action es-vm__action--primary",onClick:h,"data-testid":"voice-mode-retry",children:i("voice_conv.retry")}),t.jsx("button",{type:"button",className:"es-vm__action",onClick:b,"data-testid":"voice-mode-back",children:i("voice_conv.back_to_typing")})]})]})]});const v=!r&&(!!c||!!(a&&a.trim())),x=r?"muted":s==="speaking"?"speaking":s==="thinking"?"thinking":"listening";return t.jsxs("div",{className:"es-vm","data-testid":"voice-mode","data-state":s,children:[t.jsxs("div",{className:"es-vm__top",children:[t.jsx("span",{className:"es-vm__label",children:i("voice_conv.title")}),t.jsx(ra,{running:s!=="idle"})]}),t.jsxs("div",{className:"es-vm__orbwrap",children:[t.jsxs("div",{className:"es-vm__orb","data-s":x,"data-active":v?"1":void 0,"data-testid":"voice-mode-orb","aria-hidden":"true",children:[t.jsx("span",{className:"es-vm__orb-halo"}),t.jsx("span",{className:"es-vm__orb-halo es-vm__orb-halo--delayed"}),t.jsx("span",{className:"es-vm__orb-core"})]}),t.jsx("div",{className:"es-vm__orb-state",role:"status","data-testid":"voice-mode-state",children:i(`voice_conv.state_${x}`)}),t.jsx("div",{className:"es-vm__orb-hint",children:i(`voice_conv.state_${x}_hint`)})]}),t.jsx("div",{className:"es-vm__transcript","data-testid":"voice-mode-transcript",ref:g,children:d?p:t.jsx("div",{className:"es-vm__invite","data-testid":"voice-mode-invite",children:i("voice_conv.invite")})}),t.jsxs("div",{className:"es-vm__controls",children:[t.jsx("button",{type:"button",className:`es-vm__btn${r?" es-vm__btn--on":""}`,"aria-label":i(r?"voice_conv.unmute":"voice_conv.mute"),onClick:m,"data-testid":"voice-mode-mute",children:r?t.jsx(is,{}):t.jsx(na,{})}),t.jsx("button",{type:"button",className:"es-vm__btn es-vm__btn--end","aria-label":i("voice_conv.end"),onClick:b,"data-testid":"voice-mode-end",children:t.jsx(aa,{})})]})]})}const os=/[.!?]+(?:['")\]]+)?(\s+)/g;function ca(s){const a=[];let o=0;os.lastIndex=0;let r;for(;r=os.exec(s);){const c=r.index+r[0].length,d=s.slice(o,c),p=d.trim();if(p){const m=d.length-d.trimStart().length;a.push({text:p,start:o+m})}o=c}return{complete:a,remainder:s.slice(o)}}function la(s,a,o){return s===void 0?o:s.map(r=>{const c=r.translations?.[a]?.trim();return c||r.translations?.[r.baseLanguage]?.trim()||(Object.values(r.translations??{}).find(p=>p?.trim())?.trim()??"")}).filter(r=>r.length>0)}function ua({size:s=16}){return t.jsxs("svg",{width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function da({size:s=18}){return t.jsxs("svg",{width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("path",{d:"M12 5H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7"}),t.jsx("path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z"})]})}function fa({size:s=16}){return t.jsxs("svg",{width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("path",{d:"M2 9a3 3 0 1 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 1 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"}),t.jsx("path",{d:"m9 12 2 2 4-4"})]})}const pa=["confirm_escalation","cancel_escalation","confirm_handoff","decline_handoff"],ha="<followups>",ma=/<followups>/i;function ga(s){const a=s.search(ma);if(a!==-1)return s.slice(0,a).trimEnd();const o=s.lastIndexOf("<");return o!==-1&&ha.startsWith(s.slice(o).toLowerCase())?s.slice(0,o).trimEnd():s}function cs(s){return s>=.6?"high":s>=.35?"medium":"low"}function _a(s){return/^https?:\/\//i.test(s)}function ba(s){return s==="OUT_OF_HOURS"||s==="QUEUE_FULL"||s==="NO_OPERATOR"?s:null}function ls(s){const{metadata:a,...o}=s;return{...o,...a&&typeof a=="object"?a:{}}}function va(s){let a=null;const o=[];for(const r of s.split(`
2
+ `))r.startsWith("event:")?a=r.slice(6).trim():r.startsWith("data:")&&o.push(r.slice(5).trimStart());return{event:a,data:o.join(`
3
+ `)}}const xa=12e4,us=1500,ya=6e4,ds=120,ka=25e3,wa=600;function ja({value:s,onChange:a,disabled:o,t:r}){const[c,d]=n.useState(null),p=s??0,m=!o&&c!==null?c:p;return t.jsxs("div",{className:"es-sc__rating-group",children:[t.jsx("div",{className:"es-sc__rating",role:"radiogroup","aria-label":r("support_chat.rate_aria"),onMouseLeave:()=>!o&&d(null),children:[1,2,3,4,5].map(b=>{const h=b<=m;return t.jsx("button",{type:"button",role:"radio","aria-checked":b===p,"aria-label":r("support_chat.rate_star",{count:b}),disabled:o,onMouseEnter:()=>!o&&d(b),onFocus:()=>!o&&d(b),onBlur:()=>!o&&d(null),onClick:()=>!o&&a?.(b),className:`es-sc__rating-star${h?" es-sc__rating-star--filled":""}${o?" es-sc__rating-star--disabled":""}`,children:t.jsx("svg",{width:16,height:16,viewBox:"0 0 24 24",fill:h?"currentColor":"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})},b)})}),t.jsx("span",{className:"es-sc__rating-label","aria-live":"polite",children:m>0?r(`support_chat.rate_label_${m}`):""})]})}function $a({config:s,actions:a,baseUrl:o,externalContext:r,productId:c,i18n:d,supportSessionId:p,auth:m,readOnly:b}){const h=b===!0,i=d?.t??(e=>e),g=r?.apiKey??"",v=n.useRef(m?.jwt);n.useEffect(()=>{v.current=m?.jwt},[m?.jwt]);const x=r?.voice,N=d?.currentLanguage??"en",A=!!x?.enabled&&(x?.languages??[]).includes(N),O=s.voiceConversationEnabled===!0,X=s.voiceReadAloudEnabled===!0,M=r?.voiceOutput,k=Wn({baseUrl:o,apiKey:g,getJwt:()=>v.current}),$=n.useRef(k);$.current=k;const F=X&&!!M?.enabled&&(M?.languages??[]).includes(N),V=n.useRef(0),me=r?.userContext??void 0,oe=r?.resetSession??!1,K=r?.showTicketsTab??!1,$e=wt(s.welcomeMessage,N,{t:i,fallbackKey:"support_chat.welcome_message",enDefault:"Hi! How can I help you today?"}),Le=wt(s.placeholder,N,{t:i,fallbackKey:"support_chat.input_placeholder",enDefault:"Ask a question..."}),Te=s.showSuggestedQuestions??!0,Ee=la(s.localizedSuggestedQuestions,N,s.suggestedQuestions??[]),_e=s.escalationLabel||i("support_chat.escalation_label"),we=s.humanHandoffButton===!0,Fe=wt(s.headerTitle,N,{t:i,fallbackKey:"support.title",enDefault:"Support"}),T=s.allowedLinkHosts,z=n.useMemo(()=>Array.isArray(T)?T.filter(e=>typeof e=="string"):void 0,[T]),ie=s.allowMediaEmbeds===!0,R=typeof s._draft=="string"?s._draft:void 0,L=s._autoSend===!0,D=Array.isArray(s._quickChips)?s._quickChips:[],W=JSON.stringify(D),[E,I]=n.useState([]);n.useEffect(()=>{if(!F)return;const e=k.activeId;if(!e){V.current=0;return}const l=E.find(_=>_.id===e);if(!l)return;const u=l.role==="assistant"&&l.refusalReason?i(`support_chat.refusal_${l.refusalReason}`,{productName:l.refusalProductName??""}):l.text??"";if(u.length>V.current){const _=V.current,f=u.slice(_),{complete:w,remainder:C}=ca(f);if(w.length>0){V.current=u.length-C.length;for(const j of w)k.feed(e,j.text,N,_+j.start)}}if(!l.isPending){const _=V.current,f=u.slice(_),w=f.trim();w&&(k.feed(e,w,N,_+(f.length-f.trimStart().length)),V.current=u.length),k.finish(e)}},[E,k,F,N]);const[se,ne]=n.useState(""),[ee,ue]=n.useState([]),[Z,je]=n.useState(!1),[et,Pe]=n.useState(null),[B,q]=n.useState(null),[J,ae]=n.useState(p??null),[be,ze]=n.useState(null),[ct,gs]=n.useState(!1),[Ie,Nt]=n.useState(null),[_s,St]=n.useState(0),[Ue,bs]=n.useState("open"),[vs,Ke]=n.useState([]),[xs,tt]=n.useState(!1),[fe,We]=n.useState("chat"),[Rt,pe]=n.useState({kind:"idle"}),Me=n.useRef(null),st=n.useRef(oe),Tt=n.useRef(null),lt=n.useRef(!1),{containerRef:ys,isPinned:ks,scrollToBottom:Oe,stickToBottom:Et}=hn(),ce=n.useRef(null),ve=n.useRef(null),nt=n.useRef(null),at=n.useRef(null);n.useEffect(()=>{Et()},[E,Et]),n.useEffect(()=>()=>{ve.current?.abort()},[]),n.useEffect(()=>{if(be==null)return;const e=be-Date.now();if(e<=0){ze(null);return}const l=setTimeout(()=>ze(null),e);return()=>clearTimeout(l)},[be]),n.useEffect(()=>{if(Ie==null)return;const e=()=>{const u=Ie-Date.now();if(u<=0){Nt(null),St(0);return}St(Math.ceil(u/1e3))};e();const l=setInterval(e,1e3);return()=>clearInterval(l)},[Ie]);const De=n.useRef(null),Ce=n.useCallback(()=>{De.current&&(De.current.cancelled=!0),De.current=null},[]);n.useEffect(()=>a.on("support-chat:clearHistory",()=>{ve.current?.abort(),Ce(),I([]),Pe(null),q(null),je(!1),ae(null),at.current=null,st.current=!0}),[a,Ce]),n.useEffect(()=>{a.emit("support-chat:session",{sessionId:J})},[a,J]);const It=n.useCallback((e,l,u)=>{Ce();const _={cancelled:!1};De.current=_;const f=u?.trim()?u:null,w=`resume-${crypto.randomUUID()}`;I(Q=>[...Q,{id:w,role:"assistant",text:f??"",isPending:!f}]),Oe();const C=Date.now()+(f?6e3:ya),j=async()=>{if(_.cancelled)return;let Q=null;try{const y=v.current,P=await fetch(`${o}/api/support-chat/sessions/${e}/messages?limit=50`,{headers:{...g?{"X-API-Key":g}:{},...y?{Authorization:`Bearer ${y}`}:{}}});if(P.ok){const re=await P.json(),ke=re.success&&re.data?re.data.messages:[];for(let U=ke.length-1;U>=0;U--){const te=ke[U];if(te.role!=="assistant")continue;const S=te.createdAt?Date.parse(te.createdAt):NaN;if(Number.isFinite(S)&&S>l){Q=te;break}}}}catch{}if(!_.cancelled){if(Q){const y=Q.metadata??{},P=y.confidence,re=typeof P=="number"?cs(P):void 0;I(ke=>ke.map(U=>U.id===w?{...U,id:Q.id,serverId:Q.id,promptLogId:Q.promptLogId??null,text:Q.content,isPending:!1,confidence:P,confidenceLevel:re,sources:y.sources&&y.sources.length>0?y.sources:void 0,actions:y.actions&&y.actions.length>0?y.actions:void 0,quickReplies:y.quickReplies&&y.quickReplies.length>0?y.quickReplies:void 0,ticketCards:y.ticketCards&&y.ticketCards.length>0?y.ticketCards:void 0,suggestedFollowUps:y.suggestedFollowUps&&y.suggestedFollowUps.length>0?y.suggestedFollowUps:void 0,awaitingConfirmation:y.awaitingConfirmation,refusalReason:y.refusalReason,refusalProductName:y.refusalProductName}:U)),Oe(),De.current=null;return}if(Date.now()>=C){f||I(y=>y.map(P=>P.id===w?{...P,text:i("support_chat.error_message"),isPending:!1}:P)),De.current=null;return}setTimeout(j,us)}};setTimeout(j,us)},[g,o,Ce,Oe,i]),Je=n.useCallback(async(e,l)=>{try{const u=v.current,_=await fetch(`${o}/api/support-chat/sessions/${e}/messages?limit=50`,{headers:{...g?{"X-API-Key":g}:{},...u?{Authorization:`Bearer ${u}`}:{}}});if(!_.ok)return;const f=await _.json();if(!f.success||!f.data)return;const w=f.data.messages.filter(y=>y.role==="user"||y.role==="assistant").map(y=>{const P=y.metadata??void 0,re=P?.ticketCards&&P.ticketCards.length>0?P.ticketCards:void 0;return{id:y.id,role:y.role,text:y.content,promptLogId:y.promptLogId??null,rating:y.userScore??null,...re?{ticketCards:re}:{},...P?.suggestedFollowUps&&P.suggestedFollowUps.length>0?{suggestedFollowUps:P.suggestedFollowUps}:{},...P?.refusalReason?{refusalReason:P.refusalReason,refusalProductName:P.refusalProductName}:{}}}),C=w.length-1,j=C>=0?w[C]:void 0;if(j&&j.role==="assistant"){const y=f.data.messages[f.data.messages.length-1]?.metadata;y?.quickReplies&&y.quickReplies.length>0&&(w[C]={...j,quickReplies:y.quickReplies,...y.awaitingConfirmation?{awaitingConfirmation:y.awaitingConfirmation}:{}})}I(w),at.current=e;const Q=f.data.messages[f.data.messages.length-1];if(Q&&Q.role==="user"){const y=Q.createdAt?Date.parse(Q.createdAt):NaN;Number.isFinite(y)&&Date.now()-y<xa&&It(e,y,l)}}catch{}},[g,o,It]),xe=n.useCallback(async e=>{if(!K)return[];try{const l=v.current,u=await fetch(`${o}/api/widget/support-chat/tickets?status=${e}`,{headers:{...g?{"X-API-Key":g}:{},...l?{Authorization:`Bearer ${l}`}:{}}});if(!u.ok)return[];const _=await u.json();return _.data?.counts&&_.data?.tickets?_.data.tickets:[]}catch{return[]}},[o,g,K]);n.useEffect(()=>{let e=!1;return(async()=>{const l=await xe("open").catch(()=>[]);e||Ke(l)})(),()=>{e=!0}},[xe,m?.jwt]);const ws=n.useCallback(async e=>{bs(e),tt(!0);const l=await xe(e).catch(()=>[]);Ke(l),tt(!1)},[xe]),Mt=n.useRef(!1);n.useEffect(()=>{Mt.current||p&&m?.jwt&&(Mt.current=!0,Je(p))},[m?.jwt,p,Je]),n.useEffect(()=>Ce,[Ce]),n.useEffect(()=>a.on("support-chat:select-session",e=>{const{sessionId:l}=e;We("chat"),!(!l||l===at.current)&&(ve.current?.abort(),I([]),Pe(null),q(null),je(!1),ae(l),Je(l))}),[a,Je]);const Ne=n.useCallback(()=>{const e=ce.current;if(!e)return;e.style.height="auto";const l=e.scrollHeight>ds;e.style.height=`${Math.min(e.scrollHeight,ds)}px`,e.style.overflowY=l?"auto":"hidden"},[]);n.useEffect(()=>{Ne()},[Ne]);const ut=n.useCallback((e,l)=>{const u=l.metadata??{},_=u.confidence,f=typeof _=="number"?cs(_):void 0;I(w=>w.map(C=>C.id===e?{...C,id:l.id,serverId:l.id,promptLogId:l.promptLogId,rating:null,text:l.content,isPending:!1,confidence:_,confidenceLevel:f,sources:u.sources&&u.sources.length>0?u.sources:void 0,actions:u.actions&&u.actions.length>0?u.actions:void 0,quickReplies:u.quickReplies&&u.quickReplies.length>0?u.quickReplies:void 0,ticketCards:u.ticketCards&&u.ticketCards.length>0?u.ticketCards:void 0,suggestedFollowUps:u.suggestedFollowUps&&u.suggestedFollowUps.length>0?u.suggestedFollowUps:void 0,awaitingConfirmation:u.awaitingConfirmation,refusalReason:u.refusalReason,refusalProductName:u.refusalProductName}:C))},[]),At=n.useCallback(e=>{gs(!0),I(l=>l.map(u=>u.id===e?{...u,role:"assistant",text:i("support_chat.demo_quota_reached"),isPending:!1}:u))},[i]),dt=n.useCallback((e,l)=>{ze(l??Date.now()+6e4),I(u=>u.map(_=>_.id===e?{..._,role:"assistant",text:i("support_chat.daily_limit_reached"),isPending:!1}:_))},[i]),ft=n.useCallback((e,l)=>{const u=typeof l=="number"&&l>0?l:6e4;Nt(Date.now()+u);const _=Math.ceil(u/1e3);I(f=>f.map(w=>w.id===e?{...w,role:"assistant",text:i("support_chat.rate_limited",{seconds:String(_)}),isPending:!1}:w))},[i]),$t=n.useCallback((e,l)=>{I(u=>u.filter(_=>_.id!==e)),pe(l==="human"?{kind:"human",displayName:null}:{kind:"waiting",until:Me.current})},[]),Se=n.useCallback(()=>{lt.current&&(lt.current=!1,a.emit("chat:draftConsumed",void 0))},[a]),le=n.useCallback(async(e,l)=>{const u=e.trim();if(!u)return;Se(),Ce(),ve.current?.abort(),ve.current=new AbortController,Pe(null),q(null),ne(""),ue([]),ce.current&&(ce.current.style.height="auto");const _={id:`user-${crypto.randomUUID()}`,role:"user",text:u},f=`assistant-${crypto.randomUUID()}`,w={id:f,role:"assistant",text:"",isPending:!0};I(U=>[...U,_,w]),Oe(),je(!0),nt.current=f;const C=Date.now(),j=async()=>{const U=wa-(Date.now()-C);U>0&&await new Promise(te=>setTimeout(te,U))};a.emit("support-chat:messageSent",{text:u});const[Q]=await Ae(async()=>await m?.ensureValidToken?.()??null),y=Q??v.current,P={"Content-Type":"application/json",...g?{"X-API-Key":g}:{},...y?{Authorization:`Bearer ${y}`}:{}},re=st.current||J===null;let ke=!1;try{if(l?.quickReplyClick){const Y=await fetch(`${o}/api/widget/support-chat/message`,{method:"POST",headers:P,body:JSON.stringify({message:u,productId:c,...re?{newSession:!0}:{},...me?{userContext:ls(me)}:{},quickReplyClick:l.quickReplyClick}),signal:ve.current.signal}),G=await Y.json();if(Y.status===429&&G?.error?.code==="DAILY_TOKEN_LIMIT_EXCEEDED"){await j(),dt(f,G.error.resetAtMs);return}if(Y.status===429&&G?.error?.code==="DEMO_QUOTA_EXCEEDED"){await j(),At(f);return}if(Y.status===429&&G?.error?.code==="RATE_LIMITED"){await j(),ft(f,G.error.retryAfterMs);return}if(Y.status===409&&G?.error?.code==="HANDOFF_ACTIVE"){await j(),$t(f,G.data?.handoffState),G.data?.sessionId&&ae(G.data.sessionId);return}if(!Y.ok||!G.success||!G.data)throw new Error(G.error?.message??`HTTP ${Y.status}`);ae(G.data.sessionId),st.current=!1,ut(f,G.data.assistantMessage),l.quickReplyClick.payload==="confirm_handoff"&&((G.data.assistantMessage.metadata?.toolCalls?.includes("request_human_handoff")??!1)||(pe({kind:"idle"}),Me.current=null)),xe(Ue).then(vt=>Ke(vt));return}let U;const te=()=>{U&&clearTimeout(U),U=setTimeout(()=>{ke=!0,ve.current?.abort()},ka)};te();const S=ve.current;if(!S){clearTimeout(U);return}const[Re,Yt]=await Ae(async()=>{const Y=await fetch(`${o}/api/widget/support-chat/stream`,{method:"POST",headers:P,body:JSON.stringify({message:u,productId:c,...re?{newSession:!0}:{},...me?{userContext:ls(me)}:{}}),signal:S.signal});if(!Y.ok||!Y.body){const de=await Y.json().catch(()=>null);if(Y.status===429&&de?.error?.code==="DAILY_TOKEN_LIMIT_EXCEEDED")return{dailyLimitResetAtMs:de.error.resetAtMs};if(Y.status===429&&de?.error?.code==="DEMO_QUOTA_EXCEEDED")return{demoQuotaExhausted:!0};if(Y.status===429&&de?.error?.code==="RATE_LIMITED")return{rateLimitRetryAfterMs:de.error.retryAfterMs??6e4};if(Y.status===409&&de?.error?.code==="HANDOFF_ACTIVE")return de.data?.sessionId&&ae(de.data.sessionId),{handoffState:de.data?.handoffState??null};throw new Error(de?.error?.message??`HTTP ${Y.status}`)}const G=Y.body.getReader(),vt=new TextDecoder;let Ze="",Gt="",es=!1;for(;;){const{done:de,value:Qs}=await G.read();if(de)break;te(),Ze+=vt.decode(Qs,{stream:!0});let xt;for(;(xt=Ze.indexOf(`
4
+
5
+ `))!==-1;){const Xs=Ze.slice(0,xt);Ze=Ze.slice(xt+2);const{event:Ye,data:Ge}=va(Xs);if(!(!Ye||!Ge)){if(Ye==="start"){const ge=JSON.parse(Ge);ge.sessionId&&(ae(ge.sessionId),at.current=ge.sessionId),st.current=!1}else if(Ye==="token"){const ge=JSON.parse(Ge);Gt+=ge.value??"";const yt=ga(Gt);I(Vs=>Vs.map(kt=>kt.id===f?{...kt,text:yt}:kt))}else if(Ye==="meta"){const ge=JSON.parse(Ge);ut(f,ge.assistantMessage),xe(Ue).then(yt=>Ke(yt)),es=!0}else if(Ye==="error"){const ge=JSON.parse(Ge);if(ge.code==="HANDOFF_ACTIVE")return{handoffState:null};throw new Error(ge.message??"Stream error")}}}}if(!es)throw new Error("Stream ended before completion");return null});if(U&&clearTimeout(U),Yt)throw Yt;if(Re&&"handoffState"in Re){await j(),$t(f,Re.handoffState);return}if(Re?.dailyLimitResetAtMs!==void 0){await j(),dt(f,Re.dailyLimitResetAtMs);return}if(Re?.demoQuotaExhausted){await j(),At(f);return}if(Re?.rateLimitRetryAfterMs!==void 0){await j(),ft(f,Re.rateLimitRetryAfterMs);return}}catch(U){if(U instanceof Error&&U.name==="AbortError"&&!ke){I(te=>te.filter(S=>S.id!==f));return}await j(),I(te=>te.filter(S=>S.id!==f)),nt.current===f&&(q({text:u,options:l}),Pe(i("support_chat.error_message")))}finally{nt.current===f&&je(!1)}},[a,o,me,g,c,i,ut,dt,ft,xe,Ue,Oe,m,Ce,Se]),ye=x?.realtimeProvider==="elevenlabs",[pt,ht]=n.useState([]),Lt=n.useRef(0),Qe=n.useRef([]);Qe.current=pt;const rt=n.useRef(null),mt=n.useRef(null),Pt=n.useRef(new Set),gt=n.useRef(new Set),Xe=n.useRef(!1),Be=n.useRef(null),_t=n.useRef(null),it=n.useRef(!1),Ut=n.useRef(J);Ut.current=J;const Ot=x?.realtime===!0,Dt=n.useRef(r?.voiceStream);Dt.current=r?.voiceStream;const Bt=n.useMemo(()=>{if(ye){const e=Xn({baseUrl:o,apiKey:g,getJwt:()=>v.current,language:N,enabled:!0,getSessionId:()=>Ut.current,onSessionId:l=>{mt.current=l,ae(l)},onUserTurnEnd:()=>Be.current?.(),onTranscript:l=>ht(u=>{const _=u[u.length-1];if(!(_&&He(_)&&_.streaming&&_.role===l.role)){Lt.current+=1;const w=`${ms}${Lt.current}`;return[...u,{id:w,role:l.role,text:l.text,streaming:l.streaming}]}const f=l.role==="assistant"&&l.streaming?_.text+l.text:l.text;return[...u.slice(0,-1),{..._,text:f,streaming:l.streaming}]})});return rt.current=e,e}return rt.current=null,Qn({voiceStream:Dt.current,language:N})},[ye,o,g,N]),H=sa({transport:Bt,agentId:r?.voiceAgentId??"",onUserMessage:e=>{le(e)},onStopPlayback:()=>$.current?.stop()}),qt=H.state!=="idle"&&H.state!=="error",he=H.state!=="idle",Ht=n.useRef(!1);n.useEffect(()=>{const e=Ht.current;if(Ht.current=he,!he){const l=(()=>{const u=Qe.current;for(let _=u.length-1;_>=0;_-=1){const f=u[_];if(f&&f.role==="assistant"&&f.text?.trim())return f.text}return null})();if(ht([]),e){const u=mt.current??J;u&&Je(u,l??void 0)}}},[he]),n.useEffect(()=>{try{window.dispatchEvent(new CustomEvent("es-support-voice-mode",{detail:{active:he}}))}catch{}},[he]),n.useEffect(()=>{if(!ye||!he){Pt.current=new Set,gt.current=new Set,Xe.current=!1,Be.current=null;return}let e=!1,l=!1;it.current=!1;const u=async(C=!1)=>{const j=mt.current??J;if(!j||e)return!1;const Q=v.current;let y=null;try{const S=await fetch(`${o}/api/support-chat/sessions/${j}/messages?limit=30`,{headers:{...g?{"X-API-Key":g}:{},...Q?{Authorization:`Bearer ${Q}`}:{}}});if(!S.ok)return!1;y=await S.json()}catch{return!1}if(e)return!1;const P=y?.data?.messages??[],re=Pt.current;if(!Xe.current){if(!C)return!1;for(const S of P)S.id&&gt.current.add(S.id),S.role==="user"&&S.id&&re.add(S.id);return Xe.current=!0,!1}const ke=gt.current,U=P.filter(S=>S.id&&S.content?.trim()&&(S.role==="user"||S.role==="assistant")&&!ke.has(S.id)).map(S=>({id:S.id,role:S.role,text:S.content,...S.metadata?{metadata:S.metadata}:{}}));if(U.length===0)return!1;ht(S=>ta(S,U));const te=U.filter(S=>S.role==="user"&&!re.has(S.id));if(te.length===0)return!1;for(const S of te)re.add(S.id);return it.current=!0,!0},_=async()=>{if(!(l||e)){l=!0;for(let C=0;C<10&&!e&&!await u(!1);C++)await new Promise(j=>setTimeout(j,500));l=!1}};let f=0;const w=5e3;return Be.current=()=>{if(it.current)return;const C=Date.now();C-f<w||(f=C,_())},_t.current=async()=>{for(let C=0;C<6&&!e;C+=1){if(await u(!1),!Qe.current.some(He))return;await new Promise(j=>setTimeout(j,700))}},(async()=>{for(let C=0;C<4&&!e&&!Xe.current;C+=1){if(await u(!0),Xe.current)return;await new Promise(j=>setTimeout(j,300))}})(),()=>{e=!0,Be.current=null,_t.current=null}},[ye,he,J,o,g]);const Ft=n.useRef(!1);n.useEffect(()=>{const e=Ft.current;Ft.current=H.userSpeaking,!e&&H.userSpeaking&&(it.current=!1),e&&!H.userSpeaking&&Be.current?.()},[H.userSpeaking]);const zt=n.useRef(H.state);n.useEffect(()=>{const e=zt.current;zt.current=H.state,(H.state==="thinking"||H.state==="speaking")&&!(e==="thinking"||e==="speaking")&&Be.current?.()},[H.state]);const Ve=n.useRef(null);n.useEffect(()=>{if(!ye||!he)return;const e=Qe.current[Qe.current.length-1];if(!(!e||!He(e)||e.role!=="assistant"||!e.text.trim()))return Ve.current&&clearTimeout(Ve.current),Ve.current=setTimeout(()=>{_t.current?.()},900),()=>{Ve.current&&clearTimeout(Ve.current)}},[pt,ye,he]);const[Kt,js]=n.useState(!1),[Cs,Wt]=n.useState(!1),Ns=n.useCallback(e=>{rt.current?.sendUserMessage(e)&&Wt(!0)},[]);n.useEffect(()=>{(H.state==="thinking"||H.state==="speaking")&&Wt(!1)},[H.state]);const qe=ye?pt.map(e=>({key:e.id,role:e.role,text:e.text,...e.metadata?{metadata:e.metadata}:{},...e.streaming?{streaming:!0}:{}})):E.map(e=>{const l=e.role==="assistant"&&e.refusalReason?i(`support_chat.refusal_${e.refusalReason}`,{productName:e.refusalProductName??""}):e.text;return l?{key:e.id,role:e.role==="assistant"?"assistant":"user",text:l,confidence:e.confidenceLevel}:null}).filter(e=>e!==null),Ss=ye&&he&&qe.length>0&&qe[qe.length-1].role==="user",Rs=t.jsxs("div",{className:"es-sc__messages",children:[qe.map((e,l)=>{const u=l===qe.length-1;return t.jsxs("div",{className:`es-sc__bubble es-sc__bubble--${e.role}`,"data-confidence":e.confidence,children:[e.role==="assistant"?t.jsx(ps,{text:e.text,allowedLinkHosts:z}):t.jsx("div",{className:"es-sc__bubble-text",children:e.text}),e.role==="assistant"&&t.jsx(rs,{followUps:e.metadata?.suggestedFollowUps,isNewest:u,isPending:!!e.streaming,hasQuickReplies:!!e.metadata?.quickReplies?.length,isSending:Cs,onSelect:Ns,t:i})]},e.key)}),Ss?t.jsx("div",{className:"es-vm__answer-pending",role:"status","aria-label":i("voice_conv.thinking"),children:t.jsxs("div",{className:"es-vm__answer-wave",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]})}):null]}),Jt=n.useRef(null);n.useEffect(()=>{if(Ot||!qt||!k||!F)return;const e=E[E.length-1];!e||e.role!=="assistant"||Jt.current!==e.id&&(Jt.current=e.id,k.activate(e.id))},[E,qt,k,F]);const bt=n.useCallback(()=>{const e=r?.voiceStream;e?.getState&&e.getState()!=="idle"&&e.stop(),le(se)},[se,le,r]),Ts=n.useCallback(()=>{ve.current?.abort(),je(!1);const e=nt.current;e&&I(l=>l.filter(u=>u.id!==e))},[]),Es=n.useCallback(()=>{B&&le(B.text,B.options)},[B,le]),Is=n.useCallback(e=>{if(e.autoSend){le(e.message);return}ue([]),ne(""),Se(),ce.current&&(ce.current.style.height="auto",ce.current.focus())},[le,Se]);n.useEffect(()=>{if(!(R!==void 0||D.length>0))return;const e=`${R}${String(L)}${W}`;if(Tt.current!==e){if(Tt.current=e,lt.current=!0,L&&R!==void 0){ue([]),le(R);return}ue(D),R!==void 0&&(ne(R),requestAnimationFrame(()=>{Ne(),ce.current?.focus()}))}},[R,L,W,le]),n.useEffect(()=>{const e=r?.voiceStream;e?.getState&&e.getState()!=="idle"&&e.stop()},[p]);const Ms=n.useCallback(e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),bt())},[bt]),As=n.useCallback(e=>{Se(),ne(e.target.value),Ne()},[Ne,Se]),$s=n.useCallback(()=>{Se(),ne(""),ce.current&&(ce.current.style.height="auto",ce.current.focus())},[Se]),Ls=n.useCallback(e=>{const l=e.trim();l&&(ne(u=>u?`${u} ${l}`:l),requestAnimationFrame(()=>{Ne(),ce.current?.focus()}))},[Ne]),Ps=n.useCallback(e=>{a.emit("support-chat:escalated",{messageId:e})},[a]),Qt=n.useRef(E);n.useEffect(()=>{Qt.current=E},[E]);const Us=n.useCallback(({messageId:e,rating:l},{keepalive:u})=>{const _=Qt.current.find(f=>f.id===e);!_||!_.promptLogId||v.current&&(I(f=>f.map(w=>w.id===e?{...w,rating:l,ratingPending:!0}:w)),(async()=>{const[f,w]=await Ae(fetch(`${o}/api/widget/ai-feedback`,{method:"POST",keepalive:u,headers:{"Content-Type":"application/json",...g?{"X-API-Key":g}:{},Authorization:`Bearer ${v.current}`},body:JSON.stringify({promptLogId:_.promptLogId,rating:l})}));if(!w&&f.status===409){I(C=>C.map(j=>j.id===e?{...j,rating:l,ratingPending:!1}:j));return}if(w||!f.ok){I(C=>C.map(j=>j.id===e?{...j,rating:null,ratingPending:!1}:j));return}I(C=>C.map(j=>j.id===e?{...j,rating:l,ratingPending:!1}:j)),a.emit("support-chat:feedbackSubmitted",{messageId:e,rating:l})})())},[a,g,o]),{pending:Xt,rate:Vt,undo:Os}=mn({submit:Us}),Ds=n.useCallback((e,l)=>{const u=E.find(_=>_.id===e);!u||!u.promptLogId||u.ratingPending||v.current&&Vt(e,l)},[E,Vt]),Bs=n.useCallback(()=>{We("chat"),pe({kind:"idle"}),Me.current=null,a.emit("support-chat:clearHistory",void 0)},[a]),qs=n.useCallback(async()=>{if(!J)return;const e=v.current;try{const l=await fetch(`${o}/api/widget/support-chat/handoff/request`,{method:"POST",headers:{"Content-Type":"application/json",...g?{"X-API-Key":g}:{},...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify({sessionId:J,productId:c,conversationLanguage:N})}),u=await l.json();if(!l.ok||!u.success){pe({kind:"idle"});return}if(u.data?.outcome==="unavailable"){pe({kind:"unavailable",reason:ba(u.data.reason)});return}if(u.data?.outcome==="already_active"){pe(u.data.state==="human"?{kind:"human",displayName:null}:{kind:"waiting",until:Me.current});return}if(u.data?.outcome==="offered"){const _=u.data.acceptTimeoutSec;Me.current=typeof _=="number"?Date.now()+_*1e3:null,pe({kind:"waiting",until:Me.current})}}catch{pe({kind:"idle"})}},[g,o,N,c,J]),Hs=n.useCallback(async e=>{if(!J)return!1;const l=v.current;try{const u=await fetch(`${o}/api/widget/support-chat/handoff/contact`,{method:"POST",headers:{"Content-Type":"application/json",...g?{"X-API-Key":g}:{},...l?{Authorization:`Bearer ${l}`}:{}},body:JSON.stringify({sessionId:J,productId:c,...e.email?{email:e.email}:{},...e.phone?{phone:e.phone}:{},...e.note?{note:e.note}:{}})}),_=await u.json();return!u.ok||!_.success?!1:(pe({kind:"contact_left"}),!0)}catch{return!1}},[g,o,c,J]),Fs=n.useCallback(()=>{pe({kind:"idle"})},[]),ot=n.useCallback(()=>{We("tickets"),tt(!0),xe(Ue).then(e=>Ke(e)).catch(()=>{}).finally(()=>tt(!1))},[xe,Ue]),zs=n.useCallback(()=>{fe==="tickets"?We("chat"):ot()},[fe,ot]),Ks=n.useCallback(e=>{We("chat"),a.emit("support-chat:select-session",{sessionId:e})},[a]);n.useEffect(()=>K?a.on("support-chat:showTickets",()=>{ot()}):void 0,[a,ot,K]);const Ws=n.useCallback((e,l,u)=>{I(w=>w.map(C=>C.id===e?{...C,quickReplyAnswered:l}:C));const _=E.find(w=>w.id===e)?.awaitingConfirmation,f=pa.includes(u);u==="confirm_handoff"&&pe({kind:"waiting",until:Me.current}),le(l,{...f?{quickReplyClick:{payload:u,summary:_?.summary,details:_?.details??void 0,priority:_?.priority,sourceMessageId:e}}:{}})},[E,le]),Js=n.useCallback(()=>{a.emit("support-chat:showHistory",void 0)},[a]),Zt=E.length===0;return he?t.jsx(ts,{blockType:"support-chat",children:t.jsx(oa,{state:H.state,draft:H.draft,error:H.error,muted:Kt,listening:H.userSpeaking,hasTranscript:qe.length>0,transcript:Rs,onToggleMute:()=>{const e=!Kt;js(e),rt.current?.setMuted(e)},onEnd:()=>H.stop(),onRetry:()=>{H.start()},t:i})}):t.jsxs(ts,{blockType:"support-chat",children:[t.jsxs("div",{className:"es-sc__chat-header",children:[t.jsx("span",{className:"es-sc__chat-header-title",children:K&&fe==="tickets"?i("support_chat.tickets_view_title"):Fe}),t.jsxs("div",{className:"es-sc__chat-header-actions",children:[t.jsx("button",{type:"button",className:"es-sc__chat-action-btn","aria-label":i("support_chat.new_conversation_button"),title:i("support_chat.new_conversation_button"),onClick:Bs,children:t.jsx(da,{size:18})}),t.jsx("button",{type:"button",className:"es-sc__chat-action-btn","aria-label":i("support_chat.history_button"),title:i("support_chat.history_button"),onClick:Js,children:t.jsx(ua,{size:16})}),we&&fe==="chat"&&Rt.kind==="idle"&&t.jsx("button",{type:"button",className:"es-sc__chat-action-btn es-sc__chat-action-btn--label","aria-label":i("support_chat.handoff.button_label"),title:i("support_chat.handoff.button_label"),onClick:()=>{qs()},children:i("support_chat.handoff.button_label")}),K&&t.jsx("button",{type:"button",className:`es-sc__chat-action-btn${fe==="tickets"?" es-sc__chat-action-btn--active":""}`,"aria-label":i("support_chat.tickets_tab_button"),title:i("support_chat.tickets_tab_button"),"aria-pressed":fe==="tickets",onClick:zs,children:t.jsx(fa,{size:16})}),t.jsx(gn,{panelKey:"support-chat",baseUrl:o,apiKey:g||void 0,t:i})]})]}),t.jsx("div",{className:"es-block__body es-sc__body",children:K&&fe==="tickets"?t.jsx($n,{status:Ue,loading:xs,tickets:vs,onSelectStatus:ws,onSelectSession:Ks,t:i}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"es-sc__messages",ref:ys,children:[Zt&&t.jsx("div",{className:"es-sc__welcome",children:t.jsx("div",{className:"es-sc__welcome-text",children:$e})}),E.map((e,l)=>{const u=l===E.length-1,_=e.role==="assistant"&&e.refusalReason?i(`support_chat.refusal_${e.refusalReason}`,{productName:e.refusalProductName??""}):e.text;return t.jsxs("div",{className:`es-sc__bubble es-sc__bubble--${e.role}`,"data-confidence":e.confidenceLevel,children:[_&&(e.role==="assistant"?t.jsxs(t.Fragment,{children:[t.jsx(Tn,{text:_,allowedLinkHosts:z,cursor:F&&k.activeId===e.id?k.cursor:null}),t.jsx(In,{text:_,allowEmbeds:ie,allowedImageHosts:z,t:i}),F&&t.jsx(Fn,{id:e.id,session:k,onActivate:()=>k.activate(e.id),t:i})]}):t.jsx("div",{className:"es-sc__bubble-text",children:_})),e.isPending&&!e.text&&t.jsxs("div",{className:"es-sc__typing","aria-label":i("support_chat.typing_aria"),children:[t.jsx("span",{className:"es-sc__typing-dot"}),t.jsx("span",{className:"es-sc__typing-dot"}),t.jsx("span",{className:"es-sc__typing-dot"})]}),e.actions&&e.actions.length>0&&t.jsx("div",{className:"es-sc__actions","data-es-no-read":!0,children:e.actions.map(f=>t.jsx("a",{href:_a(f.url)?f.url:"#",target:"_blank",rel:"noopener noreferrer",className:"es-sc__action-btn",children:f.title},f.slug))}),e.ticketCards&&e.ticketCards.length>0&&t.jsx("div",{className:"es-sc__ticket-cards",children:e.ticketCards.map(f=>t.jsx(hs,{card:f,t:i},f.externalNumber))}),e.quickReplies&&e.quickReplies.length>0&&t.jsx("div",{className:"es-sc__quick-replies",children:e.quickReplies.map(f=>{const w=e.quickReplyAnswered===f.value;if(e.quickReplyAnswered!==void 0&&!w)return null;const C=f.payload==="confirm_escalation"?i("escalation.confirm_yes"):f.payload==="cancel_escalation"?i("escalation.confirm_no"):f.payload==="confirm_handoff"?i("support_chat.handoff.confirm_yes"):f.payload==="decline_handoff"?i("support_chat.handoff.confirm_no"):f.label;return t.jsx("button",{type:"button",disabled:w||Z,onClick:()=>Ws(e.id,f.value,f.payload??""),className:`es-sc__quick-reply-btn${w?" es-sc__quick-reply-btn--clicked":""}`,children:C},f.value)})}),e.role==="assistant"&&t.jsx(rs,{followUps:e.suggestedFollowUps,isNewest:u,isPending:!!e.isPending,hasQuickReplies:!!e.quickReplies?.length,isSending:Z,onSelect:f=>le(f),t:i}),e.role==="assistant"&&!e.isPending&&e.text&&t.jsxs(t.Fragment,{children:[e.promptLogId&&v.current&&(()=>{const f=Xt?.messageId===e.id?Xt.rating:null;return t.jsxs("div",{className:"es-sc__feedback","aria-label":i("support_chat.rate_aria"),"data-es-no-read":!0,children:[t.jsx("span",{className:"es-sc__feedback-label",children:e.rating&&f===null?i("support_chat.feedback_thanks"):i("support_chat.rate_aria")}),t.jsx(ja,{value:f??e.rating??null,onChange:w=>Ds(e.id,w),disabled:f===null&&(!!e.rating||e.ratingPending),t:i}),f!==null&&t.jsxs("div",{className:"es-sc__rating-undo",role:"status",children:[t.jsx("span",{className:"es-sc__rating-undo-text",children:i("support_chat.rating_undo_toast",{rating:f})}),t.jsx("button",{type:"button",className:"es-sc__rating-undo-btn",onClick:Os,children:i("support_chat.rating_undo_button")})]})]})})(),e.confidenceLevel==="low"&&t.jsxs("div",{className:"es-sc__escalation",children:[t.jsx("span",{className:"es-sc__escalation-text",children:i("support_chat.low_confidence")}),t.jsx("button",{className:"es-sc__escalation-btn",onClick:()=>Ps(e.id),type:"button","aria-label":_e,children:_e})]})]})]},e.id)}),et&&t.jsxs("div",{className:"es-sc__error",role:"alert",children:[t.jsx("span",{className:"es-sc__error-text",children:et}),B&&t.jsx("button",{type:"button",className:"es-sc__error-retry",onClick:Es,children:i("support_chat.retry")})]})]}),!ks&&E.length>0&&t.jsxs("button",{type:"button",className:"es-sc__jump",onClick:()=>Oe(),"aria-label":i("support_chat.jump_to_latest"),title:i("support_chat.jump_to_latest"),children:[t.jsxs("svg",{width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("path",{d:"M12 5v14"}),t.jsx("path",{d:"m19 12-7 7-7-7"})]}),t.jsx("span",{className:"es-sc__jump-label",children:i("support_chat.jump_to_latest")})]})]})}),fe!=="tickets"&&ee.length>0&&t.jsx("div",{className:"es-sc__suggestions",role:"group","aria-label":i("support_chat.quick_actions_aria"),children:ee.map((e,l)=>t.jsx("button",{className:"es-sc__suggestion",onClick:()=>Is(e),type:"button",disabled:Z||h,children:e.labelKey?i(e.labelKey):e.label},`${e.labelKey??e.label}-${l}`))}),fe!=="tickets"&&ee.length===0&&Zt&&Te&&Ee.length>0&&t.jsx("div",{className:"es-sc__suggestions",role:"list","aria-label":i("support_chat.suggestions_aria"),children:Ee.map((e,l)=>t.jsx("button",{className:"es-sc__suggestion",onClick:()=>le(e),type:"button",role:"listitem",children:e},l))}),fe!=="tickets"&&t.jsx(Gn,{status:Rt,onSubmitContact:Hs,onDismissContact:Fs,t:i}),fe!=="tickets"&&t.jsxs("div",{className:"es-block__footer es-sc__footer",children:[t.jsx("div",{className:"es-sc__disclaimer","data-es-no-read":!0,children:i("support_chat.disclaimer")}),t.jsxs("div",{className:"es-sc__input-row",children:[O&&Bt.available&&(ye||Ot||A)&&t.jsx("button",{type:"button",className:"es-sc__conv-start","data-testid":"conversation-start","aria-label":i("voice_conv.start"),title:i("voice_conv.start"),onClick:()=>{H.start()},children:t.jsx("svg",{width:"19",height:"19",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:t.jsx("path",{d:"M4 10v4M8 6v12M12 3v18M16 6v12M20 10v4"})})}),t.jsxs("div",{className:"es-sc__textarea-wrap",children:[t.jsx("textarea",{ref:ce,className:"es-sc__textarea",value:se,onChange:As,onKeyDown:Ms,placeholder:Ie!=null?i("support_chat.rate_limited_wait",{seconds:String(_s)}):Le,rows:1,maxLength:2e3,disabled:Z||h||be!=null||Ie!=null||ct,"aria-label":i("support_chat.input_aria")}),se.length>0&&t.jsx("button",{className:"es-sc__clear",onClick:$s,disabled:Z,type:"button","aria-label":i("support_chat.clear_input_aria"),children:t.jsx("span",{"aria-hidden":"true",children:"✕"})})]}),A&&!h&&t.jsx(On,{baseUrl:o,apiKey:g,jwt:v.current,language:N,onTranscript:Ls,t:i,disabled:Z||be!=null||Ie!=null||ct,streaming:x?.streaming,voiceStream:r?.voiceStream,baseText:()=>se,onText:e=>{if(ne(e.length>2e3?e.slice(0,2e3):e),e.length>=2e3){const l=r?.voiceStream;l?.getState&&l.getState()!=="idle"&&l.stop()}requestAnimationFrame(()=>{Ne(),ce.current?.focus()})}}),t.jsx("button",{className:`es-sc__send${Z?" es-sc__send--stop":""}`,onClick:Z?Ts:bt,disabled:!Z&&(h||!se.trim()||be!=null||Ie!=null||ct),type:"button","aria-label":i(Z?"support_chat.stop_aria":"chat.send_aria"),children:Z?t.jsx("span",{className:"es-sc__stop-icon","aria-hidden":"true"}):t.jsx("span",{"aria-hidden":"true",children:"➤"})})]})]})]})}export{In as AssistantMessageMedia,$a as Component,ps as MarkdownBubble,En as MessageMedia,oa as VoiceModeView,Aa as manifest};
6
+ //# sourceMappingURL=index-Ci7P37Ya-W5nof5Mx.js.map
@@ -1,2 +1,2 @@
1
- import{a as w,r as t,j as e,Q as k}from"../nexly.js";const S={slug:"qa",name:"AI Q&A",version:"1.0.0",category:"interactive",requiredService:"ai-orchestrator",configSchema:{properties:{readAloudEnabled:{type:"boolean",default:!1},placeholder:{type:"string",default:""},maxQuestionsPerSession:{type:"number",default:5},responseLanguage:{type:"string",default:"en"}}},defaultConfig:{readAloudEnabled:!1,placeholder:"",maxQuestionsPerSession:5,responseLanguage:"en"},dataContract:{serviceSlug:"ai-orchestrator",inputSchema:{type:"object",properties:{answer:{type:"string",description:"AI answer to the user question"},question:{type:"string",description:"The question that was asked"}},required:["answer"]},previewDataOverride:{answer:"This product is made from 100% organic cotton and is machine washable. It comes in sizes XS-XXL.",question:"What materials is this made from?"}},fields:[{id:"readAloudEnabled",type:"toggle",label:"Read this panel aloud",default:!1,group:"Voice"},{id:"placeholder",type:"localized-text",label:"Input placeholder",default:"",placeholder:'Leave empty to use translated default (e.g. "Ask a question about this product...")',group:"Content"},{id:"maxQuestionsPerSession",type:"range",label:"Max questions per session",default:5,min:1,max:20,step:1,group:"Behavior"},{id:"responseLanguage",type:"select",label:"Response language",default:"en",options:[{label:"English",value:"en"},{label:"Korean",value:"ko"},{label:"Spanish",value:"es"},{label:"French",value:"fr"},{label:"German",value:"de"}],group:"Behavior"}],events:{emits:[{name:"qa:questionAsked",description:"User submitted a question"},{name:"qa:answerReceived",description:"AI answer received"}],listens:[{name:"qa:clear",description:"Clear Q&A history"}]},sizing:{minWidth:240,preferredHeight:"auto",scrollable:!0},supportedPlacements:["main","sidebar"]};function A({config:u,actions:h,i18n:m}){const s=m?.t??(a=>a),f=m?.currentLanguage??"en",x=w(u.placeholder,f,{t:s,fallbackKey:"qa.input_placeholder",enDefault:"Ask a question about this product..."}),i=u.maxQuestionsPerSession??5,[d,_]=t.useState(""),[o,v]=t.useState([]),[n,g]=t.useState(!1),[q,c]=t.useState(null),b=t.useRef(null),r=o.length>=i,p=t.useCallback(async()=>{const a=d.trim();if(!(!a||n||r)){g(!0),c(null);try{const l=await h.call("ask",{question:a,language:u.responseLanguage??"en"});l?.error?c(l.error):l?.answer?(v(j=>[...j,{question:a,answer:l.answer}]),_(""),setTimeout(()=>{b.current?.scrollIntoView({behavior:"smooth"})},50)):c(s("qa.error_no_answer"))}catch{c(s("qa.error_generic"))}finally{g(!1)}}},[d,n,r,h,u.responseLanguage]),y=t.useCallback(a=>{a.key==="Enter"&&(a.preventDefault(),p())},[p]);return e.jsxs(k,{blockType:"qa",children:[e.jsxs("div",{className:"es-block__body",children:[o.length===0&&!n&&e.jsx("div",{className:"es-block__empty es-qa__empty",children:s("qa.empty_state")}),o.length>0&&e.jsxs("div",{className:"es-qa__history",children:[o.map((a,l)=>e.jsxs("div",{className:"es-qa__entry",children:[e.jsxs("div",{className:"es-qa__question",children:[e.jsx("span",{className:"es-qa__question-label","aria-hidden":"true",children:"Q"}),e.jsx("span",{className:"es-qa__question-text",children:a.question})]}),e.jsxs("div",{className:"es-qa__answer",children:[e.jsx("span",{className:"es-qa__answer-label","aria-hidden":"true",children:"A"}),e.jsx("span",{className:"es-qa__answer-text",children:a.answer})]})]},l)),e.jsx("div",{ref:b})]}),q&&e.jsx("div",{className:"es-qa__error",role:"alert",children:q}),r&&e.jsx("div",{className:"es-qa__limit-notice",children:s("qa.limit_reached",{count:i})})]}),e.jsxs("div",{className:"es-block__footer",children:[e.jsxs("div",{className:"es-qa__input-row",children:[e.jsx("input",{className:"es-qa__input",type:"text",value:d,onChange:a=>_(a.target.value),onKeyDown:y,placeholder:r?s("qa.limit_reached",{count:i}):x,disabled:n||r,"aria-label":s("qa.input_aria_label")}),e.jsx("button",{className:"es-qa__btn",onClick:p,disabled:!d.trim()||n||r,type:"button","aria-label":s("qa.submit_aria_label"),children:s(n?"qa.loading":"qa.ask_button")})]}),i>0&&e.jsx("div",{className:"es-qa__counter",children:s("qa.counter",{used:o.length,max:i})})]})]})}export{A as Component,S as manifest};
2
- //# sourceMappingURL=index-l8Oxwea3-Aqz1AnQ5.js.map
1
+ import{L as w,r as t,j as e,e as k}from"../nexly.js";const S={slug:"qa",name:"AI Q&A",version:"1.0.0",category:"interactive",requiredService:"ai-orchestrator",configSchema:{properties:{readAloudEnabled:{type:"boolean",default:!1},placeholder:{type:"string",default:""},maxQuestionsPerSession:{type:"number",default:5},responseLanguage:{type:"string",default:"en"}}},defaultConfig:{readAloudEnabled:!1,placeholder:"",maxQuestionsPerSession:5,responseLanguage:"en"},dataContract:{serviceSlug:"ai-orchestrator",inputSchema:{type:"object",properties:{answer:{type:"string",description:"AI answer to the user question"},question:{type:"string",description:"The question that was asked"}},required:["answer"]},previewDataOverride:{answer:"This product is made from 100% organic cotton and is machine washable. It comes in sizes XS-XXL.",question:"What materials is this made from?"}},fields:[{id:"readAloudEnabled",type:"toggle",label:"Read this panel aloud",default:!1,group:"Voice"},{id:"placeholder",type:"localized-text",label:"Input placeholder",default:"",placeholder:'Leave empty to use translated default (e.g. "Ask a question about this product...")',group:"Content"},{id:"maxQuestionsPerSession",type:"range",label:"Max questions per session",default:5,min:1,max:20,step:1,group:"Behavior"},{id:"responseLanguage",type:"select",label:"Response language",default:"en",options:[{label:"English",value:"en"},{label:"Korean",value:"ko"},{label:"Spanish",value:"es"},{label:"French",value:"fr"},{label:"German",value:"de"}],group:"Behavior"}],events:{emits:[{name:"qa:questionAsked",description:"User submitted a question"},{name:"qa:answerReceived",description:"AI answer received"}],listens:[{name:"qa:clear",description:"Clear Q&A history"}]},sizing:{minWidth:240,preferredHeight:"auto",scrollable:!0},supportedPlacements:["main","sidebar"]};function A({config:u,actions:h,i18n:m}){const s=m?.t??(a=>a),f=m?.currentLanguage??"en",x=w(u.placeholder,f,{t:s,fallbackKey:"qa.input_placeholder",enDefault:"Ask a question about this product..."}),i=u.maxQuestionsPerSession??5,[d,_]=t.useState(""),[o,v]=t.useState([]),[n,g]=t.useState(!1),[q,c]=t.useState(null),b=t.useRef(null),r=o.length>=i,p=t.useCallback(async()=>{const a=d.trim();if(!(!a||n||r)){g(!0),c(null);try{const l=await h.call("ask",{question:a,language:u.responseLanguage??"en"});l?.error?c(l.error):l?.answer?(v(j=>[...j,{question:a,answer:l.answer}]),_(""),setTimeout(()=>{b.current?.scrollIntoView({behavior:"smooth"})},50)):c(s("qa.error_no_answer"))}catch{c(s("qa.error_generic"))}finally{g(!1)}}},[d,n,r,h,u.responseLanguage]),y=t.useCallback(a=>{a.key==="Enter"&&(a.preventDefault(),p())},[p]);return e.jsxs(k,{blockType:"qa",children:[e.jsxs("div",{className:"es-block__body",children:[o.length===0&&!n&&e.jsx("div",{className:"es-block__empty es-qa__empty",children:s("qa.empty_state")}),o.length>0&&e.jsxs("div",{className:"es-qa__history",children:[o.map((a,l)=>e.jsxs("div",{className:"es-qa__entry",children:[e.jsxs("div",{className:"es-qa__question",children:[e.jsx("span",{className:"es-qa__question-label","aria-hidden":"true",children:"Q"}),e.jsx("span",{className:"es-qa__question-text",children:a.question})]}),e.jsxs("div",{className:"es-qa__answer",children:[e.jsx("span",{className:"es-qa__answer-label","aria-hidden":"true",children:"A"}),e.jsx("span",{className:"es-qa__answer-text",children:a.answer})]})]},l)),e.jsx("div",{ref:b})]}),q&&e.jsx("div",{className:"es-qa__error",role:"alert",children:q}),r&&e.jsx("div",{className:"es-qa__limit-notice",children:s("qa.limit_reached",{count:i})})]}),e.jsxs("div",{className:"es-block__footer",children:[e.jsxs("div",{className:"es-qa__input-row",children:[e.jsx("input",{className:"es-qa__input",type:"text",value:d,onChange:a=>_(a.target.value),onKeyDown:y,placeholder:r?s("qa.limit_reached",{count:i}):x,disabled:n||r,"aria-label":s("qa.input_aria_label")}),e.jsx("button",{className:"es-qa__btn",onClick:p,disabled:!d.trim()||n||r,type:"button","aria-label":s("qa.submit_aria_label"),children:s(n?"qa.loading":"qa.ask_button")})]}),i>0&&e.jsx("div",{className:"es-qa__counter",children:s("qa.counter",{used:o.length,max:i})})]})]})}export{A as Component,S as manifest};
2
+ //# sourceMappingURL=index-CmM1q2bg-D6H0juMn.js.map