@nexlylab/widget-runtime 1.35.9

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 (64) hide show
  1. package/README.md +34 -0
  2. package/dist/chunks/ClickToLoadEmbed-BPEGNGjL-Dqu4sV5j.js +1 -0
  3. package/dist/chunks/PanelInfoVideo--D2cI0c1-YtsGmc4D.js +2 -0
  4. package/dist/chunks/PanelVideoOverlay-DrBuXCt3-9CT-CwTr.js +2 -0
  5. package/dist/chunks/_commonjsHelpers-C6fGbg64-BC8KDfbh.js +1 -0
  6. package/dist/chunks/accent-legibility-BJF2VO5n-CDPQ7suO.js +1 -0
  7. package/dist/chunks/allowed-elements-C0OfX2zF-DIBV8lKu.js +27 -0
  8. package/dist/chunks/assistant-link-components--y4CIv5J-FQ5HkTEk.js +1 -0
  9. package/dist/chunks/assistant-link-policy-BCMS2TZD-CPsH3B9n.js +1 -0
  10. package/dist/chunks/block-helpers-Cg_zAqG6-DnN2COvk.js +1 -0
  11. package/dist/chunks/block-rating-_Uu_PSxk-DTJYlp2H.js +1 -0
  12. package/dist/chunks/external-url-TVXjKwdN-B68X1DIx.js +1 -0
  13. package/dist/chunks/index-0kAq-v64-Cj9hKhnd.js +49 -0
  14. package/dist/chunks/index-5dQRR-Cl-BHLOwZ63.js +1 -0
  15. package/dist/chunks/index-7NFiiSKb-Dth9nSwh.js +1 -0
  16. package/dist/chunks/index-B1X1Ctdv-B3fhz3xE.js +3 -0
  17. package/dist/chunks/index-B23y2jUJ-BaO0_6Gs.js +377 -0
  18. package/dist/chunks/index-BBDMWdMz-J8TktO92.js +1 -0
  19. package/dist/chunks/index-BPDIV1BN-DINkyYvc.js +1 -0
  20. package/dist/chunks/index-BPeArT5W-CMIft78k.js +3 -0
  21. package/dist/chunks/index-BTKcrkR9-BBbzbp4w.js +1 -0
  22. package/dist/chunks/index-B_mVvI0v-Lf3DGRi2.js +1 -0
  23. package/dist/chunks/index-Bc5yGuC9-DsvbkSc6.js +1 -0
  24. package/dist/chunks/index-BcsmWDTX-Dw9WA5Ac.js +1 -0
  25. package/dist/chunks/index-Be2ZbAFE-WSc7N-DC.js +1 -0
  26. package/dist/chunks/index-Bo2sRqLv-Ll1lwYMy.js +1 -0
  27. package/dist/chunks/index-BsKaoBfe-DzbRA9nQ.js +1 -0
  28. package/dist/chunks/index-BtQSeiip-l41McWo2.js +1 -0
  29. package/dist/chunks/index-C1c5Hlou-rjlUnXTU.js +1 -0
  30. package/dist/chunks/index-C262wwK4-DpyhuXqd.js +1 -0
  31. package/dist/chunks/index-C5rGq5Qc-F1s-uhpT.js +1 -0
  32. package/dist/chunks/index-CF98EbKR-voVzYeB8.js +1 -0
  33. package/dist/chunks/index-CK3WH5JE-D7wryOBp.js +1 -0
  34. package/dist/chunks/index-CO4N_on8-BFhGhIH1.js +5 -0
  35. package/dist/chunks/index-CQDEV8t8-BBhp-ba9.js +1 -0
  36. package/dist/chunks/index-CR83G6nv-Dgqjnh9U.js +1 -0
  37. package/dist/chunks/index-CWvBoml1-DWT7kbPC.js +1 -0
  38. package/dist/chunks/index-CaM1AB5V-BG8W_sZc.js +1 -0
  39. package/dist/chunks/index-CuMYPeuW-cS-al9E9.js +1 -0
  40. package/dist/chunks/index-CxpblUvs-B1tIB9c8.js +1 -0
  41. package/dist/chunks/index-D0EFzbHX-C1E9R_PY.js +1 -0
  42. package/dist/chunks/index-D6lq5r1c-ieawp1gM.js +1 -0
  43. package/dist/chunks/index-D9Pfcey3-Z7aU4-qs.js +1 -0
  44. package/dist/chunks/index-D9Zgyes_-q6-4GTjm.js +3 -0
  45. package/dist/chunks/index-DFMp0RDj-B7Ae5UrP.js +1 -0
  46. package/dist/chunks/index-DFTMYCH_-DzHCU5QM.js +1 -0
  47. package/dist/chunks/index-DH5dF-Vu-DEb4grOY.js +1 -0
  48. package/dist/chunks/index-DZADUAKv-DPfvWVuj.js +1 -0
  49. package/dist/chunks/index-DfEcosms-Mz6A-R9-.js +1 -0
  50. package/dist/chunks/index-Dwb8DcvL-CuiYrL-M.js +1 -0
  51. package/dist/chunks/index-P0zUoKcv-CISBzElt.js +1 -0
  52. package/dist/chunks/index-ZVYeZzJW-C1mWtfbE.js +1 -0
  53. package/dist/chunks/index-c47JESC5-BsVnPG2P.js +1 -0
  54. package/dist/chunks/index-gUmBjv1--Cmmz_3u0.js +1 -0
  55. package/dist/chunks/index-jHz_pdpv-CylxZ7NI.js +5 -0
  56. package/dist/chunks/index-n_QR9xVp-DxMysJse.js +1 -0
  57. package/dist/chunks/index-vKPrckpA-DBDxHMt7.js +1 -0
  58. package/dist/chunks/index-xcFa26x2-BZjWwuev.js +1 -0
  59. package/dist/chunks/index-zZnmAAiq-DY2zrqZq.js +1 -0
  60. package/dist/chunks/index.modern-CioVZ357-C7XPucLH.js +5 -0
  61. package/dist/chunks/inert-assistant-components-B6Cx9pG5-DWb6n3Yq.js +1 -0
  62. package/dist/chunks/use-deferred-rating-XlgCUwcY-DDVOwURi.js +1 -0
  63. package/dist/nexly.js +60 -0
  64. package/package.json +49 -0
@@ -0,0 +1,5 @@
1
+ import{r,$ as gn,z as _n,j as t,Q as Ct,a as ie,l as Ys,O as bn,E as ka,k as xa,v as wa,_ as ja,c as os,g as Na,x as Sa,y as Ca,m as Ra,d as Ia,f as Ea,A as Ta,o as ft,e as Aa,N as is}from"../nexly.js";import{H as Ma,P as La}from"./use-deferred-rating-XlgCUwcY-DDVOwURi.js";import{j as qa}from"./PanelInfoVideo--D2cI0c1-YtsGmc4D.js";import{x as $a,s as vn,f as Gs,c as Pa,a as Ua}from"./allowed-elements-C0OfX2zF-DIBV8lKu.js";import{f as Oa}from"./assistant-link-components--y4CIv5J-FQ5HkTEk.js";import{j as Da,X as Ba}from"./ClickToLoadEmbed-BPEGNGjL-Dqu4sV5j.js";import{m as Ka}from"./assistant-link-policy-BCMS2TZD-CPsH3B9n.js";import"./_commonjsHelpers-C6fGbg64-BC8KDfbh.js";var Zs={},Fa=Object.defineProperty,za=(e,s,a)=>s in e?Fa(e,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[s]=a,Ha=(e,s,a)=>za(e,s+"",a);const Ja=["en","ko","ja","es","zh","id","vi","pl"];function Xa(e){return typeof e=="string"&&Ja.includes(e)}const ts={UNSUPPORTED_TYPE:"MEDIA_UNSUPPORTED_TYPE",TOO_LARGE:"MEDIA_TOO_LARGE",INVALID_INPUT:"MEDIA_INVALID_INPUT"},Qa=5,Va="[cause chain truncated]";function pt(e){if(e instanceof Error)return!0;if(e===null||typeof e!="object")return!1;if(Object.prototype.toString.call(e)==="[object Error]")return!0;const s=e;return typeof s.name=="string"&&typeof s.message=="string"&&typeof s.stack=="string"}function Wa(e){const s=typeof e.name=="string"?e.name:"";if(s&&s!=="Error")return s;const a=e.constructor?.name;return typeof a=="string"&&a&&a!=="Object"?a:s||"Error"}function Ya(e){if(e===null)return null;const s=typeof e;if(s==="string"||s==="number"||s==="boolean")return e}function Tt(e,s=0){if(!pt(e))return e;const a=e,o={type:Wa(a),message:typeof a.message=="string"?a.message:String(a.message??"")};typeof a.stack=="string"&&(o.stack=a.stack),(typeof a.code=="string"||typeof a.code=="number")&&(o.code=a.code);const i=a.cause;if(i!==void 0)if(s>=Qa)o.cause=Va;else if(pt(i))o.cause=Tt(i,s+1);else{const c=Ya(i);c!==void 0&&(o.cause=c)}return o}function Ga(e){if(pt(e))return Tt(e);if(Array.isArray(e)){let s=!1;const a=e.map(o=>pt(o)?(s=!0,Tt(o)):o);return s?a:e}if(Za(e)){let s=!1;const a={};for(const[o,i]of Object.entries(e))pt(i)?(s=!0,a[o]=Tt(i)):a[o]=i;return s?a:e}return e}function Za(e){if(e===null||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s===Object.prototype||s===null}const cs={debug:0,info:1,warn:2,error:3};function er(){if(typeof process>"u"||!Zs)return"info";const e=Zs.LOG_LEVEL?.toLowerCase();return e&&e in cs?e:"info"}function tr(e){const s=er();return cs[e]>=cs[s]}const sr=["level","module","message","timestamp"];function Rt(e,s,a,o){return{...o?Object.fromEntries(Object.entries(o).filter(([i])=>!sr.includes(i)).map(([i,c])=>[i,Ga(c)])):{},level:e,module:s,message:a,timestamp:new Date().toISOString()}}function It(e){if(!tr(e.level))return;const s=JSON.stringify(e);switch(e.level){case"debug":console.debug(s);break;case"info":console.info(s);break;case"warn":console.warn(s);break;case"error":console.error(s);break}}function nr(e){return{debug:(s,a)=>{It(Rt("debug",e,s,a))},info:(s,a)=>{It(Rt("info",e,s,a))},warn:(s,a)=>{const o=Rt("warn",e,s,a);It(o)},error:(s,a)=>{const o=Rt("error",e,s,a);It(o)}}}const ar=["quote","consultation","group_booking","availability","callback"];function rr(e){return typeof e=="string"&&ar.includes(e)}const or=[{key:"model",kind:"text",required:!0,max:200},{key:"application",kind:"textarea",required:!1,max:1e3},{key:"requirements",kind:"textarea",required:!1,max:2e3}],ir=[{key:"topic",kind:"text",required:!0,max:200},{key:"preferred_time",kind:"text",required:!1,max:200}],cr=[{key:"group_size",kind:"number",required:!0,max:1e5},{key:"preferred_date",kind:"text",required:!1,max:100},{key:"notes",kind:"textarea",required:!1,max:1e3}],lr=[{key:"item",kind:"text",required:!0,max:200},{key:"quantity",kind:"number",required:!1,max:1e6},{key:"needed_by",kind:"text",required:!1,max:100}],ur=[{key:"topic",kind:"text",required:!1,max:200},{key:"preferred_time",kind:"text",required:!1,max:200}],dr=Object.freeze({quote:or,consultation:ir,group_booking:cr,availability:lr,callback:ur}),ss=Object.freeze({name:200,email:254,phone:32});function fr(e){return rr(e)?dr[e]:[]}const pr=8*1024*1024,mr=["jpeg","png","webp"],hr=Object.freeze(Object.assign(Object.create(null),{jpeg:"image/jpeg",png:"image/png",webp:"image/webp"})),yn=Object.freeze(mr.map(e=>hr[e])),gr=new Set(["table","thead","tbody","tfoot","tr"]);function _r(e){return/^[ \t\r\n\f]*$/.test(e)}function en(e){return typeof e?.offset=="number"?e.offset:null}function br(e){return typeof e=="object"&&e!==null&&"type"in e}function vr(e={}){const s=e.allowedElements?new Set(e.allowedElements):null,a=e.skipHtml??!1;let o=null;function i(c,l){const d=c.children;if(!d)return;const g=c.type==="element"&&typeof c.tagName=="string"&&gr.has(c.tagName);for(const _ of d){if(_.type==="element"){if(s&&typeof _.tagName=="string"&&!s.has(_.tagName))continue;i(_,l);continue}if(_.type!=="text"&&_.type!=="raw"||_.type==="raw"&&a)continue;const h=typeof _.value=="string"?_.value:"";h&&(_.type==="text"&&g&&_r(h)||l.push({value:h,sourceStart:en(_.position?.start),sourceEnd:en(_.position?.end)}))}}return{plugin:()=>c=>{o=br(c)?c:null},segments:()=>{if(!o)return[];const c=[];return i(o,c),c}}}function yr(e,s){const a=e.ownerDocument??e;if(typeof a?.createTreeWalker!="function")return null;const o=a.createTreeWalker(e,4),i=[];for(let l=o.nextNode();l;l=o.nextNode())i.push(l);if(i.length!==s.length)return null;const c=[];for(let l=0;l<i.length;l+=1){const d=i[l],g=s[l];if(!d||!g||d.data!==g.value)return null;c.push({...g,node:d})}return c}function tn(e,s,a){return Math.min(Math.max(e,s),a)}function kr(e,s,a){if(!(a>s))return null;let o=null,i=null;for(const c of e){const{sourceStart:l,sourceEnd:d}=c;if(l===null||d===null||d<=s||l>=a)continue;const g=d-l===c.value.length,_=g?tn(s-l,0,c.value.length):0,h=g?tn(a-l,0,c.value.length):c.value.length;h<=_||(o||(o={node:c.node,offset:_}),i={node:c.node,offset:h})}return o&&i?{startNode:o.node,startOffset:o.offset,endNode:i.node,endOffset:i.offset}:null}const ac={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:""},disclaimer:{type:"string",default:""},showSuggestedQuestions:{type:"boolean",default:!0},suggestedQuestions:{type:"array",items:{type:"string"},default:[]},escalationLabel:{type:"string",default:""},humanHandoffButton:{type:"boolean",default:!1},photoUploadEnabled:{type:"boolean",default:!1}}},defaultConfig:{voiceEnabled:!0,voiceConversationEnabled:!1,voiceReadAloudEnabled:!1,welcomeMessage:"",headerTitle:"",placeholder:"",disclaimer:"",showSuggestedQuestions:!0,suggestedQuestions:[],escalationLabel:"",humanHandoffButton:!1,photoUploadEnabled:!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:"disclaimer",type:"localized-text",label:"Disclaimer",default:"",maxLength:120,placeholder:'Leave empty to use translated default (e.g. "AI can make mistakes — double-check important details.")',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:"photoUploadEnabled",type:"toggle",label:"Allow photo upload",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 xr({text:e,allowedLinkHosts:s,sourceCollector:a,containerRef:o}){return t.jsx("div",{ref:o,className:"es-sc__bubble-text es-sc__bubble-text--md",children:t.jsx($a,{remarkPlugins:[...Pa],rehypePlugins:a?[...Gs,a.plugin]:[...Gs],allowedElements:[...vn],transformLinkUri:i=>Ua(i)??"",transformImageUri:()=>"",components:{input:({node:i,type:c,checked:l,...d})=>c==="checkbox"?t.jsx("input",{...d,type:"checkbox",checked:!!l,disabled:!0,readOnly:!0,className:"es-sc__md-task"}):null,...Oa({allowedHosts:s})},children:e})})}function ls({text:e,allowedLinkHosts:s,cursor:a}){const o=r.useRef(null),i=!!a,c=r.useMemo(()=>i?vr({allowedElements:vn,skipHtml:!1}):void 0,[i]);return r.useEffect(()=>{const l=o.current;if(!a||!c||!l)return;const d=gn({container:l}),g=l.ownerDocument,_=_n({currentTime:a.currentTime,words:a.words,onWord:h=>{if(h===null){d.paint(null);return}const u=yr(l,c.segments()),f=u&&kr(u,h.sourceStart,h.sourceEnd);if(!f){d.paint(null);return}const b=g.createRange();b.setStart(f.startNode,f.startOffset),b.setEnd(f.endNode,f.endOffset),d.paint(b)}});return _.start(),()=>{_.stop(),d.destroy()}},[a,c]),t.jsx(xr,{text:e,allowedLinkHosts:s,sourceCollector:c,containerRef:o})}function wr({media:e,t:s}){const{embeds:a,images:o}=e;return a.length===0&&o.length===0?null:t.jsxs("div",{className:"es-sc__media","data-testid":"support-chat-media",children:[a.map(i=>t.jsx(Ba,{embed:i,t:s,classPrefix:"es-sc"},`${i.provider}:${i.id}`)),o.map(i=>t.jsx("img",{className:"es-sc__media-img",src:i.src,alt:i.alt||s("support_chat.media_image_alt"),loading:"lazy",decoding:"async",referrerPolicy:"no-referrer"},i.src))]})}function ns(e){return e?e.join(","):""}const jr=r.memo(function({text:e,allowEmbeds:s,allowedImageHosts:a,t:o}){const i=ns(a),c=r.useMemo(()=>Da(e,{allowEmbeds:s,allowedImageHosts:a}),[e,s,i]);return t.jsx(wr,{media:c,t:o})},(e,s)=>e.text===s.text&&e.allowEmbeds===s.allowEmbeds&&e.t===s.t&&ns(e.allowedImageHosts)===ns(s.allowedImageHosts)),sn={status:"idle"};function Nr(){return t.jsxs("svg",{width:18,height:18,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("path",{d:"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8Z"}),t.jsx("path",{d:"M14 3v5h5"})]})}function Sr(e,s,a){const o=e/1024;return o<1024?a("support_chat.attachments.size_kb",{size:new Intl.NumberFormat(s,{maximumFractionDigits:0}).format(Math.max(1,Math.round(o)))}):a("support_chat.attachments.size_mb",{size:new Intl.NumberFormat(s,{minimumFractionDigits:1,maximumFractionDigits:1}).format(o/1024)})}function Cr(e,s){const a=e.status==="ready"?e.link.expiresAtMs:null;r.useEffect(()=>{if(a===null)return;const o=a-Date.now();if(o<=0){s();return}const i=setTimeout(s,o);return()=>clearTimeout(i)},[a,s])}function Rr({attachment:e,baseUrl:s,apiKey:a,language:o,t:i}){const[c,l]=r.useState(sn),d=r.useCallback(()=>l(sn),[]);Cr(c,d);const{fileId:g,title:_,contentType:h,byteSize:u}=e,f=r.useCallback(async()=>{l({status:"pending"});try{const j=await fetch(`${s}/api/widget/files/${encodeURIComponent(g)}/link`,{method:"POST",credentials:"include",headers:a?{"X-API-Key":a}:{}});if(!j.ok){l({status:"error"});return}const v=await j.json();if(typeof v.url!="string"||!v.url){l({status:"error"});return}const x=typeof v.expiresAt=="string"?Date.parse(v.expiresAt):Number.NaN;l({status:"ready",link:{url:v.url,expiresAtMs:Number.isFinite(x)?x:Date.now()+300*1e3}}),window.open(v.url,"_blank","noopener")}catch{l({status:"error"})}},[a,s,g]),b=`${i(`support_chat.attachments.type_${h}`)} · ${Sr(u,o,i)}`;return t.jsxs("div",{className:`es-sc__attachment es-sc__attachment--${h}`,children:[t.jsx("span",{className:"es-sc__attachment-icon","aria-hidden":"true",children:t.jsx(Nr,{})}),t.jsxs("span",{className:"es-sc__attachment-body",children:[t.jsx("span",{className:"es-sc__attachment-title",children:_}),t.jsx("span",{className:"es-sc__attachment-meta",children:b})]}),c.status==="ready"?t.jsx("a",{className:"es-sc__attachment-btn es-sc__attachment-btn--ready",href:c.link.url,target:"_blank",rel:"noopener noreferrer",download:!0,children:i("support_chat.attachments.download")}):t.jsx("button",{type:"button",className:"es-sc__attachment-btn",onClick:f,disabled:c.status==="pending",children:i(c.status==="pending"?"support_chat.attachments.opening":"support_chat.attachments.download")}),c.status==="error"&&t.jsx("p",{className:"es-sc__attachment-error","aria-live":"polite",children:i("support_chat.attachments.error")})]})}const Ir=r.memo(function({attachments:e,baseUrl:s,apiKey:a,language:o,t:i}){return e.length===0?null:t.jsx("div",{className:"es-sc__attachments","data-testid":"support-chat-attachments","data-es-no-read":!0,role:"group","aria-label":i("support_chat.attachments.label"),children:e.map(c=>t.jsx(Rr,{attachment:c,baseUrl:s,apiKey:a,language:o,t:i},c.fileId))})});function Er(e,s){const a=Math.round((Date.now()-e.getTime())/1e3);if(a<60)return s("time.just_now");const o=Math.round(a/60);if(o<60)return s("time.minutes_ago",{count:o});const i=Math.round(o/60);if(i<24)return s("time.hours_ago",{count:i});const c=Math.round(i/24);return s("time.days_ago",{count:c})}function kn({card:e,t:s,onSelect:a}){const o=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:["#",e.externalNumber]}),t.jsx("span",{className:`es-sc__ticket-card-status es-sc__ticket-card-status--${e.status}`,children:s(`escalation.status_${e.status}`)})]}),e.summary&&t.jsx("p",{className:"es-sc__ticket-card-summary",title:e.summary,children:e.summary}),t.jsxs("p",{className:"es-sc__ticket-card-meta",children:[Er(new Date(e.createdAt),s),e.priority?` · ${s(`support_chat.priority_${e.priority}`)}`:""]})]});if(a&&e.sessionId){const i=e.sessionId;return t.jsx("button",{type:"button",className:"es-sc__ticket-card es-sc__ticket-card--clickable",onClick:()=>a(i),"aria-label":s("support_chat.open_ticket_conversation"),title:s("support_chat.open_ticket_conversation"),children:o})}return t.jsx("div",{className:"es-sc__ticket-card",children:o})}const Tr=[{value:"open",key:"support_chat.filter_open"},{value:"closed",key:"support_chat.filter_closed"},{value:"all",key:"support_chat.filter_all"}];function Ar(e){const{status:s,loading:a,tickets:o,onSelectStatus:i,onSelectSession:c,t:l}=e;return t.jsxs("div",{className:"es-sc__tickets-view",children:[t.jsx("div",{className:"es-sc__tickets-filters",children:Tr.map(d=>t.jsx("button",{type:"button",className:`es-sc__tickets-chip${s===d.value?" es-sc__tickets-chip--active":""}`,onClick:()=>i(d.value),children:l(d.key)},d.value))}),t.jsx("div",{className:"es-sc__tickets-view-list",children:a?t.jsx("p",{className:"es-sc__tickets-empty",role:"status","aria-live":"polite",children:"…"}):o.length===0?t.jsx("p",{className:"es-sc__tickets-empty",children:l("support_chat.tickets_empty")}):o.map(d=>t.jsx(kn,{card:d,t:l,onSelect:c},d.externalNumber))})]})}const Mr=["audio/webm;codecs=opus","audio/webm","audio/mp4"];function Lr(){return typeof navigator>"u"||typeof window>"u"?!1:typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof window.MediaRecorder<"u"}function qr(){if(typeof window>"u"||typeof window.MediaRecorder>"u")return;const e=typeof window.MediaRecorder.isTypeSupported=="function";for(const s of Mr)if(!e||window.MediaRecorder.isTypeSupported(s))return s}function $r({baseUrl:e,apiKey:s,jwt:a,language:o,onTranscript:i,t:c,disabled:l=!1,streaming:d,voiceStream:g,baseText:_,onText:h}){const[u]=r.useState(Lr),[f,b]=r.useState("idle"),[j,v]=r.useState(null),[x,A]=r.useState("idle"),U=!!(d&&g&&_&&h),I=r.useRef(null),y=r.useRef(null),$=r.useRef([]),S=r.useRef(!0);r.useEffect(()=>()=>{S.current=!1},[]);const O=r.useRef({baseUrl:e,apiKey:s,jwt:a,language:o,onTranscript:i});r.useEffect(()=>{O.current={baseUrl:e,apiKey:s,jwt:a,language:o,onTranscript:i}},[e,s,a,o,i]);const X=r.useCallback(()=>{y.current?.getTracks().forEach(F=>F.stop()),y.current=null,I.current=null,$.current=[]},[]);r.useEffect(()=>X,[X]);const D=r.useRef(()=>{});D.current=()=>{U&&(x==="connecting"||x==="listening")&&g?.stop()},r.useEffect(()=>()=>D.current(),[]);const te=r.useCallback(async F=>{const{baseUrl:J,apiKey:G,jwt:ce,language:he,onTranscript:je}=O.current,fe=new FormData;fe.append("audio",F,"recording.webm"),fe.append("language",he);const Ne={};G&&(Ne["X-API-Key"]=G),ce&&(Ne.Authorization=`Bearer ${ce}`);const pe=await fetch(`${J}/api/widget/transcribe`,{method:"POST",headers:Ne,credentials:"include",body:fe});if(!pe.ok){const Y=new Error(`HTTP ${pe.status}`);throw Y.status=pe.status,Y}const Ce=await pe.json();je(Ce.text??"")},[]),R=r.useCallback(async()=>{v(null);let F;try{F=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{b("error"),v("voice.permission_denied");return}const J=qr();let G;try{G=J?new MediaRecorder(F,{mimeType:J}):new MediaRecorder(F)}catch{F.getTracks().forEach(ce=>ce.stop()),b("error"),v("voice.error_generic");return}y.current=F,I.current=G,$.current=[],G.ondataavailable=ce=>{ce.data&&ce.data.size>0&&$.current.push(ce.data)},G.onstop=async()=>{const ce=G.mimeType||J||"audio/webm",he=new Blob($.current,{type:ce});if(X(),he.size===0){b("idle");return}b("transcribing");try{if(await te(he),!S.current)return;b("idle"),v(null)}catch(je){if(!S.current)return;const fe=je.status;b("error"),v(fe===413?"voice.error_too_large":"voice.error_generic")}},G.start(),b("recording")},[X,te]),M=r.useCallback(()=>{const F=I.current;F&&F.state!=="inactive"?F.stop():(X(),b("idle"))},[X]),Q=r.useCallback(()=>{u&&(U?x==="connecting"||x==="listening"?(g.stop(),A("idle")):(v(null),g.start({language:o,baseText:_,onText:h,onState:F=>A(F),onError:F=>{v(F),A("error")}})):f==="recording"?M():(f==="idle"||f==="error")&&R())},[u,U,x,f,o,_,h,g,R,M]);if(!u)return null;const z=U?x==="connecting"||x==="listening":f==="recording",H=!U&&f==="transcribing",T=U?x==="error":f==="error",E=c(z?"voice.stop":"voice.start"),L=j?c(j):H?c("voice.transcribing"):E,ae=["es-sc__mic",z&&"es-sc__mic--recording",H&&"es-sc__mic--transcribing",T&&"es-sc__mic--error"].filter(Boolean).join(" ");return t.jsx("button",{type:"button",className:ae,onClick:Q,disabled:H||l,"aria-label":E,"aria-pressed":z,title:L,children:H?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"})}):z?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"})]})})}const Pr=yn.join(","),Ur=Object.freeze({too_large:"support_chat.photo_error_too_large",unsupported:"support_chat.photo_error_unsupported",rejected:"support_chat.photo_error_rejected",too_many:"support_chat.photo_error_too_many",failed:"support_chat.photo_error_failed"});function Or(e){return yn.includes(e.type)?e.size>pr?"too_large":null:"unsupported"}function Dr(e,s){return e===413||s===ts.TOO_LARGE?"too_large":s===ts.UNSUPPORTED_TYPE?"unsupported":e===429?"too_many":e===400&&s===ts.INVALID_INPUT?"rejected":"failed"}async function Br(e){const s=new FormData;s.append("sessionId",e.sessionId),e.productId&&s.append("productId",e.productId),s.append("file",e.file);const a=e.fetchImpl??fetch,[o,i]=await ie(()=>a(`${e.baseUrl}/api/widget/support-chat/attachments`,{method:"POST",headers:{...e.apiKey?{"X-API-Key":e.apiKey}:{},...e.jwt?{Authorization:`Bearer ${e.jwt}`}:{}},body:s,...e.signal?{signal:e.signal}:{}}));if(i)return{ok:!1,kind:"failed"};const[c]=await ie(()=>o.json()),l=c??{};return!o.ok||!l.asset?.assetId?{ok:!1,kind:Dr(o.status,l.error?.code)}:{ok:!0,assetId:l.asset.assetId}}function Kr(e){const{baseUrl:s,apiKey:a,getJwt:o,sessionId:i,productId:c,enabled:l}=e,[d,g]=r.useState([]),[_,h]=r.useState(!1),[u,f]=r.useState(null),b=r.useRef(o);b.current=o;const j=r.useRef([]);r.useEffect(()=>()=>{for(const x of j.current)URL.revokeObjectURL(x);j.current=[]},[]);const v=r.useCallback(async x=>{if(!l||!i)return;const A=Or(x);if(A){f(A);return}f(null),h(!0);const U=await Br({baseUrl:s,apiKey:a,jwt:b.current(),sessionId:i,...c?{productId:c}:{},file:x});if(h(!1),!U.ok){f(U.kind);return}const I=URL.createObjectURL(x);j.current.push(I),g(y=>[...y,{assetId:U.assetId,previewUrl:I}])},[a,s,l,c,i]);return{photos:d,uploading:_,error:u,ready:l&&i!==null,send:v,dismissError:r.useCallback(()=>f(null),[])}}function Fr({upload:e,disabled:s,t:a}){const o=r.useRef(null),i=a("support_chat.photo_attach_aria"),c=s||!e.ready||e.uploading;return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:o,type:"file",className:"es-sc__photo-input",accept:Pr,"data-testid":"support-chat-photo-input","aria-hidden":"true",tabIndex:-1,onChange:l=>{const d=l.target.files?.[0];l.target.value="",d&&e.send(d)}}),t.jsx("button",{type:"button",className:"es-sc__photo-btn","data-testid":"support-chat-photo-button","aria-label":i,title:i,disabled:c,onClick:()=>o.current?.click(),children:e.uploading?t.jsx("span",{className:"es-sc__photo-spinner","aria-hidden":"true"}):t.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("circle",{cx:"8.5",cy:"10",r:"1.5"}),t.jsx("path",{d:"m21 16-5-5L5 19"})]})})]})}function zr({upload:e,t:s}){const{photos:a,uploading:o,error:i}=e;return a.length===0&&!o&&!i?null:t.jsxs("div",{className:"es-sc__photo-strip","data-testid":"support-chat-photo-strip",children:[a.length>0&&t.jsx("ul",{className:"es-sc__photo-list","aria-label":s("support_chat.photo_strip_aria"),children:a.map(c=>t.jsx("li",{children:t.jsx("img",{className:"es-sc__photo-thumb",src:c.previewUrl,alt:s("support_chat.photo_sent_alt"),"data-testid":"support-chat-photo-thumb"})},c.assetId))}),o&&t.jsx("p",{className:"es-sc__photo-status","data-testid":"support-chat-photo-uploading",children:s("support_chat.photo_uploading")}),i&&t.jsx("p",{className:"es-sc__photo-error",role:"alert","data-testid":"support-chat-photo-error",children:s(Ur[i])})]})}function Hr(){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 Jr(){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 Xr(){return t.jsx("svg",{width:12,height:12,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 Qr(){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 Vr=r.memo(function({id:e,session:s,onActivate:a,t:o}){const i=s.activeId===e?s.status:"idle",c=r.useCallback(()=>{if(i==="idle"||i==="error"){a();return}i!=="loading"&&s.togglePause()},[i,a,s]),l=r.useCallback(()=>s.stop(),[s]),d=o(i==="playing"?"voice_output.pause":"voice_output.play"),g=i==="error"?o("voice_output.error"):d;return t.jsxs("span",{className:"es-sc__readaloud-group",children:[t.jsx("button",{type:"button",className:["es-sc__readaloud-btn",i==="playing"&&"es-sc__readaloud-btn--playing",i==="paused"&&"es-sc__readaloud-btn--paused",i==="error"&&"es-sc__readaloud-btn--error"].filter(Boolean).join(" "),onClick:c,disabled:i==="loading","aria-label":d,"aria-pressed":i==="playing",title:g,children:i==="loading"?t.jsx(Qr,{}):i==="playing"?t.jsx(Jr,{}):t.jsx(Hr,{})}),(i==="playing"||i==="paused")&&t.jsx("button",{type:"button",className:"es-sc__readaloud-btn es-sc__readaloud-btn--stop",onClick:l,"aria-label":o("voice_output.stop"),title:o("voice_output.stop"),children:t.jsx(Xr,{})})]})});function xn(e){let s=null,a=0,o=null,i=null;const c=new Set,l={ended:new Set},d=_=>{for(const h of[...l[_]])h()},g=_=>{_.onended=null,ft(()=>_.stop())};return{push(_){const h=new Uint8Array(_);let u;o&&o.length>0?(u=new Uint8Array(o.length+h.length),u.set(o,0),u.set(h,o.length),o=null):u=h;const f=u.length-u.length%2;if(f<u.length&&(o=u.slice(f)),f===0)return;const b=new Int16Array(u.buffer,u.byteOffset,f/2);if(b.length===0)return;s??(s=new AudioContext({sampleRate:e}));const j=s.createBuffer(1,b.length,e);j.getChannelData(0).set(Float32Array.from(b,A=>A/32768));const v=s.createBufferSource();v.buffer=j,v.connect(s.destination),v.onended=()=>{c.delete(v),c.size===0&&d("ended")},c.add(v);const x=Math.max(s.currentTime,a);v.start(x),i??(i=x),a=x+j.duration},reset(){for(const _ of[...c])g(_);c.clear(),a=0,i=null,o=null},pause(){s?.suspend()},resume(){s?.resume()},currentTime(){return!s||i===null?0:Math.min(Math.max(s.currentTime-i,0),a-i)},nextStartTime(){return!s||i===null?0:Math.max(s.currentTime,a)-i},on(_,h){return l[_].add(h),()=>{l[_].delete(h)}},close(){for(const _ of[...c])g(_);c.clear(),s?.close(),s=null,a=0,i=null,l.ended.clear()}}}const Wr=" ";function Yr({baseUrl:e,apiKey:s,getJwt:a}){const[o,i]=r.useState(null),[c,l]=r.useState("idle"),d=r.useRef(null),g=r.useRef(null),_=r.useRef([]),h=r.useRef(!1),u=r.useRef("en"),f=r.useRef(null),b=r.useRef([]),j=r.useRef(""),v=r.useRef(null),x=r.useCallback(()=>{f.current=null,b.current=[],j.current="",v.current=null},[]),A=r.useCallback(()=>{const E=f.current,L=b.current;if(!E||L.length===0){v.current=null;return}v.current=bn({sanitizedText:j.current,locale:u.current,charTimes:E.charTimes(),toSourceRange:(ae,F)=>{const J=L.find(he=>ae>=he.sanitizedBase&&ae<he.sanitizedBase+he.sanitizedLength);if(!J||J.spans===null||J.sourceBase===null)return null;const G=Math.min(F,J.sanitizedBase+J.sanitizedLength),ce=ka(J.spans,ae-J.sanitizedBase,G-J.sanitizedBase);return ce===null?null:{start:ce.start+J.sourceBase,end:ce.end+J.sourceBase}}})},[]),U=r.useRef(!1),I=r.useRef(!1),y=r.useRef(0),$=r.useRef(null),S=r.useRef(null),O=r.useCallback(()=>{S.current&&(clearTimeout(S.current),S.current=null)},[]),X=r.useCallback(()=>{$.current?.abort(),$.current=null,S.current&&(clearTimeout(S.current),S.current=null),g.current?.close(),g.current=null,_.current=[],h.current=!1,U.current=!1,I.current=!1,x()},[x]),D=r.useCallback(()=>{y.current+=1,X(),d.current=null,i(null),l("idle")},[X]),te=r.useCallback(()=>{const E=g.current;E&&l(L=>L==="playing"?(E.pause(),"paused"):L==="paused"?(E.resume(),"playing"):L)},[]),R=r.useCallback(E=>{if(d.current===E)return;X(),y.current+=1,$.current=new AbortController,d.current=E,i(E),l("loading");const L=y.current;S.current=setTimeout(()=>{L===y.current&&($.current?.abort(),l("error"))},12e3)},[X]),M=r.useCallback(async E=>{if(!E)return;const L=a?.();await ie(fetch(`${e}/api/widget/read-aloud-play`,{method:"POST",headers:{"Content-Type":"application/json",...s?{"X-API-Key":s}:{},...L?{Authorization:`Bearer ${L}`}:{}},body:JSON.stringify({messageId:E})}))},[e,s,a]),Q=r.useCallback((E,L)=>{h.current||(h.current=!0,(async()=>{for(;_.current.length>0;){if(E!==y.current){h.current=!1;return}const ae=_.current.shift();if(!ae)continue;const F=ae.text,J=a?.(),[G,ce]=await ie(fetch(`${e}/api/widget/read-aloud`,{method:"POST",headers:{"Content-Type":"application/json",...s?{"X-API-Key":s}:{},...J?{Authorization:`Bearer ${J}`}:{}},body:JSON.stringify({text:F,language:L,messageId:d.current??void 0,alignment:!0}),signal:$.current?.signal}));if(E!==y.current){h.current=!1;return}if(ce||!G||!G.ok||!G.body){l("error"),h.current=!1;return}const he=G.headers.get("X-Audio-Encoding");if(he&&he!=="pcm16"){l("error"),h.current=!1;return}if(!g.current){const re=Number(G.headers.get("X-Audio-Sample-Rate"))||24e3,se=xn(re);g.current=se,se.on("ended",()=>{E===y.current&&(!U.current||_.current.length>0||h.current||D())})}const je=g.current,fe=re=>{je.push(re),!I.current&&(I.current=!0,O(),l("playing"),M(d.current))},Ne=xa(G.headers.get("Content-Type"))?wa():null;let pe=null,Ce=null;const Y=[],Z=re=>{const se=f.current;!se||!pe||Ce===null||se.addUtterance({charOffset:re.charOffset,characters:re.characters,startTimes:re.startTimes,endTimes:re.endTimes,textBase:pe.sanitizedBase,timeBase:Ce})},qe=re=>{switch(re.type){case Ea:{Ce===null&&(Ce=je.nextStartTime()),fe(re.payload.slice().buffer);let se=!1;for(;Y.length>0;){const le=Y.shift();le&&(Z(le),se=!0)}return se}case Ra:{if(pe!==null)return!1;const se=Ia(re.payload);return j.current.length>0&&(j.current+=Wr),pe={sanitizedBase:j.current.length,sanitizedLength:se.length,sourceBase:ae.sourceStart??null,spans:null},j.current+=se,b.current.push(pe),f.current??(f.current=os()),!1}case Ca:return pe!==null&&(pe.spans=Ta(re.payload)),!1;case Na:{const se=Sa(re.payload);return se===null?!1:Ce===null?(Y.push(se),!1):(Z(se),!0)}default:return!1}},Ie=G.body.getReader();for(;;){const[re,se]=await ie(Ie.read());if(E!==y.current){h.current=!1;return}if(se){l("error"),h.current=!1;return}const{done:le,value:ve}=re;if(le)break;if(!ve||ve.byteLength===0)continue;if(Ne===null){fe(ve.buffer.slice(ve.byteOffset,ve.byteOffset+ve.byteLength));continue}let Ge=!1;for(const Je of Ne.push(ve))qe(Je)&&(Ge=!0);Ge&&A()}Ne!==null&&A()}h.current=!1,U.current&&!I.current&&E===y.current&&D()})())},[e,s,a,D,M,A]),z=r.useCallback((E,L,ae,F)=>{if(d.current!==E)return;const J=L.trim();J&&(u.current=ae,_.current.push({text:J,sourceStart:F}),Q(y.current,ae))},[Q]),H=r.useCallback(E=>{d.current===E&&(U.current=!0,_.current.length===0&&!h.current&&!I.current&&D())},[D]);r.useEffect(()=>()=>D(),[D]);const T=r.useMemo(()=>({words:()=>v.current,currentTime:()=>g.current?.currentTime()??0}),[]);return{activeId:o,status:c,activate:R,feed:z,finish:H,togglePause:te,stop:D,cursor:T}}function Gr(e){return e==="voice.error_mic_denied"||e==="voice.permission_denied"?"mic_permission":e==="voice.error_unauthorized"||e==="voice.error_unavailable"||e==="voice.error_generic"?"connection":"unknown"}function Zr(e){const s=e?.name??"",a=e?.message??"",o=`${s} ${a}`;return/NotAllowedError|PermissionDenied|SecurityError|NotFoundError|NotReadableError|no media devices/i.test(o)?"mic_permission":"connection"}function eo(e){switch(e){case"mic_permission":return"voice_conv.error_mic";case"connection":return"voice_conv.error_connection";case"stall":return"voice_conv.error_stall";default:return"voice_conv.error"}}const to=1200,so=8e3,no=3;function nn(e={language:"en"}){const{voiceStream:s,language:a,silenceMs:o=to,getInputStream:i,listenTimeoutMs:c=so}=e;let l=null,d=null,g="",_=!1,h=!1,u=!1,f=null,b=0;const j=()=>{d&&clearTimeout(d),d=null},v=()=>{f&&clearTimeout(f),f=null},x=(I,y)=>{j(),v(),_=!1,l?.({type:"error",kind:I,message:y})},A=()=>{if(_){if(u=!1,v(),b>=no){x("connection","voice_conv.error_connection");return}b+=1,U()}},U=()=>{if(!s||!_)return;g="",u=!1;const I=i?.()??null;v(),f=setTimeout(()=>{f=null,!(!_||u)&&x("stall","voice_conv.error_stall")},c),s.start({language:a,...I?{inputStream:I}:{},baseText:()=>"",onState:y=>{if(y==="listening"){u=!0,v();return}y==="idle"&&!h&&u&&A()},onText:y=>{const $=y.trim();!$||$===g||(b=0,g=$,l?.({type:"user_partial",text:$}),j(),d=setTimeout(()=>{const S=g;S&&(g="",l?.({type:"user_final",text:S}),h=!0,s.stop(),h=!1,U())},o))},onError:y=>x(Gr(y),y)})};return{get available(){return!!s},async start({onEvent:I}){if(!s)throw new Error("conversation transport unavailable");l=I,_=!0,b=0,U()},stop(){_=!1,u=!1,j(),v(),g="",s&&(h=!0,s.stop(),h=!1),l=null}}}const ao=1e4,ro=1e4,oo=5e4;function wn(e){let s=0;for(const a of e)s+=a.length;return s}function io(e){if(typeof e!="object"||e===null)return null;const s=e,{chars:a,char_start_times_ms:o,char_durations_ms:i}=s;return!Array.isArray(a)||!Array.isArray(o)||!Array.isArray(i)||a.length!==o.length||a.length!==i.length||a.length>ro||!a.every(c=>typeof c=="string")||wn(a)>ao?null:{chars:a,char_start_times_ms:o,char_durations_ms:i}}function an(e){return e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"")}const co=8;function lo(e,s,a){const o=is(e,a),i=is(s,a);if(o===null||i===null)return null;const c=new Map;let l=0;for(const d of o){const g=an(e.slice(d.start,d.end));if(g==="")continue;const _=Math.min(i.length,l+co);for(let h=l;h<_;h+=1){const u=i[h];if(u===void 0)break;if(an(s.slice(u.start,u.end))===g){c.set(`${d.start}:${d.end}`,{start:u.start,end:u.end}),l=h+1;break}}}return(d,g)=>c.get(`${d}:${g}`)??null}const uo=250;function fo(e){const{locale:s}=e,a=e.now??(()=>performance.now()),o=e.setTimer??((y,$)=>setTimeout(y,$)),i=e.clearTimer??(y=>clearTimeout(y)),c=e.utteranceEndGraceMs??uo;let l=os(),d="",g=0,_=null,h="",u=null,f=!1,b=!1,j=0,v=null,x=null;function A(){u!==null&&(i(u),u=null)}function U(){A(),b=!1,l=os(),d="",g=0,_=null,f=!1,j+=1,v=null,x=null}function I(){_===null&&(_=a())}return{addAlignment(y){const $=io(y);if($===null||(A(),f))return;if(d.length+wn($.chars)>oo){f=!0,j+=1,v=null,x=null;return}const{chars:S,char_start_times_ms:O,char_durations_ms:X}=$,D=[],te=[];let R=0;for(let M=0;M<S.length;M+=1){const Q=O[M],z=X[M],H=typeof Q=="number"?Q/1e3:Number.NaN,T=typeof Q=="number"&&typeof z=="number"?(Q+z)/1e3:Number.NaN;D.push(H),te.push(T),Number.isFinite(T)&&T>R&&(R=T)}l.addUtterance({charOffset:0,startTimes:D,endTimes:te,characters:S,textBase:d.length,timeBase:g}),d+=S.join(""),g+=R,j+=1,v=null,b=!0,I()},noteSpeaking(){A(),b=!0,I()},noteListening(){b=!1,u===null&&(u=o(()=>{u=null,U()},c))},endUtterance(){U()},setSourceText(y){y!==h&&(h=y,v=null)},words(){if(!b||f||d===""||h==="")return null;const y=`${j}|${h}`;if(y!==v){v=y;const $=lo(d,h,s);x=$===null?null:bn({sanitizedText:d,locale:s,charTimes:l.charTimes(),toSourceRange:$})}return x},currentTime(){if(_===null)return 0;const y=(a()-_)/1e3;return!Number.isFinite(y)||y<=0?0:Math.min(y,g)},dispose(){U()}}}const po=1024,mo=2.5;function ho(e,s={}){const a=s.audioContext??(typeof AudioContext<"u"?()=>new AudioContext:void 0);if(!a)return{getLevel:()=>null,stop:()=>{}};const[o]=ft(()=>{const c=a(),l=c.createAnalyser();return l.fftSize=po,l.smoothingTimeConstant=0,c.createMediaStreamSource(e).connect(l),{ctx:c,analyser:l,samples:new Float32Array(l.fftSize)}});if(!o)return{getLevel:()=>null,stop:()=>{}};let i=!0;return Aa(o.ctx),{getLevel(){if(!i||o.ctx.state!=="running")return null;const[c]=ft(()=>{o.analyser.getFloatTimeDomainData(o.samples);let d=0;for(const g of o.samples)d+=g*g;return Math.sqrt(d/o.samples.length)});if(c===null||!Number.isFinite(c))return null;const l=c*mo;return l>1?1:l},stop(){i=!1,ft(()=>o.analyser.disconnect()),ft(()=>{o.ctx.close()})}}}class jn extends Error{constructor(s,a){super(`microphone unavailable: ${s}`),Ha(this,"messageKey"),this.name="MicrophoneUnavailableError",this.messageKey=s,a!==void 0&&(this.cause=a)}}const go="voice_conv.mic_denied",_o="voice_conv.mic_unavailable",bo="voice_conv.mic_not_found",vo="voice_conv.mic_unsupported";function yo(e){switch(typeof e=="object"&&e!==null&&"name"in e?String(e.name):""){case"NotAllowedError":case"PermissionDeniedError":case"SecurityError":return go;case"NotFoundError":case"DevicesNotFoundError":case"OverconstrainedError":return bo;case"NotReadableError":case"TrackStartError":case"AbortError":return _o;default:return vo}}function rn(e){return Math.round(e*10)/10}function ko(){return typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia?Promise.reject(new Error("no media devices")):navigator.mediaDevices.getUserMedia({audio:!0})}function xo(e){let s=null,a=null;const o=e.now??(()=>performance.now()),i=fo({locale:e.language,now:o});let c=null,l=null,d=null;const g=()=>{d?.stop(),d=null,l?.getTracks().forEach(_=>_.stop()),l=null};return{cursor:i,lastInterruption(){return c},micStream(){return l},get available(){return e.enabled&&typeof RTCPeerConnection<"u"},async start({onEvent:_}){a=_;const h={"Content-Type":"application/json","X-API-Key":e.apiKey},u=e.getJwt?.()??e.jwt;u&&(h.Authorization=`Bearer ${u}`);const f=e.getSessionId?.()??null,b=await fetch(`${e.baseUrl}/api/widget/realtime-voice`,{method:"POST",headers:h,body:JSON.stringify({language:e.language,...f?{sessionId:f}:{}})});if(!b.ok)throw new Error("eleven token refused");const j=await b.json(),v=j.data?.token;if(j.data?.provider!=="elevenlabs"||!v)throw new Error("not an elevenlabs session");j.data?.sessionId&&e.onSessionId?.(j.data.sessionId);const x=j.data?.endUserToken??"",{Conversation:A}=await(e.loadSdk?e.loadSdk():ja(()=>import("./index-B23y2jUJ-BaO0_6Gs.js"),[])),[U,I]=await ie(()=>(e.getMicStream??ko)());if(I)throw new jn(yo(I),I);l=U,d=ho(U);let y=!1,$=null;const S=.6,O=.35;let X=!1,D=null;const te=T=>{T!==y&&(y=T,D=T&&X?o():null,a?.({type:"user_speaking",active:T}))};let R="";const M=T=>{const E=T?.trim();E&&(te(!1),i.endUtterance(),a?.({type:"thinking"}),E!==R&&(R=E,e.onUserTurnEnd?.()))},Q={conversationToken:v,connectionType:"webrtc",inputStream:l,customLlmExtraBody:{end_user_token:x},onModeChange:({mode:T})=>{X=T==="speaking",T==="speaking"?i.noteSpeaking():i.noteListening(),a?.(T==="speaking"?{type:"agent_delta",text:""}:{type:"agent_done"})},onAudioAlignment:T=>i.addAlignment(T),onVadScore:({vadScore:T})=>{T>=S?($&&(clearTimeout($),$=null),te(!0)):T<=O&&y&&!$&&($=setTimeout(()=>{$=null,te(!1)},600))},onMessage:({message:T,role:E})=>{const L=T?.trim();L&&(E==="user"?M(L):(e.onTranscript({role:"assistant",text:L,streaming:!1}),R=""))},onIncomingEvent:T=>{T?.type==="user_transcript"&&M(T.user_transcription_event?.user_transcript)},onAgentTyping:()=>a?.({type:"thinking"}),onAgentChatResponsePart:T=>{const E=T?.text??"";E&&e.onTranscript({role:"assistant",text:E,streaming:!0})},onInterruption:()=>{const T=o(),E=D;D=null,X=!1,i.endUtterance(),a?.({type:"interrupted"});const L=i.words()===null;c={bargeInToSignalMs:E===null?null:rn(T-E),signalToClearMs:rn(o()-T),cleared:L},console.info("[voice] interruption latency",c)},onError:T=>{console.warn("[voice] eleven blad:",T),a?.({type:"error",kind:"connection",message:"voice_conv.error_connection"})},onDisconnect:()=>{a?.({type:"error",kind:"connection",message:"voice_conv.error_connection"})}},[z,H]=await ie(()=>A.startSession(Q));if(H)throw g(),H;s=z},setMuted(_){s?.setMicMuted?.(_)},getInputLevel(){return d?.getLevel()??s?.getInputVolume?.()??null},getOutputLevel(){return s?.getOutputVolume?.()??null},sendUserMessage(_){const h=_.trim();return!h||!s||(i.endUtterance(),s.sendUserActivity?.(),!s.sendUserMessage)?!1:(s.sendUserMessage(h),a?.({type:"thinking"}),e.onUserTurnEnd?.(),!0)},stop(){a=null,i.dispose(),g();const _=s;s=null,_?.endSession()}}}function wo({eleven:e,scribe:s}){let a=!1,o=!0,i=!1,c=0,l=0;const d=g=>{switch(g.type){case"agent_delta":a=!0;return;case"agent_done":case"interrupted":case"error":a=!1;return;case"thinking":o=!1;return;case"user_speaking":g.active&&(o=!0);return;default:return}};return{get available(){return e.available},async start({agentId:g,onEvent:_}){const h=++c,u=l,f=()=>l!==u,b=()=>c!==h;if(await e.start({agentId:g,onEvent:v=>{d(v),_(v)}}),b())return;if(f()){e.stop();return}if(!s?.available)return;const[,j]=await ie(s.start({agentId:g,onEvent:v=>{v.type==="user_partial"&&(!o||a||_(v))}}));if(!b()){if(f()){j||s.stop(),e.stop();return}i=!j}},stop(){l+=1,i&&s?.stop(),i=!1,a=!1,o=!0,e.stop()},getInputLevel(){return e.getInputLevel?.()??null},getOutputLevel(){return e.getOutputLevel?.()??null}}}function jo(e,s=Math.random){const a=[...new Set(e.filter(c=>c.trim().length>0))];let o=[],i=null;return{draw(){if(a.length===0)return null;o.length===0&&(o=[...a]);let c=Math.min(o.length-1,Math.max(0,Math.floor(s()*o.length)));o.length>1&&o[c]===i&&(c=(c+1)%o.length);const[l]=o.splice(c,1);return i=l??null,i},remaining(){return o.length}}}function No(){let e=!1,s=!1,a={aborted:!1};const o=[],i=()=>{for(;o.length>0;)o.shift()?.()};return{ackPlaying(){return e},canStartAck(){return!e&&!s},async runAck(c){if(e||s)return!1;e=!0;const l=a;try{await c(l)}finally{e=!1,i()}return!0},whenIdle(){return e?new Promise(c=>o.push(c)):Promise.resolve()},noteAgentSpeaking(){s=!0},reset(){s=!1,a={aborted:!1}},abort(){a.aborted=!0,a={aborted:!1},s=!1}}}const So=2e3,Co=3,Ro=new Set([400,403]),Et=nr("voice-ack");function Io(e){const s=e.fetchImpl??((...R)=>fetch(...R)),a=e.createSink??xn,o=e.setTimeoutImpl??((R,M)=>setTimeout(R,M)),i=e.clearTimeoutImpl??(R=>clearTimeout(R)),c=No();let l=null,d=new Map,g=null,_=!1,h=!1,u=null,f=0,b=null,j=null,v=!1,x=null;const A=new Set;let U=0,I=0;const y=(R,M={})=>{Et.warn(R,{language:e.language,...M,report:!1})},$=()=>{const R=e.getJwt();return{"Content-Type":"application/json",...e.apiKey?{"X-API-Key":e.apiKey}:{},...R?{Authorization:`Bearer ${R}`}:{}}},S=(R,M)=>new Promise(Q=>{if(R.byteLength<2){Q();return}x??(x=a(M));const z=x;let H=!1,T=null,E=null;const L=()=>{H||(H=!0,T?.(),A.delete(L),E!==null&&i(E),Q())};T=z.on("ended",L),A.add(L);const ae=R.byteLength/2/M*1e3;E=o(L,ae+So),z.reset(),z.push(R)}),O=async()=>{const R=I,[M,Q]=await ie(s(`${e.baseUrl}/api/widget/voice-ack`,{method:"POST",headers:$(),body:JSON.stringify({language:e.language})}));if(R!==I)return;if(Q||!M){y("voice_ack.prepare_failed",{reason:"network"});return}if(!M.ok){const L=Ro.has(M.status);L&&(h=!0),y("voice_ack.prepare_failed",{reason:"http",status:M.status,permanent:L});return}const[z]=await ie(M.json());if(R!==I)return;const H=z?.data?.acks??[],T=z?.data?.audioFormat;if(!T||T.encoding!=="pcm16"||!(T.sampleRateHz>0)){h=!0,y("voice_ack.prepare_failed",{reason:"unusable_format",encoding:T?.encoding??null,permanent:!0});return}const E=H.filter(L=>typeof L?.id=="string"&&typeof L?.text=="string"&&L.text.trim().length>0);if(E.length===0){h=!0,y("voice_ack.prepare_failed",{reason:"empty_pool",permanent:!0});return}d=new Map(E.map(L=>[L.text,L.id])),g=T,l=jo(E.map(L=>L.text)),_=!0,Et.debug("voice_ack.prepared",{language:e.language,acks:E.length})},X=async R=>{const M=Date.now(),[Q,z]=await ie(s(`${e.baseUrl}/api/widget/voice-ack/audio`,{method:"POST",headers:$(),body:JSON.stringify({language:e.language,id:R})}));if(z||!Q?.ok)return{bytes:null,reason:z?"audio_network":"audio_http",status:Q?.status??null,audioMs:Date.now()-M};const[H]=await ie(Q.arrayBuffer());return{bytes:H??null,reason:H?null:"audio_body",status:Q.status??null,audioMs:Date.now()-M}},D=()=>{if(b)return Promise.resolve();if(j)return j;if(!l||!g)return Promise.resolve();const R=l.draw(),M=R?d.get(R):void 0;if(!R||!M)return y("voice_ack.prefetch_failed",{reason:"pool_exhausted"}),Promise.resolve();const Q=I,z=(async()=>{const{bytes:H,reason:T,status:E,audioMs:L}=await X(M);if(Q!==I){y("voice_ack.prefetch_failed",{reason:"disposed",ackId:M,audioMs:L});return}if(!H){y("voice_ack.prefetch_failed",{reason:T,status:E,ackId:M,audioMs:L});return}b={text:R,id:M,bytes:H},Et.debug("voice_ack.prefetched",{language:e.language,ackId:M,audioMs:L})})().finally(()=>{j===z&&(j=null)});return j=z,z},te=async()=>{if(_||h)return;if(u)return u;const R=!!e.getJwt();if(R&&!v&&(f=0),f>=Co){y("voice_ack.prepare_skipped",{reason:"attempts_exhausted"});return}f+=1,v=R;const M=O().then(()=>D()).finally(()=>{u===M&&(u=null)});return u=M,M};return{ready(){return l!==null},prepare:te,async beginTurn(){const R=U,M=I;(!l||!g)&&await te(),!b&&j&&await j;const Q=g;if(!l||!Q){y("voice_ack.turn_skipped",{reason:"no_pool"});return}if(R!==U){y("voice_ack.turn_skipped",{reason:"superseded"});return}if(!c.canStartAck()){y("voice_ack.turn_skipped",{reason:"agent_already_speaking",warm:b!==null}),D();return}const z=b;b=null;const H=z!==null;let T=z,E=0;if(!T){const F=l.draw(),J=F?d.get(F):void 0;if(!F||!J){y("voice_ack.turn_skipped",{reason:"pool_exhausted"});return}const G=await X(J);if(E=G.audioMs,R!==U){y("voice_ack.turn_dropped",{reason:"superseded",ackId:J,audioMs:E,warm:H});return}if(!G.bytes){y("voice_ack.turn_dropped",{reason:G.reason,status:G.status,ackId:J,audioMs:E,warm:H});return}T={text:F,id:J,bytes:G.bytes}}const L=T;let ae=!1;await c.runAck(async F=>{if(F.aborted||R!==U){y("voice_ack.turn_dropped",{reason:"aborted_before_play",ackId:L.id,audioMs:E,warm:H});return}ae=!0,e.onAck(L.text),await S(L.bytes,Q.sampleRateHz)})?ae&&Et.debug("voice_ack.played",{language:e.language,ackId:L.id,audioMs:E,warm:H}):y("voice_ack.turn_dropped",{reason:"agent_spoke_first",ackId:L.id,audioMs:E,warm:H}),!ae&&M===I&&!b&&(b=L),D()},noteAgentSpeaking(){c.noteAgentSpeaking()},reset(){c.reset()},abort(){U+=1,c.abort(),x?.reset();for(const R of[...A])R()},dispose(){U+=1,I+=1,c.abort();for(const R of[...A])R();x?.close(),x=null,l=null,d=new Map,g=null,_=!1,h=!1,u=null,f=0,v=!1,b=null,j=null}}}function on({followUps:e,isNewest:s,isPending:a,hasQuickReplies:o,isSending:i,onSelect:c,t:l}){return!s||a||o||!e||e.length===0?null:t.jsx("div",{className:"es-sc__followups",role:"list","aria-label":l("support_chat.followups_aria"),"data-es-no-read":!0,children:e.map(d=>t.jsx("button",{type:"button",role:"listitem",disabled:i,className:"es-sc__suggestion es-sc__suggestion--followup",onClick:()=>c(d.message),children:d.label},d.message))})}const Eo={name:"",email:"",phone:"",fields:{}};function To(e,s){const a=[];for(const o of s){const i=(e.fields[o.key]??"").trim();i.length>0&&a.push({labelKey:`contact_request.field.${o.key}`,value:i})}for(const o of["name","email","phone"]){const i=e[o].trim();i.length>0&&a.push({labelKey:`contact_request.field.${o}`,value:i})}return a}let Ao=0;function Mo({purpose:e,onSubmit:s,onDismiss:a,sent:o,t:i}){const[c,l]=r.useState(Eo),[d,g]=r.useState("fill"),[_,h]=r.useState(!1),[u,f]=r.useState(null),[b,j]=r.useState(null),v=r.useState(()=>`es-sc-contact-request-${Ao++}`)[0],x=r.useMemo(()=>fr(e),[e]),A=S=>`${v}-${S}`;if(r.useEffect(()=>{if(!b||typeof document>"u")return;const S=document.getElementById(A(b.key));S instanceof HTMLElement&&S.focus()},[b]),o)return t.jsx("div",{className:"es-sc__contact-request es-sc__contact-request--done",role:"status","aria-live":"polite","data-testid":"contact-request-done",children:t.jsx("span",{className:"es-sc__contact-request-text",children:i("contact_request.success")})});if(x.length===0)return null;const U=(S,O)=>l(X=>({...X,fields:{...X.fields,[S]:O}})),I=S=>j(O=>({key:S,nonce:(O?.nonce??0)+1})),y=()=>{const S=x.find(O=>O.required&&(c.fields[O.key]??"").trim().length===0);if(S){f(i("contact_request.validation_required")),I(S.key);return}if(c.email.trim().length===0&&c.phone.trim().length===0){f(i("contact_request.validation_contact")),I("email");return}f(null),g("review")},$=async()=>{if(_)return;h(!0),f(null);const S=await s({name:c.name.trim(),email:c.email.trim(),phone:c.phone.trim(),fields:Object.fromEntries(Object.entries(c.fields).map(([O,X])=>[O,X.trim()]))});h(!1),!S.ok&&(g("fill"),f(i("contact_request.error")),S.field&&I(S.field))};if(d==="review"){const S=To(c,x);return t.jsxs("div",{className:"es-sc__contact-request es-sc__contact-request--review","data-testid":"contact-request-review",children:[t.jsx("p",{className:"es-sc__contact-request-title",children:i("contact_request.review_title")}),t.jsx("dl",{className:"es-sc__contact-request-summary",children:S.map(O=>t.jsxs("div",{className:"es-sc__contact-request-summary-row",children:[t.jsx("dt",{children:i(O.labelKey)}),t.jsx("dd",{children:O.value})]},O.labelKey))}),t.jsx("p",{className:"es-sc__contact-request-consent",children:i("contact_request.consent")}),u&&t.jsx("p",{className:"es-sc__contact-request-error",role:"alert",children:u}),t.jsxs("div",{className:"es-sc__contact-request-actions",children:[t.jsx("button",{type:"button",className:"es-sc__contact-request-submit",disabled:_,"data-testid":"contact-request-send",onClick:$,children:i(_?"contact_request.sending":"contact_request.send")}),t.jsx("button",{type:"button",className:"es-sc__contact-request-dismiss","data-testid":"contact-request-back",onClick:()=>g("fill"),children:i("contact_request.back")})]})]})}return t.jsxs("form",{className:"es-sc__contact-request es-sc__contact-request--form","data-testid":"contact-request-form",noValidate:!0,onSubmit:S=>{S.preventDefault(),y()},children:[t.jsx("p",{className:"es-sc__contact-request-title",children:i(`contact_request.title.${e}`)}),t.jsx("p",{className:"es-sc__contact-request-text",children:i("contact_request.intro")}),x.map(S=>t.jsx(Lo,{id:A(S.key),spec:S,value:c.fields[S.key]??"",onChange:O=>U(S.key,O),t:i},S.key)),t.jsx(as,{id:A("name"),fieldKey:"name",type:"text",autoComplete:"name",maxLength:ss.name,value:c.name,onChange:S=>l(O=>({...O,name:S})),t:i}),t.jsx(as,{id:A("email"),fieldKey:"email",type:"email",autoComplete:"email",maxLength:ss.email,value:c.email,invalid:u!==null,errorId:A("error"),onChange:S=>l(O=>({...O,email:S})),t:i}),t.jsx(as,{id:A("phone"),fieldKey:"phone",type:"tel",autoComplete:"tel",maxLength:ss.phone,value:c.phone,onChange:S=>l(O=>({...O,phone:S})),t:i}),u&&t.jsx("p",{className:"es-sc__contact-request-error",id:A("error"),role:"alert",children:u}),t.jsxs("div",{className:"es-sc__contact-request-actions",children:[t.jsx("button",{type:"submit",className:"es-sc__contact-request-submit","data-testid":"contact-request-continue",children:i("contact_request.continue")}),t.jsx("button",{type:"button",className:"es-sc__contact-request-dismiss","data-testid":"contact-request-dismiss",onClick:a,children:i("contact_request.dismiss")})]})]})}function Lo({id:e,spec:s,value:a,onChange:o,t:i}){const c=i(`contact_request.field.${s.key}`);return t.jsxs(t.Fragment,{children:[t.jsx("label",{className:"es-sc__contact-request-label",htmlFor:e,children:s.required?i("contact_request.required_label",{label:c}):c}),s.kind==="textarea"?t.jsx("textarea",{id:e,"data-field":s.key,className:"es-sc__contact-request-input es-sc__contact-request-textarea",rows:3,maxLength:s.max,value:a,required:s.required,onChange:l=>o(l.target.value)}):t.jsx("input",{id:e,"data-field":s.key,className:"es-sc__contact-request-input",type:s.kind==="number"?"number":"text",...s.kind==="number"?{min:0,max:s.max}:{maxLength:s.max},value:a,required:s.required,onChange:l=>o(l.target.value)})]})}function as({id:e,fieldKey:s,type:a,autoComplete:o,maxLength:i,value:c,invalid:l,errorId:d,onChange:g,t:_}){return t.jsxs(t.Fragment,{children:[t.jsx("label",{className:"es-sc__contact-request-label",htmlFor:e,children:_(`contact_request.field.${s}`)}),t.jsx("input",{id:e,"data-field":s,className:"es-sc__contact-request-input",type:a,autoComplete:o,maxLength:i,value:c,...s==="email"?{"aria-invalid":l===!0,"aria-describedby":l?d:void 0}:{},onChange:h=>g(h.target.value)})]})}function qo(e,s){if(typeof e.page=="number")return s("support_chat.source_page",{page:String(e.page)});if(e.section)return e.section}function $o({sources:e,enabled:s,allowedLinkHosts:a,t:o}){return!s||!e||e.length===0?null:t.jsxs("div",{className:"es-sc__sources","data-testid":"support-chat-sources","data-es-no-read":!0,children:[t.jsx("div",{className:"es-sc__sources-heading",children:o("support_chat.sources_heading")}),t.jsx("ul",{className:"es-sc__sources-list",children:e.map((i,c)=>{const l=qo(i,o),d=i.url!==void 0&&Ka(i.url,a??[]),g=`${i.kind}:${i.title}:${i.section??""}:${i.page??""}:${c}`,_=t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"es-sc__source-title",children:i.title}),l&&t.jsx("span",{className:"es-sc__source-locator",children:l})]});return t.jsx("li",{className:"es-sc__source",children:d?t.jsx("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",className:"es-sc__source-chip es-sc__source-chip--link",children:_}):t.jsx("span",{className:"es-sc__source-chip",children:_})},g)})})]})}function Po(e){switch(e){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"}}function Uo(e,s){return Xa(e)?s(`languages.${e}`):e.toUpperCase()}const rs={email:254,phone:32,note:2e3},Oo={email:"",phone:"",note:""};function Do(e){const[s,a]=r.useState(()=>Date.now());return r.useEffect(()=>{if(e===null)return;const o=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(o)},[e]),e===null?null:Math.max(0,Math.ceil((e-s)/1e3))}function Bo({status:e,onSubmitContact:s,onDismiss:a,onChooseLanguage:o,autoReadAloud:i,onToggleAutoReadAloud:c,onResumeVoice:l,t:d}){const[g,_]=r.useState(Oo),[h,u]=r.useState(!1),[f,b]=r.useState(null),j=r.useRef(null),v=Do(e.kind==="waiting"?e.until:null);return r.useEffect(()=>{e.kind==="unavailable"&&j.current?.focus()},[e.kind]),e.kind==="idle"?null:e.kind==="choose_language"?t.jsxs("div",{className:"es-sc__handoff es-sc__handoff--languages",children:[t.jsx("p",{className:"es-sc__handoff-title",id:"es-sc-handoff-language-prompt",children:d("support_chat.handoff.language_prompt")}),t.jsxs("div",{className:"es-sc__handoff-actions",role:"group","aria-labelledby":"es-sc-handoff-language-prompt",children:[e.options.map(x=>t.jsx("button",{type:"button",className:"es-sc__handoff-language","data-language":x,onClick:()=>o(x),children:Uo(x,d)},x)),t.jsx("button",{className:"es-sc__handoff-dismiss",type:"button",onClick:a,children:d("support_chat.handoff.contact_dismiss")})]})]}):e.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:v===null?d("support_chat.handoff.queued"):d("support_chat.handoff.waiting",{seconds:v})})]}):e.kind==="human"?t.jsxs("div",{className:"es-sc__handoff es-sc__handoff--human",role:"status","aria-live":"polite",children:[t.jsx("span",{className:"es-sc__handoff-text",children:e.displayName?d("support_chat.handoff.human_joined",{name:e.displayName}):d("support_chat.handoff.human_joined_unnamed")}),i!==null&&t.jsxs("label",{className:"es-sc__handoff-readaloud",children:[t.jsx("input",{type:"checkbox",checked:i,onChange:c,"data-testid":"handoff-read-aloud-toggle"}),t.jsx("span",{children:d("support_chat.read_aloud_auto")})]})]}):e.kind==="returned"?t.jsxs("div",{className:"es-sc__handoff es-sc__handoff--returned",role:"status","aria-live":"polite",children:[t.jsx("span",{className:"es-sc__handoff-text",children:e.displayName?d("support_chat.handoff.human_left",{name:e.displayName}):d("support_chat.handoff.human_left_unnamed")}),l&&t.jsx("button",{type:"button",className:"es-sc__handoff-resume-voice","data-testid":"handoff-resume-voice",onClick:l,children:d("voice_conv.start")})]}):e.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:d("support_chat.handoff.contact_success")})}):t.jsxs("form",{className:"es-sc__handoff es-sc__handoff--form",onSubmit:async x=>{if(x.preventDefault(),h)return;if(g.email.trim().length===0&&g.phone.trim().length===0){b(d("support_chat.handoff.contact_validation")),j.current?.focus();return}u(!0),b(null);const A=await s({email:g.email.trim(),phone:g.phone.trim(),note:g.note.trim()});u(!1),A||b(d("support_chat.handoff.contact_error"))},noValidate:!0,children:[t.jsx("p",{className:"es-sc__handoff-title",children:d(Po(e.reason))}),t.jsx("p",{className:"es-sc__handoff-text",children:d("support_chat.handoff.contact_prompt")}),t.jsx("label",{className:"es-sc__handoff-label",htmlFor:"es-sc-handoff-email",children:d("support_chat.handoff.contact_email_label")}),t.jsx("input",{id:"es-sc-handoff-email",ref:j,className:"es-sc__handoff-input",type:"email",autoComplete:"email",maxLength:rs.email,value:g.email,"aria-invalid":f!==null,"aria-describedby":f?"es-sc-handoff-error":void 0,onChange:x=>_(A=>({...A,email:x.target.value}))}),t.jsx("label",{className:"es-sc__handoff-label",htmlFor:"es-sc-handoff-phone",children:d("support_chat.handoff.contact_phone_label")}),t.jsx("input",{id:"es-sc-handoff-phone",className:"es-sc__handoff-input",type:"tel",autoComplete:"tel",maxLength:rs.phone,value:g.phone,onChange:x=>_(A=>({...A,phone:x.target.value}))}),t.jsx("label",{className:"es-sc__handoff-label",htmlFor:"es-sc-handoff-note",children:d("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:rs.note,value:g.note,onChange:x=>_(A=>({...A,note:x.target.value}))}),f&&t.jsx("p",{className:"es-sc__handoff-error",id:"es-sc-handoff-error",role:"alert",children:f}),t.jsxs("div",{className:"es-sc__handoff-actions",children:[t.jsx("button",{className:"es-sc__handoff-submit",type:"submit",disabled:h,children:d("support_chat.handoff.contact_submit")}),t.jsx("button",{className:"es-sc__handoff-dismiss",type:"button",onClick:a,children:d("support_chat.handoff.contact_dismiss")})]})]})}function Ko({onAnswer:e,onDismiss:s,t:a}){const[o,i]=r.useState(!1),[c,l]=r.useState(!1),d=async g=>{o||(i(!0),l(!1),await e(g)||(l(!0),i(!1)))};return t.jsxs("section",{className:"es-sc__outcome","data-testid":"support-chat-outcome-prompt","aria-label":a("support_chat.outcome.aria_label"),children:[t.jsx("p",{className:"es-sc__outcome-title",children:a("support_chat.outcome.question")}),t.jsxs("div",{className:"es-sc__outcome-actions",children:[t.jsx("button",{type:"button",className:"es-sc__outcome-btn es-sc__outcome-btn--yes",onClick:()=>{d(!0)},disabled:o,children:a("support_chat.outcome.yes")}),t.jsx("button",{type:"button",className:"es-sc__outcome-btn es-sc__outcome-btn--no",onClick:()=>{d(!1)},disabled:o,children:a("support_chat.outcome.no")}),t.jsx("button",{type:"button",className:"es-sc__outcome-dismiss",onClick:s,disabled:o,children:a("support_chat.outcome.dismiss")})]}),c&&t.jsx("p",{className:"es-sc__outcome-error",children:a("support_chat.outcome.failed")})]})}const Fo=9e4;function zo(e){return e.sessionId?e.hasAssistantReply?e.streaming?{ask:!1,reason:"streaming"}:e.handoffActive?{ask:!1,reason:"handoff_active"}:e.settledSessions.has(e.sessionId)?{ask:!1,reason:"already_settled"}:{ask:!0,sessionId:e.sessionId}:{ask:!1,reason:"no_reply"}:{ask:!1,reason:"no_session"}}const At="live:";function Le(e){return e.id.startsWith(At)}function Ho(e,s){return e.text!==s.text?!0:JSON.stringify(e.metadata??null)!==JSON.stringify(s.metadata??null)}function Jo(e,s){if(s.length===0)return e;const a=new Map;e.forEach((f,b)=>a.set(f.id,b));let o=null;const i=[];let c=!1;for(const f of s){const b=a.get(f.id);if(b===void 0){i.push(f),f.role==="assistant"&&(c=!0);continue}const j=e[b];Ho(j,f)&&(o??(o=[...e]),o[b]={...j,...f})}if(i.length===0)return o??e;const l=o??[...e],d=Xo(i),g=d?l.filter(f=>!d(f)):l,_=c?g.filter(Le):[],h=c?g.filter(f=>!Le(f)):g,u=h.filter(Le);return[...h.filter(f=>!Le(f)),...Qo(i,_),...u]}function Xo(e){const s=new Set;for(const a of e){if(a.role!=="user")continue;const o=a.text.trim();o&&s.add(o)}return s.size===0?null:a=>Le(a)&&a.role==="user"&&s.has(a.text.trim())}function Qo(e,s){let a;for(const c of s)c.ack&&(a=c.ack);if(!a)return e;const o=e.findIndex(c=>c.role==="assistant"&&!c.ack);if(o===-1)return e;const i=[...e];return i[o]={...i[o],ack:a},i}function Vo({transport:e,agentId:s,onUserMessage:a,onStopPlayback:o}){const[i,c]=r.useState("idle"),[l,d]=r.useState(null),[g,_]=r.useState(!1),[h,u]=r.useState(null),[f,b]=r.useState(null),j=r.useRef(a);j.current=a;const v=r.useRef(o);v.current=o;const x=r.useCallback(y=>{switch(y.type){case"user_partial":v.current(),d(y.text),c("listening");return;case"user_final":d(null),_(!1),c("listening"),y.text.trim()&&j.current(y.text);return;case"user_speaking":_(y.active),y.active&&(v.current(),c("listening"));return;case"thinking":d(null),_(!1),c("thinking");return;case"agent_delta":c("speaking");return;case"agent_done":c("listening");return;case"interrupted":v.current(),c("listening");return;case"error":u(y.message),b(y.kind),c("error");return}},[]),A=r.useCallback(async()=>{if(!e.available){u("voice_conv.unsupported_browser"),b("connection"),c("error");return}u(null),b(null),c("connecting"),v.current();const[,y]=await ie(e.start({agentId:s,onEvent:x}));if(y){const $=y instanceof jn?y:null,S=$?"mic_permission":Zr(y);u($?$.messageKey:eo(S)),b(S),c("error");return}c("listening")},[e,s,x]),U=r.useCallback(()=>{e.stop(),d(null),_(!1),u(null),b(null),c("idle")},[e]),I=r.useRef(e);return I.current=e,r.useEffect(()=>()=>I.current.stop(),[]),{state:i,draft:l,userSpeaking:g,error:h,errorKind:f,start:A,stop:U}}const Wo=.03,Yo=.5,Go=.8,Zo=45,ei=180,ti=.06,si=.6,ni=.45,ai=250,ri=.2,oi=300,ii=900,ci=3,li=100,ui=e=>e<0?0:e>1?1:e;function di({orbRef:e,mode:s,getLevel:a,fallbackActive:o}){const i=r.useRef(a);i.current=a;const c=r.useRef(o);c.current=o;const l=r.useRef(s);l.current=s,r.useEffect(()=>{const d=e.current;if(!d)return;const g=d.ownerDocument,_=g.defaultView;if(!_)return;let h=null,u=0,f=null,b=!0,j=0,v=Number.NEGATIVE_INFINITY,x=!1;const A=new Set,U=typeof _.matchMedia=="function"&&_.matchMedia("(prefers-reduced-motion: reduce)").matches,I=(D,te)=>{d.style.setProperty("--es-vm-lvl",D.toFixed(3)),d.dataset.quiet=te?"1":"0"},y=D=>{const te=d.querySelectorAll(".es-vm__orb-ripple");te.length>=ci&&te[0]?.remove();const R=g.createElement("span");R.className="es-vm__orb-ripple",d.appendChild(R),v=D;const M=setTimeout(()=>{A.delete(M),R.remove()},ii);A.add(M)},$=D=>{h=_.requestAnimationFrame($);const te=f===null?16:Math.min(D-f,li);f=D;const R=i.current;let M;if(R){const H=R()??0;M=ui((H-Wo)/Yo)**Go}else c.current?M=l.current==="speaking"?ni:si:M=0;const Q=M>u?Zo:ei;u+=(M-u)*(1-Math.exp(-te/Q));const z=b;b=u<ti,b?(z||(j=D),x=!1):z&&D-j>=ai&&(x=!0),x&&!U&&u>=ri&&D-v>=oi&&(x=!1,y(D)),I(u,b)},S=()=>{h===null&&(f=null,h=_.requestAnimationFrame($))},O=()=>{h!==null&&(_.cancelAnimationFrame(h),h=null),u=0,b=!0,j=0,x=!1,I(0,!0)};if(s==="off"){O();return}const X=()=>{g.visibilityState==="visible"?S():O()};return g.addEventListener("visibilitychange",X),g.visibilityState==="visible"?S():O(),()=>{g.removeEventListener("visibilitychange",X),O();for(const D of A)clearTimeout(D);A.clear();for(const D of d.querySelectorAll(".es-vm__orb-ripple"))D.remove()}},[s,e])}const fi=()=>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"})]}),Nn=()=>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"})]}),pi=()=>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"})}),mi=()=>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:"M2.5 9a15 15 0 0 1 5.2-3.1M13 5.2A15 15 0 0 1 21.5 9"}),t.jsx("path",{d:"M5.6 12.6a10.5 10.5 0 0 1 3-1.9M15.4 10.9a10.5 10.5 0 0 1 3 1.7"}),t.jsx("path",{d:"M8.8 16.2a5.5 5.5 0 0 1 5.6-.5"}),t.jsx("path",{d:"M12 20h.01"})]}),hi=()=>t.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("circle",{cx:"12",cy:"12",r:"8.5"}),t.jsx("path",{d:"M12 7.5V12l3 2"})]}),gi=()=>t.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("circle",{cx:"12",cy:"12",r:"8.5"}),t.jsx("path",{d:"M12 7.8v4.6M12 16.2h.01"})]}),_i={mic_permission:{Icon:Nn,titleKey:"voice_conv.denied_title",bodyKey:"voice_conv.denied_body",tone:"error"},connection:{Icon:mi,titleKey:"voice_conv.error_connection_title",bodyKey:"voice_conv.error_connection",tone:"warn"},stall:{Icon:hi,titleKey:"voice_conv.error_stall_title",bodyKey:"voice_conv.error_stall",tone:"warn"},unknown:{Icon:gi,titleKey:"voice_conv.error_title",bodyKey:"voice_conv.error_body",tone:"error"}},bi="voice_conv.error";function vi({running:e}){const[s,a]=r.useState(0);return r.useEffect(()=>{if(!e)return;const o=setInterval(()=>a(i=>i+1),1e3);return()=>clearInterval(o)},[e]),t.jsx("span",{className:"es-vm__elapsed","data-testid":"voice-mode-elapsed",children:yi(s)})}function yi(e){const s=Math.floor(e/60),a=e%60;return`${s}:${String(a).padStart(2,"0")}`}function ki({state:e,draft:s,error:a,errorKind:o,muted:i,listening:c,levelSource:l,hasTranscript:d,transcript:g,onToggleMute:_,onEnd:h,onRetry:u,t:f}){const b=s&&s.trim()?s:null,j=r.useRef(null);r.useEffect(()=>{const I=j.current;I&&(I.scrollTop=I.scrollHeight)},[g,b]);const v=i?"muted":e==="speaking"?"speaking":e==="thinking"?"thinking":"listening",x=e==="error"||v==="thinking"||v==="muted"?"off":v,A=r.useRef(null),U=r.useMemo(()=>{const I=l?.getInputLevel,y=l?.getOutputLevel;if(x==="listening"&&I)return()=>I()??null;if(x==="speaking"&&y)return()=>y()??null},[x,l]);if(di({orbRef:A,mode:x,getLevel:U,fallbackActive:!i&&(!!c||!!(s&&s.trim()))}),e==="error"){const I=_i[o??"unknown"],{Icon:y}=I,$=a&&a!==bi?a:I.bodyKey;return t.jsxs("div",{className:"es-vm","data-testid":"voice-mode","data-error-kind":o??void 0,children:[t.jsxs("div",{className:"es-vm__top",children:[t.jsx("span",{className:`es-vm__dot es-vm__dot--${I.tone}`}),t.jsx("span",{className:"es-vm__label",children:f("voice_conv.title")})]}),t.jsxs("div",{className:"es-vm__denied",role:"alert",children:[t.jsx("div",{className:`es-vm__denied-icon es-vm__denied-icon--${I.tone}`,children:t.jsx(y,{})}),t.jsxs("div",{children:[t.jsx("div",{className:"es-vm__denied-title","data-testid":"voice-mode-error-title",children:f(I.titleKey)}),t.jsx("div",{className:"es-vm__denied-body",children:f($)})]}),t.jsxs("div",{className:"es-vm__denied-actions",children:[t.jsx("button",{type:"button",className:"es-vm__action es-vm__action--primary",onClick:u,"data-testid":"voice-mode-retry",children:f("voice_conv.retry")}),t.jsx("button",{type:"button",className:"es-vm__action",onClick:h,"data-testid":"voice-mode-back",children:f("voice_conv.back_to_typing")})]})]})]})}return t.jsxs("div",{className:"es-vm","data-testid":"voice-mode","data-state":e,children:[t.jsxs("div",{className:"es-vm__top",children:[t.jsx("span",{className:"es-vm__label",children:f("voice_conv.title")}),t.jsx(vi,{running:e!=="idle"})]}),t.jsxs("div",{className:"es-vm__orbwrap",children:[t.jsxs("div",{className:"es-vm__orb","data-s":v,"data-quiet":"1","data-testid":"voice-mode-orb",ref:A,"aria-hidden":"true",children:[t.jsx("span",{className:"es-vm__orb-idle"}),t.jsx("span",{className:"es-vm__orb-glow"}),t.jsx("span",{className:"es-vm__orb-core"})]}),t.jsx("div",{className:"es-vm__orb-state",role:"status","data-testid":"voice-mode-state",children:f(`voice_conv.state_${v}`)}),t.jsx("div",{className:"es-vm__orb-hint",children:f(`voice_conv.state_${v}_hint`)})]}),t.jsxs("div",{className:"es-vm__transcript","data-testid":"voice-mode-transcript",ref:j,children:[d?g:null,b!==null&&t.jsx("div",{className:"es-sc__bubble es-sc__bubble--user es-vm__draft","data-testid":"voice-mode-draft",children:t.jsxs("div",{className:"es-sc__bubble-text","aria-live":"polite","aria-label":f("voice_conv.draft_aria"),children:[t.jsx("span",{className:"es-vm__draft-text",children:b}),t.jsx("span",{className:"es-vm__caret","aria-hidden":"true"})]})}),!d&&b===null&&t.jsx("div",{className:"es-vm__invite","data-testid":"voice-mode-invite",children:f("voice_conv.invite")})]}),t.jsxs("div",{className:"es-vm__controls",children:[t.jsx("button",{type:"button",className:`es-vm__btn${i?" es-vm__btn--on":""}`,"aria-label":f(i?"voice_conv.unmute":"voice_conv.mute"),onClick:_,"data-testid":"voice-mode-mute",children:i?t.jsx(Nn,{}):t.jsx(fi,{})}),t.jsx("button",{type:"button",className:"es-vm__btn es-vm__btn--end","aria-label":f("voice_conv.end"),onClick:h,"data-testid":"voice-mode-end",children:t.jsx(pi,{})})]})]})}function Sn(){return t.jsxs("span",{className:"es-vm__answer-wave","aria-hidden":"true",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]})}const xi=3;function wi({text:e,cursor:s,locale:a="en"}){const o=r.useRef(null),i=r.useMemo(()=>is(e,a)?.length??0,[e,a]),c=s&&i>=xi?s:null;return r.useEffect(()=>{const l=o.current;if(!c||!l)return;const d=gn({container:l}),g=l.ownerDocument,_=_n({currentTime:c.currentTime,words:c.words,onWord:h=>{if(h===null){d.paint(null);return}const u=Array.from(l.childNodes).find(j=>j.nodeType===3),f=u?.textContent?.length??0;if(!u||h.sourceStart<0||h.sourceEnd>f||h.sourceStart>=h.sourceEnd){d.paint(null);return}const b=g.createRange();b.setStart(u,h.sourceStart),b.setEnd(u,h.sourceEnd),d.paint(b)}});return _.start(),()=>{_.stop(),d.destroy()}},[c]),t.jsx("span",{className:"es-vm__ack-text",ref:o,children:e})}function ji({text:e,ack:s,allowedLinkHosts:a,cursor:o,ackCursor:i,locale:c}){if(!s)return t.jsx(ls,{text:e,allowedLinkHosts:a,cursor:o});const l=e.trim()!=="";return t.jsxs("div",{className:"es-sc__bubble-text es-vm__ackbubble","data-testid":"voice-ack-bubble",children:[t.jsxs("span",{className:"es-vm__ack-row",children:[t.jsx(wi,{text:s,cursor:l?null:i,...c?{locale:c}:{}}),!l&&t.jsx(Sn,{})]}),l&&t.jsx("div",{className:"es-vm__ans",children:t.jsx(ls,{text:e,allowedLinkHosts:a,cursor:o})})]})}const cn=/[.!?]+(?:['")\]]+)?(\s+)/g;function Ni(e){const s=[];let a=0;cn.lastIndex=0;let o;for(;o=cn.exec(e);){const i=o.index+o[0].length,c=e.slice(a,i),l=c.trim();if(l){const d=c.length-c.trimStart().length;s.push({text:l,start:a+d})}a=i}return{complete:s,remainder:e.slice(a)}}function Si(e,s,a){return e===void 0?a:e.map(o=>{const i=o.translations?.[s]?.trim();return i||o.translations?.[o.baseLanguage]?.trim()||(Object.values(o.translations??{}).find(l=>l?.trim())?.trim()??"")}).filter(o=>o.length>0)}function Ci({size:e=16}){return t.jsxs("svg",{width:e,height:e,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 Ri({size:e=18}){return t.jsxs("svg",{width:e,height:e,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 Ii({size:e=16}){return t.jsxs("svg",{width:e,height:e,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 Ei=["confirm_escalation","cancel_escalation","confirm_handoff","decline_handoff"],Ti="<followups>",Ai=/<followups>/i;function Mi(e){const s=e.search(Ai);if(s!==-1)return e.slice(0,s).trimEnd();const a=e.lastIndexOf("<");return a!==-1&&Ti.startsWith(e.slice(a).toLowerCase())?e.slice(0,a).trimEnd():e}const ln="offered-options",Li=/offered-options/i,qi=/[[(]\s*(?:\*{1,2}\s*)?$/,$i=16,Pi=8;function un(e,s){const a=e.slice(Math.max(0,s-$i),s),o=qi.exec(a);return s-(o?o[0].length:0)}function Ui(e){for(let s=ln.length-1;s>=Pi;s-=1)if(!(e.length<s)&&e.slice(e.length-s).toLowerCase()===ln.slice(0,s))return e.length-s;return-1}function Oi(e){const s=e.search(Li);if(s!==-1)return e.slice(0,un(e,s)).trimEnd();const a=Ui(e);return a!==-1?e.slice(0,un(e,a)).trimEnd():e}function dn(e){return e>=.6?"high":e>=.35?"medium":"low"}function Di(e){return/^https?:\/\//i.test(e)}function Bi(e){return e==="OUT_OF_HOURS"||e==="QUEUE_FULL"||e==="NO_OPERATOR"?e:null}function fn(e){const{metadata:s,...a}=e;return{...a,...s&&typeof s=="object"?s:{}}}function Ki(e){let s=null;const a=[];for(const o of e.split(`
2
+ `))o.startsWith("event:")?s=o.slice(6).trim():o.startsWith("data:")&&a.push(o.slice(5).trimStart());return{event:s,data:a.join(`
3
+ `)}}const Fi=12e4,pn=1500,zi=6e4,mn=1500,Hi=6e5,hn=120,Ji=25e3,Xi=600;function Qi({value:e,onChange:s,disabled:a,onPreviewChange:o,t:i}){const[c,l]=r.useState(null),d=e??0,g=!a&&c!==null?c:d,_=r.useRef(o);_.current=o;const h=r.useCallback(u=>{l(u),_.current?.(u)},[]);return r.useEffect(()=>{a&&h(null)},[a,h]),t.jsx("div",{className:"es-sc__rating",role:"radiogroup","aria-label":i("support_chat.rate_aria"),onMouseLeave:()=>!a&&h(null),children:[1,2,3,4,5].map(u=>{const f=u<=g;return t.jsx("button",{type:"button",role:"radio","aria-checked":u===d,"aria-label":i("support_chat.rate_star",{count:u}),disabled:a,onMouseEnter:()=>!a&&h(u),onFocus:()=>!a&&h(u),onBlur:()=>!a&&h(null),onClick:()=>!a&&s?.(u),className:`es-sc__rating-star${f?" es-sc__rating-star--filled":""}${a?" es-sc__rating-star--disabled":""}`,children:t.jsx("svg",{width:16,height:16,viewBox:"0 0 24 24",fill:f?"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"})})},u)})})}function Vi({messageId:e,readAloudEnabled:s,readAloud:a,onActivateReadAloud:o,showRating:i,rating:c,ratingPending:l,undoable:d,onRate:g,onUndo:_,t:h}){const[u,f]=r.useState(null),b=d===null&&(!!c||l),j=!!c||l;let v="",x;return d!==null?x=t.jsxs(t.Fragment,{children:[h("support_chat.rating_undo_toast",{rating:d})," ",t.jsx("button",{type:"button",className:"es-sc__rating-undo-btn",onClick:_,children:h("support_chat.rating_undo_button")})]}):u!==null&&!b?(v=" es-sc__bubble-footer-label--preview",x=h(`support_chat.rate_label_${u}`)):j?(v=" es-sc__bubble-footer-label--thanks",x=h("support_chat.feedback_thanks")):x=h("support_chat.rate_aria"),t.jsxs("div",{className:"es-sc__bubble-footer","data-es-no-read":!0,"aria-label":h("support_chat.rate_aria"),children:[s&&t.jsx(Vr,{id:e,session:a,onActivate:o,t:h}),i&&s&&t.jsx("span",{className:"es-sc__bubble-footer-sep","aria-hidden":"true"}),i&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`es-sc__bubble-footer-label${v}`,"aria-live":"polite",...d!==null?{role:"status"}:{},children:x}),t.jsx(Qi,{value:d??c??null,onChange:g,disabled:b,onPreviewChange:f,t:h})]})]})}function rc({config:e,actions:s,baseUrl:a,externalContext:o,productId:i,i18n:c,supportSessionId:l,supportLiveSocketConnected:d,auth:g,readOnly:_}){const h=_===!0,u=c?.t??(n=>n),f=o?.apiKey??"",b=r.useRef(g?.jwt);r.useEffect(()=>{b.current=g?.jwt},[g?.jwt]);const j=o?.voice,v=c?.currentLanguage??"en",x=!!j?.enabled&&(j?.languages??[]).includes(v),A=e.voiceConversationEnabled===!0,U=e.voiceReadAloudEnabled===!0,I=o?.voiceOutput,y=Yr({baseUrl:a,apiKey:f,getJwt:()=>b.current}),$=r.useRef(y);$.current=y;const S=U&&!!I?.enabled&&(I?.languages??[]).includes(v),O=r.useRef(0),X=r.useRef(null),D=o?.userContext??void 0,te=o?.resetSession??!1,R=o?.showTicketsTab??!1,M=Ct(e.welcomeMessage,v,{t:u,fallbackKey:"support_chat.welcome_message",enDefault:"Hi! How can I help you today?"}),Q=Ct(e.placeholder,v,{t:u,fallbackKey:"support_chat.input_placeholder",enDefault:"Ask a question..."}),z=e.showSuggestedQuestions??!0,H=Si(e.localizedSuggestedQuestions,v,e.suggestedQuestions??[]),T=e.escalationLabel||u("support_chat.escalation_label"),E=e.humanHandoffButton===!0,L=Ct(e.headerTitle,v,{t:u,fallbackKey:"support.title",enDefault:"Support"}),ae=Ct(e.disclaimer,v,{t:u,fallbackKey:"support_chat.disclaimer"}),F=e.allowedLinkHosts,J=r.useMemo(()=>Array.isArray(F)?F.filter(n=>typeof n=="string"):void 0,[F]),G=e.allowMediaEmbeds===!0,ce=e.citationsEnabled===!0,he=e.liveChatLanguages,je=r.useMemo(()=>Array.isArray(he)?he.filter(n=>typeof n=="string"&&n.length>0):[],[he]),fe=typeof e._draft=="string"?e._draft:void 0,Ne=e._autoSend===!0,pe=Array.isArray(e._quickChips)?e._quickChips:[],Ce=JSON.stringify(pe),[Y,Z]=r.useState([]);r.useEffect(()=>{if(!S)return;const n=y.activeId;if(n!==X.current&&(X.current=n,O.current=0),!n)return;const p=Y.find(k=>k.id===n);if(!p)return;const m=p.role==="assistant"&&p.refusalReason?u(`support_chat.refusal_${p.refusalReason}`,{productName:p.refusalProductName??""}):p.text??"";if(m.length>O.current){const k=O.current,w=m.slice(k),{complete:q,remainder:P}=Ni(w);if(q.length>0){O.current=m.length-P.length;for(const N of q)y.feed(n,N.text,v,k+N.start)}}if(!p.isPending){const k=O.current,w=m.slice(k),q=w.trim();q&&(y.feed(n,q,v,k+(w.length-w.trimStart().length)),O.current=m.length),y.finish(n)}},[Y,y,S,v]);const[qe,Ie]=r.useState(""),[re,se]=r.useState([]),[le,ve]=r.useState(!1),[Ge,Je]=r.useState(null),[Ze,mt]=r.useState(null),[ne,Fe]=r.useState(l??null),Xe=r.useRef(ne);Xe.current=ne;const Mt=e.photoUploadEnabled===!0,us=Kr({baseUrl:a,apiKey:f,getJwt:()=>b.current,sessionId:ne,...i?{productId:i}:{},enabled:Mt}),[ze,Lt]=r.useState(null),[ht,Cn]=r.useState(!1),[$e,ds]=r.useState(null),[Rn,fs]=r.useState(0),[Qe,In]=r.useState("open"),[En,et]=r.useState([]),[Tn,gt]=r.useState(!1),[xe,tt]=r.useState("chat"),[Pe,oe]=r.useState({kind:"idle"}),[ps,_t]=r.useState(!1),[ms,An]=r.useState(()=>new Set),[Mn,hs]=r.useState(()=>new Set),[Ln,gs]=r.useState(()=>new Set),Se=r.useRef(null),bt=r.useRef(te),_s=r.useRef(null),qt=r.useRef(!1),{containerRef:qn,isPinned:$n,scrollToBottom:Ue,stickToBottom:bs}=Ma(),ye=r.useRef(null),Ee=r.useRef(null),vt=r.useRef(null),yt=r.useRef(null);r.useEffect(()=>{bs()},[Y,bs]),r.useEffect(()=>()=>{Ee.current?.abort()},[]),r.useEffect(()=>{if(ze==null)return;const n=ze-Date.now();if(n<=0){Lt(null);return}const p=setTimeout(()=>Lt(null),n);return()=>clearTimeout(p)},[ze]),r.useEffect(()=>{if($e==null)return;const n=()=>{const m=$e-Date.now();if(m<=0){ds(null),fs(0);return}fs(Math.ceil(m/1e3))};n();const p=setInterval(n,1e3);return()=>clearInterval(p)},[$e]);const Ve=r.useRef(null),Oe=r.useCallback(()=>{Ve.current&&(Ve.current.cancelled=!0),Ve.current=null},[]);r.useEffect(()=>s.on("support-chat:clearHistory",()=>{Ee.current?.abort(),Oe(),Z([]),Je(null),mt(null),ve(!1),Fe(null),yt.current=null,bt.current=!0}),[s,Oe]),r.useEffect(()=>{s.emit("support-chat:session",{sessionId:ne})},[s,ne]);const vs=r.useCallback((n,p,m)=>{Oe();const k={cancelled:!1};Ve.current=k;const w=m?.trim()?m:null,q=`resume-${crypto.randomUUID()}`;Z(ee=>[...ee,{id:q,role:"assistant",text:w??"",isPending:!w}]),Ue();const P=Date.now()+(w?6e3:zi),N=async()=>{if(k.cancelled)return;let ee=null;try{const C=b.current,B=await fetch(`${a}/api/support-chat/sessions/${n}/messages?limit=50`,{headers:{...f?{"X-API-Key":f}:{},...C?{Authorization:`Bearer ${C}`}:{}}});if(B.ok){const be=await B.json(),Me=be.success&&be.data?be.data.messages:[];for(let W=Me.length-1;W>=0;W--){const me=Me[W];if(me.role!=="assistant")continue;const K=me.createdAt?Date.parse(me.createdAt):NaN;if(Number.isFinite(K)&&K>p){ee=me;break}}}}catch{}if(!k.cancelled){if(ee){const C=ee.metadata??{},B=C.confidence,be=typeof B=="number"?dn(B):void 0;Z(Me=>Me.map(W=>W.id===q?{...W,id:ee.id,serverId:ee.id,promptLogId:ee.promptLogId??null,text:ee.content,isPending:!1,confidence:B,confidenceLevel:be,sources:C.sources&&C.sources.length>0?C.sources:void 0,actions:C.actions&&C.actions.length>0?C.actions:void 0,quickReplies:C.quickReplies&&C.quickReplies.length>0?C.quickReplies:void 0,ticketCards:C.ticketCards&&C.ticketCards.length>0?C.ticketCards:void 0,attachments:C.attachments&&C.attachments.length>0?C.attachments:void 0,sourceRefs:C.sourceRefs&&C.sourceRefs.length>0?C.sourceRefs:void 0,suggestedFollowUps:C.suggestedFollowUps&&C.suggestedFollowUps.length>0?C.suggestedFollowUps:void 0,awaitingConfirmation:C.awaitingConfirmation,contactRequest:C.contactRequest,refusalReason:C.refusalReason,refusalProductName:C.refusalProductName}:W)),Ue(),Ve.current=null;return}if(Date.now()>=P){w||Z(C=>C.map(B=>B.id===q?{...B,text:u("support_chat.error_message"),isPending:!1}:B)),Ve.current=null;return}setTimeout(N,pn)}};setTimeout(N,pn)},[f,a,Oe,Ue,u]),st=r.useCallback(async(n,p)=>{try{const m=b.current,k=await fetch(`${a}/api/support-chat/sessions/${n}/messages?limit=50`,{headers:{...f?{"X-API-Key":f}:{},...m?{Authorization:`Bearer ${m}`}:{}}});if(!k.ok)return;const w=await k.json();if(!w.success||!w.data)return;const q=w.data.messages.filter(C=>C.role==="user"||C.role==="assistant").map(C=>{const B=C.metadata??void 0,be=B?.ticketCards&&B.ticketCards.length>0?B.ticketCards:void 0;return{id:C.id,role:C.role,text:C.content,promptLogId:C.promptLogId??null,rating:C.userScore??null,...be?{ticketCards:be}:{},...B?.attachments&&B.attachments.length>0?{attachments:B.attachments}:{},...B?.sourceRefs&&B.sourceRefs.length>0?{sourceRefs:B.sourceRefs}:{},...B?.suggestedFollowUps&&B.suggestedFollowUps.length>0?{suggestedFollowUps:B.suggestedFollowUps}:{},...B?.contactRequest?{contactRequest:B.contactRequest}:{},...B?.refusalReason?{refusalReason:B.refusalReason,refusalProductName:B.refusalProductName}:{},...B?.author?.type==="human"?{humanAuthor:{...B.author.displayName?{displayName:B.author.displayName}:{}}}:{}}}),P=q.length-1,N=P>=0?q[P]:void 0;if(N&&N.role==="assistant"){const C=w.data.messages[w.data.messages.length-1]?.metadata;C?.quickReplies&&C.quickReplies.length>0&&(q[P]={...N,quickReplies:C.quickReplies,...C.awaitingConfirmation?{awaitingConfirmation:C.awaitingConfirmation}:{}})}Z(q),yt.current=n;const ee=w.data.messages[w.data.messages.length-1];if(ee&&ee.role==="user"){const C=ee.createdAt?Date.parse(ee.createdAt):NaN;Number.isFinite(C)&&Date.now()-C<Fi&&vs(n,C,p)}}catch{}},[f,a,vs]),Te=r.useCallback(async n=>{if(!R)return[];try{const p=b.current,m=await fetch(`${a}/api/widget/support-chat/tickets?status=${n}`,{headers:{...f?{"X-API-Key":f}:{},...p?{Authorization:`Bearer ${p}`}:{}}});if(!m.ok)return[];const k=await m.json();return k.data?.counts&&k.data?.tickets?k.data.tickets:[]}catch{return[]}},[a,f,R]);r.useEffect(()=>{let n=!1;return(async()=>{const p=await Te("open").catch(()=>[]);n||et(p)})(),()=>{n=!0}},[Te,g?.jwt]);const Pn=r.useCallback(async n=>{In(n),gt(!0);const p=await Te(n).catch(()=>[]);et(p),gt(!1)},[Te]),ys=r.useRef(!1);r.useEffect(()=>{ys.current||l&&g?.jwt&&(ys.current=!0,st(l))},[g?.jwt,l,st]),r.useEffect(()=>Oe,[Oe]),r.useEffect(()=>s.on("support-chat:select-session",n=>{const{sessionId:p}=n;tt("chat"),!(!p||p===yt.current)&&(Ee.current?.abort(),Z([]),Je(null),mt(null),ve(!1),Fe(p),st(p))}),[s,st]);const De=r.useCallback(()=>{const n=ye.current;if(!n)return;n.style.height="auto";const p=n.scrollHeight>hn;n.style.height=`${Math.min(n.scrollHeight,hn)}px`,n.style.overflowY=p?"auto":"hidden"},[]);r.useEffect(()=>{De()},[De]);const $t=r.useCallback((n,p)=>{const m=p.metadata??{},k=m.confidence,w=typeof k=="number"?dn(k):void 0;Z(q=>q.map(P=>P.id===n?{...P,id:p.id,serverId:p.id,promptLogId:p.promptLogId,rating:null,text:p.content,isPending:!1,confidence:k,confidenceLevel:w,sources:m.sources&&m.sources.length>0?m.sources:void 0,actions:m.actions&&m.actions.length>0?m.actions:void 0,quickReplies:m.quickReplies&&m.quickReplies.length>0?m.quickReplies:void 0,ticketCards:m.ticketCards&&m.ticketCards.length>0?m.ticketCards:void 0,attachments:m.attachments&&m.attachments.length>0?m.attachments:void 0,sourceRefs:m.sourceRefs&&m.sourceRefs.length>0?m.sourceRefs:void 0,suggestedFollowUps:m.suggestedFollowUps&&m.suggestedFollowUps.length>0?m.suggestedFollowUps:void 0,awaitingConfirmation:m.awaitingConfirmation,contactRequest:m.contactRequest,refusalReason:m.refusalReason,refusalProductName:m.refusalProductName}:P))},[]),ks=r.useCallback(n=>{Cn(!0),Z(p=>p.map(m=>m.id===n?{...m,role:"assistant",text:u("support_chat.demo_quota_reached"),isPending:!1}:m))},[u]),Pt=r.useCallback((n,p)=>{Lt(p??Date.now()+6e4),Z(m=>m.map(k=>k.id===n?{...k,role:"assistant",text:u("support_chat.daily_limit_reached"),isPending:!1}:k))},[u]),Ut=r.useCallback((n,p)=>{const m=typeof p=="number"&&p>0?p:6e4;ds(Date.now()+m);const k=Math.ceil(m/1e3);Z(w=>w.map(q=>q.id===n?{...q,role:"assistant",text:u("support_chat.rate_limited",{seconds:String(k)}),isPending:!1}:q))},[u]),xs=r.useCallback((n,p)=>{Z(m=>m.filter(k=>k.id!==n)),oe(p==="human"?{kind:"human",displayName:null}:{kind:"waiting",until:Se.current})},[]),[kt,Un]=r.useState("unset"),[On,Dn]=r.useState(!1),ws=r.useRef(new Set),Ot=kt==="unset"?On:kt==="on",js=r.useRef(Ot);js.current=Ot;const Dt=r.useRef(kt);Dt.current=kt;const Bn=r.useCallback(()=>{const n=js.current;n&&$.current?.stop(),Un(n?"off":"on")},[]),xt=r.useCallback(n=>{const p=n.messageId,m=n.content;if(!p||typeof m!="string"||!n.sessionId||n.sessionId!==Xe.current||ws.current.has(p))return;ws.current.add(p),Z(w=>w.some(q=>q.id===p||q.serverId===p)?w:[...w,{id:p,serverId:p,role:"assistant",text:m,humanAuthor:{...n.displayName?{displayName:n.displayName}:{}}}]),oe({kind:"human",displayName:n.displayName??null}),Ue();const k=n.voiceRequested===!0;Dn(k),(Dt.current==="unset"?k:Dt.current==="on")&&$.current?.activate(p)},[Ue]);r.useEffect(()=>s.on("support-chat:live-message",n=>{const p=n;p?.author?.type==="human"&&xt({sessionId:p.sessionId,messageId:p.messageId,content:p.content,displayName:p.author?.displayName,voiceRequested:p.voiceRequested===!0})}),[s,xt]),r.useEffect(()=>{if(Pe.kind!=="human"||d)return;const n=ne;if(!n)return;let p=!1,m;const k=Date.now()+Hi,w=async()=>{p||(await ie(async()=>{const q=b.current,P=await fetch(`${a}/api/support-chat/sessions/${n}/messages?limit=50`,{headers:{...f?{"X-API-Key":f}:{},...q?{Authorization:`Bearer ${q}`}:{}}});if(!P.ok)return;const N=await P.json(),ee=N.success&&N.data?N.data.messages:[];for(const C of ee)C.role!=="assistant"||C.metadata?.author?.type!=="human"||xt({sessionId:n,messageId:C.id,content:C.content,displayName:C.metadata?.author?.displayName,voiceRequested:C.metadata?.voiceRequested===!0})}),!(p||Date.now()>=k)&&(m=setTimeout(w,mn)))};return m=setTimeout(w,mn),()=>{p=!0,m&&clearTimeout(m)}},[Pe.kind,d,ne,a,f,xt]);const Be=r.useCallback(()=>{qt.current&&(qt.current=!1,s.emit("chat:draftConsumed",void 0))},[s]),ke=r.useCallback(async(n,p)=>{const m=n.trim();if(!m)return;Be(),Oe(),Ee.current?.abort(),Ee.current=new AbortController,Je(null),mt(null),Ie(""),oe(W=>W.kind==="returned"?{kind:"idle"}:W),se([]),ye.current&&(ye.current.style.height="auto");const k={id:`user-${crypto.randomUUID()}`,role:"user",text:m},w=`assistant-${crypto.randomUUID()}`,q={id:w,role:"assistant",text:"",isPending:!0};Z(W=>[...W,k,q]),Ue(),ve(!0),vt.current=w;const P=Date.now(),N=async()=>{const W=Xi-(Date.now()-P);W>0&&await new Promise(me=>setTimeout(me,W))};s.emit("support-chat:messageSent",{text:m});const[ee]=await ie(async()=>await g?.ensureValidToken?.()??null),C=ee??b.current,B={"Content-Type":"application/json",...f?{"X-API-Key":f}:{},...C?{Authorization:`Bearer ${C}`}:{}},be=bt.current||ne===null;let Me=!1;try{if(p?.quickReplyClick){const ue=await fetch(`${a}/api/widget/support-chat/message`,{method:"POST",headers:B,body:JSON.stringify({message:m,productId:i,...be?{newSession:!0}:{},...D?{userContext:fn(D)}:{},quickReplyClick:p.quickReplyClick}),signal:Ee.current.signal}),de=await ue.json();if(ue.status===429&&de?.error?.code==="DAILY_TOKEN_LIMIT_EXCEEDED"){await N(),Pt(w,de.error.resetAtMs);return}if(ue.status===429&&de?.error?.code==="DEMO_QUOTA_EXCEEDED"){await N(),ks(w);return}if(ue.status===429&&de?.error?.code==="RATE_LIMITED"){await N(),Ut(w,de.error.retryAfterMs);return}if(ue.status===409&&de?.error?.code==="HANDOFF_ACTIVE"){await N(),xs(w,de.data?.handoffState),de.data?.sessionId&&Fe(de.data.sessionId);return}if(!ue.ok||!de.success||!de.data)throw new Error(de.error?.message??`HTTP ${ue.status}`);Fe(de.data.sessionId),bt.current=!1,$t(w,de.data.assistantMessage),p.quickReplyClick.payload==="confirm_handoff"&&((de.data.assistantMessage.metadata?.toolCalls?.includes("request_human_handoff")??!1)||(oe({kind:"idle"}),Se.current=null)),Te(Qe).then(Yt=>et(Yt));return}let W;const me=()=>{W&&clearTimeout(W),W=setTimeout(()=>{Me=!0,Ee.current?.abort()},Ji)};me();const K=Ee.current;if(!K){clearTimeout(W);return}const[Ke,Qs]=await ie(async()=>{const ue=await fetch(`${a}/api/widget/support-chat/stream`,{method:"POST",headers:B,body:JSON.stringify({message:m,productId:i,...be?{newSession:!0}:{},...D?{userContext:fn(D)}:{}}),signal:K.signal});if(!ue.ok||!ue.body){const we=await ue.json().catch(()=>null);if(ue.status===429&&we?.error?.code==="DAILY_TOKEN_LIMIT_EXCEEDED")return{dailyLimitResetAtMs:we.error.resetAtMs};if(ue.status===429&&we?.error?.code==="DEMO_QUOTA_EXCEEDED")return{demoQuotaExhausted:!0};if(ue.status===429&&we?.error?.code==="RATE_LIMITED")return{rateLimitRetryAfterMs:we.error.retryAfterMs??6e4};if(ue.status===409&&we?.error?.code==="HANDOFF_ACTIVE")return we.data?.sessionId&&Fe(we.data.sessionId),{handoffState:we.data?.handoffState??null};throw new Error(we?.error?.message??`HTTP ${ue.status}`)}const de=ue.body.getReader(),Yt=new TextDecoder;let lt="",Vs="",Ws=!1;for(;;){const{done:we,value:ba}=await de.read();if(we)break;me(),lt+=Yt.decode(ba,{stream:!0});let Gt;for(;(Gt=lt.indexOf(`
4
+
5
+ `))!==-1;){const va=lt.slice(0,Gt);lt=lt.slice(Gt+2);const{event:ut,data:dt}=Ki(va);if(!(!ut||!dt)){if(ut==="start"){const Re=JSON.parse(dt);Re.sessionId&&(Fe(Re.sessionId),yt.current=Re.sessionId),bt.current=!1}else if(ut==="token"){const Re=JSON.parse(dt);Vs+=Re.value??"";const Zt=Mi(Oi(Vs));Z(ya=>ya.map(es=>es.id===w?{...es,text:Zt}:es))}else if(ut==="meta"){const Re=JSON.parse(dt);$t(w,Re.assistantMessage),Te(Qe).then(Zt=>et(Zt)),Ws=!0}else if(ut==="error"){const Re=JSON.parse(dt);if(Re.code==="HANDOFF_ACTIVE")return{handoffState:null};throw new Error(Re.message??"Stream error")}}}}if(!Ws)throw new Error("Stream ended before completion");return null});if(W&&clearTimeout(W),Qs)throw Qs;if(Ke&&"handoffState"in Ke){await N(),xs(w,Ke.handoffState);return}if(Ke?.dailyLimitResetAtMs!==void 0){await N(),Pt(w,Ke.dailyLimitResetAtMs);return}if(Ke?.demoQuotaExhausted){await N(),ks(w);return}if(Ke?.rateLimitRetryAfterMs!==void 0){await N(),Ut(w,Ke.rateLimitRetryAfterMs);return}}catch(W){if(W instanceof Error&&W.name==="AbortError"&&!Me){Z(me=>me.filter(K=>K.id!==w));return}await N(),Z(me=>me.filter(K=>K.id!==w)),vt.current===w&&(mt({text:m,options:p}),Je(u("support_chat.error_message")))}finally{vt.current===w&&ve(!1)}},[s,a,D,f,i,u,$t,Pt,Ut,Te,Qe,Ue,g,Oe,Be]),ge=j?.realtimeProvider==="elevenlabs",[Bt,nt]=r.useState([]),We=r.useRef(0),at=r.useRef([]);at.current=Bt;const Kt=r.useRef(null),Ft=r.useRef(null),Ns=r.useRef(new Set),zt=r.useRef(new Set),rt=r.useRef(!1),Ye=r.useRef(null),Ht=r.useRef(null),ot=r.useRef(!1),Ss=j?.realtime===!0,wt=r.useRef(o?.voiceStream);wt.current=o?.voiceStream;const Cs=r.useRef(o?.voiceSdkLoader);Cs.current=o?.voiceSdkLoader;const Rs=r.useMemo(()=>{if(ge){const n=Cs.current,p=xo({baseUrl:a,apiKey:f,...typeof n=="function"?{loadSdk:n}:{},getJwt:()=>b.current,language:v,enabled:!0,getSessionId:()=>Xe.current,onSessionId:k=>{Ft.current=k,Fe(k)},onUserTurnEnd:()=>Ye.current?.(),onTranscript:k=>nt(w=>{const q=w[w.length-1];if(!(q&&Le(q)&&q.streaming&&q.role===k.role)){We.current+=1;const N=`${At}${We.current}`;return[...w,{id:N,role:k.role,text:k.text,streaming:k.streaming}]}const P=k.role==="assistant"&&k.streaming?q.text+k.text:k.text;return[...w.slice(0,-1),{...q,text:P,streaming:k.streaming}]})}),m=wt.current?nn({voiceStream:wt.current,language:v,getInputStream:()=>p.micStream()}):null;return{transport:wo({eleven:p,scribe:m}),eleven:p}}return{transport:nn({voiceStream:wt.current,language:v}),eleven:null}},[ge,a,f,v]),Jt=Rs.transport,Is=Rs.eleven;Kt.current=Is;const Xt=ge?Is?.cursor??null:null,V=Vo({transport:Jt,agentId:o?.voiceAgentId??"",onUserMessage:n=>{ke(n)},onStopPlayback:()=>$.current?.stop()}),jt=V.state!=="idle"&&V.state!=="error",Es=r.useRef(null),Ts=r.useCallback(n=>{if(!n.sessionId||n.sessionId!==Xe.current||typeof n.version!="number"||!Number.isFinite(n.version))return;const p=Es.current;if(!(p&&p.sessionId===n.sessionId&&n.version<=p.version))switch(Es.current={sessionId:n.sessionId,version:n.version},n.state){case"waiting":oe(m=>m.kind==="waiting"?m:{kind:"waiting",until:Se.current});return;case"human":oe(m=>m.kind==="human"?m:{kind:"human",displayName:null});return;case"returned":Se.current=null,oe(m=>({kind:"returned",displayName:m.kind==="human"?m.displayName:null}));return;case"expired":Se.current=null,oe(m=>m.kind==="waiting"?{kind:"unavailable",reason:null}:{kind:"idle"});return;case"declined":case"cancelled":Se.current=null,oe({kind:"idle"});return;default:return}},[]);r.useEffect(()=>s.on("support-chat:live-handoff",n=>{Ts(n)}),[s,Ts]);const Qt=Pe.kind==="waiting"||Pe.kind==="human",[Kn,As]=r.useState(!1),Ms=r.useRef(V.stop);Ms.current=V.stop,r.useEffect(()=>{!Qt||!jt||(As(!0),Ms.current())},[Qt,jt]);const Ls=A&&Jt.available&&(ge||Ss||x),Fn=r.useCallback(()=>{As(!1),oe({kind:"idle"}),V.start()},[V]),_e=V.state!=="idle",qs=r.useRef(!1);r.useEffect(()=>{const n=qs.current;if(qs.current=_e,!_e){const p=(()=>{const m=at.current;for(let k=m.length-1;k>=0;k-=1){const w=m[k];if(w&&w.role==="assistant"&&w.text?.trim())return w.text}return null})();if(nt([]),n){const m=Ft.current??ne;m&&st(m,p??void 0)}}},[_e]),r.useEffect(()=>{try{window.dispatchEvent(new CustomEvent("es-support-voice-mode",{detail:{active:_e}}))}catch{}},[_e]),r.useEffect(()=>{if(!ge||!_e){Ns.current=new Set,zt.current=new Set,rt.current=!1,Ye.current=null;return}let n=!1,p=!1;ot.current=!1;const m=async(P=!1)=>{const N=Ft.current??ne;if(!N||n)return!1;const ee=b.current;let C=null;try{const K=await fetch(`${a}/api/support-chat/sessions/${N}/messages?limit=30`,{headers:{...f?{"X-API-Key":f}:{},...ee?{Authorization:`Bearer ${ee}`}:{}}});if(!K.ok)return!1;C=await K.json()}catch{return!1}if(n)return!1;const B=C?.data?.messages??[],be=Ns.current;if(!rt.current){if(!P)return!1;for(const K of B)K.id&&zt.current.add(K.id),K.role==="user"&&K.id&&be.add(K.id);return rt.current=!0,!1}const Me=zt.current,W=B.filter(K=>K.id&&K.content?.trim()&&(K.role==="user"||K.role==="assistant")&&!Me.has(K.id)).map(K=>({id:K.id,role:K.role,text:K.content,...K.metadata?{metadata:K.metadata}:{}}));if(W.length===0)return!1;nt(K=>Jo(K,W));const me=W.filter(K=>K.role==="user"&&!be.has(K.id));if(me.length===0)return!1;for(const K of me)be.add(K.id);return ot.current=!0,!0},k=async()=>{if(!(p||n)){p=!0;for(let P=0;P<10&&!n&&!await m(!1);P++)await new Promise(N=>setTimeout(N,500));p=!1}};let w=0;const q=5e3;return Ye.current=()=>{if(ot.current)return;const P=Date.now();P-w<q||(w=P,k())},Ht.current=async()=>{for(let P=0;P<6&&!n;P+=1){if(await m(!1),!at.current.some(Le))return;await new Promise(N=>setTimeout(N,700))}},(async()=>{for(let P=0;P<4&&!n&&!rt.current;P+=1){if(await m(!0),rt.current)return;await new Promise(N=>setTimeout(N,300))}})(),()=>{n=!0,Ye.current=null,Ht.current=null}},[ge,_e,ne,a,f]);const Ae=r.useRef(null),it=r.useRef(!1),$s=r.useCallback(n=>{nt(p=>{const m=p[p.length-1];return m&&Le(m)&&m.role==="assistant"&&m.streaming?m.ack?p:[...p.slice(0,-1),{...m,ack:n}]:(We.current+=1,[...p,{id:`${At}${We.current}`,role:"assistant",text:"",streaming:!0,ack:n}])})},[]);r.useEffect(()=>{if(!ge||!_e)return;const n=Io({baseUrl:a,apiKey:f,getJwt:()=>b.current,language:v,onAck:$s});return Ae.current=n,it.current=!1,n.prepare(),()=>{Ae.current=null,n.dispose()}},[ge,_e,a,f,v,$s]),r.useEffect(()=>{!ge||!_e||!g?.jwt||Ae.current?.prepare()},[ge,_e,g?.jwt]);const Ps=r.useRef(!1);r.useEffect(()=>{const n=Ps.current;Ps.current=V.userSpeaking,!n&&V.userSpeaking&&(ot.current=!1,Ae.current?.abort(),Ae.current?.reset(),it.current=!1),n&&!V.userSpeaking&&Ye.current?.()},[V.userSpeaking]);const Us=r.useRef(V.state);r.useEffect(()=>{const n=Us.current;Us.current=V.state,(V.state==="thinking"||V.state==="speaking")&&!(n==="thinking"||n==="speaking")&&Ye.current?.(),V.state==="speaking"&&Ae.current?.noteAgentSpeaking(),V.state==="thinking"&&n!=="thinking"&&!it.current&&(it.current=!0,Ae.current?.beginTurn())},[V.state]);const ct=r.useRef(null);r.useEffect(()=>{if(!ge||!_e)return;const n=at.current[at.current.length-1];if(!(!n||!Le(n)||n.role!=="assistant"||!n.text.trim()))return ct.current&&clearTimeout(ct.current),ct.current=setTimeout(()=>{Ht.current?.()},900),()=>{ct.current&&clearTimeout(ct.current)}},[Bt,ge,_e]);const[Os,zn]=r.useState(!1),[Hn,Ds]=r.useState(!1),Jn=r.useCallback(n=>{if(ot.current=!1,Ae.current?.abort(),Ae.current?.reset(),it.current=!1,!Kt.current?.sendUserMessage(n))return;Ds(!0);const p=n.trim();if(!p)return;We.current+=1;const m=`${At}${We.current}`;nt(k=>[...k,{id:m,role:"user",text:p}])},[]);r.useEffect(()=>{(V.state==="thinking"||V.state==="speaking")&&Ds(!1)},[V.state]);const He=ge?Bt.map(n=>({key:n.id,role:n.role,text:n.text,...n.metadata?{metadata:n.metadata}:{},...n.streaming?{streaming:!0}:{},...n.ack?{ack:n.ack}:{}})):Y.map(n=>{const p=n.role==="assistant"&&n.refusalReason?u(`support_chat.refusal_${n.refusalReason}`,{productName:n.refusalProductName??""}):n.text;return p?{key:n.id,role:n.role==="assistant"?"assistant":"user",text:p,confidence:n.confidenceLevel}:null}).filter(n=>n!==null),Xn=ge&&_e&&He.length>0&&He[He.length-1].role==="user",Bs=ge?[...He].reverse().find(n=>n.role==="assistant"):void 0,Qn=Bs?.key??null,Ks=Bs?.text??"";r.useEffect(()=>{Xt?.setSourceText(Ks)},[Xt,Ks]);const Vn=t.jsxs("div",{className:"es-sc__messages",children:[He.map((n,p)=>{const m=p===He.length-1;return t.jsxs("div",{className:`es-sc__bubble es-sc__bubble--${n.role}`,"data-confidence":n.confidence,children:[n.role==="assistant"?t.jsx(ji,{text:n.text,ack:n.ack,allowedLinkHosts:J,cursor:n.key===Qn?Xt:null,locale:v}):t.jsx("div",{className:"es-sc__bubble-text",children:n.text}),n.role==="assistant"&&t.jsx(on,{followUps:n.metadata?.suggestedFollowUps,isNewest:m,isPending:!!n.streaming,hasQuickReplies:!!n.metadata?.quickReplies?.length,isSending:Hn,onSelect:Jn,t:u})]},n.key)}),Xn?t.jsx("div",{className:"es-vm__answer-pending",role:"status","aria-label":u("voice_conv.thinking"),children:t.jsx(Sn,{})}):null]}),Fs=r.useRef(null);r.useEffect(()=>{if(Ss||!jt||!y||!S)return;const n=Y[Y.length-1];!n||n.role!=="assistant"||Fs.current!==n.id&&(Fs.current=n.id,y.activate(n.id))},[Y,jt,y,S]);const Vt=r.useCallback(()=>{const n=o?.voiceStream;n?.getState&&n.getState()!=="idle"&&n.stop(),ke(qe)},[qe,ke,o]),Wn=r.useCallback(()=>{Ee.current?.abort(),ve(!1);const n=vt.current;n&&Z(p=>p.filter(m=>m.id!==n))},[]),Yn=r.useCallback(()=>{Ze&&ke(Ze.text,Ze.options)},[Ze,ke]),Gn=r.useCallback(n=>{if(n.autoSend){ke(n.message);return}se([]),Ie(""),Be(),ye.current&&(ye.current.style.height="auto",ye.current.focus())},[ke,Be]);r.useEffect(()=>{if(!(fe!==void 0||pe.length>0))return;const n=`${fe}${String(Ne)}${Ce}`;if(_s.current!==n){if(_s.current=n,qt.current=!0,Ne&&fe!==void 0){se([]),ke(fe);return}se(pe),fe!==void 0&&(Ie(fe),requestAnimationFrame(()=>{De(),ye.current?.focus()}))}},[fe,Ne,Ce,ke]),r.useEffect(()=>{const n=o?.voiceStream;n?.getState&&n.getState()!=="idle"&&n.stop()},[l]);const Zn=r.useCallback(n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),Vt())},[Vt]),ea=r.useCallback(n=>{Be(),Ie(n.target.value),De()},[De,Be]),ta=r.useCallback(()=>{Be(),Ie(""),ye.current&&(ye.current.style.height="auto",ye.current.focus())},[Be]),sa=r.useCallback(n=>{const p=n.trim();p&&(Ie(m=>m?`${m} ${p}`:p),requestAnimationFrame(()=>{De(),ye.current?.focus()}))},[De]),na=r.useCallback(n=>{s.emit("support-chat:escalated",{messageId:n})},[s]),zs=r.useRef(Y);r.useEffect(()=>{zs.current=Y},[Y]);const aa=r.useCallback(({messageId:n,rating:p},{keepalive:m})=>{const k=zs.current.find(w=>w.id===n);!k||!k.promptLogId||b.current&&(Z(w=>w.map(q=>q.id===n?{...q,rating:p,ratingPending:!0}:q)),(async()=>{const[w,q]=await ie(fetch(`${a}/api/widget/ai-feedback`,{method:"POST",keepalive:m,headers:{"Content-Type":"application/json",...f?{"X-API-Key":f}:{},Authorization:`Bearer ${b.current}`},body:JSON.stringify({promptLogId:k.promptLogId,rating:p})}));if(!q&&w.status===409){Z(P=>P.map(N=>N.id===n?{...N,rating:p,ratingPending:!1}:N));return}if(q||!w.ok){Z(P=>P.map(N=>N.id===n?{...N,rating:null,ratingPending:!1}:N));return}Z(P=>P.map(N=>N.id===n?{...N,rating:p,ratingPending:!1}:N)),s.emit("support-chat:feedbackSubmitted",{messageId:n,rating:p})})())},[s,f,a]),{pending:Hs,rate:Js,undo:ra}=La({submit:aa}),oa=r.useCallback((n,p)=>{const m=Y.find(k=>k.id===n);!m||!m.promptLogId||m.ratingPending||b.current&&Js(n,p)},[Y,Js]),ia=r.useCallback(()=>{tt("chat"),oe({kind:"idle"}),Se.current=null,hs(new Set),gs(new Set),s.emit("support-chat:clearHistory",void 0)},[s]),Wt=r.useCallback(async n=>{if(!ne)return;const p=b.current;try{const m=await fetch(`${a}/api/widget/support-chat/handoff/request`,{method:"POST",headers:{"Content-Type":"application/json",...f?{"X-API-Key":f}:{},...p?{Authorization:`Bearer ${p}`}:{}},body:JSON.stringify({sessionId:ne,productId:i,conversationLanguage:n})}),k=await m.json();if(!m.ok||!k.success){oe({kind:"idle"});return}if(k.data?.outcome==="unavailable"){oe({kind:"unavailable",reason:Bi(k.data.reason)});return}if(k.data?.outcome==="already_active"){oe(k.data.state==="human"?{kind:"human",displayName:null}:{kind:"waiting",until:Se.current});return}if(k.data?.outcome==="offered"){const w=k.data.acceptTimeoutSec;Se.current=typeof w=="number"?Date.now()+w*1e3:null,oe({kind:"waiting",until:Se.current})}}catch{oe({kind:"idle"})}},[f,a,i,ne]),ca=r.useCallback(()=>{const n=je.some(p=>p.toLowerCase()===v.toLowerCase());if(je.length===0||n){Wt(v);return}oe({kind:"choose_language",options:je})},[je,v,Wt]),la=r.useCallback(async n=>{if(!ne)return!1;const p=b.current;try{const m=await fetch(`${a}/api/widget/support-chat/handoff/contact`,{method:"POST",headers:{"Content-Type":"application/json",...f?{"X-API-Key":f}:{},...p?{Authorization:`Bearer ${p}`}:{}},body:JSON.stringify({sessionId:ne,productId:i,...n.email?{email:n.email}:{},...n.phone?{phone:n.phone}:{},...n.note?{note:n.note}:{}})}),k=await m.json();return!m.ok||!k.success?!1:(oe({kind:"contact_left"}),!0)}catch{return!1}},[f,a,i,ne]),ua=r.useCallback(async(n,p,m)=>{if(!ne)return{ok:!1};const k=b.current,[w,q]=await ie(fetch(`${a}/api/widget/support-chat/contact-request`,{method:"POST",headers:{"Content-Type":"application/json",...f?{"X-API-Key":f}:{},...k?{Authorization:`Bearer ${k}`}:{}},body:JSON.stringify({sessionId:ne,productId:i,purpose:p,...m.name?{name:m.name}:{},...m.email?{email:m.email}:{},...m.phone?{phone:m.phone}:{},fields:m.fields})}));if(q||!w)return{ok:!1};const[P]=await ie(w.json());return!w.ok||!P?.success?{ok:!1,...P?.error?.field?{field:P.error.field}:{}}:(hs(N=>new Set(N).add(n)),{ok:!0})},[f,a,i,ne]),da=r.useCallback(()=>{oe({kind:"idle"})},[]),Nt=r.useCallback(n=>{_t(!1),An(p=>{if(p.has(n))return p;const m=new Set(p);return m.add(n),m})},[]),fa=r.useCallback(async n=>{const p=Xe.current;if(!p)return!1;const m=b.current,[k,w]=await ie(fetch(`${a}/api/widget/support-chat/outcome`,{method:"POST",headers:{"Content-Type":"application/json",...f?{"X-API-Key":f}:{},...m?{Authorization:`Bearer ${m}`}:{}},body:JSON.stringify({sessionId:p,resolved:n})}));return w||!k.ok?!1:(Nt(p),!0)},[f,a,Nt]),pa=r.useCallback(()=>{const n=Xe.current;n?Nt(n):_t(!1)},[Nt]);r.useEffect(()=>{if(!zo({sessionId:ne,hasAssistantReply:Y.some(p=>p.role==="assistant"&&!p.isPending),streaming:Y.some(p=>p.isPending),handoffActive:Pe.kind!=="idle",settledSessions:ms}).ask){ps&&_t(!1);return}const n=setTimeout(()=>_t(!0),Fo);return()=>clearTimeout(n)},[ne,Y,Pe.kind,ms]);const St=r.useCallback(()=>{tt("tickets"),gt(!0),Te(Qe).then(n=>et(n)).catch(()=>{}).finally(()=>gt(!1))},[Te,Qe]),ma=r.useCallback(()=>{xe==="tickets"?tt("chat"):St()},[xe,St]),ha=r.useCallback(n=>{tt("chat"),s.emit("support-chat:select-session",{sessionId:n})},[s]);r.useEffect(()=>R?s.on("support-chat:showTickets",()=>{St()}):void 0,[s,St,R]);const ga=r.useCallback((n,p,m)=>{Z(q=>q.map(P=>P.id===n?{...P,quickReplyAnswered:p}:P));const k=Y.find(q=>q.id===n)?.awaitingConfirmation,w=Ei.includes(m);m==="confirm_handoff"&&oe({kind:"waiting",until:Se.current}),ke(p,{...w?{quickReplyClick:{payload:m,summary:k?.summary,details:k?.details??void 0,priority:k?.priority,sourceMessageId:n}}:{}})},[Y,ke]),_a=r.useCallback(()=>{s.emit("support-chat:showHistory",void 0)},[s]),Xs=Y.length===0;return _e?t.jsx(Ys,{blockType:"support-chat",children:t.jsx(ki,{state:V.state,draft:V.draft,error:V.error,errorKind:V.errorKind,muted:Os,listening:V.userSpeaking,levelSource:Jt,hasTranscript:He.length>0,transcript:Vn,onToggleMute:()=>{const n=!Os;zn(n),Kt.current?.setMuted(n)},onEnd:()=>V.stop(),onRetry:()=>{V.start()},t:u})}):t.jsxs(Ys,{blockType:"support-chat",children:[t.jsxs("div",{className:"es-sc__chat-header",children:[t.jsx("span",{className:"es-sc__chat-header-title",children:R&&xe==="tickets"?u("support_chat.tickets_view_title"):L}),t.jsxs("div",{className:"es-sc__chat-header-actions",children:[t.jsx("button",{type:"button",className:"es-sc__chat-action-btn","aria-label":u("support_chat.new_conversation_button"),title:u("support_chat.new_conversation_button"),onClick:ia,children:t.jsx(Ri,{size:18})}),t.jsx("button",{type:"button",className:"es-sc__chat-action-btn","aria-label":u("support_chat.history_button"),title:u("support_chat.history_button"),onClick:_a,children:t.jsx(Ci,{size:16})}),E&&xe==="chat"&&Pe.kind==="idle"&&t.jsx("button",{type:"button",className:"es-sc__chat-action-btn es-sc__chat-action-btn--label","aria-label":u("support_chat.handoff.button_label"),title:u("support_chat.handoff.button_label"),onClick:ca,children:u("support_chat.handoff.button_label")}),R&&t.jsx("button",{type:"button",className:`es-sc__chat-action-btn${xe==="tickets"?" es-sc__chat-action-btn--active":""}`,"aria-label":u("support_chat.tickets_tab_button"),title:u("support_chat.tickets_tab_button"),"aria-pressed":xe==="tickets",onClick:ma,children:t.jsx(Ii,{size:16})}),t.jsx(qa,{panelKey:"support-chat",baseUrl:a,apiKey:f||void 0,t:u})]})]}),t.jsx("div",{className:"es-block__body es-sc__body",ref:qn,children:R&&xe==="tickets"?t.jsx(Ar,{status:Qe,loading:Tn,tickets:En,onSelectStatus:Pn,onSelectSession:ha,t:u}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"es-sc__messages",children:[Xs&&t.jsx("div",{className:"es-sc__welcome",children:t.jsx("div",{className:"es-sc__welcome-text",children:M})}),Y.map((n,p)=>{const m=p===Y.length-1,k=n.role==="assistant"&&n.refusalReason?u(`support_chat.refusal_${n.refusalReason}`,{productName:n.refusalProductName??""}):n.text,w=Hs?.messageId===n.id?Hs.rating:null,q=!!(n.role==="assistant"&&!n.isPending&&n.text&&n.promptLogId&&b.current),P=n.role==="assistant"&&!!k&&(S||q);return t.jsxs("div",{className:`es-sc__bubble es-sc__bubble--${n.role}${P?" es-sc__bubble--with-footer":""}`,"data-confidence":n.confidenceLevel,children:[k&&(n.role==="assistant"?t.jsxs(t.Fragment,{children:[n.humanAuthor&&t.jsx("div",{className:"es-sc__human-author",children:n.humanAuthor.displayName?u("support_chat.human_author",{name:n.humanAuthor.displayName}):u("support_chat.human_author_unnamed")}),t.jsxs("div",{className:"es-sc__bubble-surface",children:[t.jsx(ls,{text:k,allowedLinkHosts:J,cursor:S&&y.activeId===n.id?y.cursor:null}),P&&t.jsx(Vi,{messageId:n.id,readAloudEnabled:S,readAloud:y,onActivateReadAloud:()=>y.activate(n.id),showRating:q,rating:n.rating??null,ratingPending:!!n.ratingPending,undoable:w,onRate:N=>oa(n.id,N),onUndo:ra,t:u})]}),t.jsx(jr,{text:k,allowEmbeds:G,allowedImageHosts:J,t:u}),n.attachments&&n.attachments.length>0&&t.jsx(Ir,{attachments:n.attachments,baseUrl:a,apiKey:f,language:v,t:u}),t.jsx($o,{sources:n.sourceRefs,enabled:ce,allowedLinkHosts:J,t:u})]}):t.jsx("div",{className:"es-sc__bubble-text",children:k})),n.isPending&&!n.text&&t.jsxs("div",{className:"es-sc__typing","aria-label":u("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"})]}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"es-sc__actions","data-es-no-read":!0,children:n.actions.map(N=>t.jsx("a",{href:Di(N.url)?N.url:"#",target:"_blank",rel:"noopener noreferrer",className:"es-sc__action-btn",children:N.title},N.slug))}),n.ticketCards&&n.ticketCards.length>0&&t.jsx("div",{className:"es-sc__ticket-cards",children:n.ticketCards.map(N=>t.jsx(kn,{card:N,t:u},N.externalNumber))}),n.quickReplies&&n.quickReplies.length>0&&t.jsx("div",{className:"es-sc__quick-replies",children:n.quickReplies.map(N=>{const ee=n.quickReplyAnswered===N.value;if(n.quickReplyAnswered!==void 0&&!ee)return null;const C=N.payload==="confirm_escalation"?u("escalation.confirm_yes"):N.payload==="cancel_escalation"?u("escalation.confirm_no"):N.payload==="confirm_handoff"?u("support_chat.handoff.confirm_yes"):N.payload==="decline_handoff"?u("support_chat.handoff.confirm_no"):N.label;return t.jsx("button",{type:"button",disabled:ee||le,onClick:()=>ga(n.id,N.value,N.payload??""),className:`es-sc__quick-reply-btn${ee?" es-sc__quick-reply-btn--clicked":""}`,children:C},N.value)})}),n.role==="assistant"&&n.contactRequest&&!Ln.has(n.id)&&t.jsx(Mo,{purpose:n.contactRequest.purpose,sent:Mn.has(n.id),onSubmit:N=>ua(n.id,n.contactRequest.purpose,N),onDismiss:()=>gs(N=>new Set(N).add(n.id)),t:u}),n.role==="assistant"&&t.jsx(on,{followUps:n.suggestedFollowUps,isNewest:m,isPending:!!n.isPending,hasQuickReplies:!!n.quickReplies?.length,isSending:le,onSelect:N=>ke(N),t:u}),n.role==="assistant"&&!n.isPending&&n.text&&t.jsx(t.Fragment,{children:n.confidenceLevel==="low"&&t.jsxs("div",{className:"es-sc__escalation",children:[t.jsx("span",{className:"es-sc__escalation-text",children:u("support_chat.low_confidence")}),t.jsx("button",{className:"es-sc__escalation-btn",onClick:()=>na(n.id),type:"button","aria-label":T,children:T})]})})]},n.id)}),Ge&&t.jsxs("div",{className:"es-sc__error",role:"alert",children:[t.jsx("span",{className:"es-sc__error-text",children:Ge}),Ze&&t.jsx("button",{type:"button",className:"es-sc__error-retry",onClick:Yn,children:u("support_chat.retry")})]})]}),!$n&&Y.length>0&&t.jsx("div",{className:"es-sc__jump-anchor",children:t.jsxs("button",{type:"button",className:"es-sc__jump",onClick:()=>Ue(),"aria-label":u("support_chat.jump_to_latest"),title:u("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:u("support_chat.jump_to_latest")})]})})]})}),xe!=="tickets"&&re.length>0&&t.jsx("div",{className:"es-sc__suggestions",role:"group","aria-label":u("support_chat.quick_actions_aria"),children:re.map((n,p)=>t.jsx("button",{className:"es-sc__suggestion",onClick:()=>Gn(n),type:"button",disabled:le||h,children:n.labelKey?u(n.labelKey):n.label},`${n.labelKey??n.label}-${p}`))}),xe!=="tickets"&&re.length===0&&Xs&&z&&H.length>0&&t.jsx("div",{className:"es-sc__suggestions",role:"list","aria-label":u("support_chat.suggestions_aria"),children:H.map((n,p)=>t.jsx("button",{className:"es-sc__suggestion",onClick:()=>ke(n),type:"button",role:"listitem",children:n},p))}),xe!=="tickets"&&ps&&t.jsx(Ko,{onAnswer:fa,onDismiss:pa,t:u}),xe!=="tickets"&&t.jsx(Bo,{status:Pe,onSubmitContact:la,onDismiss:da,onChooseLanguage:n=>{Wt(n)},autoReadAloud:S?Ot:null,onToggleAutoReadAloud:Bn,onResumeVoice:Kn&&Ls?Fn:null,t:u}),xe!=="tickets"&&t.jsxs("div",{className:"es-block__footer es-sc__footer",children:[Mt&&t.jsx(zr,{upload:us,t:u}),t.jsxs("div",{className:"es-sc__input-row",children:[Ls&&!Qt&&t.jsx("button",{type:"button",className:"es-sc__conv-start","data-testid":"conversation-start","aria-label":u("voice_conv.start"),title:u("voice_conv.start"),onClick:()=>{V.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:ye,className:"es-sc__textarea",value:qe,onChange:ea,onKeyDown:Zn,placeholder:$e!=null?u("support_chat.rate_limited_wait",{seconds:String(Rn)}):Q,rows:1,maxLength:2e3,disabled:le||h||ze!=null||$e!=null||ht,"aria-label":u("support_chat.input_aria")}),qe.length>0&&t.jsx("button",{className:"es-sc__clear",onClick:ta,disabled:le,type:"button","aria-label":u("support_chat.clear_input_aria"),children:t.jsx("span",{"aria-hidden":"true",children:"✕"})})]}),x&&!h&&t.jsx($r,{baseUrl:a,apiKey:f,jwt:b.current,language:v,onTranscript:sa,t:u,disabled:le||ze!=null||$e!=null||ht,streaming:j?.streaming,voiceStream:o?.voiceStream,baseText:()=>qe,onText:n=>{if(Ie(n.length>2e3?n.slice(0,2e3):n),n.length>=2e3){const p=o?.voiceStream;p?.getState&&p.getState()!=="idle"&&p.stop()}requestAnimationFrame(()=>{De(),ye.current?.focus()})}}),Mt&&t.jsx(Fr,{upload:us,t:u,disabled:le||h||ze!=null||$e!=null||ht}),t.jsx("button",{className:`es-sc__send${le?" es-sc__send--stop":""}`,onClick:le?Wn:Vt,disabled:!le&&(h||!qe.trim()||ze!=null||$e!=null||ht),type:"button","aria-label":u(le?"support_chat.stop_aria":"chat.send_aria"),children:le?t.jsx("span",{className:"es-sc__stop-icon","aria-hidden":"true"}):t.jsx("span",{"aria-hidden":"true",children:"➤"})})]}),t.jsx("div",{className:"es-sc__disclaimer","data-es-no-read":!0,children:ae})]})]})}export{ls as AssistantBubble,jr as AssistantMessageMedia,Ir as AttachmentCards,rc as Component,Mo as ContactRequestPanel,xr as MarkdownBubble,wr as MessageMedia,Fo as OUTCOME_PROMPT_IDLE_MS,Ko as OutcomePrompt,Fr as PhotoButton,zr as PhotoStrip,$o as SourceChips,ki as VoiceModeView,To as buildSummary,fo as createVoiceWordCursor,zo as decideOutcomePrompt,ac as manifest,Kr as usePhotoUpload};
@@ -0,0 +1 @@
1
+ import{Q as w,r as t,j as e,l 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};
@@ -0,0 +1 @@
1
+ import{j as e,Y as _,r as n}from"../nexly.js";const v={"--ai-bg":"#141414","--ai-bg-elevated":"#1F1F1F","--ai-bg-card":"#1F1F1F","--ai-bg-input":"#141414","--ai-bg-footer":"#141414","--ai-fg":"#F5F5F5","--ai-fg-secondary":"#D1D5DB","--ai-muted":"#9CA3AF","--ai-muted-dim":"#6B7280","--ai-border":"#2a2a2a","--ai-border-subtle":"#1e1e1e","--ai-accent":"#FFCC00","--ai-accent-fg":"#1A1A1A","--ai-accent-hover":"#E6B800","--ai-accent-subtle":"rgba(255, 204, 0, 0.12)","--ai-accent-on-subtle":"#FFCC00","--ai-accent-on-subtle-strong":"#FFCC00","--ai-accent-border":"#75600C","--ai-user-bubble":"#FFCC00","--ai-user-bubble-fg":"#1A1A1A","--ai-assistant-bubble":"#1F1F1F","--ai-assistant-bubble-fg":"#F5F5F5","--ai-shadow":"0 20px 60px -15px rgba(0, 0, 0, 0.7)","--ai-scrollbar":"#FFCC00","--ai-success":"#22C55E","--ai-warning":"#EAB308","--ai-error":"#F87171","--ai-info":"#38BDF8","--es-color-surface":"#141414","--es-color-surface-elevated":"#1F1F1F","--es-color-surface-hover":"#2E2E2E","--es-color-on-surface":"#F5F5F5","--es-color-on-surface-muted":"#9CA3AF","--es-color-primary":"#FFCC00","--es-color-on-primary":"#1A1A1A","--es-color-primary-muted":"rgba(255, 204, 0, 0.12)","--es-color-primary-on-muted":"#FFCC00","--es-color-border":"#2a2a2a","--es-color-control-border":"#6B7280","--es-color-error":"#F87171","--es-color-success":"#22C55E","--es-color-on-success":"#1A1A1A","--es-color-warning":"#EAB308","--es-color-interactive":"#FFE066"},I={"--ai-bg":"#FFFFFF","--ai-bg-elevated":"#FAFAFA","--ai-bg-card":"#F2F2F2","--ai-bg-input":"#F2F2F2","--ai-bg-footer":"#FFFFFF","--ai-fg":"#1A1A1A","--ai-fg-secondary":"#4B4B4F","--ai-muted":"#67696E","--ai-muted-dim":"#9CA3AF","--ai-border":"#E5E5E5","--ai-border-subtle":"#EFEFEF","--ai-accent":"#856900","--ai-accent-fg":"#FFFFFF","--ai-accent-hover":"#6B5400","--ai-accent-subtle":"rgba(125, 98, 0, 0.10)","--ai-accent-on-subtle":"#7D6200","--ai-accent-on-subtle-strong":"#765D00","--ai-accent-border":"#A8944A","--ai-user-bubble":"#856900","--ai-user-bubble-fg":"#FFFFFF","--ai-assistant-bubble":"#F2F2F2","--ai-assistant-bubble-fg":"#1A1A1A","--ai-shadow":"0 20px 60px -15px rgba(0, 0, 0, 0.12)","--ai-scrollbar":"#D1D5DB","--ai-success":"#00672B","--ai-warning":"#9C5300","--ai-error":"#AD2C26","--ai-info":"#03669D","--es-color-surface":"#FFFFFF","--es-color-surface-elevated":"#F2F2F2","--es-color-surface-hover":"#EAEAEA","--es-color-on-surface":"#1A1A1A","--es-color-on-surface-muted":"#67696E","--es-color-primary":"#856900","--es-color-on-primary":"#FFFFFF","--es-color-primary-muted":"rgba(118, 93, 0, 0.10)","--es-color-primary-on-muted":"#765D00","--es-color-border":"#E5E5E5","--es-color-control-border":"#6B7280","--es-color-error":"#AD2C26","--es-color-success":"#00672B","--es-color-on-success":"#FFFFFF","--es-color-interactive":"#92400E"},W={slug:"ambient-signal-black",name:"Signal Black",version:"0.1.0",slots:["header","main","footer"],cssVariables:v,structure:{header:{id:"header",label:"Header",accepts:!0},main:{id:"main",label:"Main Content",accepts:!0},footer:{id:"footer",label:"Footer",accepts:!0}},defaultViews:[],requiredServices:["chat-bot"],description:"Bold monochrome theme with a #FFCC00 signal-gold accent, built for the AmbientSystem SupportChat widget.",author:"E-Commerce Studio",packageName:"@ecommerce-studio/theme-ambient-signal-black",options:[{id:"colorScheme",type:"select",label:"Appearance mode",default:"auto",group:"Appearance",options:[{label:"Auto (match visitor)",value:"auto"},{label:"Light",value:"light"},{label:"Dark",value:"dark"}]}],supports:{customCss:!1,customJs:!1,darkMode:!0,rtl:!1,views:!1}},R=105,z=82,y="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGkAAABSCAYAAABXP/pUAAACiklEQVR42u2c23GDQAxFtyc3oGrShupINWogPTn+sCcewmMxSKtdzp3RX2CcPVxJaIFSUEvJM+wZ90coy+KzyLoQsnLcC8o00AlQdGWBl8LeoK0di4sOwtkL5pNAieHgog+lQXBe6XDtAkEzskBAUxfNuRclAUTHlzDF0VAMBIiGIjkgXNSwDuEiXDSesgIy0Py1vXecRKo7EgKivA0DKa+DegSkjiBdvi5J+dtBtcSpD63AMyDRAQJp4ogtV1jZfnikBSwbEcqZtUUXZmeRsHQ0OJ5XszYCpcA5tmARoIDzoaskaPbXrYuyzNo0ABTuOXn4qVd3UeZJtTgNaw1APosp5YLbFNkBXd5N1gkgbzcByMlNw6c87RDQ1E1Dp7xeAV0GUs+ApvVDR4V0B1JuSAqkOkhfADptMV0g3R7xs7HRBaT6WZt5nPcd0vQPhFq0G5LLfdISJO+prA4EyX3i8FUB6e6QDkd0kTqddxekM4GN5qLiCP9jSEfS4SipTiJcdBaktSdrRoXkuTNbPCHVpkPpHJQ4Nguza/btBKm2ndeOgNnM/xHyAEoEpNr6lRmYzmQDi1qbaEi19SsLsDn3aPDF2wxSdmC2kKItGlB5AvpJllbWfrQ4QrMS/1ZF1e1LNkh7W/p3aLbz3C8osnH+5q+23J5teA+vJu6dcshM1B5nDRuo3Xq/UjNBtBNniVJiX8EMf4xYSp6XhK38/+TzNFr/TikJlQlitla+G/U+IrrU52dGBDXk9+qU1AYo4JwMSoEDrKgNTmA1AiMgaTNc3UplgEkyzjGgtJty1DiP+pJAQAISAhKQ6OJaNxBHtkas1H1VEh2Aw01t4ukEWxKd1x5AIYQQQgihhvoFxm18xEWNaMwAAAAASUVORK5CYII=",J=z/R,Q=.62;function N({size:a=64,className:i,registerEl:o}){const u=a*Q,s=u*J;return e.jsx("div",{className:i,"aria-hidden":"true","data-bird":"badge",style:{position:"relative",width:a,height:a,borderRadius:"9999px",background:"var(--ai-accent, #FFCC00)",color:"var(--ai-accent-fg, #1A1A1A)",display:"flex",alignItems:"center",justifyContent:"center",overflow:"visible"},children:e.jsxs("div",{ref:o,"data-bird":"root",style:{position:"relative",width:u,height:s,transformOrigin:"50% 50%"},children:[e.jsx("div",{"data-bird":"glow",style:{position:"absolute",inset:"-35%",borderRadius:"9999px",background:"radial-gradient(closest-side, currentColor, transparent 72%)",opacity:0,filter:"blur(6px)",pointerEvents:"none"}}),e.jsx("div",{"data-bird":"mark",style:{position:"relative",width:"100%",height:"100%",backgroundColor:"currentColor",WebkitMaskImage:`url("${y}")`,maskImage:`url("${y}")`,WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskPosition:"center",maskPosition:"center",WebkitMaskSize:"contain",maskSize:"contain"}})]})})}const P=3200,V=2.5,X=4200,U=3,q=Math.PI/3,K=5200,C=.12,L=.34;function x(a,i){const o=a.querySelector('[data-bird="glow"]');o&&(o.style.opacity=i.toFixed(3))}function O(a){const i=n.useRef(new Set),o=n.useRef(0),u=n.useCallback(s=>{const r=i.current;if(s)r.add(s);else for(const t of r)t.isConnected||r.delete(t)},[]);return n.useEffect(()=>{if(!a)return;if(typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches){for(const t of i.current)t.style.transform="",x(t,C);return}const s=performance.now();function r(t){const b=t-s,g=Math.sin(b/P*Math.PI*2)*V,l=Math.sin(b/X*Math.PI*2+q)*U,m=(Math.sin(b/K*Math.PI*2)+1)/2,f=C+(L-C)*m;for(const F of i.current)F.style.transform=`translateY(${g.toFixed(2)}px) rotate(${l.toFixed(2)}deg)`,x(F,f);o.current=requestAnimationFrame(r)}return o.current=requestAnimationFrame(r),()=>{cancelAnimationFrame(o.current);for(const t of i.current)t.style.transform="",x(t,0)}},[a]),{registerEl:u}}function Y({brandName:a="AMBIENT",position:i="bottom-right",initialOpen:o=!1,children:u,cssVariables:s,t:r,colorScheme:t,builderMode:b=!1,builderPresentation:g="inline",open:l,direction:m="ltr",owlIdleLife:f=!1,onOpenChange:F}){const A=_(t),c=b&&g!=="floating",[d,p]=n.useState(l??(o||c)),E=n.useRef(d);n.useEffect(()=>{E.current=d},[d]),n.useEffect(()=>{l===void 0||l===E.current||(E.current=l,p(l))},[l]);const B=O(f),S=()=>p(k=>{const h=!k;return F?.(h),h}),D=()=>{p(!1),F?.(!1)},w=i==="bottom-left",j=n.useMemo(()=>{const k=Object.fromEntries(Object.entries(s??{}).filter(([h,M])=>v[h]!==M));return{...A==="light"?I:v,...k,...c?{width:"100%",height:"100%"}:{}}},[s,A,c]);return e.jsxs("div",{className:["ambient-shell",`ambient-shell--${A}`].join(" "),dir:m,style:{...j,direction:m},children:[!c&&e.jsx("button",{type:"button",className:["ambient-shell__button",w&&"ambient-shell__button--left",d&&"ambient-shell__button--hidden"].filter(Boolean).join(" "),onClick:S,"aria-label":r?.("floating.open_widget")??"Open chat widget",tabIndex:d?-1:0,"aria-hidden":d,children:e.jsx(N,{size:64,registerEl:B.registerEl})}),e.jsxs("div",{className:["ambient-shell__panel",w&&!c&&"ambient-shell__panel--left",(d||c)&&"ambient-shell__panel--open"].filter(Boolean).join(" "),role:"dialog","aria-label":r?.("chat.widget_aria")??"Chat widget","aria-hidden":c?!1:!d,children:[e.jsxs("header",{className:"ambient-shell__header",children:[e.jsxs("div",{className:"ambient-shell__header-brand",children:[e.jsx(N,{size:40,registerEl:B.registerEl}),e.jsxs("div",{className:"ambient-shell__header-info",children:[e.jsx("h1",{className:"ambient-shell__brand-name",children:a}),e.jsx("p",{className:"ambient-shell__brand-tagline",children:r?.("header.brand_tagline_support")??"Support"})]})]}),!c&&e.jsx("button",{type:"button",className:"ambient-shell__header-btn",onClick:D,"aria-label":r?.("header.close_widget")??"Close widget",children:e.jsx(T,{size:20})})]}),e.jsx("main",{className:"ambient-shell__content",style:{containerName:"es-slot",containerType:"inline-size"},children:u})]})]})}function T({size:a=20}){return e.jsx("svg",{width:a,height:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"m6 9 6 6 6-6"})})}export{N as BirdIcon,Y as ThemeShell,v as darkVariables,I as lightVariables,W as manifest,O as useBirdAnimation};
@@ -0,0 +1 @@
1
+ import{r as p,j as e,l as N}from"../nexly.js";import{S as k,I,L as M,$ as T,j as L,_ as E,k as z,m as D}from"./index.modern-CioVZ357-C7XPucLH.js";import"./_commonjsHelpers-C6fGbg64-BC8KDfbh.js";const R={slug:"event-map",name:"Event Map",version:"1.0.0",category:"interactive",requiredService:"event-scraper",configSchema:{properties:{zoom:{type:"number",default:12},showFilters:{type:"boolean",default:!0}}},defaultConfig:{zoom:12,showFilters:!0},dataContract:{serviceSlug:"event-scraper",inputSchema:{type:"object",properties:{events:{type:"array",items:{type:"object",properties:{id:{type:"string"},title:{type:"string"},date:{type:"string"},lat:{type:"number"},lng:{type:"number"},isFree:{type:"boolean"}}}},centerLat:{type:"number"},centerLng:{type:"number"}},required:["events"]},previewDataOverride:{events:[{id:"evt-1",title:"Tech Startup Networking Night",date:"2026-04-10T18:00:00Z",lat:37.4979,lng:127.0276,isFree:!0},{id:"evt-2",title:"AI & Machine Learning Summit",date:"2026-04-15T09:00:00Z",lat:37.5563,lng:126.9177,isFree:!1},{id:"evt-3",title:"Web3 Developer Workshop",date:"2026-04-20T14:00:00Z",lat:37.5145,lng:127.1059,isFree:!0}],centerLat:37.5665,centerLng:126.978}},fields:[{id:"zoom",type:"range",label:"Default zoom level",default:12,min:8,max:18,step:1,group:"Map"},{id:"showFilters",type:"toggle",label:"Show filter controls",default:!0,group:"Display"}],events:{emits:[{name:"eventMap:markerClicked",description:"User clicked on an event map marker"},{name:"eventMap:viewChanged",description:"Map viewport moved or zoomed"}],listens:[{name:"events:refresh",description:"Reload events and re-render markers"}]},sizing:{minWidth:240,preferredHeight:"auto",scrollable:!1},supportedPlacements:["main","sidebar"]};function A(s,n){const d=new Date(s);return Number.isNaN(d.getTime())?s:new Intl.DateTimeFormat(n,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(d)}function W({events:s,selectedId:n,onSelect:d,useAdvanced:v,onPrimaryInk:r,onSuccessInk:g}){const c=T();return p.useEffect(()=>{if(!c||!n)return;const t=s.find(o=>o.id===n);t&&c.panTo({lat:t.lat,lng:t.lng})},[c,n,s]),v?e.jsx(e.Fragment,{children:s.map((t,o)=>{const u=t.id!=null&&t.id===n;return e.jsx(L,{position:{lat:t.lat,lng:t.lng},title:t.title,onClick:()=>d(t.id??null),children:e.jsx(E,{background:u?"var(--es-color-interactive, #2563EB)":t.isFree?"var(--es-color-success, #00672B)":"var(--es-color-primary, #2563EB)",borderColor:z,glyphColor:!u&&t.isFree?g:r,scale:u?1.25:1})},t.id??o)})}):e.jsx(e.Fragment,{children:s.map((t,o)=>e.jsx(D,{position:{lat:t.lat,lng:t.lng},title:t.title,onClick:()=>d(t.id??null)},t.id??o))})}const Z={id:"__builder_placeholder__",title:"Sample event location",lat:37.5665,lng:126.978};function q({data:s,actions:n,i18n:d,builderMode:v}){const r=d?.t??(a=>a),g=d?.currentLanguage??s.language??"en",[c,t]=p.useState(null),o=p.useRef(null),u=k(o,"--es-color-on-primary","#ffffff"),S=k(o,"--es-color-on-success","#ffffff"),b=s.events??[],j=s.googleMapsApiKey,y=s.googleMapsMapId??void 0,C=!!y,m=b.length,i=p.useMemo(()=>b.filter(a=>typeof a.lat=="number"&&typeof a.lng=="number"),[b]),l=c!=null?i.find(a=>a.id===c)??null:null,x=p.useCallback(a=>{if(t(a),a){const f=i.find(h=>h.id===a);f&&n.emit("events:eventSelected",{id:a,event:f}),n.emit("events:markerHighlight",{id:a})}else n.emit("events:markerHighlight",{id:null})},[n,i]);if(p.useEffect(()=>{const a=n.on("events:hover",f=>{const h=f?.id??null;h!=null&&i.some(w=>w.id===h)&&t(h)});return()=>a()},[n,i]),!j)return e.jsx(N,{blockType:"event-map",children:e.jsx("div",{className:"es-block__body",children:e.jsxs("div",{className:"es-map-placeholder",children:[e.jsx("div",{className:"es-map-placeholder__icon","aria-hidden":"true",children:"🗺"}),e.jsx("div",{className:"es-map-placeholder__message",children:r("event_map.no_key_message")}),m>0&&e.jsx("div",{className:"es-map-placeholder__count",children:r("event_map.events_available",{count:m})}),e.jsx("div",{className:"es-map-placeholder__hint",children:r("event_map.use_event_list_hint")})]})})});const _=v&&i.length===0?[Z]:i,F=_.length>0?{lat:_[0].lat,lng:_[0].lng}:{lat:37.5665,lng:126.978};return e.jsx(N,{blockType:"event-map",children:e.jsxs("div",{className:"es-block__body es-block__body--map",ref:o,children:[e.jsx(I,{apiKey:j,language:g,children:e.jsx(M,{className:"es-eventmap__canvas",defaultCenter:F,defaultZoom:_.length>0?12:10,mapTypeControl:!1,fullscreenControl:!1,streetViewControl:!1,...y?{mapId:y}:{},children:e.jsx(W,{events:_,selectedId:c,onSelect:x,useAdvanced:C,onPrimaryInk:u,onSuccessInk:S})})}),!v&&m>0&&i.length===0&&e.jsxs("div",{className:"es-eventmap__no-coords-overlay",role:"note",children:[e.jsx("div",{className:"es-eventmap__no-coords-overlay__icon","aria-hidden":"true",children:"📍"}),e.jsx("div",{className:"es-eventmap__no-coords-overlay__message",children:r("event_map.no_coords_notice")}),e.jsx("div",{className:"es-eventmap__no-coords-overlay__count",children:r("event_map.events_no_coords",{count:m})})]}),!v&&i.length>0&&m>i.length&&e.jsxs("div",{className:"es-eventmap__no-coords-badge",role:"note",children:[e.jsx("span",{className:"es-eventmap__no-coords-badge__icon","aria-hidden":"true",children:"📍"}),e.jsx("span",{className:"es-eventmap__no-coords-badge__text",children:r("event_map.partial_no_coords_badge",{count:m-i.length})})]}),l&&e.jsxs("div",{className:"es-eventmap__detail",role:"dialog","aria-label":l.title,children:[e.jsx("button",{type:"button",className:"es-eventmap__detail-close",onClick:()=>x(null),"aria-label":r("event_map.close_details"),children:"×"}),e.jsxs("div",{className:"es-eventmap__detail-header",children:[e.jsx("h3",{className:"es-eventmap__detail-title",children:l.title}),l.isFree&&e.jsx("span",{className:"es-eventmap__detail-badge",children:r("event_list.free")})]}),e.jsxs("div",{className:"es-eventmap__detail-meta",children:[l.date&&e.jsxs("span",{className:"es-eventmap__detail-meta-item",children:[e.jsx("span",{"aria-hidden":"true",children:"🗓"}),A(l.date,g)]}),(l.address||l.location)&&e.jsxs("span",{className:"es-eventmap__detail-meta-item",children:[e.jsx("span",{"aria-hidden":"true",children:"📍"}),l.address||l.location]})]}),l.url&&e.jsxs("a",{href:l.url,className:"es-eventmap__detail-cta",target:"_blank",rel:"noopener noreferrer",children:[r("event_list.view_details")," →"]})]})]})})}export{q as Component,R as manifest};
@@ -0,0 +1 @@
1
+ import{j as e,l as u}from"../nexly.js";const y={slug:"demo-shipping-returns",name:"DEMO — Contact details",version:"0.1.0",category:"content",configSchema:{properties:{rows:{type:"array",items:{type:"object",properties:{label:{type:"string"},value:{type:"string"},note:{type:"string"}},required:["label","value"]},default:[]}}},defaultConfig:{rows:[]},sizing:{minWidth:240,preferredHeight:"auto",scrollable:!1},supportedPlacements:["main","sidebar"]};function _(t){return Array.isArray(t)?t.flatMap(s=>{if(typeof s!="object"||s===null)return[];const n=s,d=typeof n.label=="string"?n.label.trim():"",a=typeof n.value=="string"?n.value.trim():"";if(!d||!a)return[];const c=typeof n.note=="string"?n.note.trim():"";return[{label:d,value:a,...c?{note:c}:{}}]}):[]}function i(t){if(typeof t!="string")return null;const s=t.trim();return s.length>0?s:null}function x(t){const s=i(t);if(!s||/\s/.test(s))return null;const n=s.indexOf("@");return n>0&&n<s.length-1?s:null}function j(t){const s=i(t);return!s||!/[0-9]/.test(s)?null:s}function f(t){return t.split(/\s+/).filter(s=>/[\p{L}\p{N}]/u.test(s)).slice(0,2).map(s=>s[0].toUpperCase()).join("")}function v({data:t,config:s,i18n:n}){const d=n?.t??(o=>o),a=t?.rows?t:s??{},c=_(a.rows),m=i(a.company),p=i(a.tagline),r=x(a.email),l=j(a.phone),h=i(a.note);return!m&&!r&&!l&&c.length===0?e.jsx(u,{blockType:"demo-shipping-returns",children:e.jsx("div",{className:"es-block__body",children:e.jsx("div",{className:"es-block__empty",children:d("demoTerms.empty")})})}):e.jsx(u,{blockType:"demo-shipping-returns",children:e.jsxs("div",{className:"es-block__body es-democontact",children:[e.jsxs("div",{className:"es-democontact__card",children:[m&&e.jsxs("div",{className:"es-democontact__identity",children:[e.jsx("div",{className:"es-democontact__coin","aria-hidden":"true",children:f(m)}),e.jsxs("div",{className:"es-democontact__names",children:[e.jsx("p",{className:"es-democontact__company",children:m}),p&&e.jsx("p",{className:"es-democontact__tagline",children:p})]})]}),c.length>0&&e.jsx("dl",{className:"es-democontact__grid",children:c.map(o=>e.jsxs("div",{className:"es-democontact__cell",children:[e.jsx("dt",{className:"es-democontact__label",children:o.label}),e.jsx("dd",{className:"es-democontact__value",children:o.value}),o.note&&e.jsx("dd",{className:"es-democontact__note",children:o.note})]},o.label))}),(r||l)&&e.jsxs("div",{className:"es-democontact__actions",children:[r&&e.jsxs("a",{className:"es-democontact__action",href:`mailto:${r}`,children:[e.jsxs("svg",{className:"es-democontact__glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("rect",{x:"2.5",y:"4.5",width:"19",height:"15",rx:"2.5"}),e.jsx("path",{d:"M3 7l9 6 9-6"})]}),e.jsx("span",{className:"es-democontact__action-text",children:r})]}),l&&e.jsxs("a",{className:"es-democontact__action",href:`tel:${l.replace(/\s+/g,"")}`,children:[e.jsx("svg",{className:"es-democontact__glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"M6.5 3.5h3l1.5 4-2 1.5a11 11 0 006 6l1.5-2 4 1.5v3a2 2 0 01-2.2 2A17 17 0 014.5 5.7 2 2 0 016.5 3.5z"})}),e.jsx("span",{className:"es-democontact__action-text",children:l})]})]})]}),h&&e.jsxs("div",{className:"es-democontact__reassurance",children:[e.jsxs("svg",{className:"es-democontact__glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M12 3l7.5 3v5.5c0 4.6-3.1 8.4-7.5 9.5-4.4-1.1-7.5-4.9-7.5-9.5V6z"}),e.jsx("path",{d:"M9 12.2l2.2 2.2 4-4.2"})]}),e.jsx("p",{className:"es-democontact__reassurance-text",children:h})]})]})})}export{v as Component,y as manifest};
@@ -0,0 +1 @@
1
+ import{j as e,l}from"../nexly.js";const m={slug:"demo-services",name:"DEMO — Services",version:"0.1.0",category:"content",configSchema:{properties:{items:{type:"array",items:{type:"object",properties:{title:{type:"string"},description:{type:"string"}},required:["title"]},default:[]}}},defaultConfig:{items:[]},sizing:{minWidth:240,preferredHeight:"auto",scrollable:!1},supportedPlacements:["main","sidebar"]};function d(r){return Array.isArray(r)?r.flatMap(i=>{if(typeof i!="object"||i===null)return[];const s=i,c=typeof s.title=="string"?s.title.trim():"";if(!c)return[];const n=typeof s.description=="string"&&s.description.trim().length>0?s.description.trim():void 0;return[{title:c,description:n}]}):[]}function p({data:r,config:i,i18n:s}){const c=s?.t??(t=>t),n=d(r?.items??i?.items);return n.length===0?e.jsx(l,{blockType:"demo-services",children:e.jsx("div",{className:"es-block__body",children:e.jsx("div",{className:"es-block__empty",children:c("demoServices.empty")})})}):e.jsx(l,{blockType:"demo-services",children:e.jsx("div",{className:"es-block__body es-demosvc",children:e.jsx("ul",{className:"es-demosvc__list",children:n.map((t,o)=>e.jsxs("li",{className:"es-demosvc__item",children:[e.jsx("span",{className:"es-demosvc__ordinal","aria-hidden":"true",children:o+1}),e.jsxs("div",{className:"es-demosvc__text",children:[e.jsx("h3",{className:"es-demosvc__title",children:t.title}),t.description&&e.jsx("p",{className:"es-demosvc__desc",children:t.description})]})]},o))})})})}export{p as Component,m as manifest};
@@ -0,0 +1 @@
1
+ import{w as E,p as H,f as P,x as T,A as K,S as ee,O as q}from"./accent-legibility-BJF2VO5n-CDPQ7suO.js";import{Y as ae,r as x,j as s,p as re}from"../nexly.js";const oe=4.5,_="#3B6FD4",se={"--ai-bg":"#FFFFFF","--ai-bg-elevated":"#F9FAFB","--ai-bg-card":"#F3F4F6","--ai-bg-input":"#FFFFFF","--ai-bg-footer":"#F9FAFB","--ai-fg":"#111827","--ai-fg-secondary":"#374151","--ai-muted":"#4B5563","--ai-muted-dim":"#6B7280","--ai-border":"#E5E7EB","--ai-border-subtle":"#F3F4F6","--ai-assistant-bubble":"#F3F4F6","--ai-assistant-bubble-fg":"#111827","--ai-shadow":"0 20px 60px -15px rgba(15, 23, 42, 0.25)","--ai-success":"#00672B","--ai-warning":"#9C5300","--ai-error":"#AD2C26","--ai-info":"#03669D","--es-color-surface":"#FFFFFF","--es-color-surface-elevated":"#F9FAFB","--es-color-surface-hover":"#F3F4F6","--es-color-on-surface":"#111827","--es-color-on-surface-muted":"#4B5563","--es-color-border":"#E5E7EB","--es-color-control-border":"#6B7280","--es-color-error":"#AD2C26","--es-color-success":"#00672B","--es-color-on-success":"#FFFFFF"},te={"--ai-bg":"#0F1115","--ai-bg-elevated":"#171A20","--ai-bg-card":"#171A20","--ai-bg-input":"#0F1115","--ai-bg-footer":"#0F1115","--ai-fg":"#F3F4F6","--ai-fg-secondary":"#D1D5DB","--ai-muted":"#9CA3AF","--ai-muted-dim":"#6B7280","--ai-border":"#252A33","--ai-border-subtle":"#1B1F26","--ai-assistant-bubble":"#171A20","--ai-assistant-bubble-fg":"#F3F4F6","--ai-shadow":"0 20px 60px -15px rgba(0, 0, 0, 0.7)","--ai-success":"#4ADE80","--ai-warning":"#FACC15","--ai-error":"#F87171","--ai-info":"#38BDF8","--es-color-surface":"#0F1115","--es-color-surface-elevated":"#171A20","--es-color-surface-hover":"#252A33","--es-color-on-surface":"#F3F4F6","--es-color-on-surface-muted":"#9CA3AF","--es-color-border":"#252A33","--es-color-control-border":"#6B7280","--es-color-error":"#F87171","--es-color-success":"#4ADE80","--es-color-on-success":"#0F1115"};function O(e){const a=q("#FFFFFF",e),r=q("#000000",e);return a>=r?"#FFFFFF":"#000000"}function ne(e){const[a,r,o]=P(e),t=ee(e)<.2?28:-28;return H([Math.max(0,Math.min(255,a+t)),Math.max(0,Math.min(255,r+t)),Math.max(0,Math.min(255,o+t))])}function V({brandColor:e,mode:a}){const r=a==="light"?se:te,o=e&&E(e)?e:_,t=H(P(o)),l=O(t),g={ai:["--ai-bg","--ai-bg-elevated","--ai-bg-card","--ai-bg-input","--ai-bg-sidebar","--ai-bg-footer"],es:["--es-color-surface","--es-color-surface-elevated","--es-color-surface-hover"]},v=(C,j)=>{const k=new Set([j]);for(const h of g[C]){const F=r[h];typeof F=="string"&&E(F)&&k.add(F)}return[...k]},b=T({accent:t,surface:v("ai",r["--ai-bg-card"]),backdrop:r["--ai-bg"],tintAlpha:a==="light"?.08:.12,mode:a}),p=T({accent:t,surface:v("es",r["--es-color-surface-elevated"]),backdrop:r["--es-color-surface"],tintAlpha:a==="light"?.08:.12,mode:a}),d=K(t,v("es",r["--es-color-surface"]),oe,a);return{...r,"--ai-accent":t,"--ai-accent-fg":l,"--ai-accent-hover":ne(t),"--ai-accent-subtle":b.tint,"--ai-accent-on-subtle":b.onTint,"--ai-accent-on-subtle-strong":b.onStrongTint,"--ai-accent-border":b.boundary,"--ai-user-bubble":t,"--ai-user-bubble-fg":l,"--ai-scrollbar":t,"--es-color-primary":d,"--es-color-on-primary":O(d),"--es-color-primary-muted":p.tint,"--es-color-primary-on-muted":p.onTint,"--es-color-interactive":d}}const _e=V({brandColor:_,mode:"light"}),ve=V({brandColor:_,mode:"dark"}),n={shape:"--es-demo-launcher-shape",width:"--es-demo-launcher-width",height:"--es-demo-launcher-height",radius:"--es-demo-launcher-radius",background:"--es-demo-launcher-background",shadow:"--es-demo-launcher-shadow",padding:"--es-demo-launcher-padding",offsetX:"--es-demo-launcher-offset-x",offsetY:"--es-demo-launcher-offset-y"},i={width:{min:32,max:240,step:2},height:{min:32,max:240,step:2},radius:{min:0,max:64,step:1},padding:{min:0,max:32,step:1},offsetX:{min:0,max:240,step:2},offsetY:{min:0,max:240,step:2}},z=8,I=8,ie=.6,c={shape:"circle",width:56,height:56,radius:12,background:"accent",shadow:!0,padding:I,offsetX:20,offsetY:20},le=new Set(["pill","circle","square","rectangle"]),ce=new Set(["accent","neutral","none"]);function de(e){if(typeof e!="string")return;const a=/^\s*(-?\d+(?:\.\d+)?)\s*(?:px)?\s*$/i.exec(e);if(!a)return;const r=Number(a[1]);return Number.isFinite(r)?r:void 0}function w(e,a,r){const o=de(e);return o===void 0?r:Math.min(a.max,Math.max(a.min,o))}function U(e,a,r){if(typeof e!="string")return r;const o=e.trim().toLowerCase();return a.has(o)?o:r}function ue(e,a){if(typeof e!="string")return a;const r=e.trim().toLowerCase();return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:a}function W(e){const a=e.shape==="circle"||e.shape==="square";return{width:e.width,height:a?e.width:e.height}}function he(e,a,r,o){if(e==="pill")return o;const t=Math.max(0,Math.floor((Math.min(r.width,r.height)-z)/2)),l=a==="accent"?Math.min(I,t):0;return Math.min(t,Math.max(l,o))}function me(e){const a=e??{},r=c,o=U(a[n.shape],le,r.shape),t=U(a[n.background],ce,r.background),l=w(a[n.width],i.width,r.width),g=w(a[n.height],i.height,r.height);return{shape:o,width:l,height:g,radius:w(a[n.radius],i.radius,r.radius),background:t,shadow:ue(a[n.shadow],r.shadow),padding:he(o,t,W({shape:o,width:l,height:g}),w(a[n.padding],i.padding,r.padding)),offsetX:w(a[n.offsetX],i.offsetX,r.offsetX),offsetY:w(a[n.offsetY],i.offsetY,r.offsetY)}}const D={accent:"var(--ai-accent)",neutral:"var(--ai-bg)",none:"transparent"};function fe(e){const{width:a,height:r}=W(e),o=e.shape==="circle"?"50%":e.shape==="pill"?"calc(var(--es-demo-launcher-h) / 2)":`${e.radius}px`;return{"--es-demo-launcher-w":`${a}px`,"--es-demo-launcher-h":`${r}px`,"--es-demo-launcher-radius":o,"--es-demo-launcher-bg":D[e.background],"--es-demo-launcher-dot-ring":e.background==="none"?D.neutral:D[e.background],"--es-demo-launcher-shadow":e.shadow?"var(--ai-shadow)":"none","--es-demo-launcher-pad":`${e.padding}px`,"--es-demo-launcher-coin":`${ie}`,"--es-demo-launcher-mark-min":`${z}px`,"--es-demo-launcher-x":`${e.offsetX}px`,"--es-demo-launcher-y":`${e.offsetY}px`}}const ye={slug:"demo",name:"Demo",version:"0.1.0",slots:["header","main","footer"],cssVariables:{"--ai-accent":_},structure:{header:{id:"header",label:"Header",accepts:!0},main:{id:"main",label:"Main Content",accepts:!0},footer:{id:"footer",label:"Footer",accepts:!0}},defaultViews:[],requiredServices:["support-chat"],description:"Neutral, brand-adaptive shell for demo clones. Carries no mascot and no brand of its own: the logo, name and accent colour all come from the product, and the rest of the palette is derived around them so it stays legible for any input.",author:"E-Commerce Studio",packageName:"@ecommerce-studio/theme-demo",options:[{id:"colorScheme",type:"select",label:"Appearance mode",default:"auto",group:"Appearance",options:[{label:"Auto (match visitor)",value:"auto"},{label:"Light",value:"light"},{label:"Dark",value:"dark"}]},{id:"brandColor",type:"color",label:"Brand colour",default:_,cssVariable:"--ai-accent",group:"Colors"},{id:"launcherShape",type:"select",label:"Button shape",default:c.shape,cssVariable:n.shape,group:"Launcher",options:[{label:"Pill (wordmark on a chip)",value:"pill"},{label:"Circle",value:"circle"},{label:"Square",value:"square"},{label:"Rectangle",value:"rectangle"}]},{id:"launcherWidth",type:"range",label:"Width (side for circle / square)",default:c.width,unit:"px",cssVariable:n.width,group:"Launcher",...i.width},{id:"launcherHeight",type:"range",label:"Height (pill / rectangle)",default:c.height,unit:"px",cssVariable:n.height,group:"Launcher",...i.height},{id:"launcherRadius",type:"range",label:"Corner radius (square / rectangle)",default:c.radius,unit:"px",cssVariable:n.radius,group:"Launcher",...i.radius},{id:"launcherBackground",type:"select",label:"Background",default:c.background,cssVariable:n.background,group:"Launcher",options:[{label:"Brand colour",value:"accent"},{label:"Neutral",value:"neutral"},{label:"None (transparent)",value:"none"}]},{id:"launcherShadow",type:"toggle",label:"Shadow",default:c.shadow,cssVariable:n.shadow,group:"Launcher"},{id:"launcherPadding",type:"range",label:"Logo padding",default:c.padding,unit:"px",cssVariable:n.padding,group:"Launcher",...i.padding},{id:"launcherOffsetX",type:"range",label:"Distance from side",default:c.offsetX,unit:"px",cssVariable:n.offsetX,group:"Launcher",...i.offsetX},{id:"launcherOffsetY",type:"range",label:"Distance from bottom",default:c.offsetY,unit:"px",cssVariable:n.offsetY,group:"Launcher",...i.offsetY}],supports:{customCss:!1,customJs:!1,darkMode:!0,rtl:!1,views:!0}};function pe(e){const a=[e?.["--ai-accent"],e?.["--es-color-primary"]];for(const r of a)if(typeof r=="string"&&E(r))return r;return _}function ge(e){const a=(e??"").trim().split(/\s+/).filter(Boolean);return a.length===0?"":a.slice(0,2).map(r=>[...r][0]??"").join("").toLocaleUpperCase()}function ke({brandName:e="",logoUrl:a,position:r="bottom-right",sidebarPosition:o="right",initialOpen:t=!1,views:l=[],activeView:g="",onViewChange:v=()=>{},children:b=null,cssVariables:p,t:d,colorScheme:C,builderMode:j=!1,builderPresentation:k="inline",open:h,direction:F="ltr",unreadCount:B=0,onSettingsClick:Fe,onOpenChange:$,panelReadAloudControl:G}){const N=ae(C)==="light"?"light":"dark",m=j&&k!=="floating",[f,L]=x.useState(h??(t||m)),S=x.useRef(f);x.useEffect(()=>{S.current=f},[f]),x.useEffect(()=>{h===void 0||h===S.current||(S.current=h,L(h))},[h]);const A=x.useMemo(()=>me(p),[p]),J=x.useMemo(()=>({...V({brandColor:pe(p),mode:N}),...fe(A),...m?{width:"100%",height:"100%"}:{}}),[p,A,N,m]),Q=()=>L(u=>{const y=!u;return $?.(y),y}),Z=()=>{L(!1),$?.(!1)},X=r==="bottom-left",Y=o!=="hidden"&&l.length>1,M=ge(e);return s.jsxs("div",{className:["es-demo",`es-demo--${N}`].join(" "),dir:F,style:{...J,direction:F},children:[!m&&s.jsxs("button",{type:"button",className:["es-demo__launcher",`es-demo__launcher--${A.shape}`,`es-demo__launcher--bg-${A.background}`,X&&"es-demo__launcher--left",f&&"es-demo__launcher--hidden"].filter(Boolean).join(" "),onClick:Q,"aria-label":d?.("floating.open_widget")??"Open chat widget",tabIndex:f?-1:0,"aria-hidden":f,children:[a?s.jsx("img",{className:"es-demo__launcher-logo",src:a,alt:""}):s.jsx("span",{className:"es-demo__launcher-monogram","aria-hidden":"true",children:M||"•"}),B>0&&s.jsx("span",{className:"es-demo__launcher-dot","aria-label":d?.("floating.unread",{count:B})??`${B} unread`})]}),s.jsxs("div",{className:["es-demo__panel",X&&!m&&"es-demo__panel--left",(f||m)&&"es-demo__panel--open"].filter(Boolean).join(" "),role:"dialog","aria-label":d?.("chat.widget_aria")??"Chat widget","aria-hidden":m?!1:!f,children:[s.jsxs("header",{className:"es-demo__header",children:[s.jsxs("div",{className:"es-demo__brand",children:[a?s.jsx("img",{className:"es-demo__brand-logo",src:a,alt:""}):M&&s.jsx("span",{className:"es-demo__brand-monogram","aria-hidden":"true",children:M}),e&&s.jsx("h1",{className:"es-demo__brand-name",children:e})]}),s.jsxs("div",{className:"es-demo__header-actions",children:[G,!m&&s.jsx("button",{type:"button",className:"es-demo__header-btn",onClick:Z,"aria-label":d?.("header.close_widget")??"Close widget",children:s.jsx(be,{})})]})]}),s.jsxs("div",{className:["es-demo__body",Y&&`es-demo__body--rail-${o}`].filter(Boolean).join(" "),children:[Y&&s.jsx("nav",{className:`es-demo__rail es-demo__rail--${o}`,"aria-label":d?.("nav.views")??"Views",children:l.map(u=>{const y=re(u.icon||u.slug),R=u.slug===g;return s.jsxs("button",{type:"button",className:["es-demo__rail-item",R&&"es-demo__rail-item--active"].filter(Boolean).join(" "),onClick:()=>v(u.slug),"aria-current":R?"page":void 0,title:u.label,children:[y?s.jsx(y,{size:20}):null,s.jsx("span",{className:"es-demo__rail-label",children:u.label})]},u.slug)})}),s.jsx("main",{className:"es-demo__content",style:{containerName:"es-slot",containerType:"inline-size"},children:b})]})]})]})}function be({size:e=20}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"m6 9 6 6 6-6"})})}export{_ as DEFAULT_BRAND,c as LAUNCHER_DEFAULTS,i as LAUNCHER_LIMITS,n as LAUNCHER_VARS,oe as TEXT_FLOOR,ke as ThemeShell,ve as darkVariables,V as deriveDemoPalette,ne as hoverStep,O as inkOn,fe as launcherRootStyle,_e as lightVariables,ye as manifest,ge as monogram,me as resolveLauncherSettings};
@@ -0,0 +1 @@
1
+ import{r as i,Q as B,j as e,l as j}from"../nexly.js";const z={slug:"auth-login",name:"User Login",version:"1.0.0",category:"interactive",requiredService:"",configSchema:{properties:{loginMethod:{type:"string",default:"password"},showGuestOption:{type:"boolean",default:!0},submitLabel:{type:"string",default:""}}},defaultConfig:{loginMethod:"password",showGuestOption:!0,submitLabel:""},dataContract:{serviceSlug:"chat-bot",inputSchema:{type:"object",properties:{authenticated:{type:"boolean"}}},previewDataOverride:{authenticated:!1}},fields:[{id:"loginMethod",type:"select",label:"Login method",default:"password",options:[{label:"Password",value:"password"},{label:"Magic Link",value:"magic-link"},{label:"Guest",value:"guest"}],group:"Behavior"},{id:"showGuestOption",type:"toggle",label:"Show guest login option",default:!0,group:"Behavior"},{id:"submitLabel",type:"localized-text",label:"Submit button label",default:"",placeholder:'Leave empty to use translated default (e.g. "Login")',group:"Content"}],events:{emits:[{name:"auth:login",description:"User successfully logged in — carries { user, accessToken }"},{name:"auth:loginFailed",description:"Login attempt failed"},{name:"auth:guestContinued",description:"User chose to continue as guest"}],listens:[{name:"auth:reset",description:"Reset the login form"}]},supportedPlacements:["main"],sizing:{minWidth:280,preferredHeight:"auto",scrollable:!1}};function L({config:u,actions:s,i18n:d}){const r=d?.t??(o=>o),h=d?.currentLanguage??"en",[p,m]=i.useState(""),[g,y]=i.useState(""),[b,v]=i.useState(""),[l,n]=i.useState(!1),[c,t]=i.useState(null),f=u.loginMethod??"password",x=u.showGuestOption??!0,w=B(u.submitLabel,h,{t:r,fallbackKey:"auth.login.submit",enDefault:"Login"});async function S(o){o.preventDefault(),n(!0),t(null);try{let a;f==="api_key"?a=await s.call("login",{apiKey:p}):a=await s.call("login",{email:g,password:b}),a?.error?t({error:a.error}):(s.emit("auth:login",{user:a.user,accessToken:a.accessToken}),t({success:!0,user:a?.user}))}catch{t({error:r("auth.login.error_failed")})}finally{n(!1)}}async function k(){n(!0),t(null);try{const o=await s.call("login",{guest:!0});o?.error?t({error:o.error}):(s.emit("auth:login",{user:o.user}),t({success:!0}))}catch{t({error:r("auth.login.error_guest_failed")})}finally{n(!1)}}return c?.success?null:e.jsx(j,{blockType:"auth-login",children:e.jsxs("div",{className:"es-block__body",style:{padding:16},children:[e.jsxs("form",{onSubmit:S,children:[f==="api_key"?e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("label",{style:{display:"block",fontSize:12,color:"var(--es-color-on-surface-muted, #4B5563)",marginBottom:4},children:r("auth.login.api_key_label")}),e.jsx("input",{type:"text",value:p,onChange:o=>m(o.target.value),placeholder:"eu_live_...",required:!0,style:{width:"100%",padding:"8px 12px",borderRadius:6,border:"1px solid var(--es-color-control-border, #6B7280)",background:"var(--es-color-surface-elevated, #f5f5f5)",color:"var(--es-color-on-surface, #1a1a1a)",fontSize:14,outline:"none",fontFamily:"monospace",boxSizing:"border-box"}})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("label",{style:{display:"block",fontSize:12,color:"var(--es-color-on-surface-muted, #4B5563)",marginBottom:4},children:r("auth.email_label")}),e.jsx("input",{type:"email",value:g,onChange:o=>y(o.target.value),placeholder:r("auth.email_placeholder"),required:!0,style:{width:"100%",padding:"8px 12px",borderRadius:6,border:"1px solid var(--es-color-control-border, #6B7280)",background:"var(--es-color-surface-elevated, #f5f5f5)",color:"var(--es-color-on-surface, #1a1a1a)",fontSize:14,outline:"none",boxSizing:"border-box"}})]}),e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("label",{style:{display:"block",fontSize:12,color:"var(--es-color-on-surface-muted, #4B5563)",marginBottom:4},children:r("auth.password_label")}),e.jsx("input",{type:"password",value:b,onChange:o=>v(o.target.value),placeholder:r("auth.password_placeholder"),required:!0,style:{width:"100%",padding:"8px 12px",borderRadius:6,border:"1px solid var(--es-color-control-border, #6B7280)",background:"var(--es-color-surface-elevated, #f5f5f5)",color:"var(--es-color-on-surface, #1a1a1a)",fontSize:14,outline:"none",boxSizing:"border-box"}})]})]}),c?.error&&e.jsx("div",{style:{fontSize:12,color:"var(--es-color-error, #AD2C26)",marginBottom:8},children:c.error}),e.jsx("button",{type:"submit",disabled:l,style:{width:"100%",padding:"10px 16px",borderRadius:6,border:"none",background:l?"var(--es-color-on-surface-muted, #4B5563)":"var(--es-color-primary, #2563EB)",color:"var(--es-color-on-primary, #ffffff)",fontSize:14,fontWeight:600,cursor:l?"wait":"pointer"},children:l?r("auth.login.submitting"):w})]}),x&&e.jsx("button",{type:"button",onClick:k,disabled:l,style:{width:"100%",marginTop:8,padding:"8px 16px",borderRadius:6,border:"1px solid var(--es-color-control-border, #6B7280)",background:"transparent",color:"var(--es-color-on-surface-muted, #4B5563)",fontSize:13,cursor:l?"wait":"pointer"},children:r("auth.gate.guest_cta")})]})})}export{L as Component,z as manifest};
@@ -0,0 +1 @@
1
+ import{r as d,j as e,l as n}from"../nexly.js";const M={slug:"presentation-trainer",name:"Presentation Training",version:"1.0.0",category:"interactive",requiredService:"presentation-training",configSchema:{properties:{timeWarningPercent:{type:"number",default:20},showHints:{type:"boolean",default:!0}}},defaultConfig:{timeWarningPercent:20,showHints:!0},dataContract:{serviceSlug:"presentation-training",inputSchema:{type:"object",properties:{scenarios:{type:"array",description:"Live scenarios in the learner’s language, in author order"},remainingToday:{type:"number",description:"Sessions the learner may still start today"},dailyLimit:{type:"number",description:"Configured sessions per user per day"},productBudgetSpent:{type:"boolean",description:"True when the product’s monthly audio budget is exhausted"}}}},sizing:{minWidth:280,preferredHeight:"auto",scrollable:!0},supportedPlacements:["main"]},T={state:"idle",errorKey:null,turns:[],elapsedSec:0,maxSessionSec:0,hint:null,report:null,gradeErrorKey:null};function f(p){return p.trim().split(/\s+/).filter(Boolean).slice(0,2).map(o=>o[0]?.toUpperCase()??"").join("")||"—"}function $(p){const o=Math.floor(p/60),x=p%60;return`${o}:${String(x).padStart(2,"0")}`}function E({data:p,config:o,actions:x,i18n:N}){const t=N?.t??(s=>s),r=x?.externalContext?.trainer,m=p??{},g=d.useMemo(()=>m.scenarios??[],[m.scenarios]),h=m.remainingToday??0,y=m.dailyLimit??0,[u,_]=d.useState(null),[k,l]=d.useState(!1),[a,S]=d.useState(r?.get()??T);d.useEffect(()=>r?.subscribe(S),[r]),d.useEffect(()=>()=>r?.stop(),[r]);const i=g.find(s=>s.id===u)??null,b=a.state==="connecting"||a.state==="speaking"||a.state==="listening",C=Math.max(30,Math.min(60,Math.round(a.maxSessionSec*(o.timeWarningPercent??20)/100))),w=Math.max(0,a.maxSessionSec-a.elapsedSec),v=b&&a.maxSessionSec>0&&w<=C,j=d.useCallback(()=>{u&&r?.start(u)},[u,r]);if(m.productBudgetSpent)return e.jsx(n,{blockType:"presentation-trainer",children:e.jsx("div",{className:"es-pt","data-testid":"pt-budget-spent",children:e.jsx("p",{className:"es-pt__notice es-pt__notice--warn",children:t("training.product_budget_spent")})})});if(g.length===0)return e.jsx(n,{blockType:"presentation-trainer",children:e.jsx("div",{className:"es-pt","data-testid":"pt-empty",children:e.jsx("p",{className:"es-pt__empty",children:t("training.no_scenarios")})})});if(i&&(a.state==="grading"||a.report||a.gradeErrorKey)){if(a.state==="grading")return e.jsx(n,{blockType:"presentation-trainer",children:e.jsx("div",{className:"es-pt","data-testid":"pt-grading",children:e.jsx("p",{className:"es-pt__muted",children:t("training.grading")})})});if(!a.report)return e.jsx(n,{blockType:"presentation-trainer",children:e.jsxs("div",{className:"es-pt","data-testid":"pt-grade-failed",children:[e.jsx("p",{className:"es-pt__notice es-pt__notice--warn",children:t(`training.grade_${a.gradeErrorKey??"grader_failed"}`)}),e.jsx("button",{type:"button",className:"es-pt__cta es-pt__cta--ghost",onClick:()=>{l(!1),_(null)},children:t("training.back_to_list")})]})});const s=a.report;return e.jsx(n,{blockType:"presentation-trainer",children:e.jsxs("div",{className:"es-pt","data-testid":"pt-report",children:[e.jsxs("div",{className:"es-pt__score",children:[e.jsxs("span",{className:`es-pt__score-value${s.passed?"":" es-pt__score-value--fail"}`,"data-testid":"pt-score",children:[s.totalScore,"%"]}),e.jsx("span",{className:"es-pt__muted",children:s.passed?t("training.passed",{threshold:s.passThreshold}):t("training.not_passed",{threshold:s.passThreshold})})]}),s.feedback&&e.jsxs("div",{className:"es-pt__feedback","data-testid":"pt-feedback",children:[e.jsx("span",{className:"es-pt__turn-who",children:t("training.to_improve")}),s.feedback.headline,s.feedback.quote&&e.jsx("q",{className:"es-pt__quote",children:s.feedback.quote})]}),e.jsx("div",{className:"es-pt__criteria",children:s.criteria.map(c=>e.jsxs("div",{className:"es-pt__criterion",children:[e.jsxs("div",{className:"es-pt__criterion-row",children:[e.jsx("span",{className:"es-pt__criterion-label",children:c.label}),e.jsxs("span",{className:"es-pt__criterion-score",children:[c.score,"/4"]})]}),e.jsx("p",{className:"es-pt__muted",children:c.rationale}),c.quote&&e.jsx("q",{className:"es-pt__quote",children:c.quote})]},c.key))}),s.delivery&&e.jsxs("div",{className:"es-pt__delivery","data-testid":"pt-delivery",children:[e.jsx("span",{className:"es-pt__turn-who",children:t("training.how_you_spoke")}),e.jsxs("div",{className:"es-pt__delivery-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:t("training.longest_monologue")}),e.jsxs("b",{children:[s.delivery.longestMonologueSec,"s"]})]}),e.jsxs("div",{children:[e.jsx("span",{children:t("training.talk_share")}),e.jsxs("b",{children:[s.delivery.talkSharePercent,"%"]})]}),e.jsxs("div",{children:[e.jsx("span",{children:t("training.response_delay")}),e.jsxs("b",{children:[s.delivery.medianResponseDelaySec,"s"]})]}),e.jsxs("div",{children:[e.jsx("span",{children:t("training.exchanges")}),e.jsx("b",{children:s.delivery.exchanges})]}),e.jsxs("div",{children:[e.jsx("span",{children:t(`training.rate_${s.delivery.rateUnit}`)}),e.jsx("b",{children:s.delivery.rate})]})]})]}),e.jsx("button",{type:"button",className:"es-pt__cta",onClick:j,"data-testid":"pt-retry",children:t("training.try_again")}),e.jsx("button",{type:"button",className:"es-pt__cta es-pt__cta--ghost",onClick:()=>{l(!1),_(null)},children:t("training.back_to_list")})]})})}if(i&&(b||a.state==="ending"||a.state==="error"||a.state==="closed"))return a.state==="error"?e.jsx(n,{blockType:"presentation-trainer",children:e.jsxs("div",{className:"es-pt","data-testid":"pt-error",children:[e.jsx("p",{className:"es-pt__notice es-pt__notice--bad",children:t(`training.error_${a.errorKey??"generic"}`)}),e.jsx("button",{type:"button",className:"es-pt__cta",onClick:j,children:t("training.try_again")}),e.jsx("button",{type:"button",className:"es-pt__cta es-pt__cta--ghost",onClick:()=>{l(!1),_(null)},children:t("training.back_to_list")})]})}):e.jsx(n,{blockType:"presentation-trainer",children:e.jsxs("div",{className:"es-pt","data-testid":"pt-conversation",children:[e.jsxs("div",{className:"es-pt__strip",children:[e.jsx("div",{className:`es-pt__avatar${a.state==="speaking"?" es-pt__avatar--speaking":""}`,"aria-hidden":"true",children:f(i.personaName)}),e.jsxs("div",{className:"es-pt__strip-meta",children:[e.jsx("div",{className:"es-pt__strip-name",children:i.personaName}),e.jsxs("div",{className:"es-pt__strip-state",children:[a.state==="connecting"&&t("training.state_connecting"),a.state==="speaking"&&t("training.state_speaking"),a.state==="listening"&&t("training.state_listening"),a.state==="ending"&&t("training.state_ending"),a.state==="closed"&&t("training.state_closed")]})]})]}),e.jsx("div",{className:"es-pt__transcript","data-testid":"pt-transcript","aria-live":"polite",children:a.turns.length===0?e.jsx("p",{className:"es-pt__muted",children:t("training.transcript_empty")}):a.turns.map((s,c)=>e.jsxs("div",{className:`es-pt__turn es-pt__turn--${s.role}${s.final?"":" es-pt__turn--live"}`,children:[e.jsx("span",{className:"es-pt__turn-who",children:s.role==="persona"?i.personaName:t("training.you")}),s.text]},c))}),o.showHints!==!1&&a.hint&&e.jsx("p",{className:"es-pt__hint","data-testid":"pt-hint",children:a.hint}),v&&!a.hint&&e.jsx("p",{className:"es-pt__hint","data-testid":"pt-time-warning",children:t("training.time_almost_up")}),e.jsxs("div",{className:"es-pt__controls",children:[e.jsx("span",{className:`es-pt__timer${v?" es-pt__timer--warn":""}`,"data-testid":"pt-timer",children:$(a.elapsedSec)}),a.state==="closed"?e.jsx("button",{type:"button",className:"es-pt__cta es-pt__cta--ghost",onClick:()=>{l(!1),_(null)},children:t("training.back_to_list")}):e.jsx("button",{type:"button",className:"es-pt__end",onClick:()=>r?.stop(),children:t("training.end_conversation")})]})]})});if(i&&k)return e.jsx(n,{blockType:"presentation-trainer",children:e.jsxs("div",{className:"es-pt","data-testid":"pt-history",children:[e.jsxs("div",{className:"es-pt__strip",children:[e.jsx("button",{type:"button",className:"es-pt__back",onClick:()=>l(!1),"aria-label":t("training.back"),children:"←"}),e.jsxs("div",{className:"es-pt__strip-meta",children:[e.jsx("div",{className:"es-pt__strip-name",children:t("training.your_attempts")}),e.jsx("div",{className:"es-pt__strip-state",children:i.title})]})]}),i.history.length===0?e.jsx("p",{className:"es-pt__muted",children:t("training.no_attempts_yet")}):e.jsx("ul",{className:"es-pt__attempts",children:i.history.map(s=>e.jsxs("li",{className:"es-pt__attempt",children:[e.jsx("span",{className:"es-pt__attempt-date",children:new Intl.DateTimeFormat(N?.currentLanguage??"en",{day:"numeric",month:"short"}).format(new Date(s.at))}),e.jsx("span",{className:"es-pt__attempt-score",children:s.score===null?t("training.not_scored"):`${s.score}%`}),s.status!=="completed"&&e.jsx("span",{className:"es-pt__pill",children:t(`training.status_${s.status}`)})]},s.sessionId))})]})});if(i){const s=h<=0;return e.jsx(n,{blockType:"presentation-trainer",children:e.jsxs("div",{className:"es-pt","data-testid":"pt-brief",children:[e.jsxs("div",{className:"es-pt__strip",children:[e.jsx("button",{type:"button",className:"es-pt__back",onClick:()=>{l(!1),_(null)},"aria-label":t("training.back_to_list"),children:"←"}),e.jsx("div",{className:"es-pt__avatar","aria-hidden":"true",children:f(i.personaName)}),e.jsxs("div",{className:"es-pt__strip-meta",children:[e.jsx("div",{className:"es-pt__strip-name",children:i.personaName}),e.jsx("div",{className:"es-pt__strip-state",children:i.title})]}),e.jsxs("div",{className:"es-pt__strip-right",children:[e.jsx("span",{className:`es-pt__pill es-pt__pill--${i.difficulty}`,children:t(`training.difficulty_${i.difficulty}`)}),e.jsx("span",{className:"es-pt__strip-time",children:t("training.minutes",{count:Math.round(i.maxDurationSec/60)})})]})]}),e.jsx("div",{className:"es-pt__situation",children:i.situation}),e.jsx("p",{className:"es-pt__muted",children:t("training.sessions_left",{count:h,total:y})}),s?e.jsx("p",{className:"es-pt__notice es-pt__notice--warn",children:t("training.daily_limit_reached")}):e.jsx("button",{type:"button",className:"es-pt__cta",onClick:j,"data-testid":"pt-start",children:t("training.start_conversation")}),i.attempts>0&&e.jsx("button",{type:"button",className:"es-pt__cta es-pt__cta--ghost",onClick:()=>l(!0),"data-testid":"pt-history-open",children:t("training.see_attempts",{count:i.attempts})})]})})}return e.jsx(n,{blockType:"presentation-trainer",children:e.jsxs("div",{className:"es-pt","data-testid":"pt-list",children:[e.jsxs("div",{className:"es-pt__quota",children:[e.jsx("span",{children:t("training.sessions_today")}),e.jsx("b",{children:t("training.sessions_left_short",{count:h,total:y})})]}),g.map(s=>e.jsxs("button",{type:"button",className:"es-pt__scenario",onClick:()=>_(s.id),disabled:h<=0,children:[e.jsxs("span",{className:"es-pt__scenario-row",children:[e.jsx("span",{className:"es-pt__scenario-title",children:s.title}),e.jsx("span",{className:`es-pt__pill es-pt__pill--${s.difficulty}`,children:t(`training.difficulty_${s.difficulty}`)})]}),e.jsxs("span",{className:"es-pt__scenario-meta",children:[t("training.minutes",{count:Math.round(s.maxDurationSec/60)}),s.attempts>0&&e.jsxs(e.Fragment,{children:[" · ",t("training.best_score",{score:s.bestScore??0})," · ",t("training.last_score",{score:s.lastScore??0})," · ",t("training.attempts",{count:s.attempts})]}),s.attempts===0&&e.jsxs(e.Fragment,{children:[" · ",t("training.not_attempted")]})]})]},s.id)),h<=0&&e.jsx("p",{className:"es-pt__notice es-pt__notice--warn",children:t("training.daily_limit_reached")})]})})}export{E as Component,M as manifest};
@@ -0,0 +1 @@
1
+ import{r as g,j as a,l as B}from"../nexly.js";import{C as K}from"./block-rating-_Uu_PSxk-DTJYlp2H.js";import{m as L}from"./block-helpers-Cg_zAqG6-DnN2COvk.js";const v=["G-Miner","Miner","Developer","Team Leader","Manager","Senior Manager","Vice President","President","Chairman"],F={"G-Miner":0,Miner:2,Developer:4,"Team Leader":6,Manager:7,"Senior Manager":8,"Vice President":9,President:10,Chairman:15},W={"G-Miner":0,Miner:2,Developer:4,"Team Leader":6,Manager:8,"Senior Manager":9,"Vice President":10,President:11,Chairman:12},A={"G-Miner":50,Miner:50,Developer:50,"Team Leader":50,Manager:50,"Senior Manager":50,"Vice President":50,President:50,Chairman:75},X=.1,I=50,O=150,U=5,R=1,$=10,z=5e4,H=100,q=7,J=30,S={paidRank:"Miner",scp1Cycles:1,scp1PerCycle:100,scp2Cycles:1,scp2PerCycle:5,scp3DirectSales:500};function E(e){return typeof e=="string"&&v.includes(e)}function G(e,d){const c=F[d];return!Number.isFinite(e)||e<0?0:Math.min(e,c)}function Q(e,d){const c=A[d];return!Number.isFinite(e)||e<0?0:Math.min(e,c)}function Y(e){const d=e.paidRank==="G-Miner",c=d?0:Math.max(0,e.scp1Cycles)*Math.max(0,e.scp1PerCycle),s=d?0:Math.max(0,e.scp2Cycles)*Math.max(0,e.scp2PerCycle),m=Math.round(Math.max(0,e.scp3DirectSales)*X),o=c+s+m,x=o*q,l=o*J;return{scp1Daily:c,scp2Daily:s,scp3Daily:m,totalDaily:o,totalWeekly:x,totalMonthly:l}}function Z(e,d){const c=d.currentPayoutRank,s=e.defaultPaidRank,m=E(c)?c:E(s)?s:v[0],o=e.defaultScp2PerCycle,x=typeof o=="number"&&Number.isFinite(o)?Math.min($,Math.max(R,o)):S.scp2PerCycle;return{...S,paidRank:m,scp1Cycles:G(S.scp1Cycles,m),scp2PerCycle:x}}function p(e,d,c){return`${c}${new Intl.NumberFormat(d,{style:"decimal",minimumFractionDigits:0,maximumFractionDigits:0}).format(e)}`}function N({id:e,label:d,value:c,min:s,max:m,step:o,unit:x,currencySymbol:l,locale:n,disabled:b,onChange:i}){const C=x==="$"?p(c,n,l):c.toLocaleString(n),u=x==="$"?p(s,n,l):String(s),t=x==="$"?p(m,n,l):String(m);return a.jsxs("div",{className:`mlmcalc-slider-row${b?" mlmcalc-slider-row--disabled":""}`,children:[a.jsxs("div",{className:"mlmcalc-slider-header",children:[a.jsx("label",{className:"mlmcalc-slider-label",htmlFor:e,children:d}),a.jsx("span",{className:"mlmcalc-slider-value",children:C})]}),a.jsx("input",{id:e,type:"range",className:"mlmcalc-slider",min:s,max:m,step:o,value:c,disabled:b,onChange:h=>i(Number(h.target.value)),onPointerDown:h=>{if(b)return;const k=h.currentTarget.getBoundingClientRect(),f=h.clientX-k.left,M=m-s;if(M<=0)return;const _=(c-s)/M*k.width;if(Math.abs(f-_)<=12)return;const j=Math.max(0,Math.min(1,f/k.width)),D=s+j*M,P=Math.max(s,Math.min(m,Math.round((D-s)/o)*o+s));let r=P;if(P===c){const y=f>_?1:-1;r=Math.max(s,Math.min(m,c+y*o))}r!==c&&(h.preventDefault(),i(r))},style:{"--mlmcalc-fill":`${m>s?(c-s)/(m-s)*100:0}%`}}),a.jsxs("div",{className:"mlmcalc-slider-bounds",children:[a.jsx("span",{children:u}),a.jsx("span",{children:t})]})]})}function ca({data:e,config:d,i18n:c,baseUrl:s,externalContext:m,auth:o,previewMode:x}){const l=c?.t??(r=>r),n=c?.currentLanguage??"en",b=g.useMemo(()=>Z(d,e),[d,e]),[i,C]=g.useState(b),u=g.useMemo(()=>Y(i),[i]),t=l("mlm_calculator.currency_symbol"),h=i.paidRank==="G-Miner",k=F[i.paidRank],f=A[i.paidRank],M=W[i.paidRank],_=g.useCallback(r=>{C(y=>({...y,paidRank:r,scp1Cycles:G(y.scp1Cycles,r),scp2Cycles:Q(y.scp2Cycles,r)}))},[]),j=g.useCallback(r=>y=>{C(w=>({...w,[r]:y}))},[]),D=g.useCallback(()=>{C(b)},[b]),P=v.indexOf(i.paidRank);return a.jsx(B,{blockType:"mlm-calculator",children:a.jsxs("div",{className:"es-block__body",children:[a.jsx(K,{blockSlug:"mlm-calculator",baseUrl:s,apiKey:m?.apiKey,jwt:o?.jwt,previewMode:x,t:l,promptKey:"block_rating.prompt_calculator"}),a.jsxs("div",{className:"mlmcalc-block","aria-label":l("mlm_calculator.aria_label"),children:[a.jsx("div",{className:"mlmcalc-title",children:l("mlm_calculator.title")}),a.jsxs("div",{className:"mlmcalc-rank-bar",children:[a.jsx("span",{className:"mlmcalc-rank-label",children:l("mlm_calculator.paid_rank")}),a.jsx("div",{className:"mlmcalc-rank-track",role:"radiogroup","aria-label":l("mlm_calculator.paid_rank"),children:v.map((r,y)=>{const w=r===i.paidRank,T=y<=P,V=["mlmcalc-rank-node",y%2===0?"mlmcalc-rank-node--above":"mlmcalc-rank-node--below",w?"mlmcalc-rank-node--active":"",T?"mlmcalc-rank-node--past":""].filter(Boolean).join(" ");return a.jsxs("button",{type:"button",role:"radio","aria-checked":w,"aria-label":L(r,l),className:V,onClick:()=>_(r),children:[a.jsx("span",{className:"mlmcalc-rank-dot","aria-hidden":"true"}),a.jsx("span",{className:"mlmcalc-rank-name",children:L(r,l)})]},r)})})]}),a.jsxs("div",{className:"mlmcalc-earnings-grid",children:[a.jsxs("div",{className:"mlmcalc-earnings-card",children:[a.jsx("span",{className:"mlmcalc-earnings-label",children:l("mlm_calculator.weekly")}),a.jsx("span",{className:"mlmcalc-earnings-amount",children:p(u.totalWeekly,n,t)})]}),a.jsxs("div",{className:"mlmcalc-earnings-card",children:[a.jsx("span",{className:"mlmcalc-earnings-label",children:l("mlm_calculator.monthly")}),a.jsx("span",{className:"mlmcalc-earnings-amount mlmcalc-earnings-amount--monthly",children:p(u.totalMonthly,n,t)})]})]}),h&&a.jsx("div",{className:"mlmcalc-warning",role:"alert",children:l("mlm_calculator.warning.g_miner")}),a.jsxs("div",{className:"mlmcalc-scp-group",children:[a.jsxs("div",{className:"mlmcalc-scp-header",children:[a.jsx("span",{className:"mlmcalc-scp-title",children:l("mlm_calculator.scp1.title")}),a.jsx("span",{className:"mlmcalc-scp-subtotal",children:l("mlm_calculator.subtotal_per_day",{amount:p(u.scp1Daily,n,t)})})]}),a.jsx(N,{id:"mlmcalc-scp1-cycles",label:l("mlm_calculator.scp1.cycles"),value:i.scp1Cycles,min:0,max:k,step:1,unit:"",currencySymbol:t,locale:n,disabled:h,onChange:j("scp1Cycles")}),a.jsx(N,{id:"mlmcalc-scp1-per-cycle",label:l("mlm_calculator.scp1.per_cycle"),value:i.scp1PerCycle,min:I,max:O,step:U,unit:"$",currencySymbol:t,locale:n,disabled:h,onChange:j("scp1PerCycle")})]}),a.jsxs("div",{className:"mlmcalc-scp-group",children:[a.jsxs("div",{className:"mlmcalc-scp-header",children:[a.jsx("span",{className:"mlmcalc-scp-title",children:l("mlm_calculator.scp2.title")}),a.jsx("span",{className:"mlmcalc-scp-subtotal",children:l("mlm_calculator.subtotal_per_day",{amount:p(u.scp2Daily,n,t)})})]}),a.jsx(N,{id:"mlmcalc-scp2-cycles",label:l("mlm_calculator.scp2.cycles",{levels:M}),value:i.scp2Cycles,min:0,max:f,step:1,unit:"",currencySymbol:t,locale:n,disabled:h,onChange:j("scp2Cycles")}),a.jsx(N,{id:"mlmcalc-scp2-per-cycle",label:l("mlm_calculator.scp2.per_cycle"),value:i.scp2PerCycle,min:R,max:$,step:1,unit:"$",currencySymbol:t,locale:n,disabled:h,onChange:j("scp2PerCycle")})]}),a.jsxs("div",{className:"mlmcalc-scp-group",children:[a.jsxs("div",{className:"mlmcalc-scp-header",children:[a.jsx("span",{className:"mlmcalc-scp-title",children:l("mlm_calculator.scp3.title")}),a.jsx("span",{className:"mlmcalc-scp-subtotal",children:l("mlm_calculator.subtotal_per_day",{amount:p(u.scp3Daily,n,t)})})]}),a.jsx(N,{id:"mlmcalc-scp3-sales",label:l("mlm_calculator.scp3.daily_sales"),value:i.scp3DirectSales,min:0,max:z,step:H,unit:"$",currencySymbol:t,locale:n,onChange:j("scp3DirectSales")})]}),a.jsxs("div",{className:"mlmcalc-breakdown",children:[a.jsxs("div",{className:"mlmcalc-breakdown-row",children:[a.jsx("span",{children:l("mlm_calculator.breakdown.scp1")}),a.jsx("span",{children:p(u.scp1Daily,n,t)})]}),a.jsxs("div",{className:"mlmcalc-breakdown-row",children:[a.jsx("span",{children:l("mlm_calculator.breakdown.scp2")}),a.jsx("span",{children:p(u.scp2Daily,n,t)})]}),a.jsxs("div",{className:"mlmcalc-breakdown-row",children:[a.jsx("span",{children:l("mlm_calculator.breakdown.scp3")}),a.jsx("span",{children:p(u.scp3Daily,n,t)})]}),a.jsxs("div",{className:"mlmcalc-breakdown-row mlmcalc-breakdown-row--total",children:[a.jsx("span",{children:l("mlm_calculator.breakdown.total")}),a.jsx("span",{children:p(u.totalDaily,n,t)})]})]}),a.jsx("div",{className:"mlmcalc-actions",children:a.jsx("button",{type:"button",className:"mlmcalc-reset",onClick:D,children:l("mlm_calculator.reset")})}),a.jsx("p",{className:"mlmcalc-disclaimer",children:l("mlm_calculator.disclaimer")})]})]})})}const sa={slug:"mlm-calculator",name:"MLM Commission Calculator",version:"2.0.0",category:"interactive",configSchema:{properties:{readAloudEnabled:{type:"boolean",default:!1},defaultPaidRank:{type:"string",default:"Miner"},defaultScp2PerCycle:{type:"number",default:5}}},defaultConfig:{readAloudEnabled:!1,defaultPaidRank:"Miner",defaultScp2PerCycle:5},sizing:{minWidth:300,preferredHeight:"auto",scrollable:!0},supportedPlacements:["main","sidebar"],fields:[{id:"readAloudEnabled",type:"toggle",label:"Read this panel aloud",default:!1,group:"Voice"},{id:"defaultPaidRank",type:"select",label:"Default paid rank",default:"Miner",options:v.map(e=>({label:e,value:e})),group:"Defaults"},{id:"defaultScp2PerCycle",type:"number",label:"Default SCP2 per-cycle amount",default:5,min:R,max:$,group:"Defaults"}],events:{}};export{ca as Component,ca as MlmCalculatorBlock,v as RANK_ORDER,F as SCP1_MAX_CYCLES,W as SCP2_MAX_LEVELS,Y as computeImineEarnings,sa as manifest};