@accurix/centrinfo-widget 5.1.1 → 5.1.2

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.
@@ -1,5 +1,5 @@
1
- var Centrinfo=(function(St){"use strict";var Pp=Object.defineProperty;var Op=(St,$t,Jt)=>$t in St?Pp(St,$t,{enumerable:!0,configurable:!0,writable:!0,value:Jt}):St[$t]=Jt;var q=(St,$t,Jt)=>Op(St,typeof $t!="symbol"?$t+"":$t,Jt);const $t={notComparable:"Not comparable yet"},Jt=e=>!e||e==="observed"||e==="confirmed_zero",Ir=(e,t)=>{let n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:null,a=typeof t.value=="number"&&Number.isFinite(t.value)?t.value:null;return e.status==="missing"||t.status==="missing"||n===null||a===null?{kind:"not_comparable",reason:"missing",label:$t.notComparable}:Jt(e.status)?Jt(t.status)?a===0?{kind:"not_comparable",reason:"previous_zero",label:n===0?"No change (0)":n>0?"Up from 0":"Down from 0"}:{kind:"change",percent:(n-a)/Math.abs(a)*100}:{kind:"not_comparable",reason:"previous_no_records",label:$t.notComparable}:{kind:"not_comparable",reason:"current_no_records",label:`${e.label?.trim()||"Current period"}: no records yet`}},yn=e=>e&&["day","week","month","quarter","year"].includes(e)?e:"period",Er=e=>e==="day"?"vs yesterday at this time":`vs same point last ${yn(e)}`,os=(e,t)=>{if(!e.cutoffAt)return;let n=new Date(e.cutoffAt);if(Number.isNaN(n.getTime()))return;let a=e.timezone||void 0,i="";try{i=new Intl.DateTimeFormat(t,{...e.grain==="day"?{}:{weekday:"short",day:"numeric",month:"short"},hour:"2-digit",minute:"2-digit",timeZone:a}).format(n)}catch{i=n.toISOString()}let o=e.grain==="day"?"on both days":`in both ${yn(e.grain)}s`,s=e.cutoffSource==="data_as_of"?", the time of the latest record":"";return`Compared up to ${i} ${o}${s}${a?` (${a})`:""}`},zr=(e,t,n,a={format:String})=>{if(!e||!e.comparisonBasis||e.comparisonBasis==="complete")return;let i=e.comparisonBasis,o=Ir(t,n);if(o.kind==="not_comparable"&&o.reason!=="previous_zero")return{basis:i,kind:"neutral",tone:"neutral",label:o.label,copy:"",reason:o.reason};let s=a.format,c=e.currentPeriod?.label||t.label||"Current period",d=e.previousPeriod?.label||n.label||"Previous period",l=typeof t.value=="number"?t.value:e.currentValue,u=typeof e.previousFullValue=="number"?e.previousFullValue:typeof n.value=="number"?n.value:void 0,p=e.grain==="day"?"full day":`full ${yn(e.grain)}`,m=u===void 0?void 0:`${d} ${p}: ${s(u)}`,f=u===void 0?void 0:`${p.charAt(0).toUpperCase()}${p.slice(1)}: ${s(u)}`;if(i==="like_for_like"&&typeof e.previousToDateValue=="number"&&typeof l=="number"){let h=Ir({value:l,status:t.status},{value:e.previousToDateValue,status:"observed"}),I=os(e,a.locale);if(h.kind==="change"){let x=h.percent;return{basis:i,kind:"change",percent:x,tone:x===0?"neutral":x>0?"positive":"negative",label:`${x>0?"↑":x<0?"↓":"→"} ${Math.abs(x).toFixed(1)}%`,copy:Er(e.grain),secondary:m,compactSecondary:f,title:I}}return{basis:i,kind:"neutral",tone:"neutral",label:h.label,copy:Er(e.grain),secondary:m,compactSecondary:f,title:I,reason:h.reason}}if(i==="not_comparable")return{basis:i,kind:"neutral",tone:"neutral",label:"Not comparable",copy:e.reason||"",reason:e.reason};let _=[typeof l=="number"?`${c} so far: ${s(l)}`:`${c}: in progress`];return u!==void 0&&_.push(`${d}: ${s(u)} (${p})`),{basis:"current_in_progress_no_time",kind:"neutral",tone:"neutral",label:_.join(" · "),copy:"",title:e.reason,reason:e.reason}},Nr=e=>e?.grain==="day"?"Yesterday at this time":`Same point last ${yn(e?.grain)}`,Ra=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?"":e.toISOString().slice(0,10);let t=typeof e=="string"?e.trim():"";return/^\d{4}-\d{2}-\d{2}/.test(t)?t.slice(0,10):""},Rr=(e,t)=>{let n=Ra(t);if(!(!n||!e)){if(e.previousPeriod?.start&&Ra(e.previousPeriod.start)===n)return"previous";if(e.currentPeriod?.start&&Ra(e.currentPeriod.start)===n)return"current"}},Lr=(e,t,n,a={format:String})=>{if(!e||!e.series?.length||!e.comparisonBasis||e.comparisonBasis==="complete")return;let i=Rr(e,t);if(!i)return;let o=String(n??""),s=e.series.find(d=>d.key===o);if(!s)return;let c=e.comparisonBasis;if(i==="previous"){let d=c==="like_for_like"&&typeof s.previousToDateValue=="number";return{side:i,basis:c,toDate:d,plotValue:d?s.previousToDateValue:void 0,fullValue:s.previousFullValue}}return{side:i,basis:c,toDate:!1,display:zr({...e,currentValue:s.currentValue,previousToDateValue:s.previousToDateValue,previousFullValue:s.previousFullValue},{value:s.currentValue,status:s.currentValue===void 0?"missing":"observed"},{value:s.previousFullValue,status:s.previousFullValue===void 0?"missing":"observed"},a)}},La=e=>!!(e&&e.seriesField&&e.series?.length&&e.comparisonBasis&&e.comparisonBasis!=="complete"&&e.comparisonBasis!=="not_comparable"),ss=e=>{if(!La(e))return;let t=e.currentPeriod?.label||"Current period";return e.comparisonBasis==="like_for_like"?`${t} so far, compared with ${Nr(e).toLowerCase()}`:`${t} so far; the previous period is shown in full, so the bars are not like for like`},cs=(e,t,n)=>{if(!t)return[];if(t.side==="previous")return typeof t.fullValue=="number"&&t.toDate?[`Full ${e?.grain==="day"?"day":yn(e?.grain)}: ${n(t.fullValue)}`]:[];let a=t.display;return a?a.kind==="change"&&a.percent!==void 0?[`${a.label} ${a.copy}`.trim()]:a.kind==="neutral"&&a.label&&t.basis==="like_for_like"?[a.label]:[]:[]},na="__previous_to_date",ls="Previous to date",Dr=(e,t)=>{let n=e.trim().toLowerCase(),a=t.trim().toLowerCase();return n===a||n.endsWith(`.${a}`)||a.endsWith(`.${n}`)},ds=e=>{let t=e.periodComparison,n=e.rows;if(!n?.length||!La(t)||t.comparisonBasis!=="like_for_like"||!t.series?.some(p=>typeof p.previousToDateValue=="number"))return e;let a=e.columnMetadata??[],i=e.columns?.filter(Boolean)??(a.length?a.map(p=>String(p.key??p.name??"")).filter(Boolean):Object.keys(n[0]??{}));if(i.includes(na))return e;let o=i.find(p=>Dr(t.seriesField,p));if(!o)return e;let s=p=>a.find(m=>(m.key??m.name)===p),c=i.find(p=>{let m=s(p);return m?.semanticRole==="date"||m?.role==="date"||m?.dataType==="date"||m?.dataType==="datetime"}),d=(t.measureField?i.find(p=>Dr(t.measureField,p)):void 0)??i.find(p=>s(p)?.semanticRole==="measure"),l=n.map(p=>{let m=c?Rr(t,p[c]):"current",f=t.series?.find(h=>h.key===String(p[o]??"")),_=m&&typeof f?.previousToDateValue=="number"?f.previousToDateValue:null;return{...p,[na]:_}}),u={...(d?s(d):void 0)??{dataType:"number",semanticRole:"measure"},key:na,name:void 0,label:ls,aggregation:"none",sourceField:void 0,priority:"secondary",groupable:!1,filterable:!1};return{...e,rows:l,columns:e.columns?[...e.columns,na]:e.columns,columnMetadata:a.length?[...a,u]:e.columnMetadata}},us=e=>!!(e?.lastPeriodInProgress||e?.caveats?.some(t=>t.code==="incomplete_final_period")||e?.periodComparison?.currentPeriod?.inProgress),ps="In progress";var aa,Re,Pr,Vt,Or,Fr,Ur,Da,ra,_n,Br,Pa,Oa,Fa,qr,ia={},oa=[],fs=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,sa=Array.isArray;function Rt(e,t){for(var n in t)e[n]=t[n];return e}function Ua(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function hs(e,t,n){var a,i,o,s={};for(o in t)o=="key"?a=t[o]:o=="ref"?i=t[o]:s[o]=t[o];if(arguments.length>2&&(s.children=arguments.length>3?aa.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(o in e.defaultProps)s[o]===void 0&&(s[o]=e.defaultProps[o]);return ca(e,s,a,i,null)}function ca(e,t,n,a,i){var o={type:e,props:t,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Pr,__i:-1,__u:0};return i==null&&Re.vnode!=null&&Re.vnode(o),o}function se(e){return e.children}function la(e,t){this.props=e,this.context=t}function cn(e,t){if(t==null)return e.__?cn(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?cn(e):null}function ms(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,a=[],i=[],o=Rt({},t);o.__v=t.__v+1,Re.vnode&&Re.vnode(o),qa(e.__P,o,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,a,n??cn(t),!!(32&t.__u),i),o.__v=t.__v,o.__.__k[o.__i]=o,Kr(a,o,i),t.__e=t.__=null,o.__e!=n&&Vr(o)}}function Vr(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),Vr(e)}function Ba(e){(!e.__d&&(e.__d=!0)&&Vt.push(e)&&!da.__r++||Or!=Re.debounceRendering)&&((Or=Re.debounceRendering)||Fr)(da)}function da(){try{for(var e,t=1;Vt.length;)Vt.length>t&&Vt.sort(Ur),e=Vt.shift(),t=Vt.length,ms(e)}finally{Vt.length=da.__r=0}}function jr(e,t,n,a,i,o,s,c,d,l,u){var p,m,f,_,h,I,x,g=a&&a.__k||oa,T=t.length;for(d=gs(n,t,g,d,T),p=0;p<T;p++)(f=n.__k[p])!=null&&(m=f.__i!=-1&&g[f.__i]||ia,f.__i=p,I=qa(e,f,m,i,o,s,c,d,l,u),_=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&ja(m.ref,null,f),u.push(f.ref,f.__c||_,f)),h==null&&_!=null&&(h=_),(x=!!(4&f.__u))||m.__k===f.__k?(d=Hr(f,d,e,x),x&&m.__e&&(m.__e=null)):typeof f.type=="function"&&I!==void 0?d=I:_&&(d=_.nextSibling),f.__u&=-7);return n.__e=h,d}function gs(e,t,n,a,i){var o,s,c,d,l,u=n.length,p=u,m=0;for(e.__k=new Array(i),o=0;o<i;o++)(s=t[o])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[o]=ca(null,s,null,null,null):sa(s)?s=e.__k[o]=ca(se,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=ca(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[o]=s,d=o+m,s.__=e,s.__b=e.__b+1,c=null,(l=s.__i=bs(s,n,d,p))!=-1&&(p--,(c=n[l])&&(c.__u|=2)),c==null||c.__v==null?(l==-1&&(i>u?m--:i<u&&m++),typeof s.type!="function"&&(s.__u|=4)):l!=d&&(l==d-1?m--:l==d+1?m++:(l>d?m--:m++,s.__u|=4))):e.__k[o]=null;if(p)for(o=0;o<u;o++)(c=n[o])!=null&&(2&c.__u)==0&&(c.__e==a&&(a=cn(c)),Zr(c,c));return a}function Hr(e,t,n,a){var i,o;if(typeof e.type=="function"){for(i=e.__k,o=0;i&&o<i.length;o++)i[o]&&(i[o].__=e,t=Hr(i[o],t,n,a));return t}e.__e!=t&&(a&&(t&&e.type&&!t.parentNode&&(t=cn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function bs(e,t,n,a){var i,o,s,c=e.key,d=e.type,l=t[n],u=l!=null&&(2&l.__u)==0;if(l===null&&c==null||u&&c==l.key&&d==l.type)return n;if(a>(u?1:0)){for(i=n-1,o=n+1;i>=0||o<t.length;)if((l=t[s=i>=0?i--:o++])!=null&&(2&l.__u)==0&&c==l.key&&d==l.type)return s}return-1}function Wr(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||fs.test(t)?n:n+"px"}function ua(e,t,n,a,i){var o,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof a=="string"&&(e.style.cssText=a=""),a)for(t in a)n&&t in n||Wr(e.style,t,"");if(n)for(t in n)a&&n[t]==a[t]||Wr(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(Br,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+o]=n,n?a?n[_n]=a[_n]:(n[_n]=Pa,e.addEventListener(t,o?Fa:Oa,o)):e.removeEventListener(t,o?Fa:Oa,o);else{if(i=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Gr(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[ra]==null)t[ra]=Pa++;else if(t[ra]<n[_n])return;return n(Re.event?Re.event(t):t)}}}function qa(e,t,n,a,i,o,s,c,d,l){var u,p,m,f,_,h,I,x,g,T,V,P,ee,Z,Y,z=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(d=!!(32&n.__u),o=[c=t.__e=n.__e]),(u=Re.__b)&&u(t);e:if(typeof z=="function")try{if(x=t.props,g=z.prototype&&z.prototype.render,T=(u=z.contextType)&&a[u.__c],V=u?T?T.props.value:u.__:a,n.__c?I=(p=t.__c=n.__c).__=p.__E:(g?t.__c=p=new z(x,V):(t.__c=p=new la(x,V),p.constructor=z,p.render=xs),T&&T.sub(p),p.state||(p.state={}),p.__n=a,m=p.__d=!0,p.__h=[],p._sb=[]),g&&p.__s==null&&(p.__s=p.state),g&&z.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Rt({},p.__s)),Rt(p.__s,z.getDerivedStateFromProps(x,p.__s))),f=p.props,_=p.state,p.__v=t,m)g&&z.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),g&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(g&&z.getDerivedStateFromProps==null&&x!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(x,V),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(x,p.__s,V)===!1){t.__v!=n.__v&&(p.props=x,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(te){te&&(te.__=t)}),oa.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(x,p.__s,V),g&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,_,h)})}if(p.context=V,p.props=x,p.__P=e,p.__e=!1,P=Re.__r,ee=0,g)p.state=p.__s,p.__d=!1,P&&P(t),u=p.render(p.props,p.state,p.context),oa.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,P&&P(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++ee<25);p.state=p.__s,p.getChildContext!=null&&(a=Rt(Rt({},a),p.getChildContext())),g&&!m&&p.getSnapshotBeforeUpdate!=null&&(h=p.getSnapshotBeforeUpdate(f,_)),Z=u!=null&&u.type===se&&u.key==null?Yr(u.props.children):u,c=jr(e,sa(Z)?Z:[Z],t,n,a,i,o,s,c,d,l),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),I&&(p.__E=p.__=null)}catch(te){if(t.__v=null,d||o!=null)if(te.then){for(t.__u|=d?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;o[o.indexOf(c)]=null,t.__e=c}else{for(Y=o.length;Y--;)Ua(o[Y]);Va(t)}else t.__e=n.__e,t.__k=n.__k,te.then||Va(t);Re.__e(te,t,n)}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=vs(n.__e,t,n,a,i,o,s,d,l);return(u=Re.diffed)&&u(t),128&t.__u?void 0:c}function Va(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Va))}function Kr(e,t,n){for(var a=0;a<n.length;a++)ja(n[a],n[++a],n[++a]);Re.__c&&Re.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(o){o.call(i)})}catch(o){Re.__e(o,i.__v)}})}function Yr(e){return typeof e!="object"||e==null||e.__b>0?e:sa(e)?e.map(Yr):e.constructor!==void 0?null:Rt({},e)}function vs(e,t,n,a,i,o,s,c,d){var l,u,p,m,f,_,h,I=n.props||ia,x=t.props,g=t.type;if(g=="svg"?i="http://www.w3.org/2000/svg":g=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),o!=null){for(l=0;l<o.length;l++)if((f=o[l])&&"setAttribute"in f==!!g&&(g?f.localName==g:f.nodeType==3)){e=f,o[l]=null;break}}if(e==null){if(g==null)return document.createTextNode(x);e=document.createElementNS(i,g,x.is&&x),c&&(Re.__m&&Re.__m(t,o),c=!1),o=null}if(g==null)I===x||c&&e.data==x||(e.data=x);else{if(o=g=="textarea"&&x.defaultValue!=null?null:o&&aa.call(e.childNodes),!c&&o!=null)for(I={},l=0;l<e.attributes.length;l++)I[(f=e.attributes[l]).name]=f.value;for(l in I)f=I[l],l=="dangerouslySetInnerHTML"?p=f:l=="children"||l in x||l=="value"&&"defaultValue"in x||l=="checked"&&"defaultChecked"in x||ua(e,l,null,f,i);for(l in x)f=x[l],l=="children"?m=f:l=="dangerouslySetInnerHTML"?u=f:l=="value"?_=f:l=="checked"?h=f:c&&typeof f!="function"||I[l]===f||ua(e,l,f,I[l],i);if(u)c||p&&(u.__html==p.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),jr(t.type=="template"?e.content:e,sa(m)?m:[m],t,n,a,g=="foreignObject"?"http://www.w3.org/1999/xhtml":i,o,s,o?o[0]:n.__k&&cn(n,0),c,d),o!=null)for(l=o.length;l--;)Ua(o[l]);c&&g!="textarea"||(l="value",g=="progress"&&_==null?e.removeAttribute("value"):_!=null&&(_!==e[l]||g=="progress"&&!_||g=="option"&&_!=I[l])&&ua(e,l,_,I[l],i),l="checked",h!=null&&h!=e[l]&&ua(e,l,h,I[l],i))}return e}function ja(e,t,n){try{if(typeof e=="function"){var a=typeof e.__u=="function";a&&e.__u(),a&&t==null||(e.__u=e(t))}else e.current=t}catch(i){Re.__e(i,n)}}function Zr(e,t,n){var a,i;if(Re.unmount&&Re.unmount(e),(a=e.ref)&&(a.current&&a.current!=e.__e||ja(a,null,t)),(a=e.__c)!=null){if(a.componentWillUnmount)try{a.componentWillUnmount()}catch(o){Re.__e(o,t)}a.base=a.__P=null}if(a=e.__k)for(i=0;i<a.length;i++)a[i]&&Zr(a[i],t,n||typeof e.type!="function");n||Ua(e.__e),e.__c=e.__=e.__e=void 0}function xs(e,t,n){return this.constructor(e,n)}function Jr(e,t,n){var a,i,o,s;t==document&&(t=document.documentElement),Re.__&&Re.__(e,t),i=(a=!1)?null:t.__k,o=[],s=[],qa(t,e=t.__k=hs(se,null,[e]),i||ia,ia,t.namespaceURI,i?null:t.firstChild?aa.call(t.childNodes):null,o,i?i.__e:t.firstChild,a,s),Kr(o,e,s)}function Ha(e){function t(n){var a,i;return this.getChildContext||(a=new Set,(i={})[t.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){a=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&a.forEach(function(s){s.__e=!0,Ba(s)})},this.sub=function(o){a.add(o);var s=o.componentWillUnmount;o.componentWillUnmount=function(){a&&a.delete(o),s&&s.call(o)}}),n.children}return t.__c="__cC"+qr++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,a){return n.children(a)}).contextType=t,t}aa=oa.slice,Re={__e:function(e,t,n,a){for(var i,o,s;t=t.__;)if((i=t.__c)&&!i.__)try{if((o=i.constructor)&&o.getDerivedStateFromError!=null&&(i.setState(o.getDerivedStateFromError(e)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,a||{}),s=i.__d),s)return i.__E=i}catch(c){e=c}throw e}},Pr=0,la.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Rt({},this.state),typeof e=="function"&&(e=e(Rt({},n),this.props)),e&&Rt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Ba(this))},la.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Ba(this))},la.prototype.render=se,Vt=[],Fr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ur=function(e,t){return e.__v.__b-t.__v.__b},da.__r=0,Da=Math.random().toString(8),ra="__d"+Da,_n="__a"+Da,Br=/(PointerCapture)$|Capture$/i,Pa=0,Oa=Gr(!1),Fa=Gr(!0),qr=0;var Xt,Pe,Wa,Xr,wn=0,Qr=[],je=Re,ei=je.__b,ti=je.__r,ni=je.diffed,ai=je.__c,ri=je.unmount,ii=je.__;function kn(e,t){je.__h&&je.__h(Pe,e,wn||t),wn=0;var n=Pe.__H||(Pe.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function $(e){return wn=1,ys(si,e)}function ys(e,t,n){var a=kn(Xt++,2);if(a.t=e,!a.__c&&(a.__=[si(void 0,t),function(c){var d=a.__N?a.__N[0]:a.__[0],l=a.t(d,c);d!==l&&(a.__N=[l,a.__[1]],a.__c.setState({}))}],a.__c=Pe,!Pe.__f)){var i=function(c,d,l){if(!a.__c.__H)return!0;var u=a.__c.__H.__.filter(function(m){return m.__c});if(u.every(function(m){return!m.__N}))return!o||o.call(this,c,d,l);var p=a.__c.props!==c;return u.some(function(m){if(m.__N){var f=m.__[0];m.__=m.__N,m.__N=void 0,f!==m.__[0]&&(p=!0)}}),o&&o.call(this,c,d,l)||p};Pe.__f=!0;var o=Pe.shouldComponentUpdate,s=Pe.componentWillUpdate;Pe.componentWillUpdate=function(c,d,l){if(this.__e){var u=o;o=void 0,i(c,d,l),o=u}s&&s.call(this,c,d,l)},Pe.shouldComponentUpdate=i}return a.__N||a.__}function X(e,t){var n=kn(Xt++,3);!je.__s&&Ya(n.__H,t)&&(n.__=e,n.u=t,Pe.__H.__h.push(n))}function Sn(e,t){var n=kn(Xt++,4);!je.__s&&Ya(n.__H,t)&&(n.__=e,n.u=t,Pe.__h.push(n))}function R(e){return wn=5,Be(function(){return{current:e}},[])}function Be(e,t){var n=kn(Xt++,7);return Ya(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function F(e,t){return wn=8,Be(function(){return e},t)}function Ga(e){var t=Pe.context[e.__c],n=kn(Xt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(Pe)),t.props.value):e.__}function _s(){for(var e;e=Qr.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(pa),t.__h.some(Ka),t.__h=[]}catch(n){t.__h=[],je.__e(n,e.__v)}}}je.__b=function(e){Pe=null,ei&&ei(e)},je.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ii&&ii(e,t)},je.__r=function(e){ti&&ti(e),Xt=0;var t=(Pe=e.__c).__H;t&&(Wa===Pe?(t.__h=[],Pe.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(pa),t.__h.some(Ka),t.__h=[],Xt=0)),Wa=Pe},je.diffed=function(e){ni&&ni(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Qr.push(t)!==1&&Xr===je.requestAnimationFrame||((Xr=je.requestAnimationFrame)||ws)(_s)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Wa=Pe=null},je.__c=function(e,t){t.some(function(n){try{n.__h.some(pa),n.__h=n.__h.filter(function(a){return!a.__||Ka(a)})}catch(a){t.some(function(i){i.__h&&(i.__h=[])}),t=[],je.__e(a,n.__v)}}),ai&&ai(e,t)},je.unmount=function(e){ri&&ri(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(a){try{pa(a)}catch(i){t=i}}),n.__H=void 0,t&&je.__e(t,n.__v))};var oi=typeof requestAnimationFrame=="function";function ws(e){var t,n=function(){clearTimeout(a),oi&&cancelAnimationFrame(t),setTimeout(e)},a=setTimeout(n,35);oi&&(t=requestAnimationFrame(n))}function pa(e){var t=Pe,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Pe=t}function Ka(e){var t=Pe;e.__c=e.__(),Pe=t}function Ya(e,t){return!e||e.length!==t.length||t.some(function(n,a){return n!==e[a]})}function si(e,t){return typeof t=="function"?t(e):t}var ks=0;function r(e,t,n,a,i,o){t||(t={});var s,c,d=t;if("ref"in d)for(c in d={},t)c=="ref"?s=t[c]:d[c]=t[c];var l={type:e,props:d,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ks,__i:-1,__u:0,__source:i,__self:o};if(typeof e=="function"&&(s=e.defaultProps))for(c in s)d[c]===void 0&&(d[c]=s[c]);return Re.vnode&&Re.vnode(l),l}const fa=(e,t=11)=>{let n=0;for(let a of e)n+=(a.codePointAt(0)??0)>11904?1:.58;return Math.ceil(n*t)},Ss=(e,t=12,n=20)=>Math.max(n,Math.ceil(e)+t),$s=(e,t=12,n=8)=>Math.ceil(t+e+n),Ts=(e,t,n=11)=>e.length===0||Math.max(...e.map(a=>fa(a,n)))<=t-4?{kind:"native"}:e.length>12?{kind:"auto"}:Math.floor((t-4)/(.58*n))>=6?{kind:"truncate",width:Math.max(16,Math.floor(t-4))}:{kind:"rotate",rotate:40,width:72},Za=e=>Array.isArray(e)?e:e?[e]:[],Cs=(e,t)=>{let n=[];for(let a of e)if(Array.isArray(a.data))for(let i of a.data){let o=i;i&&typeof i=="object"&&!Array.isArray(i)&&(o=i.value),Array.isArray(o)&&(o=o[1]),typeof o=="number"&&Number.isFinite(o)&&n.push(o)}return n},As=(e,t,n)=>{let a=e.axisLabel?.formatter,i=Cs(t),o=typeof e.min=="number"?e.min:Math.min(0,...i),s=typeof e.max=="number"?e.max:Math.max(0,...i)*1.1,c=i.length||e.min!==void 0?[o,s]:[];return c.length?Math.max(...c.map(d=>{let l=String(d);try{typeof a=="function"&&(l=String(a(d)))}catch{}return fa(l)})):fa("00000")},Ms=(e,t)=>{if(!(t>0)||Array.isArray(e.grid))return e;let n=Za(e.xAxis),a=Za(e.yAxis),i=a[0]?.type==="category",o=i?a[0]:n[0],s=i?n[0]:a[0];if(!o||o.type!=="category"||!s||s.type!=="value")return e;let c=t<420,d=Za(e.series),l={...e.grid??{}},u=(o.data??[]).map(h=>String(h&&typeof h=="object"?h.value??"":h)),p={...e,grid:l},m={...o},f={...s},_=0;if(i)c&&(_=Math.min(t*.35,90),m={...m,axisLabel:{...o.axisLabel,width:Math.floor(_),overflow:"truncate",ellipsis:"…"}},l.left=8);else{let h=As(s,d);if(_=h+8,c&&!s.name)l.left=8;else if(s.name){let I=Ss(h);f={...f,nameGap:Math.min(s.nameGap??I,I)},_+=18}}if(!i){let h=typeof l.left=="number"?l.left:0,I=typeof l.right=="number"?l.right:0,x=Ts(u,Math.max(40,t-h-I-_)/Math.max(1,u.length)),g=o.axisLabel?.fontSize??11,T=g+2;if(x.kind==="truncate"||x.kind==="rotate"){let V=x.kind==="rotate"?x.rotate:0;if(m.axisLabel={...o.axisLabel,interval:0,hideOverlap:!1,rotate:V,width:x.width,overflow:"truncate",ellipsis:"…"},V){let P=Math.max(0,...u.map(Z=>fa(Z,g))),ee=Math.min(x.width,P);T=Math.ceil(ee*Math.sin(V*Math.PI/180))+g}}o.name&&c?m.nameGap=Math.min(o.nameGap??99,$s(T,6,4)):c&&l.containLabel===!0&&typeof l.bottom=="number"&&(l.bottom=Math.min(l.bottom,8))}return i?(p.yAxis=Array.isArray(e.yAxis)?[m,...a.slice(1)]:m,p.xAxis=Array.isArray(e.xAxis)?[f,...n.slice(1)]:f):(p.xAxis=Array.isArray(e.xAxis)?[m,...n.slice(1)]:m,p.yAxis=Array.isArray(e.yAxis)?[f,...a.slice(1)]:f),p},Is=/^(\d{4})-(\d{2})-(\d{2})$/,Es=/^(\d{4})-(\d{2})$/,zs=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?$/,Ns=/(?:Z|[+-]\d{2}:?\d{2})$/i,ci=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:{date:e,calendar:!1,hasTime:!0};if(typeof e=="number"&&Number.isFinite(e))return{date:new Date(e),calendar:!1,hasTime:!0};if(typeof e!="string")return null;let t=e.trim(),n=Is.exec(t);if(n)return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]))),calendar:!0,hasTime:!1};if(n=Es.exec(t),n)return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,1)),calendar:!0,hasTime:!1};if(n=zs.exec(t),n&&!Ns.test(t))return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]),Number(n[4]),Number(n[5]),Number(n[6]??0))),calendar:!0,hasTime:!0};if(!/^\d{4}-\d{2}-\d{2}T/.test(t))return null;let a=new Date(t);return Number.isNaN(a.getTime())?null:{date:a,calendar:!1,hasTime:!0}},Rs=e=>{if(e){if(/h/i.test(e)&&/:/.test(e))return"hour";if(/d{2}/i.test(e))return"day";if(/q/i.test(e))return"quarter";if(/M{2,}/.test(e))return"month";if(/y{2,}/i.test(e))return"year"}},li=e=>{let t=e.map(ci).filter(a=>a!==null);if(t.length===0)return;let n=a=>a.date.getUTCHours()+a.date.getUTCMinutes();return t.some(a=>a.hasTime&&n(a)!==0)?t.every(a=>a.date.getUTCMinutes()===0)?"hour":void 0:t.length>1&&t.every(a=>a.date.getUTCDate()===1)?"month":"day"},Qt=(e,t)=>{try{return new Intl.DateTimeFormat(e,t)}catch{return new Intl.DateTimeFormat(e,{...t,timeZone:"UTC"})}},di=(e,t,n={})=>{let a=ci(e);if(!a)return;let i=t?.grain??Rs(t?.formatPattern)??n.grain,o=a.calendar?"UTC":n.timezone||void 0,{date:s}=a;switch(i){case"year":return Qt(n.locale,{year:"numeric",timeZone:o}).format(s);case"quarter":{let c=Number(Qt("en-US",{month:"numeric",timeZone:o}).format(s)),d=Qt(n.locale,{year:"numeric",timeZone:o}).format(s);return`Q${Math.floor((c-1)/3)+1} ${d}`}case"month":return Qt(n.locale,{month:"short",year:"numeric",timeZone:o}).format(s);case"week":case"day":return Qt(n.locale,{day:"numeric",month:"short",year:"numeric",timeZone:o}).format(s);case"hour":return Qt(n.locale,{day:"numeric",month:"short",hour:"numeric",minute:"2-digit",timeZone:o}).format(s);default:return Qt(n.locale,{dateStyle:"medium",...a.hasTime?{timeStyle:"short"}:{},timeZone:o}).format(s)}},ui=e=>{let t=e?/\.([0#]+)/.exec(e):null;if(!t)return;let n=t[1];return{min:(n.match(/0/g)??[]).length,max:n.length}},Ja=(e,t)=>{let n=ui(e);return n?{minimumFractionDigits:n.min,maximumFractionDigits:n.max}:{maximumFractionDigits:t}},$n=e=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()){let t=Number(e);if(Number.isFinite(t))return t}return null},pi=(e,t)=>t&&Math.abs(e)>=1e4?"compact":"standard",fi=(e,t={})=>new Intl.NumberFormat(t.locale,{notation:pi(e,t.compact),...Ja(t.pattern,t.maxFractionDigits??2)}).format(e),Ls=(e,t,n={})=>{let a=t?.trim().toUpperCase();if(a&&/^[A-Z]{3}$/.test(a))try{return new Intl.NumberFormat(n.locale,{style:"currency",currency:a,notation:pi(e,n.compact),...ui(n.pattern)?Ja(n.pattern,2):{}}).format(e)}catch{}return fi(e,{...n,maxFractionDigits:2})},Ds=(e,t={})=>{let n=!!(t.pattern&&/(?<!\\)%/.test(t.pattern)),a=Ja(t.pattern,2);return new Intl.NumberFormat(t.locale,{style:"percent",...a}).format(n?e:e/100)},Xa=(e,t,n={})=>{let{locale:a,compact:i}=n;return t?.dataType==="currency"?Ls(e,t.currencyCode||n.currencyCode,{locale:a,compact:i,pattern:t.formatPattern}):t?.dataType==="percent"?Ds(e,{locale:a,pattern:t.formatPattern}):fi(e,{locale:a,compact:i,pattern:t?.formatPattern,maxFractionDigits:n.maxFractionDigits})},Ps=(e,t,n={})=>{if(e==null||e==="")return"—";if(t?.dataType==="date"||t?.dataType==="datetime"){let a=di(e,t,n);if(a)return a}if(t?.dataType==="currency"||t?.dataType==="percent"){let a=$n(e);if(a!==null)return Xa(a,t,n)}return typeof e=="number"&&Number.isFinite(e)?Xa(e,t,{...n,maxFractionDigits:4}):typeof e=="boolean"?e?n.yes??"Yes":n.no??"No":String(e)},ha={resultDetails:"Result details",liveMetric:"Live metric",currentValue:"Current value",noMatchTitle:"No matching data",noMatchBody:"No approved records matched this question.",chartType:"Chart type",chooseChartType:"Choose chart type",aggregate:"Aggregate",aggregateTitle:"Ask for a new governed calculation",aggregateCharge:"New governed answer. Query charges may apply.",chartFallback:"Chart",chartLine:"Line",chartBar:"Bar",chartStackedBar:"Stacked bar",chartLineHint:"Best for change over time.",chartBarHint:"Compare categories or ranked values.",chartStackedBarHint:"Compare totals and their parts.",aggregationSum:"Total",aggregationAvg:"Average",aggregationMin:"Minimum",aggregationMax:"Maximum",aggregationCount:"Total count",aggregationCountDistinct:"Unique count",download:"Download",downloadData:"Download this data",expandTable:"Expand table",expandChart:"Expand chart",restoreView:"Restore assistant view",aboutResult:"About this result",aboutPeriod:"Period",aboutResults:"Results",aboutChecked:"Checked",aboutTimezone:"Timezone",aboutSourceData:"Source data",aboutFilters:"Filters",rowOne:"{count} row",rowMany:"{count} rows",filtersOne:"{count} applied filter",filtersMany:"{count} applied filters",filtersApplied:"{count} applied",notSet:"Not set",noValue:"No value",yes:"Yes",no:"No",chartValues:"Values",chartTitle:"{measure} by {dimension}",seriesLimited:"Showing {shown} of {total} series.",summaryLatest:"Latest ({category}): {values}.",summaryNoTrend:"No numeric trend values are available.",summaryHighest:"Highest: {category}, {series} {value}.",summaryNoComparison:"No numeric comparison values are available.",zoomControls:"Chart zoom controls",zoomIn:"Zoom in chart",zoomOut:"Zoom out chart",zoomReset:"Reset chart zoom",zoomResetShort:"Reset",zoomNone:"No chart points",zoomAllOne:"All {count} point",zoomAllMany:"All {count} points",zoomRange:"{start} – {end} · {visible} of {count} points",inProgress:"in progress",newContent:"New content",updatedAt:"Updated {time}",liveData:"Live data",viewData:"View data",hideData:"Hide data",inProgressLegend:"In progress",governedResult:"Governed result"},vt=(e,t)=>e.replace(/\{(\w+)\}/g,(n,a)=>String(t[a]??"")),Os=e=>Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!=null)),Qa=e=>({...ha,...Os(e),explanation:{...e?.explanation}});let hi=()=>Promise.resolve().then(()=>Fo),Tn=null,mi=!1;const Fs=e=>{hi=e,Tn=null,mi=!0},Us=()=>(Tn||(Tn=hi().catch(e=>{throw Tn=null,e})),Tn),en={background:"#ffffff",border:"#dce4e9",muted:"#5b7186",surface:"#ffffff",text:"#0f1e2a",colors:["#2f7f55","#2563eb","#b45309","#7c3aed"]},gi="cf-widget-category-zoom",bi=.68,ln=e=>({startIndex:0,endIndex:Math.max(0,e-1)}),Cn=(e,t)=>{if(t<=0)return ln(0);let n=t-1,a=Math.max(0,Math.min(n,Math.floor(Math.min(e.startIndex,e.endIndex))));return{startIndex:a,endIndex:Math.max(a,Math.min(n,Math.floor(Math.max(e.startIndex,e.endIndex))))}},vi=(e,t,n)=>{let a=Cn(e,n);if(n<=2)return ln(n);let i=a.endIndex-a.startIndex+1,o=t==="in"?Math.max(2,Math.floor(i*bi)):Math.min(n,Math.ceil(i/bi));if(o===i)return a;let s=(a.startIndex+a.endIndex)/2,c=n-o,d=Math.max(0,Math.min(c,Math.round(s-(o-1)/2)));return{startIndex:d,endIndex:d+o-1}},Bs=(e,t,n=ha)=>{let a=e.length;if(a===0)return n.zoomNone;let i=Cn(t,a);return i.startIndex===0&&i.endIndex===a-1?vt(a===1?n.zoomAllOne:n.zoomAllMany,{count:a}):vt(n.zoomRange,{start:e[i.startIndex]??"",end:e[i.endIndex]??"",visible:i.endIndex-i.startIndex+1,count:a})},qs=e=>{let t=e.replaceAll("_"," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim();return t?`${t.charAt(0).toUpperCase()}${t.slice(1)}`:"Value"},Vs=e=>{let t=new Set,n=[];return e.forEach(a=>{let i=a?.trim();!i||t.has(i)||(t.add(i),n.push(i))}),n},er=$n,An=e=>{if(e===null)return"null:";if(e===void 0)return"undefined:";if(typeof e=="object")try{return`object:${JSON.stringify(e)}`}catch{return"object:"}return`${typeof e}:${String(e)}`},Mn=(e,t)=>t?e.columnMetadata?.find(n=>n.key===t):void 0,tr=(e,t)=>{let n=Mn(e,t);if(!n||n.currencyCode||n.dataType!=="currency")return n;let a=e.currency;return a?.code&&!a.isMixed?{...n,currencyCode:a.code}:n},In=(e,t)=>Mn(e,t)?.label?.trim()||qs(t),js=(e,t,n,a)=>({locale:t,timezone:e.timezone||e.periodComparison?.timezone,grain:a,yes:n.yes,no:n.no}),xi=e=>e?.dataType==="date"||e?.dataType==="datetime"||e?.semanticRole==="date",yi=(e,t,n)=>{let a=Mn(e,t);if(xi(a))return a?.grain??e.periodComparison?.grain??li(n.map(i=>i[t]))},_i=(e,t,n,a,i,o)=>{if(n==null||n==="")return a.notSet;let s=Mn(e,t);if(s?.dataType==="boolean"){let c=String(n).trim().toLowerCase();return n===!1||n===0||["0","false","no"].includes(c)?a.no:a.yes}if(xi(s)){let c=di(n,s,js(e,i,a,o));if(c)return c}return String(n)},tn=(e,t,n,a=!1,i)=>Xa(e,t,{locale:i,compact:a,currencyCode:n?.currency?.code&&!n.currency.isMixed?n.currency.code:void 0}),Hs=(e,t)=>{if(e.presentation==="table"||e.presentation==="kpi")return null;if(t)return t;let n=e.chartRecommendation?.type;return n==="line"||n==="bar"||n==="stacked_bar"?n:e.type==="line"||e.type==="bar"||e.type==="stacked_bar"?e.type:null},wi=e=>e.chartRecommendation?.categoryField?.trim()||e.label?.trim()||e.columnMetadata?.find(t=>["date","dimension","geography","boolean"].includes(t.semanticRole))?.key||e.columns?.[0],ki=e=>e.chartRecommendation?.seriesField?.trim()||e.seriesField?.trim()||e.series?.trim()||void 0,Si=(e,t,n)=>{let a=Vs([...e.chartRecommendation?.valueFields??[],...e.valueFields??[],e.value,...e.columnMetadata?.filter(o=>o.semanticRole==="measure").map(o=>o.key)??[]]),i=new Set([...e.columns??[],...e.columnMetadata?.map(o=>o.key)??[],...Object.keys(e.rows?.[0]??{})]);return a.filter(o=>o!==t&&o!==n&&i.has(o)).filter(o=>e.rows?.some(s=>er(s[o])!==null))},Ws=(e,t,n,a,i,o,s)=>{let c=i?` ${vt(o.seriesLimited,{shown:a.length,total:a.length+i})}`:"",d=(u,p)=>tn(u,p,e,!1,s);if(t==="line"){let u=n.length-1,p=a.map(m=>{let f=m.values[u];return f==null?null:`${m.name}: ${d(f,m.valueColumn)}`}).filter(m=>!!m);return p.length?`${vt(o.summaryLatest,{category:n[u]??"",values:p.join("; ")})}${c}`:`${o.summaryNoTrend}${c}`}let l;return a.forEach(u=>{u.values.forEach((p,m)=>{p===null||l&&p<=l.value||(l={category:n[m]??o.notSet,series:u,value:p})})}),l?`${vt(o.summaryHighest,{category:l.category,series:l.series.name,value:d(l.value,l.series.valueColumn)})}${c}`:`${o.summaryNoComparison}${c}`},nr=(e,t,n={})=>{let a=Qa(n.labels),i=n.locale,o=Hs(e,t),s=wi(e),c=e.rows??[];if(!o||!s||c.length===0)return null;let d=ki(e),l=Si(e,s,d);if(l.length===0)return null;let u=l.length===1?d:void 0,p=yi(e,s,c),m=l[0],f=u&&La(e.periodComparison)&&(!e.periodComparison.measureField||!m||m===e.periodComparison.measureField||m.endsWith(`.${e.periodComparison.measureField}`)||e.periodComparison.measureField.endsWith(`.${m}`))?e.periodComparison:void 0,_=(()=>{if(!f?.seriesField||!u)return;let U=(B,A)=>B===A||B.endsWith(`.${A}`)||A.endsWith(`.${B}`);if(U(f.seriesField,s))return{group:s,time:u,timeIsSeries:!0};if(U(f.seriesField,u))return{group:u,time:s,timeIsSeries:!1}})(),h=U=>tn(U,tr(e,m??""),e,!1,i),I=U=>f&&_?Lr(f,U[_.time],U[_.group],{format:h,locale:i}):void 0,x=(U,B)=>f?.comparisonBasis==="like_for_like"&&Lr(f,U,f.series?.[0]?.key)?.side==="previous"?Nr(f):B,g=[],T=new Set;c.forEach(U=>{let B=An(U[s]);if(T.has(B))return;T.add(B);let A=_i(e,s,U[s],a,i,p);g.push({key:B,label:_&&!_.timeIsSeries?x(U[s],A):A})});let V=g.map(U=>U.label),P=0,ee;if(u){let U=[],B=new Set;c.forEach(y=>{let D=An(y[u]);if(B.has(D))return;B.add(D);let S=_i(e,u,y[u],a,i,yi(e,u,c));U.push({key:D,label:_?.timeIsSeries?x(y[u],S):S})});let A=U.slice(0,4);P=Math.max(0,U.length-A.length);let N=l[0];ee=A.map(y=>{let D=new Map,S=new Map;return c.forEach(O=>{if(An(O[u])!==y.key)return;let ue=An(O[s]);if(!D.has(ue)){let oe=I(O);S.set(ue,oe),D.set(ue,oe?.side==="previous"&&oe.plotValue!==void 0?oe.plotValue:er(O[N]))}}),{field:N,name:y.label,values:g.map(O=>D.get(O.key)??null),valueColumn:tr(e,N),..._?{points:g.map(O=>S.get(O.key))}:{}}})}else P=Math.max(0,l.length-4),ee=l.slice(0,4).map(U=>({field:U,name:In(e,U),values:c.map(B=>er(B[U])),valueColumn:tr(e,U)}));if(ee.length===0)return null;let Z=In(e,s),Y=a.chartValues;u?Y=In(e,l[0]):ee.length===1&&(Y=ee[0].name);let z=e.title?.trim()||vt(a.chartTitle,{measure:Y,dimension:Z}),te;if(Mn(e,s)?.semanticRole==="date"&&g.length>1&&us(e)){let U="";c.forEach(A=>{let N=String(A[s]??"");N>U&&(U=N)});let B=g.findIndex(A=>A.key===An(U));B>=0&&(te=B)}return{type:o,title:z,xAxisTitle:Z,yAxisTitle:Y,categories:V,series:ee,omittedSeriesCount:P,inProgressIndex:te,..._&&f?{comparison:f,comparisonNote:ss(f)}:{},locale:i,labels:a,summary:Ws(e,o,V,ee,P,a,i)}},ar=[{value:"sum",label:"Total"},{value:"avg",label:"Average"},{value:"min",label:"Minimum"},{value:"max",label:"Maximum"},{value:"count",label:"Total count"},{value:"count_distinct",label:"Unique count"}],Gs={sum:"aggregationSum",avg:"aggregationAvg",min:"aggregationMin",max:"aggregationMax",count:"aggregationCount",count_distinct:"aggregationCountDistinct"},Ks=(e,t=ha)=>String(t[Gs[e]]),$i=(e,t)=>{let n=e.columnMetadata?.find(a=>a.key===t)?.allowedAggregations;return n?.length?ar.filter(a=>n.includes(a.value)):[...ar]},Ys=(e,t,n)=>{let a=wi(e);if(!a||!Si(e,a,ki(e)).includes(t)||!$i(e,t).some(o=>o.value===n))return;let i=ar.find(o=>o.value===n)?.label;if(i)return`Using the same approved data, filters, and period as "${e.title?.trim()||e.label?.trim()||"the previous chart"}", calculate ${i.toLowerCase()} of ${In(e,t)} for each ${In(e,a)}. Return a chart and show a table if this app permits it.`},Zs=(e,t=ha)=>{if(e.presentation==="table"||e.presentation==="kpi")return[];let n=nr(e);if(!n)return[];let a=[{type:"line",label:t.chartLine,hint:t.chartLineHint},{type:"bar",label:t.chartBar,hint:t.chartBarHint}];return n.series.length>1&&a.push({type:"stacked_bar",label:t.chartStackedBar,hint:t.chartStackedBarHint}),a},Js=e=>t=>{let n=e.inProgressIndex??-1,a=(Array.isArray(t)?t:[t]).filter(s=>{if(!s||typeof s!="object")return!1;let c=String(s.seriesId??"").startsWith("in-progress:"),d=s.dataIndex,l=s.value;return c?d===n:!(d===n&&l==null)}),i=String(a[0]?.axisValueLabel??a[0]?.name??""),o=s=>s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");return[i?`<strong>${o(i)}</strong>`:"",...a.map(s=>{let c=e.series[Math.floor(Number(s.seriesIndex)/2)]??e.series[0];return`${String(s.marker??"")}${o(String(s.seriesName??""))}: ${o(tn(s.value,c?.valueColumn,void 0,!1,e.locale))}`})].filter(Boolean).join("<br/>")},Xs=e=>t=>{let n=(Array.isArray(t)?t:[t]).filter(s=>!!s&&typeof s=="object"),a=s=>s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),i=String(n[0]?.axisValueLabel??n[0]?.name??""),o=n.flatMap(s=>{let c=e.series[Number(s.seriesIndex)]??e.series[0],d=c?.points?.[Number(s.dataIndex)],l=u=>tn(u,c?.valueColumn,void 0,!1,e.locale);return[`${String(s.marker??"")}${a(String(s.seriesName??""))}: ${a(l(s.value))}`,...cs(e.comparison,d,l).map(u=>`<span style="opacity:.75">${a(u)}</span>`)]});return[i?`<strong>${a(i)}</strong>`:"",...o].filter(Boolean).join("<br/>")},Qs=(e,{expanded:t=!1,reducedMotion:n=!1,theme:a=en,zoomWindow:i=ln(e.categories.length)}={})=>{let o=e.series.length>1||e.type==="line"&&(e.inProgressIndex??0)>0,s=e.type==="stacked_bar",c=e.categories.length>2,d=Cn(i,e.categories.length);return{animation:!n,animationDuration:n?0:260,aria:{enabled:!0,decal:{show:!0},label:{description:`${e.title}. ${e.summary}`}},backgroundColor:"transparent",color:a.colors,textStyle:{color:a.text,fontFamily:"inherit"},grid:{top:o?t?48:42:14,right:12,bottom:t?18:10,left:10,containLabel:!0},legend:{show:o,type:"scroll",top:0,left:"center",itemWidth:12,itemHeight:8,textStyle:{color:a.muted,fontSize:t?11:10}},tooltip:{trigger:"axis",...e.type==="line"&&(e.inProgressIndex??0)>0?{formatter:Js(e)}:e.comparison?{formatter:Xs(e)}:{},triggerOn:"mousemove|click",confine:!0,backgroundColor:a.surface,borderColor:a.border,borderWidth:1,textStyle:{color:a.text,fontSize:12},axisPointer:{type:"line",lineStyle:{color:a.muted,opacity:.5}}},dataZoom:c?[{id:gi,type:"inside",xAxisIndex:0,startValue:d.startIndex,endValue:d.endIndex,minValueSpan:1,filterMode:"filter",disabled:!0}]:void 0,xAxis:{type:"category",data:e.categories,name:e.xAxisTitle,nameLocation:"middle",nameGap:t?38:32,nameTextStyle:{color:a.muted,fontSize:t?11:10},axisLine:{lineStyle:{color:a.border}},axisTick:{show:!1},axisLabel:{color:a.muted,fontSize:t?11:9,hideOverlap:!0,interval:"auto",rotate:!t&&e.categories.length>5?28:0,formatter:l=>l.length>(t?18:11)?`${l.slice(0,t?16:9)}…`:l}},yAxis:{type:"value",name:e.yAxisTitle,nameLocation:"middle",nameGap:t?52:44,nameTextStyle:{color:a.muted,fontSize:t?11:10},axisLabel:{color:a.muted,fontSize:t?11:9,formatter:l=>tn(l,e.series[0]?.valueColumn,void 0,!0,e.locale)},axisLine:{show:!1},axisTick:{show:!1},splitNumber:4,splitLine:{lineStyle:{color:a.border,opacity:.75}}},series:e.series.flatMap((l,u)=>{let p=e.inProgressIndex??-1,m={type:e.type==="line"?"line":"bar",name:l.name,data:l.values,stack:s?"total":void 0,connectNulls:!1,showSymbol:e.type==="line"&&e.categories.length<=18,symbol:"circle",symbolSize:t?7:6,smooth:!1,maxBarWidth:t?38:28,lineStyle:e.type==="line"?{width:t?3:2.5}:void 0,itemStyle:e.type==="line"?{borderColor:a.background,borderWidth:2}:{borderRadius:s?0:[4,4,0,0]},emphasis:{focus:"series"},tooltip:{valueFormatter:_=>tn(_,l.valueColumn,void 0,!1,e.locale)}};if(p<0)return[m];let f=a.colors[u%a.colors.length];return e.type==="line"?p===0?[m]:[{...m,lineStyle:{...m.lineStyle,color:f},itemStyle:{...m.itemStyle,color:f},data:l.values.map((_,h)=>h===p?null:_)},{...m,id:`in-progress:${u}`,name:e.labels.inProgressLegend||ps,showSymbol:!0,symbol:"emptyCircle",lineStyle:{width:t?3:2.5,type:"dashed",color:f,opacity:.6},itemStyle:{color:f,opacity:.6},data:l.values.map((_,h)=>h===p||h===p-1?_:null)}]:[{...m,data:l.values.map((_,h)=>h===p?{value:_,itemStyle:{opacity:.45,borderType:"dashed",borderWidth:1.5,borderColor:f}}:_)}]})}},ec=e=>{let t=getComputedStyle(e),n=(c,d)=>{for(let l of c){let u=t.getPropertyValue(l).trim();if(u)return u}return d},[a,i,o,s]=en.colors;return{background:n(["--rv-bg","--cf-bg"],en.background),border:n(["--rv-border","--cf-border"],en.border),muted:n(["--rv-muted","--cf-muted"],en.muted),surface:n(["--rv-surface","--cf-surface"],en.surface),text:n(["--rv-text","--cf-text"],en.text),colors:[n(["--rv-chart-1","--rv-accent","--cf-accent"],a),n(["--rv-chart-2"],i),n(["--rv-chart-3"],o),n(["--rv-chart-4"],s)]}},tc=["data-theme","data-color-scheme","class","style"],nc=(e,t)=>{let n=[];if(typeof matchMedia<"u"){let a=matchMedia("(prefers-color-scheme: dark)");a.addEventListener?.("change",t),n.push(()=>a.removeEventListener?.("change",t))}if(typeof MutationObserver<"u"){let a=new MutationObserver(t),i=e;for(;i;){i instanceof Element&&a.observe(i,{attributes:!0,attributeFilter:tc});let o=i.parentNode;i=o instanceof ShadowRoot?o.host:o}n.push(()=>a.disconnect())}return()=>n.forEach(a=>a())},ac=({model:e,expanded:t=!1,classPrefix:n="cf"})=>{let a=R(null),i=R(null),[o,s]=$(()=>({model:e,window:ln(e.categories.length)})),[c,d]=$(!1),l=o.model===e?Cn(o.window,e.categories.length):ln(e.categories.length),u=R(l);u.current=l;let p=Y=>{let z=Cn(Y,e.categories.length);u.current=z,s({model:e,window:z}),i.current?.dispatchAction({type:"dataZoom",dataZoomId:gi,startValue:z.startIndex,endValue:z.endIndex})},[m,f]=$(!1),[_,h]=$(0),[I,x]=$(0);X(()=>{let Y=a.current;if(Y)return nc(Y,()=>x(z=>z+1))},[]),X(()=>{let Y=a.current;if(!Y)return;let z=!1,te=null;return Us().then(({init:U})=>{if(z||!Y.isConnected||!mi&&typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("jsdom"))return;let B=U(Y,null,{renderer:"canvas",devicePixelRatio:Math.min(window.devicePixelRatio||1,2)});i.current=B;let A=()=>{B.resize(),h(Math.round(Y.clientWidth/40))},N=typeof ResizeObserver>"u"?null:new ResizeObserver(A);N?.observe(Y),N||window.addEventListener("resize",A,{passive:!0}),te=()=>{N?.disconnect(),N||window.removeEventListener("resize",A),B.dispose(),i.current=null},f(!0)}).catch(()=>{z||d(!0)}),()=>{z=!0,te?.()}},[]),X(()=>{let Y=a.current,z=i.current;if(!Y||!z)return;let te=typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;z.setOption(Ms(Qs(e,{expanded:t,reducedMotion:te,theme:ec(Y),zoomWindow:u.current}),Y.clientWidth),{lazyUpdate:!0,notMerge:!0}),z.resize()},[t,e,m,I,_]);let g=e.labels,T=!c&&e.categories.length>2,V=l.endIndex-l.startIndex+1,P=l.startIndex===0&&l.endIndex===e.categories.length-1,ee=T&&V>2,Z=T&&!P;return r(se,{children:[r("div",{ref:a,class:`${n}-analytics-echart${t?" is-expanded":""}`,role:"img","aria-label":`${e.title}. ${e.summary}`,"data-chart-status":c?"fallback":"ready",children:c?r("span",{class:`${n}-analytics-echart__fallback`,children:e.summary}):null}),e.comparisonNote?r("p",{class:`${n}-analytics-comparison-note`,"data-comparison-note":!0,style:"margin:4px 2px 0;font-size:11px;color:var(--rv-muted,#5b7186)",children:e.comparisonNote}):null,T?r("div",{class:`${n}-analytics-zoom`,children:[r("span",{class:`${n}-analytics-zoom__range`,"aria-live":"polite","aria-atomic":"true",children:Bs(e.categories,l,g)}),r("div",{class:`${n}-analytics-zoom__controls`,role:"group","aria-label":g.zoomControls,children:[r("button",{type:"button","aria-label":g.zoomOut,title:g.zoomOut,disabled:!Z,onClick:()=>p(vi(u.current,"out",e.categories.length)),children:"−"}),r("button",{type:"button",class:`${n}-analytics-zoom__reset`,"aria-label":g.zoomReset,title:g.zoomReset,disabled:P,onClick:()=>p(ln(e.categories.length)),children:g.zoomResetShort}),r("button",{type:"button","aria-label":g.zoomIn,title:g.zoomIn,disabled:!ee,onClick:()=>p(vi(u.current,"in",e.categories.length)),children:"+"})]})]}):null]})},En=e=>{let t=e.replaceAll("_"," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim();return t?`${t.charAt(0).toUpperCase()}${t.slice(1)}`:"Value"},Ti=(e,t)=>(t?.length?t:Object.keys(e[0]??{})).map(n=>typeof n=="string"?{key:n,label:En(n)}:{...n,label:n.label?.trim()||En(n.key)}),rr=(e,t,n,a={})=>Ps(e,n,{...a,locale:t??a.locale}),Ci=e=>{let t=String(e??"");return/[",\r\n]/.test(t)?`"${t.replaceAll('"','""')}"`:t},rc=(e,t)=>{let n=Ti(e,t);return[n.map(a=>Ci(a.label)).join(","),...e.map(a=>n.map(i=>Ci(a[i.key])).join(","))].join(`\r
2
- `)},Ai=({label:e,options:t,value:n,onChange:a,classPrefix:i})=>{let o=R(null),s=R(null),[c,d]=$(n),[l,u]=$(!1);X(()=>d(n),[n]);let p=f=>`${i}-${f}`,m=f=>{d(f),o.current&&(o.current.dataset.value=f,o.current.open=!1,o.current.querySelector("summary")?.focus()),a?.(f)};return r("details",{ref:o,"data-result-popover":!0,"data-result-select":!0,"data-value":c,class:p("sdk-select"),onToggle:f=>{let _=f.currentTarget.open;u(_);let h=s.current;if(h){if(h.setAttribute("popover","manual"),!_){typeof h.hidePopover=="function"&&h.matches(":popover-open")&&h.hidePopover();return}typeof h.showPopover=="function"&&!h.matches(":popover-open")&&h.showPopover(),requestAnimationFrame(()=>{if(!o.current?.open||!h.isConnected)return;let I=o.current.querySelector("summary").getBoundingClientRect(),x=Math.max(I.width,Math.min(220,innerWidth-24)),g=Math.min(h.scrollHeight,240);h.style.width=`${x}px`,h.style.left=`${Math.max(12,Math.min(I.left,innerWidth-x-12))}px`,h.style.top=`${I.bottom+g+6<=innerHeight-12?I.bottom+6:Math.max(12,I.top-g-6)}px`})}},children:[r("summary",{class:p("sdk-select-trigger"),role:"combobox","aria-label":e,"aria-haspopup":"listbox","aria-expanded":l,children:[r("span",{children:t.find(([f])=>f===c)?.[1]??c}),r("span",{"aria-hidden":"true",children:"⌄"})]}),r("div",{ref:s,class:p("sdk-select-list"),role:"listbox","aria-label":e,popover:"manual",children:t.map(([f,_])=>r("button",{type:"button",role:"option","aria-selected":f===c,onClick:()=>m(f),children:_},f))})]})},ic=(e,t,n)=>{let a=n.value.trim();if(!a)return!0;let i=String(e??""),o=typeof e=="number"?e:NaN,s=Number(a),c=!Number.isNaN(o)&&!Number.isNaN(s)?o-s:i.localeCompare(a,void 0,{numeric:!0,sensitivity:"base"});switch(n.operator){case"equals":return c===0;case"not_equals":return c!==0;case"gt":return c>0;case"gte":return c>=0;case"lt":return c<0;case"lte":return c<=0;default:return i.toLocaleLowerCase().includes(a.toLocaleLowerCase())||t.toLocaleLowerCase().includes(a.toLocaleLowerCase())}},oc=({rows:e,columns:t,maxRows:n=100,locale:a,format:i,expanded:o=!1,classPrefix:s="cr",pageSize:c=10})=>{let d=Be(()=>Ti(e,t),[t,e]),l=d.map(k=>k.key).join("\0"),[u,p]=$(()=>d.map(k=>k.key)),[m,f]=$(""),[_,h]=$(),[I,x]=$("asc"),[g,T]=$({}),[V,P]=$(),[ee,Z]=$([]),[Y,z]=$({}),[te,U]=$(()=>d.map(k=>k.key)),[B,A]=$(!1),[N,y]=$([]),[D,S]=$("table"),[O,ue]=$(1),[oe,Fe]=$(c),_e=R(null);X(()=>{let k=j=>{let G=j.composedPath();_e.current?.querySelectorAll("details[data-result-popover][open]").forEach(ne=>{G.includes(ne)||(ne.open=!1)})},K=j=>{let G=[..._e.current?.querySelectorAll("details[data-result-popover][open]")??[]].at(-1);j.key!=="Escape"||!G||(G.open=!1,G.querySelector("summary")?.focus(),j.preventDefault())};return document.addEventListener("pointerdown",k),document.addEventListener("keydown",K),()=>{document.removeEventListener("pointerdown",k),document.removeEventListener("keydown",K)}},[]),X(()=>{p(d.map(k=>k.key)),h(void 0),T({}),P(void 0),Z([]),z({}),U(d.map(k=>k.key)),y([]),ue(1)},[l]);let Te=te.map(k=>d.find(K=>K.key===k)).filter(k=>!!(k&&u.includes(k.key))),Le=Be(()=>{let k=m.toLocaleLowerCase(a),K=e.map((j,G)=>({row:j,index:G})).filter(({row:j})=>Te.some(G=>rr(j[G.key],a,G,i).toLocaleLowerCase(a).includes(k))&&Object.entries(g).every(([G,ne])=>{let ye=d.find(Se=>Se.key===G);return ic(j[G],rr(j[G],a,ye,i),ne)}));return _?K.sort((j,G)=>{let ne=j.row[_],ye=G.row[_],Se=typeof ne=="number"?ne:NaN,et=typeof ye=="number"?ye:NaN,Ye=!Number.isNaN(Se)&&!Number.isNaN(et)?Se-et:String(ne??"").localeCompare(String(ye??""),a,{numeric:!0,sensitivity:"base"});return I==="asc"?Ye:-Ye}):K},[Te,g,i,a,m,d,e,I,_]),Ie=Le.slice(0,Math.max(1,n)),Ce=Math.max(1,Math.ceil(Ie.length/oe)),ve=Math.min(O,Ce),Xe=o?Ie:Ie.slice((ve-1)*oe,ve*oe),ge=Xe.length>0&&Xe.every(({index:k})=>N.includes(k)),ie=k=>`${s}-${k}`,He=()=>{p(d.map(k=>k.key)),U(d.map(k=>k.key)),z({}),h(void 0),x("asc"),T({}),P(void 0),Z([]),A(!1),f(""),y([]),S("table"),ue(1)};if(e.length===0||d.length===0)return r("div",{class:ie("table-note"),children:"No rows returned."});let We=k=>{let K=new Set(Xe.map(({index:j})=>j));y(j=>k?[...new Set([...j,...K])]:j.filter(G=>!K.has(G)))};return r("section",{ref:_e,class:ie("data-table"),children:[r("div",{class:ie("table-fields"),children:[r("strong",{children:"Fields"}),r("div",{class:ie("field-list"),children:d.map(k=>r("span",{class:ie("field-chip"),children:k.label},k.key))}),r("span",{class:ie("table-field-count"),children:[e.length.toLocaleString(a)," rows"]})]}),r("div",{class:ie("table-controls"),children:[r("label",{class:ie("table-search"),children:[r("span",{"aria-hidden":"true",children:"⌕"}),r("input",{type:"search",value:m,placeholder:"Search this result...","aria-label":"Search this result",onInput:k=>{f(k.currentTarget.value.trim()),ue(1)}})]}),r("div",{class:ie("table-modes"),role:"group","aria-label":"Table display mode",children:["table","matrix"].map(k=>r("button",{type:"button",class:`${ie("segment")}${D===k?" is-active":""}`,"aria-pressed":D===k,onClick:()=>S(k),children:k==="table"?"Table":"Matrix"},k))})]}),r("div",{class:ie("table-column-bar"),children:[r("details",{"data-result-popover":!0,class:ie("column-picker"),children:[r("summary",{children:"Columns"}),r("div",{class:ie("column-menu"),children:te.map((k,K)=>{let j=d.find(G=>G.key===k);return j?r("div",{class:ie("column-picker-row"),children:[r("label",{children:[r("input",{type:"checkbox",checked:u.includes(j.key),onChange:G=>{let ne=G.currentTarget.checked;p(ye=>ne?[...new Set([...ye,j.key])]:ye.length>1?ye.filter(Se=>Se!==j.key):ye)}}),r("span",{children:Y[j.key]||j.label})]}),r("button",{type:"button","aria-label":`Move ${j.label} left`,disabled:K===0,onClick:()=>U(G=>{let ne=[...G];return[ne[K-1],ne[K]]=[ne[K],ne[K-1]],ne}),children:"↑"}),r("button",{type:"button","aria-label":`Move ${j.label} right`,disabled:K===te.length-1,onClick:()=>U(G=>{let ne=[...G];return[ne[K+1],ne[K]]=[ne[K],ne[K+1]],ne}),children:"↓"})]},j.key):null})})]}),r("button",{type:"button",class:ie("table-view-button"),"aria-pressed":B,onClick:()=>A(k=>!k),children:B?"Comfortable rows":"Compact rows"}),r("button",{type:"button",class:ie("table-view-button"),onClick:He,children:"Reset view"})]}),Object.keys(g).length?r("div",{class:ie("table-filter-bar"),children:Object.entries(g).map(([k,K])=>{let j=d.find(G=>G.key===k);return r("button",{type:"button",class:ie("table-filter-chip"),"aria-label":`Clear ${j?.label??k} filter`,onClick:()=>T(G=>{let ne={...G};return delete ne[k],ne}),children:[Y[k]||j?.label||k," ",K.operator.replaceAll("_"," ")," ",K.value," ×"]},k)})}):null,r("div",{class:ie("table-wrap"),role:"region","aria-label":"Scrollable result table",tabIndex:0,children:r("table",{class:`${ie("table")}${D==="matrix"?" is-matrix":""}${B?" is-compact":""}`,children:[r("caption",{class:ie("visually-hidden"),children:["Result table with ",Le.length," ",Le.length===1?"row":"rows"]}),r("thead",{children:r("tr",{children:[r("th",{class:ie("select-cell"),children:r("input",{type:"checkbox","aria-label":"Select all visible rows",checked:ge,onChange:k=>We(k.currentTarget.checked)})}),Te.map(k=>r("th",{scope:"col",class:V===k.key?"is-pinned":void 0,style:V===k.key?{left:"34px"}:void 0,"aria-sort":_===k.key?I==="asc"?"ascending":"descending":"none",children:[r("button",{type:"button",class:ie("table-sort"),"aria-label":`Sort by ${k.label}`,onClick:()=>{_===k.key?x(K=>K==="asc"?"desc":"asc"):(h(k.key),x("asc")),ue(1)},children:[r("span",{children:Y[k.key]||k.label}),r("span",{class:ie("sort-direction"),"aria-hidden":"true",children:_===k.key?I==="asc"?"↑":"↓":"↕"})]}),r("details",{"data-result-popover":!0,class:ie("table-column-menu"),onToggle:K=>{let j=K.currentTarget,G=j.querySelector(`.${ie("table-column-panel")}`);if(G?.setAttribute("popover","manual"),!j.open){G&&typeof G.hidePopover=="function"&&G.matches(":popover-open")&&G.hidePopover(),j.querySelectorAll("details[data-result-select][open]").forEach(ne=>{ne.open=!1});return}_e.current?.querySelectorAll("details[data-result-popover][open]").forEach(ne=>{ne!==j&&!j.contains(ne)&&(ne.open=!1)}),G&&typeof G.showPopover=="function"&&!G.matches(":popover-open")&&G.showPopover(),requestAnimationFrame(()=>{if(!j.open||!j.isConnected)return;let ne=j.querySelector("summary")?.getBoundingClientRect();if(!ne||!G)return;let{width:ye,height:Se}=G.getBoundingClientRect(),et=ne.bottom+Se+5<=innerHeight-12?ne.bottom+5:ne.top-Se-5;G.style.left=`${Math.max(12,Math.min(ne.right-ye,innerWidth-ye-12))}px`,G.style.top=`${Math.max(12,Math.min(et,innerHeight-Se-12))}px`})},children:[r("summary",{"aria-label":`Actions for ${k.label}`,children:"⋯"}),r("div",{class:ie("table-column-panel"),popover:"manual",children:[r("strong",{children:Y[k.key]||k.label}),r("button",{type:"button",onClick:()=>{h(k.key),x("asc"),ue(1)},children:"Sort ascending"}),r("button",{type:"button",onClick:()=>{h(k.key),x("desc"),ue(1)},children:"Sort descending"}),r("span",{children:"Filter values"}),r(Ai,{classPrefix:s,label:`Filter operator for ${k.label}`,value:g[k.key]?.operator??"contains",options:[["contains","Contains"],["equals","Equals"],["not_equals","Does not equal"],["gt","Greater than"],["gte","At least"],["lt","Less than"],["lte","At most"]]}),r("input",{type:"text","aria-label":`Filter value for ${k.label}`,defaultValue:g[k.key]?.value??"",placeholder:"Enter a value"}),r("button",{type:"button",onClick:K=>{let j=K.currentTarget.parentElement,G=j.querySelector('input[aria-label^="Filter value"]').value.trim(),ne=j.querySelector("[data-result-select]").dataset.value;T(ye=>{let Se={...ye};return G?Se[k.key]={operator:ne,value:G}:delete Se[k.key],Se}),ue(1),K.currentTarget.closest("details").open=!1},children:"Apply filter"}),r("button",{type:"button",onClick:K=>{P(j=>j===k.key?void 0:k.key),U(j=>[k.key,...j.filter(G=>G!==k.key)]),K.currentTarget.closest("details").open=!1},children:V===k.key?"Unpin column":"Pin column"}),r("button",{type:"button",onClick:K=>{Z(j=>j.includes(k.key)?j.filter(G=>G!==k.key):[...j,k.key]),K.currentTarget.closest("details").open=!1},children:ee.includes(k.key)?"Do not wrap text":"Wrap text"}),r("input",{type:"text","aria-label":`Display name for ${k.label}`,defaultValue:Y[k.key]||k.label,maxLength:80}),r("button",{type:"button",onClick:K=>{let j=K.currentTarget.parentElement.querySelector('input[aria-label^="Display name"]').value.trim();z(G=>({...G,[k.key]:j||k.label||k.key})),K.currentTarget.closest("details").open=!1},children:"Apply display name"})]})]})]},k.key))]})}),r("tbody",{children:Xe.map(({row:k,index:K})=>r("tr",{class:N.includes(K)?"is-selected":void 0,children:[r("td",{class:ie("select-cell"),children:r("input",{type:"checkbox","aria-label":`Select row ${K+1}`,checked:N.includes(K),onChange:j=>y(G=>j.currentTarget.checked?[...new Set([...G,K])]:G.filter(ne=>ne!==K))})}),Te.map(j=>r("td",{class:`${ee.includes(j.key)?"is-wrapped":""} ${V===j.key?"is-pinned":""}`.trim(),style:V===j.key?{left:"34px"}:void 0,children:rr(k[j.key],a,j,i)},j.key))]},K))})]})}),r("div",{class:ie("table-summary"),children:[r("span",{children:Ie.length?`${((ve-1)*oe+1).toLocaleString(a)}-${Math.min(ve*oe,Ie.length).toLocaleString(a)} of ${Le.length.toLocaleString(a)}`:`0 of ${Le.length.toLocaleString(a)}`}),o?r("span",{children:e.length>n?`First ${n.toLocaleString(a)} rows available`:"All returned rows loaded"}):r("div",{class:ie("table-pagination"),"aria-label":"Table pagination",children:[r("label",{children:[r("span",{children:"Rows"}),r(Ai,{classPrefix:s,label:"Rows per page",value:String(oe),options:[["10","10"],["25","25"],["50","50"]],onChange:k=>{Fe(Number(k)),ue(1)}})]}),r("button",{type:"button","aria-label":"Previous page",disabled:ve<=1,onClick:()=>ue(k=>Math.max(1,k-1)),children:"‹"}),r("span",{children:[ve," / ",Ce]}),r("button",{type:"button","aria-label":"Next page",disabled:ve>=Ce,onClick:()=>ue(k=>Math.min(Ce,k+1)),children:"›"})]})]})]})},sc=(e,t,n)=>{let a=Qa(t),i=[],o=e.reportingPeriod?.label?.trim();o&&i.push({label:a.aboutPeriod,value:o});let s=e.rowCount??e.rows?.length;typeof s=="number"&&i.push({label:a.aboutResults,value:vt(s===1?a.rowOne:a.rowMany,{count:s})});let c=e.explanation?.checkedAt??e.freshness?.answeredAt,d=e.explanation?.timezone??e.timezone??e.reportingPeriod?.timezone;if(c){let u=new Date(c),p=c;if(!Number.isNaN(u.getTime()))try{p=new Intl.DateTimeFormat(n,{dateStyle:"medium",timeStyle:"short",...d?{timeZone:d}:{}}).format(u)}catch{p=u.toLocaleString(n)}i.push({label:a.aboutChecked,value:p})}d&&i.push({label:a.aboutTimezone,value:d});let l=e.explanation?.dataFreshness?.status??e.freshness?.status;return l&&l!=="unknown"&&i.push({label:a.aboutSourceData,value:l.replaceAll("_"," ")}),e.appliedFilters?.length&&i.push({label:a.aboutFilters,value:vt(a.filtersApplied,{count:e.appliedFilters.length})}),i},Mi=e=>e.columns?.length?e.columns:Object.keys(e.rows?.[0]??{}),cc=e=>{let t=e.rows??[],n=e.currency?.code&&!e.currency.isMixed?e.currency.code:void 0;return Mi(e).map(a=>{let i=e.columnMetadata?.find(s=>s.key===a);if(!i)return{key:a,label:En(a)};let o=i.dataType==="date"||i.dataType==="datetime"||i.semanticRole==="date";return{key:a,label:i.label,dataType:i.dataType,currencyCode:i.currencyCode||(i.dataType==="currency"?n:void 0),formatPattern:i.formatPattern,grain:o?i.grain??e.periodComparison?.grain??li(t.map(s=>s[a])):void 0}})},lc=(e,t)=>{let n=e.rows?.[0]??{};return e.chartRecommendation?.valueFields?.[0]??e.valueFields?.[0]??e.value??e.columnMetadata?.find(a=>a.semanticRole==="measure"&&a.key in n)?.key??t.find(a=>$n(n[a])!==null)??t[1]??t[0]},dc=(e,t,n="analytics-result.csv")=>{if(typeof document>"u"||e.length===0)return;let a=rc(t,e),i=URL.createObjectURL(new Blob([a],{type:"text/csv;charset=utf-8"})),o=document.createElement("a");o.href=i,o.download=n,o.click(),URL.revokeObjectURL(i)},dn=new Set,Ii=e=>{let t=e.composedPath();dn.forEach(n=>{n.isOpen()&&!n.contains(t)&&n.close(!1)})},Ei=e=>{if(e.key==="Escape"){for(let t of dn)if(t.isOpen()){t.close(!0),e.preventDefault();return}}},uc=e=>(dn.size===0&&typeof document<"u"&&(document.addEventListener("pointerdown",Ii),document.addEventListener("keydown",Ei)),dn.add(e),()=>{dn.delete(e),dn.size===0&&typeof document<"u"&&(document.removeEventListener("pointerdown",Ii),document.removeEventListener("keydown",Ei))}),ma=({children:e,size:t=15})=>r("svg",{viewBox:"0 0 24 24",width:t,height:t,fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false",children:e}),pc=()=>r(ma,{children:r("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})}),fc=()=>r(ma,{children:r("path",{d:"M18 6 6 18M6 6l12 12"})}),zi=()=>r(ma,{size:13,children:r("path",{d:"m6 9 6 6 6-6"})}),hc=()=>r(ma,{size:13,children:r("path",{d:"m5 12 5 5L20 7"})}),Ni=({type:e,className:t})=>r("svg",{viewBox:"0 0 32 32","aria-hidden":"true",class:t,fill:"none",children:[r("path",{d:"M6 26h21M6 7v19",stroke:"var(--rv-muted)","stroke-width":"1.4","stroke-linecap":"round"}),e==="line"?r("path",{d:"M8 21c4-7 7 2 11-6 2.5-5 4.5-2 7-7",stroke:"var(--rv-chart-2)","stroke-width":"2.1","stroke-linecap":"round","stroke-linejoin":"round"}):e==="stacked_bar"?r(se,{children:[9,15,21].map((n,a)=>r("g",{children:[r("rect",{x:n,y:18-a*2,width:"4",height:8+a*2,fill:"var(--rv-chart-2)",rx:"0.6"}),r("rect",{x:n,y:13-a,width:"4",height:"5",fill:"var(--rv-chart-3)",rx:"0.6"}),r("rect",{x:n,y:9-a,width:"4",height:"4",fill:"var(--rv-chart-1)",rx:"0.6"})]},n))}):r(se,{children:[r("rect",{x:"9",y:"18",width:"4",height:"8",fill:"var(--rv-chart-2)",rx:"0.7"}),r("rect",{x:"15",y:"13",width:"4",height:"13",fill:"var(--rv-chart-2)",rx:"0.7"}),r("rect",{x:"21",y:"8",width:"4",height:"18",fill:"var(--rv-chart-2)",rx:"0.7"})]})]}),Ri=e=>{let[t,n]=$(!1),a=R(null),i=R(null),o=R(t);return o.current=t,X(()=>uc({isOpen:()=>o.current,contains:s=>!!(a.current&&s.includes(a.current)||i.current&&s.includes(i.current)),close:s=>{n(!1),s&&a.current?.focus()}}),[]),Sn(()=>{if(!t)return;let s=()=>{let c=a.current,d=i.current;if(!c||!d)return;d.style.left="0px",d.style.top="0px";let l=d.getBoundingClientRect(),u=c.getBoundingClientRect(),p=document.documentElement.clientWidth||window.innerWidth,m=document.documentElement.clientHeight||window.innerHeight,f=getComputedStyle(c).direction==="rtl",_=e==="end"===f?u.left:u.right-l.width;_=Math.max(8,Math.min(_,p-l.width-8));let h=u.bottom+7;h+l.height>m-8&&u.top-7-l.height>8&&(h=u.top-7-l.height),d.style.left=`${_-l.left}px`,d.style.top=`${h-l.top}px`};return s(),window.addEventListener("resize",s),window.addEventListener("scroll",s,!0),i.current?.querySelector('[aria-selected="true"], button')?.focus({preventScroll:!0}),()=>{window.removeEventListener("resize",s),window.removeEventListener("scroll",s,!0)}},[t,e]),{open:t,setOpen:n,triggerRef:a,layerRef:i}},mc=({visualization:e,field:t,prefix:n,labels:a,locale:i,headerTitle:o})=>{let s=e.rows??[],c=e.columnMetadata?.find(x=>x.key===t),d=t?s[0]?.[t]:void 0,l=$n(d),u=x=>tn(x,c,e,!1,i),p=l===null?String(d??a.noValue):u(l),m=e.periodComparison,f=!m?.measureField||m.measureField===t,_=t?$n(s[1]?.[t]):null,h=l!==null&&m&&f?zr(m,{value:l,status:"observed",label:m.currentPeriod?.label},{value:_??m.previousFullValue??m.previousToDateValue,status:"observed",label:m.previousPeriod?.label},{format:u,locale:i}):void 0,I=c?.label??(t?En(t):a.currentValue);return r("section",{class:`${n}-analytics-kpi`,"aria-label":o??I,"data-testid":"analytics-kpi",children:[r("div",{class:`${n}-analytics-kpi__label`,children:I}),r("div",{class:`${n}-analytics-kpi__value`,children:p}),h?r(se,{children:[r("div",{class:`${n}-analytics-kpi__change is-${h.tone}`,"data-comparison-basis":h.basis,title:h.title,children:[r("span",{children:h.label}),h.copy?r("span",{class:`${n}-analytics-kpi__copy`,children:h.copy}):null]}),h.secondary?r("div",{class:`${n}-analytics-kpi__secondary`,children:h.secondary}):null]}):null]})},gc=({visualization:e,classPrefix:t,labels:n,locale:a,expanded:i=!1,onExpand:o,onClose:s,expandControlId:c,onFollowUp:d,onDownload:l,headerActions:u,children:p,dataToggle:m,cardRef:f,maxTableRows:_=100})=>{let h=Be(()=>Qa(n),[n]),I=Be(()=>nr(e,void 0,{labels:h,locale:a}),[e,h,a]),[x,g]=$(I?.type);X(()=>g(I?.type),[I]);let[T,V]=$(!1),P=Be(()=>Zs(e,h),[e,h]),ee=Be(()=>nr(e,x,{labels:h,locale:a}),[e,x,h,a]),Z=x??ee?.type??I?.type,Y=P.find(ge=>ge.type===Z),z=[...new Set(ee?.series.map(ge=>ge.field)??[])],te=Ri("end"),U=Ri("start"),B=e.rows??[],A=Mi(e),N=Be(()=>ds(e),[e]),y=Be(()=>cc(N),[N]),D=Be(()=>({locale:a,timezone:e.timezone||e.periodComparison?.timezone,yes:h.yes,no:h.no}),[a,e.timezone,e.periodComparison?.timezone,h]),S=sc(e,h,a),O=l===!1||!e.downloadAvailable?null:()=>(l??dc)(A,B),ue=S.length?r("details",{class:`${t}-analytics-inspect`,children:[r("summary",{children:h.aboutResult}),r("dl",{children:S.map(ge=>r("div",{children:[r("dt",{children:ge.label}),r("dd",{children:ge.value})]},ge.label))})]}):null,oe=(()=>{let ge=e.freshness?.answeredAt,ie=ge?new Date(ge):null;return!ie||Number.isNaN(ie.getTime())?h.liveData:vt(h.updatedAt,{time:new Intl.DateTimeFormat(a,{hour:"numeric",minute:"2-digit"}).format(ie)})})(),Fe=e.rowCount??B.length,_e=e.appliedFilters?.length??0,Te=r("div",{class:`${t}-analytics-meta`,"data-testid":"analytics-result-meta",role:"group","aria-label":h.resultDetails,children:[r("span",{children:[r("span",{"aria-hidden":"true",class:`${t}-analytics-meta__dot`}),oe]}),e.reportingPeriod?.label?r("span",{children:e.reportingPeriod.label}):null,r("span",{children:vt(Fe===1?h.rowOne:h.rowMany,{count:Fe})}),_e>0?r("span",{children:vt(_e===1?h.filtersOne:h.filtersMany,{count:_e})}):null]}),Le=(ge,ie,He,We=h.expandChart)=>r("div",{class:`${t}-analytics-result`,children:[r("section",{ref:f,class:`${t}-analytics-visualization${i?" is-expanded":""}`,"aria-label":ge,children:[r("div",{class:`${t}-analytics-visualization__header`,children:[r("div",{children:[r("div",{class:`${t}-analytics-visualization__title`,children:ge}),Te]}),r("div",{class:`${t}-analytics-visualization__actions`,children:[He,u,i&&s?r("button",{type:"button",class:`${t}-analytics-visualization__close`,"aria-label":h.restoreView,title:h.restoreView,onClick:s,children:r(fc,{})}):o&&e.expandable!==!1?r("button",{type:"button",class:`${t}-analytics-visualization__expand`,"aria-label":We,title:We,"data-visualization-message":c,onClick:o,children:r(pc,{})}):null]})]}),ie,ue,p]}),r("div",{class:`${t}-analytics-layer`,children:[d?r("div",{ref:U.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:"fixed"},role:"menu","aria-label":h.aggregate,hidden:!U.open,children:z.flatMap(k=>$i(e,k).map(K=>{let j=e.columnMetadata?.find(G=>G.key===k)?.label??En(k);return r("button",{type:"button",role:"menuitem",onClick:()=>{let G=Ys(e,k,K.value);G&&d(G),U.setOpen(!1)},children:r("span",{class:`${t}-analytics-chart-picker__copy`,children:[r("strong",{children:[Ks(K.value,h)," · ",j]}),r("small",{children:h.aggregateCharge})]})},`${k}:${K.value}`)}))}):null,r("div",{ref:te.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:"fixed"},role:"listbox","aria-label":h.chartType,hidden:!te.open,children:P.map(k=>{let K=k.type===Z;return r("button",{type:"button",role:"option","aria-selected":K,class:K?"is-selected":"",onClick:()=>{g(k.type),te.setOpen(!1),te.triggerRef.current?.focus()},children:[r("span",{class:`${t}-analytics-chart-picker__icon`,children:r(Ni,{type:k.type,className:`${t}-chart-type-icon`})}),r("span",{class:`${t}-analytics-chart-picker__copy`,children:[r("strong",{children:k.label}),r("small",{children:k.hint})]}),K?r(hc,{}):null]},k.type)})})]})]}),Ie=r(oc,{rows:N.rows??B,columns:y,maxRows:_,expanded:i,classPrefix:t,locale:a,format:D}),Ce=()=>e.tableAvailable===!1||A.length===0?null:Le(e.title?.trim()||h.resultDetails,r(se,{children:Ie}),O?r("button",{type:"button",class:`${t}-analytics-visualization__download`,onClick:O,children:h.download}):null,h.expandTable);if(B.length===0)return r(se,{children:[r("section",{class:`${t}-analytics-empty`,role:"status","data-testid":"analytics-empty-state",children:[r("p",{children:h.noMatchTitle}),r("p",{children:h.noMatchBody})]}),ue,p]});if(e.presentation==="table"||!e.presentation&&e.type==="table")return Ce()??r(se,{children:p});let ve=m&&e.tableAvailable!==!1?r("button",{type:"button",class:`${t}-analytics-visualization__download`,"aria-expanded":T,onClick:()=>V(ge=>{let ie=!ge;return m.onToggle?.(ie),ie}),children:T?h.hideData:h.viewData}):null,Xe=T?r("div",{class:`${t}-analytics-data`,children:Ie}):null;return e.presentation==="kpi"||!e.presentation&&e.type==="kpi"?Le(h.liveMetric,r(se,{children:[r(mc,{visualization:e,field:lc(e,A),prefix:t,labels:h,locale:a}),ve,Xe]})):ee?Le(ee.title,r(se,{children:[r(ac,{model:ee,expanded:i,classPrefix:t}),O?r("button",{type:"button",class:`${t}-analytics-visualization__download`,onClick:O,children:h.downloadData}):null,ve,Xe]}),r(se,{children:[d?r("div",{class:`${t}-analytics-chart-picker ${t}-analytics-chart-picker--aggregation`,children:r("button",{type:"button",ref:U.triggerRef,"aria-haspopup":"menu","aria-expanded":U.open,"aria-label":h.aggregate,title:h.aggregateTitle,onClick:()=>{te.setOpen(!1),U.setOpen(!U.open)},children:[r("span",{class:`${t}-analytics-chart-picker__current`,children:r("span",{children:h.aggregate})}),r(zi,{})]})}):null,P.length>1?r("div",{class:`${t}-analytics-chart-picker`,children:r("button",{type:"button",ref:te.triggerRef,"aria-haspopup":"listbox","aria-expanded":te.open,"aria-label":h.chooseChartType,title:h.chooseChartType,onClick:()=>{U.setOpen(!1),te.setOpen(!te.open)},children:[r("span",{class:`${t}-analytics-chart-picker__current`,children:[r(Ni,{type:Z??ee.type,className:`${t}-chart-type-icon`}),r("span",{children:Y?.label??h.chartFallback})]}),r(zi,{})]})}):null]})):Ce()??r(se,{children:p})},bc=["#2563eb","#b45309","#7c3aed"],vc=["#60a5fa","#fbbf24","#a78bfa"],xc=(e,t)=>{let n=`.${e}-analytics-visualization`,a=`.${e}-analytics-result`,i=`.${e}-analytics-chart-picker`,o=`.${e}-analytics-kpi`;return`
1
+ var Centrinfo=(function(St){"use strict";var qp=Object.defineProperty;var Vp=(St,$t,Jt)=>$t in St?qp(St,$t,{enumerable:!0,configurable:!0,writable:!0,value:Jt}):St[$t]=Jt;var B=(St,$t,Jt)=>Vp(St,typeof $t!="symbol"?$t+"":$t,Jt);const $t={notComparable:"Not comparable yet"},Jt=e=>!e||e==="observed"||e==="confirmed_zero",Er=(e,t)=>{let n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:null,a=typeof t.value=="number"&&Number.isFinite(t.value)?t.value:null;return e.status==="missing"||t.status==="missing"||n===null||a===null?{kind:"not_comparable",reason:"missing",label:$t.notComparable}:Jt(e.status)?Jt(t.status)?a===0?{kind:"not_comparable",reason:"previous_zero",label:n===0?"No change (0)":n>0?"Up from 0":"Down from 0"}:{kind:"change",percent:(n-a)/Math.abs(a)*100}:{kind:"not_comparable",reason:"previous_no_records",label:$t.notComparable}:{kind:"not_comparable",reason:"current_no_records",label:`${e.label?.trim()||"Current period"}: no records yet`}},yn=e=>e&&["day","week","month","quarter","year"].includes(e)?e:"period",zr=e=>e==="day"?"vs yesterday at this time":`vs same point last ${yn(e)}`,ds=(e,t)=>{if(!e.cutoffAt)return;let n=new Date(e.cutoffAt);if(Number.isNaN(n.getTime()))return;let a=e.timezone||void 0,i="";try{i=new Intl.DateTimeFormat(t,{...e.grain==="day"?{}:{weekday:"short",day:"numeric",month:"short"},hour:"2-digit",minute:"2-digit",timeZone:a}).format(n)}catch{i=n.toISOString()}let o=e.grain==="day"?"on both days":`in both ${yn(e.grain)}s`,s=e.cutoffSource==="data_as_of"?", the time of the latest record":"";return`Compared up to ${i} ${o}${s}${a?` (${a})`:""}`},Nr=(e,t,n,a={format:String})=>{if(!e||!e.comparisonBasis||e.comparisonBasis==="complete")return;let i=e.comparisonBasis,o=Er(t,n);if(o.kind==="not_comparable"&&o.reason!=="previous_zero")return{basis:i,kind:"neutral",tone:"neutral",label:o.label,copy:"",reason:o.reason};let s=a.format,c=e.currentPeriod?.label||t.label||"Current period",u=e.previousPeriod?.label||n.label||"Previous period",l=typeof t.value=="number"?t.value:e.currentValue,d=typeof e.previousFullValue=="number"?e.previousFullValue:typeof n.value=="number"?n.value:void 0,p=e.grain==="day"?"full day":`full ${yn(e.grain)}`,h=d===void 0?void 0:`${u} ${p}: ${s(d)}`,f=d===void 0?void 0:`${p.charAt(0).toUpperCase()}${p.slice(1)}: ${s(d)}`;if(i==="like_for_like"&&typeof e.previousToDateValue=="number"&&typeof l=="number"){let x=Er({value:l,status:t.status},{value:e.previousToDateValue,status:"observed"}),w=ds(e,a.locale);if(x.kind==="change"){let v=x.percent;return{basis:i,kind:"change",percent:v,tone:v===0?"neutral":v>0?"positive":"negative",label:`${v>0?"↑":v<0?"↓":"→"} ${Math.abs(v).toFixed(1)}%`,copy:zr(e.grain),secondary:h,compactSecondary:f,title:w}}return{basis:i,kind:"neutral",tone:"neutral",label:x.label,copy:zr(e.grain),secondary:h,compactSecondary:f,title:w,reason:x.reason}}if(i==="not_comparable")return{basis:i,kind:"neutral",tone:"neutral",label:"Not comparable",copy:e.reason||"",reason:e.reason};let _=[typeof l=="number"?`${c} so far: ${s(l)}`:`${c}: in progress`];return d!==void 0&&_.push(`${u}: ${s(d)} (${p})`),{basis:"current_in_progress_no_time",kind:"neutral",tone:"neutral",label:_.join(" · "),copy:"",title:e.reason,reason:e.reason}},Rr=e=>e?.grain==="day"?"Yesterday at this time":`Same point last ${yn(e?.grain)}`,La=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?"":e.toISOString().slice(0,10);let t=typeof e=="string"?e.trim():"";return/^\d{4}-\d{2}-\d{2}/.test(t)?t.slice(0,10):""},Lr=(e,t)=>{let n=La(t);if(!(!n||!e)){if(e.previousPeriod?.start&&La(e.previousPeriod.start)===n)return"previous";if(e.currentPeriod?.start&&La(e.currentPeriod.start)===n)return"current"}},Dr=(e,t,n,a={format:String})=>{if(!e||!e.series?.length||!e.comparisonBasis||e.comparisonBasis==="complete")return;let i=Lr(e,t);if(!i)return;let o=String(n??""),s=e.series.find(u=>u.key===o);if(!s)return;let c=e.comparisonBasis;if(i==="previous"){let u=c==="like_for_like"&&typeof s.previousToDateValue=="number";return{side:i,basis:c,toDate:u,plotValue:u?s.previousToDateValue:void 0,fullValue:s.previousFullValue}}return{side:i,basis:c,toDate:!1,display:Nr({...e,currentValue:s.currentValue,previousToDateValue:s.previousToDateValue,previousFullValue:s.previousFullValue},{value:s.currentValue,status:s.currentValue===void 0?"missing":"observed"},{value:s.previousFullValue,status:s.previousFullValue===void 0?"missing":"observed"},a)}},Da=e=>!!(e&&e.seriesField&&e.series?.length&&e.comparisonBasis&&e.comparisonBasis!=="complete"&&e.comparisonBasis!=="not_comparable"),us=e=>{if(!Da(e))return;let t=e.currentPeriod?.label||"Current period";return e.comparisonBasis==="like_for_like"?`${t} so far, compared with ${Rr(e).toLowerCase()}`:`${t} so far; the previous period is shown in full, so the bars are not like for like`},ps=(e,t,n)=>{if(!t)return[];if(t.side==="previous")return typeof t.fullValue=="number"&&t.toDate?[`Full ${e?.grain==="day"?"day":yn(e?.grain)}: ${n(t.fullValue)}`]:[];let a=t.display;return a?a.kind==="change"&&a.percent!==void 0?[`${a.label} ${a.copy}`.trim()]:a.kind==="neutral"&&a.label&&t.basis==="like_for_like"?[a.label]:[]:[]},aa="__previous_to_date",fs="Previous to date",Pr=(e,t)=>{let n=e.trim().toLowerCase(),a=t.trim().toLowerCase();return n===a||n.endsWith(`.${a}`)||a.endsWith(`.${n}`)},hs=e=>{let t=e.periodComparison,n=e.rows;if(!n?.length||!Da(t)||t.comparisonBasis!=="like_for_like"||!t.series?.some(p=>typeof p.previousToDateValue=="number"))return e;let a=e.columnMetadata??[],i=e.columns?.filter(Boolean)??(a.length?a.map(p=>String(p.key??p.name??"")).filter(Boolean):Object.keys(n[0]??{}));if(i.includes(aa))return e;let o=i.find(p=>Pr(t.seriesField,p));if(!o)return e;let s=p=>a.find(h=>(h.key??h.name)===p),c=i.find(p=>{let h=s(p);return h?.semanticRole==="date"||h?.role==="date"||h?.dataType==="date"||h?.dataType==="datetime"}),u=(t.measureField?i.find(p=>Pr(t.measureField,p)):void 0)??i.find(p=>s(p)?.semanticRole==="measure"),l=n.map(p=>{let h=c?Lr(t,p[c]):"current",f=t.series?.find(x=>x.key===String(p[o]??"")),_=h&&typeof f?.previousToDateValue=="number"?f.previousToDateValue:null;return{...p,[aa]:_}}),d={...(u?s(u):void 0)??{dataType:"number",semanticRole:"measure"},key:aa,name:void 0,label:fs,aggregation:"none",sourceField:void 0,priority:"secondary",groupable:!1,filterable:!1};return{...e,rows:l,columns:e.columns?[...e.columns,aa]:e.columns,columnMetadata:a.length?[...a,d]:e.columnMetadata}},ms=e=>!!(e?.lastPeriodInProgress||e?.caveats?.some(t=>t.code==="incomplete_final_period")||e?.periodComparison?.currentPeriod?.inProgress),gs="In progress";var ra,De,Or,Vt,Fr,Ur,Br,Pa,ia,_n,qr,Oa,Fa,Ua,Vr,oa={},sa=[],bs=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,ca=Array.isArray;function Rt(e,t){for(var n in t)e[n]=t[n];return e}function Ba(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function vs(e,t,n){var a,i,o,s={};for(o in t)o=="key"?a=t[o]:o=="ref"?i=t[o]:s[o]=t[o];if(arguments.length>2&&(s.children=arguments.length>3?ra.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(o in e.defaultProps)s[o]===void 0&&(s[o]=e.defaultProps[o]);return la(e,s,a,i,null)}function la(e,t,n,a,i){var o={type:e,props:t,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Or,__i:-1,__u:0};return i==null&&De.vnode!=null&&De.vnode(o),o}function de(e){return e.children}function da(e,t){this.props=e,this.context=t}function cn(e,t){if(t==null)return e.__?cn(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?cn(e):null}function xs(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,a=[],i=[],o=Rt({},t);o.__v=t.__v+1,De.vnode&&De.vnode(o),Va(e.__P,o,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,a,n??cn(t),!!(32&t.__u),i),o.__v=t.__v,o.__.__k[o.__i]=o,Yr(a,o,i),t.__e=t.__=null,o.__e!=n&&Hr(o)}}function Hr(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),Hr(e)}function qa(e){(!e.__d&&(e.__d=!0)&&Vt.push(e)&&!ua.__r++||Fr!=De.debounceRendering)&&((Fr=De.debounceRendering)||Ur)(ua)}function ua(){try{for(var e,t=1;Vt.length;)Vt.length>t&&Vt.sort(Br),e=Vt.shift(),t=Vt.length,xs(e)}finally{Vt.length=ua.__r=0}}function jr(e,t,n,a,i,o,s,c,u,l,d){var p,h,f,_,x,w,v,m=a&&a.__k||sa,T=t.length;for(u=ys(n,t,m,u,T),p=0;p<T;p++)(f=n.__k[p])!=null&&(h=f.__i!=-1&&m[f.__i]||oa,f.__i=p,w=Va(e,f,h,i,o,s,c,u,l,d),_=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&ja(h.ref,null,f),d.push(f.ref,f.__c||_,f)),x==null&&_!=null&&(x=_),(v=!!(4&f.__u))||h.__k===f.__k?(u=Wr(f,u,e,v),v&&h.__e&&(h.__e=null)):typeof f.type=="function"&&w!==void 0?u=w:_&&(u=_.nextSibling),f.__u&=-7);return n.__e=x,u}function ys(e,t,n,a,i){var o,s,c,u,l,d=n.length,p=d,h=0;for(e.__k=new Array(i),o=0;o<i;o++)(s=t[o])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[o]=la(null,s,null,null,null):ca(s)?s=e.__k[o]=la(de,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=la(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[o]=s,u=o+h,s.__=e,s.__b=e.__b+1,c=null,(l=s.__i=_s(s,n,u,p))!=-1&&(p--,(c=n[l])&&(c.__u|=2)),c==null||c.__v==null?(l==-1&&(i>d?h--:i<d&&h++),typeof s.type!="function"&&(s.__u|=4)):l!=u&&(l==u-1?h--:l==u+1?h++:(l>u?h--:h++,s.__u|=4))):e.__k[o]=null;if(p)for(o=0;o<d;o++)(c=n[o])!=null&&(2&c.__u)==0&&(c.__e==a&&(a=cn(c)),Jr(c,c));return a}function Wr(e,t,n,a){var i,o;if(typeof e.type=="function"){for(i=e.__k,o=0;i&&o<i.length;o++)i[o]&&(i[o].__=e,t=Wr(i[o],t,n,a));return t}e.__e!=t&&(a&&(t&&e.type&&!t.parentNode&&(t=cn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function _s(e,t,n,a){var i,o,s,c=e.key,u=e.type,l=t[n],d=l!=null&&(2&l.__u)==0;if(l===null&&c==null||d&&c==l.key&&u==l.type)return n;if(a>(d?1:0)){for(i=n-1,o=n+1;i>=0||o<t.length;)if((l=t[s=i>=0?i--:o++])!=null&&(2&l.__u)==0&&c==l.key&&u==l.type)return s}return-1}function Gr(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||bs.test(t)?n:n+"px"}function pa(e,t,n,a,i){var o,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof a=="string"&&(e.style.cssText=a=""),a)for(t in a)n&&t in n||Gr(e.style,t,"");if(n)for(t in n)a&&n[t]==a[t]||Gr(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(qr,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+o]=n,n?a?n[_n]=a[_n]:(n[_n]=Oa,e.addEventListener(t,o?Ua:Fa,o)):e.removeEventListener(t,o?Ua:Fa,o);else{if(i=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Kr(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[ia]==null)t[ia]=Oa++;else if(t[ia]<n[_n])return;return n(De.event?De.event(t):t)}}}function Va(e,t,n,a,i,o,s,c,u,l){var d,p,h,f,_,x,w,v,m,T,P,O,re,J,G,N=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(u=!!(32&n.__u),o=[c=t.__e=n.__e]),(d=De.__b)&&d(t);e:if(typeof N=="function")try{if(v=t.props,m=N.prototype&&N.prototype.render,T=(d=N.contextType)&&a[d.__c],P=d?T?T.props.value:d.__:a,n.__c?w=(p=t.__c=n.__c).__=p.__E:(m?t.__c=p=new N(v,P):(t.__c=p=new da(v,P),p.constructor=N,p.render=ks),T&&T.sub(p),p.state||(p.state={}),p.__n=a,h=p.__d=!0,p.__h=[],p._sb=[]),m&&p.__s==null&&(p.__s=p.state),m&&N.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Rt({},p.__s)),Rt(p.__s,N.getDerivedStateFromProps(v,p.__s))),f=p.props,_=p.state,p.__v=t,h)m&&N.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),m&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(m&&N.getDerivedStateFromProps==null&&v!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(v,P),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(v,p.__s,P)===!1){t.__v!=n.__v&&(p.props=v,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(se){se&&(se.__=t)}),sa.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(v,p.__s,P),m&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,_,x)})}if(p.context=P,p.props=v,p.__P=e,p.__e=!1,O=De.__r,re=0,m)p.state=p.__s,p.__d=!1,O&&O(t),d=p.render(p.props,p.state,p.context),sa.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,O&&O(t),d=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++re<25);p.state=p.__s,p.getChildContext!=null&&(a=Rt(Rt({},a),p.getChildContext())),m&&!h&&p.getSnapshotBeforeUpdate!=null&&(x=p.getSnapshotBeforeUpdate(f,_)),J=d!=null&&d.type===de&&d.key==null?Zr(d.props.children):d,c=jr(e,ca(J)?J:[J],t,n,a,i,o,s,c,u,l),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),w&&(p.__E=p.__=null)}catch(se){if(t.__v=null,u||o!=null)if(se.then){for(t.__u|=u?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;o[o.indexOf(c)]=null,t.__e=c}else{for(G=o.length;G--;)Ba(o[G]);Ha(t)}else t.__e=n.__e,t.__k=n.__k,se.then||Ha(t);De.__e(se,t,n)}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=ws(n.__e,t,n,a,i,o,s,u,l);return(d=De.diffed)&&d(t),128&t.__u?void 0:c}function Ha(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Ha))}function Yr(e,t,n){for(var a=0;a<n.length;a++)ja(n[a],n[++a],n[++a]);De.__c&&De.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(o){o.call(i)})}catch(o){De.__e(o,i.__v)}})}function Zr(e){return typeof e!="object"||e==null||e.__b>0?e:ca(e)?e.map(Zr):e.constructor!==void 0?null:Rt({},e)}function ws(e,t,n,a,i,o,s,c,u){var l,d,p,h,f,_,x,w=n.props||oa,v=t.props,m=t.type;if(m=="svg"?i="http://www.w3.org/2000/svg":m=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),o!=null){for(l=0;l<o.length;l++)if((f=o[l])&&"setAttribute"in f==!!m&&(m?f.localName==m:f.nodeType==3)){e=f,o[l]=null;break}}if(e==null){if(m==null)return document.createTextNode(v);e=document.createElementNS(i,m,v.is&&v),c&&(De.__m&&De.__m(t,o),c=!1),o=null}if(m==null)w===v||c&&e.data==v||(e.data=v);else{if(o=m=="textarea"&&v.defaultValue!=null?null:o&&ra.call(e.childNodes),!c&&o!=null)for(w={},l=0;l<e.attributes.length;l++)w[(f=e.attributes[l]).name]=f.value;for(l in w)f=w[l],l=="dangerouslySetInnerHTML"?p=f:l=="children"||l in v||l=="value"&&"defaultValue"in v||l=="checked"&&"defaultChecked"in v||pa(e,l,null,f,i);for(l in v)f=v[l],l=="children"?h=f:l=="dangerouslySetInnerHTML"?d=f:l=="value"?_=f:l=="checked"?x=f:c&&typeof f!="function"||w[l]===f||pa(e,l,f,w[l],i);if(d)c||p&&(d.__html==p.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(p&&(e.innerHTML=""),jr(t.type=="template"?e.content:e,ca(h)?h:[h],t,n,a,m=="foreignObject"?"http://www.w3.org/1999/xhtml":i,o,s,o?o[0]:n.__k&&cn(n,0),c,u),o!=null)for(l=o.length;l--;)Ba(o[l]);c&&m!="textarea"||(l="value",m=="progress"&&_==null?e.removeAttribute("value"):_!=null&&(_!==e[l]||m=="progress"&&!_||m=="option"&&_!=w[l])&&pa(e,l,_,w[l],i),l="checked",x!=null&&x!=e[l]&&pa(e,l,x,w[l],i))}return e}function ja(e,t,n){try{if(typeof e=="function"){var a=typeof e.__u=="function";a&&e.__u(),a&&t==null||(e.__u=e(t))}else e.current=t}catch(i){De.__e(i,n)}}function Jr(e,t,n){var a,i;if(De.unmount&&De.unmount(e),(a=e.ref)&&(a.current&&a.current!=e.__e||ja(a,null,t)),(a=e.__c)!=null){if(a.componentWillUnmount)try{a.componentWillUnmount()}catch(o){De.__e(o,t)}a.base=a.__P=null}if(a=e.__k)for(i=0;i<a.length;i++)a[i]&&Jr(a[i],t,n||typeof e.type!="function");n||Ba(e.__e),e.__c=e.__=e.__e=void 0}function ks(e,t,n){return this.constructor(e,n)}function Xr(e,t,n){var a,i,o,s;t==document&&(t=document.documentElement),De.__&&De.__(e,t),i=(a=!1)?null:t.__k,o=[],s=[],Va(t,e=t.__k=vs(de,null,[e]),i||oa,oa,t.namespaceURI,i?null:t.firstChild?ra.call(t.childNodes):null,o,i?i.__e:t.firstChild,a,s),Yr(o,e,s)}function Wa(e){function t(n){var a,i;return this.getChildContext||(a=new Set,(i={})[t.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){a=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&a.forEach(function(s){s.__e=!0,qa(s)})},this.sub=function(o){a.add(o);var s=o.componentWillUnmount;o.componentWillUnmount=function(){a&&a.delete(o),s&&s.call(o)}}),n.children}return t.__c="__cC"+Vr++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,a){return n.children(a)}).contextType=t,t}ra=sa.slice,De={__e:function(e,t,n,a){for(var i,o,s;t=t.__;)if((i=t.__c)&&!i.__)try{if((o=i.constructor)&&o.getDerivedStateFromError!=null&&(i.setState(o.getDerivedStateFromError(e)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,a||{}),s=i.__d),s)return i.__E=i}catch(c){e=c}throw e}},Or=0,da.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Rt({},this.state),typeof e=="function"&&(e=e(Rt({},n),this.props)),e&&Rt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),qa(this))},da.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),qa(this))},da.prototype.render=de,Vt=[],Ur=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Br=function(e,t){return e.__v.__b-t.__v.__b},ua.__r=0,Pa=Math.random().toString(8),ia="__d"+Pa,_n="__a"+Pa,qr=/(PointerCapture)$|Capture$/i,Oa=0,Fa=Kr(!1),Ua=Kr(!0),Vr=0;var Xt,Fe,Ga,Qr,wn=0,ei=[],We=De,ti=We.__b,ni=We.__r,ai=We.diffed,ri=We.__c,ii=We.unmount,oi=We.__;function kn(e,t){We.__h&&We.__h(Fe,e,wn||t),wn=0;var n=Fe.__H||(Fe.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function S(e){return wn=1,Ss(ci,e)}function Ss(e,t,n){var a=kn(Xt++,2);if(a.t=e,!a.__c&&(a.__=[ci(void 0,t),function(c){var u=a.__N?a.__N[0]:a.__[0],l=a.t(u,c);u!==l&&(a.__N=[l,a.__[1]],a.__c.setState({}))}],a.__c=Fe,!Fe.__f)){var i=function(c,u,l){if(!a.__c.__H)return!0;var d=a.__c.__H.__.filter(function(h){return h.__c});if(d.every(function(h){return!h.__N}))return!o||o.call(this,c,u,l);var p=a.__c.props!==c;return d.some(function(h){if(h.__N){var f=h.__[0];h.__=h.__N,h.__N=void 0,f!==h.__[0]&&(p=!0)}}),o&&o.call(this,c,u,l)||p};Fe.__f=!0;var o=Fe.shouldComponentUpdate,s=Fe.componentWillUpdate;Fe.componentWillUpdate=function(c,u,l){if(this.__e){var d=o;o=void 0,i(c,u,l),o=d}s&&s.call(this,c,u,l)},Fe.shouldComponentUpdate=i}return a.__N||a.__}function X(e,t){var n=kn(Xt++,3);!We.__s&&Za(n.__H,t)&&(n.__=e,n.u=t,Fe.__H.__h.push(n))}function Sn(e,t){var n=kn(Xt++,4);!We.__s&&Za(n.__H,t)&&(n.__=e,n.u=t,Fe.__h.push(n))}function R(e){return wn=5,qe(function(){return{current:e}},[])}function qe(e,t){var n=kn(Xt++,7);return Za(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function D(e,t){return wn=8,qe(function(){return e},t)}function Ka(e){var t=Fe.context[e.__c],n=kn(Xt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(Fe)),t.props.value):e.__}function $s(){for(var e;e=ei.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(fa),t.__h.some(Ya),t.__h=[]}catch(n){t.__h=[],We.__e(n,e.__v)}}}We.__b=function(e){Fe=null,ti&&ti(e)},We.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),oi&&oi(e,t)},We.__r=function(e){ni&&ni(e),Xt=0;var t=(Fe=e.__c).__H;t&&(Ga===Fe?(t.__h=[],Fe.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(fa),t.__h.some(Ya),t.__h=[],Xt=0)),Ga=Fe},We.diffed=function(e){ai&&ai(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(ei.push(t)!==1&&Qr===We.requestAnimationFrame||((Qr=We.requestAnimationFrame)||Ts)($s)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Ga=Fe=null},We.__c=function(e,t){t.some(function(n){try{n.__h.some(fa),n.__h=n.__h.filter(function(a){return!a.__||Ya(a)})}catch(a){t.some(function(i){i.__h&&(i.__h=[])}),t=[],We.__e(a,n.__v)}}),ri&&ri(e,t)},We.unmount=function(e){ii&&ii(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(a){try{fa(a)}catch(i){t=i}}),n.__H=void 0,t&&We.__e(t,n.__v))};var si=typeof requestAnimationFrame=="function";function Ts(e){var t,n=function(){clearTimeout(a),si&&cancelAnimationFrame(t),setTimeout(e)},a=setTimeout(n,35);si&&(t=requestAnimationFrame(n))}function fa(e){var t=Fe,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Fe=t}function Ya(e){var t=Fe;e.__c=e.__(),Fe=t}function Za(e,t){return!e||e.length!==t.length||t.some(function(n,a){return n!==e[a]})}function ci(e,t){return typeof t=="function"?t(e):t}var Cs=0;function r(e,t,n,a,i,o){t||(t={});var s,c,u=t;if("ref"in u)for(c in u={},t)c=="ref"?s=t[c]:u[c]=t[c];var l={type:e,props:u,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Cs,__i:-1,__u:0,__source:i,__self:o};if(typeof e=="function"&&(s=e.defaultProps))for(c in s)u[c]===void 0&&(u[c]=s[c]);return De.vnode&&De.vnode(l),l}const ha=(e,t=11)=>{let n=0;for(let a of e)n+=(a.codePointAt(0)??0)>11904?1:.58;return Math.ceil(n*t)},Ms=(e,t=12,n=20)=>Math.max(n,Math.ceil(e)+t),As=(e,t=12,n=8)=>Math.ceil(t+e+n),Is=(e,t,n=11)=>e.length===0||Math.max(...e.map(a=>ha(a,n)))<=t-4?{kind:"native"}:e.length>12?{kind:"auto"}:Math.floor((t-4)/(.58*n))>=6?{kind:"truncate",width:Math.max(16,Math.floor(t-4))}:{kind:"rotate",rotate:40,width:72},Ja=e=>Array.isArray(e)?e:e?[e]:[],Es=(e,t)=>{let n=[];for(let a of e)if(Array.isArray(a.data))for(let i of a.data){let o=i;i&&typeof i=="object"&&!Array.isArray(i)&&(o=i.value),Array.isArray(o)&&(o=o[1]),typeof o=="number"&&Number.isFinite(o)&&n.push(o)}return n},zs=(e,t,n)=>{let a=e.axisLabel?.formatter,i=Es(t),o=typeof e.min=="number"?e.min:Math.min(0,...i),s=typeof e.max=="number"?e.max:Math.max(0,...i)*1.1,c=i.length||e.min!==void 0?[o,s]:[];return c.length?Math.max(...c.map(u=>{let l=String(u);try{typeof a=="function"&&(l=String(a(u)))}catch{}return ha(l)})):ha("00000")},Ns=(e,t)=>{if(!(t>0)||Array.isArray(e.grid))return e;let n=Ja(e.xAxis),a=Ja(e.yAxis),i=a[0]?.type==="category",o=i?a[0]:n[0],s=i?n[0]:a[0];if(!o||o.type!=="category"||!s||s.type!=="value")return e;let c=t<420,u=Ja(e.series),l={...e.grid??{}},d=(o.data??[]).map(x=>String(x&&typeof x=="object"?x.value??"":x)),p={...e,grid:l},h={...o},f={...s},_=0;if(i)c&&(_=Math.min(t*.35,90),h={...h,axisLabel:{...o.axisLabel,width:Math.floor(_),overflow:"truncate",ellipsis:"…"}},l.left=8);else{let x=zs(s,u);if(_=x+8,c&&!s.name)l.left=8;else if(s.name){let w=Ms(x);f={...f,nameGap:Math.min(s.nameGap??w,w)},_+=18}}if(!i){let x=typeof l.left=="number"?l.left:0,w=typeof l.right=="number"?l.right:0,v=Is(d,Math.max(40,t-x-w-_)/Math.max(1,d.length)),m=o.axisLabel?.fontSize??11,T=m+2;if(v.kind==="truncate"||v.kind==="rotate"){let P=v.kind==="rotate"?v.rotate:0;if(h.axisLabel={...o.axisLabel,interval:0,hideOverlap:!1,rotate:P,width:v.width,overflow:"truncate",ellipsis:"…"},P){let O=Math.max(0,...d.map(J=>ha(J,m))),re=Math.min(v.width,O);T=Math.ceil(re*Math.sin(P*Math.PI/180))+m}}o.name&&c?h.nameGap=Math.min(o.nameGap??99,As(T,6,4)):c&&l.containLabel===!0&&typeof l.bottom=="number"&&(l.bottom=Math.min(l.bottom,8))}return i?(p.yAxis=Array.isArray(e.yAxis)?[h,...a.slice(1)]:h,p.xAxis=Array.isArray(e.xAxis)?[f,...n.slice(1)]:f):(p.xAxis=Array.isArray(e.xAxis)?[h,...n.slice(1)]:h,p.yAxis=Array.isArray(e.yAxis)?[f,...a.slice(1)]:f),p},Rs=/^(\d{4})-(\d{2})-(\d{2})$/,Ls=/^(\d{4})-(\d{2})$/,Ds=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?$/,Ps=/(?:Z|[+-]\d{2}:?\d{2})$/i,li=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:{date:e,calendar:!1,hasTime:!0};if(typeof e=="number"&&Number.isFinite(e))return{date:new Date(e),calendar:!1,hasTime:!0};if(typeof e!="string")return null;let t=e.trim(),n=Rs.exec(t);if(n)return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]))),calendar:!0,hasTime:!1};if(n=Ls.exec(t),n)return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,1)),calendar:!0,hasTime:!1};if(n=Ds.exec(t),n&&!Ps.test(t))return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]),Number(n[4]),Number(n[5]),Number(n[6]??0))),calendar:!0,hasTime:!0};if(!/^\d{4}-\d{2}-\d{2}T/.test(t))return null;let a=new Date(t);return Number.isNaN(a.getTime())?null:{date:a,calendar:!1,hasTime:!0}},Os=e=>{if(e){if(/h/i.test(e)&&/:/.test(e))return"hour";if(/d{2}/i.test(e))return"day";if(/q/i.test(e))return"quarter";if(/M{2,}/.test(e))return"month";if(/y{2,}/i.test(e))return"year"}},di=e=>{let t=e.map(li).filter(a=>a!==null);if(t.length===0)return;let n=a=>a.date.getUTCHours()+a.date.getUTCMinutes();return t.some(a=>a.hasTime&&n(a)!==0)?t.every(a=>a.date.getUTCMinutes()===0)?"hour":void 0:t.length>1&&t.every(a=>a.date.getUTCDate()===1)?"month":"day"},Qt=(e,t)=>{try{return new Intl.DateTimeFormat(e,t)}catch{return new Intl.DateTimeFormat(e,{...t,timeZone:"UTC"})}},ui=(e,t,n={})=>{let a=li(e);if(!a)return;let i=t?.grain??Os(t?.formatPattern)??n.grain,o=a.calendar?"UTC":n.timezone||void 0,{date:s}=a;switch(i){case"year":return Qt(n.locale,{year:"numeric",timeZone:o}).format(s);case"quarter":{let c=Number(Qt("en-US",{month:"numeric",timeZone:o}).format(s)),u=Qt(n.locale,{year:"numeric",timeZone:o}).format(s);return`Q${Math.floor((c-1)/3)+1} ${u}`}case"month":return Qt(n.locale,{month:"short",year:"numeric",timeZone:o}).format(s);case"week":case"day":return Qt(n.locale,{day:"numeric",month:"short",year:"numeric",timeZone:o}).format(s);case"hour":return Qt(n.locale,{day:"numeric",month:"short",hour:"numeric",minute:"2-digit",timeZone:o}).format(s);default:return Qt(n.locale,{dateStyle:"medium",...a.hasTime?{timeStyle:"short"}:{},timeZone:o}).format(s)}},pi=e=>{let t=e?/\.([0#]+)/.exec(e):null;if(!t)return;let n=t[1];return{min:(n.match(/0/g)??[]).length,max:n.length}},Xa=(e,t)=>{let n=pi(e);return n?{minimumFractionDigits:n.min,maximumFractionDigits:n.max}:{maximumFractionDigits:t}},$n=e=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()){let t=Number(e);if(Number.isFinite(t))return t}return null},fi=(e,t)=>t&&Math.abs(e)>=1e4?"compact":"standard",hi=(e,t={})=>new Intl.NumberFormat(t.locale,{notation:fi(e,t.compact),...Xa(t.pattern,t.maxFractionDigits??2)}).format(e),Fs=(e,t,n={})=>{let a=t?.trim().toUpperCase();if(a&&/^[A-Z]{3}$/.test(a))try{return new Intl.NumberFormat(n.locale,{style:"currency",currency:a,notation:fi(e,n.compact),...pi(n.pattern)?Xa(n.pattern,2):{}}).format(e)}catch{}return hi(e,{...n,maxFractionDigits:2})},Us=(e,t={})=>{let n=!!(t.pattern&&/(?<!\\)%/.test(t.pattern)),a=Xa(t.pattern,2);return new Intl.NumberFormat(t.locale,{style:"percent",...a}).format(n?e:e/100)},Qa=(e,t,n={})=>{let{locale:a,compact:i}=n;return t?.dataType==="currency"?Fs(e,t.currencyCode||n.currencyCode,{locale:a,compact:i,pattern:t.formatPattern}):t?.dataType==="percent"?Us(e,{locale:a,pattern:t.formatPattern}):hi(e,{locale:a,compact:i,pattern:t?.formatPattern,maxFractionDigits:n.maxFractionDigits})},mi=(e,t,n={})=>{if(e==null||e==="")return"—";if(t?.dataType==="date"||t?.dataType==="datetime"){let i=ui(e,t,n);if(i)return i}if(t?.dataType==="currency"||t?.dataType==="percent"){let i=$n(e);if(i!==null)return Qa(i,t,n)}if(typeof e=="number"&&Number.isFinite(e))return Qa(e,t,{...n,maxFractionDigits:4});if(typeof e=="boolean")return e?n.yes??"Yes":n.no??"No";let a=String(e);return t?.semanticRole==="dimension"&&/^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/.test(a)?a.replaceAll("_"," ").replace(/^\w/,i=>i.toUpperCase()):a},ma={resultDetails:"Result details",liveMetric:"Live metric",currentValue:"Current value",noMatchTitle:"No matching data",noMatchBody:"No approved records matched this question.",chartType:"Chart type",chooseChartType:"Choose chart type",aggregate:"Aggregate",aggregateTitle:"Ask for a new governed calculation",aggregateCharge:"New governed answer. Query charges may apply.",chartFallback:"Chart",chartLine:"Line",chartBar:"Bar",chartStackedBar:"Stacked bar",chartLineHint:"Best for change over time.",chartBarHint:"Compare categories or ranked values.",chartStackedBarHint:"Compare totals and their parts.",aggregationSum:"Total",aggregationAvg:"Average",aggregationMin:"Minimum",aggregationMax:"Maximum",aggregationCount:"Total count",aggregationCountDistinct:"Unique count",download:"Download",downloadData:"Download this data",expandTable:"Expand table",expandChart:"Expand chart",restoreView:"Restore assistant view",aboutResult:"About this result",aboutPeriod:"Period",aboutResults:"Results",aboutChecked:"Checked",aboutTimezone:"Timezone",aboutSourceData:"Source data",aboutFilters:"Filters",rowOne:"{count} row",rowMany:"{count} rows",filtersOne:"{count} applied filter",filtersMany:"{count} applied filters",filtersApplied:"{count} applied",notSet:"Not set",noValue:"No value",yes:"Yes",no:"No",chartValues:"Values",chartTitle:"{measure} by {dimension}",seriesLimited:"Showing {shown} of {total} series.",summaryLatest:"Latest ({category}): {values}.",summaryNoTrend:"No numeric trend values are available.",summaryHighest:"Highest: {category}, {series} {value}.",summaryNoComparison:"No numeric comparison values are available.",zoomControls:"Chart zoom controls",zoomIn:"Zoom in chart",zoomOut:"Zoom out chart",zoomReset:"Reset chart zoom",zoomResetShort:"Reset",zoomNone:"No chart points",zoomAllOne:"All {count} point",zoomAllMany:"All {count} points",zoomRange:"{start} – {end} · {visible} of {count} points",inProgress:"in progress",newContent:"New content",updatedAt:"Updated {time}",liveData:"Live data",viewData:"View data",hideData:"Hide data",inProgressLegend:"In progress",governedResult:"Governed result"},xt=(e,t)=>e.replace(/\{(\w+)\}/g,(n,a)=>String(t[a]??"")),Bs=e=>Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!=null)),er=e=>({...ma,...Bs(e),explanation:{...e?.explanation}});let gi=()=>Promise.resolve().then(()=>Vo),Tn=null,bi=!1;const qs=e=>{gi=e,Tn=null,bi=!0},Vs=()=>(Tn||(Tn=gi().catch(e=>{throw Tn=null,e})),Tn),en={background:"#ffffff",border:"#dce4e9",muted:"#5b7186",surface:"#ffffff",text:"#0f1e2a",colors:["#2f7f55","#2563eb","#b45309","#7c3aed"]},vi="cf-widget-category-zoom",xi=.68,ln=e=>({startIndex:0,endIndex:Math.max(0,e-1)}),Cn=(e,t)=>{if(t<=0)return ln(0);let n=t-1,a=Math.max(0,Math.min(n,Math.floor(Math.min(e.startIndex,e.endIndex))));return{startIndex:a,endIndex:Math.max(a,Math.min(n,Math.floor(Math.max(e.startIndex,e.endIndex))))}},yi=(e,t,n)=>{let a=Cn(e,n);if(n<=2)return ln(n);let i=a.endIndex-a.startIndex+1,o=t==="in"?Math.max(2,Math.floor(i*xi)):Math.min(n,Math.ceil(i/xi));if(o===i)return a;let s=(a.startIndex+a.endIndex)/2,c=n-o,u=Math.max(0,Math.min(c,Math.round(s-(o-1)/2)));return{startIndex:u,endIndex:u+o-1}},Hs=(e,t,n=ma)=>{let a=e.length;if(a===0)return n.zoomNone;let i=Cn(t,a);return i.startIndex===0&&i.endIndex===a-1?xt(a===1?n.zoomAllOne:n.zoomAllMany,{count:a}):xt(n.zoomRange,{start:e[i.startIndex]??"",end:e[i.endIndex]??"",visible:i.endIndex-i.startIndex+1,count:a})},js=e=>{let t=e.replaceAll("_"," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim();return t?`${t.charAt(0).toUpperCase()}${t.slice(1)}`:"Value"},Ws=e=>{let t=new Set,n=[];return e.forEach(a=>{let i=a?.trim();!i||t.has(i)||(t.add(i),n.push(i))}),n},tr=$n,Mn=e=>{if(e===null)return"null:";if(e===void 0)return"undefined:";if(typeof e=="object")try{return`object:${JSON.stringify(e)}`}catch{return"object:"}return`${typeof e}:${String(e)}`},An=(e,t)=>t?e.columnMetadata?.find(n=>n.key===t):void 0,nr=(e,t)=>{let n=An(e,t);if(!n||n.currencyCode||n.dataType!=="currency")return n;let a=e.currency;return a?.code&&!a.isMixed?{...n,currencyCode:a.code}:n},In=(e,t)=>An(e,t)?.label?.trim()||js(t),Gs=(e,t,n,a)=>({locale:t,timezone:e.timezone||e.periodComparison?.timezone,grain:a,yes:n.yes,no:n.no}),_i=e=>e?.dataType==="date"||e?.dataType==="datetime"||e?.semanticRole==="date",wi=(e,t,n)=>{let a=An(e,t);if(_i(a))return a?.grain??e.periodComparison?.grain??di(n.map(i=>i[t]))},ki=(e,t,n,a,i,o)=>{if(n==null||n==="")return a.notSet;let s=An(e,t);if(s?.dataType==="boolean"){let c=String(n).trim().toLowerCase();return n===!1||n===0||["0","false","no"].includes(c)?a.no:a.yes}if(_i(s)){let c=ui(n,s,Gs(e,i,a,o));if(c)return c}return mi(n,s,{locale:i})},tn=(e,t,n,a=!1,i)=>Qa(e,t,{locale:i,compact:a,currencyCode:n?.currency?.code&&!n.currency.isMixed?n.currency.code:void 0}),Ks=(e,t)=>{if(e.presentation==="table"||e.presentation==="kpi")return null;if(t)return t;let n=e.chartRecommendation?.type;return n==="line"||n==="bar"||n==="stacked_bar"?n:e.type==="line"||e.type==="bar"||e.type==="stacked_bar"?e.type:null},Si=e=>e.chartRecommendation?.categoryField?.trim()||e.label?.trim()||e.columnMetadata?.find(t=>["date","dimension","geography","boolean"].includes(t.semanticRole))?.key||e.columns?.[0],$i=e=>e.chartRecommendation?.seriesField?.trim()||e.seriesField?.trim()||e.series?.trim()||void 0,Ti=(e,t,n)=>{let a=Ws([...e.chartRecommendation?.valueFields??[],...e.valueFields??[],e.value,...e.columnMetadata?.filter(o=>o.semanticRole==="measure").map(o=>o.key)??[]]),i=new Set([...e.columns??[],...e.columnMetadata?.map(o=>o.key)??[],...Object.keys(e.rows?.[0]??{})]);return a.filter(o=>o!==t&&o!==n&&i.has(o)).filter(o=>e.rows?.some(s=>tr(s[o])!==null))},Ys=(e,t,n,a,i,o,s)=>{let c=i?` ${xt(o.seriesLimited,{shown:a.length,total:a.length+i})}`:"",u=(d,p)=>tn(d,p,e,!1,s);if(t==="line"){let d=n.length-1,p=a.map(h=>{let f=h.values[d];return f==null?null:`${h.name}: ${u(f,h.valueColumn)}`}).filter(h=>!!h);return p.length?`${xt(o.summaryLatest,{category:n[d]??"",values:p.join("; ")})}${c}`:`${o.summaryNoTrend}${c}`}let l;return a.forEach(d=>{d.values.forEach((p,h)=>{p===null||l&&p<=l.value||(l={category:n[h]??o.notSet,series:d,value:p})})}),l?`${xt(o.summaryHighest,{category:l.category,series:l.series.name,value:u(l.value,l.series.valueColumn)})}${c}`:`${o.summaryNoComparison}${c}`},ar=(e,t,n={})=>{let a=er(n.labels),i=n.locale,o=Ks(e,t),s=Si(e),c=e.rows??[];if(!o||!s||c.length===0)return null;let u=$i(e),l=Ti(e,s,u);if(l.length===0)return null;let d=l.length===1?u:void 0,p=wi(e,s,c),h=l[0],f=d&&Da(e.periodComparison)&&(!e.periodComparison.measureField||!h||h===e.periodComparison.measureField||h.endsWith(`.${e.periodComparison.measureField}`)||e.periodComparison.measureField.endsWith(`.${h}`))?e.periodComparison:void 0,_=(()=>{if(!f?.seriesField||!d)return;let q=(F,C)=>F===C||F.endsWith(`.${C}`)||C.endsWith(`.${F}`);if(q(f.seriesField,s))return{group:s,time:d,timeIsSeries:!0};if(q(f.seriesField,d))return{group:d,time:s,timeIsSeries:!1}})(),x=q=>tn(q,nr(e,h??""),e,!1,i),w=q=>f&&_?Dr(f,q[_.time],q[_.group],{format:x,locale:i}):void 0,v=(q,F)=>f?.comparisonBasis==="like_for_like"&&Dr(f,q,f.series?.[0]?.key)?.side==="previous"?Rr(f):F,m=[],T=new Set;c.forEach(q=>{let F=Mn(q[s]);if(T.has(F))return;T.add(F);let C=ki(e,s,q[s],a,i,p);m.push({key:F,label:_&&!_.timeIsSeries?v(q[s],C):C})});let P=m.map(q=>q.label),O=0,re;if(d){let q=[],F=new Set;c.forEach(ce=>{let te=Mn(ce[d]);if(F.has(te))return;F.add(te);let ue=ki(e,d,ce[d],a,i,wi(e,d,c));q.push({key:te,label:_?.timeIsSeries?v(ce[d],ue):ue})});let C=q.slice(0,4);O=Math.max(0,q.length-C.length);let I=l[0];re=C.map(ce=>{let te=new Map,ue=new Map;return c.forEach(le=>{if(Mn(le[d])!==ce.key)return;let z=Mn(le[s]);if(!te.has(z)){let ne=w(le);ue.set(z,ne),te.set(z,ne?.side==="previous"&&ne.plotValue!==void 0?ne.plotValue:tr(le[I]))}}),{field:I,name:ce.label,values:m.map(le=>te.get(le.key)??null),valueColumn:nr(e,I),..._?{points:m.map(le=>ue.get(le.key))}:{}}})}else O=Math.max(0,l.length-4),re=l.slice(0,4).map(q=>({field:q,name:In(e,q),values:c.map(F=>tr(F[q])),valueColumn:nr(e,q)}));if(re.length===0)return null;let J=In(e,s),G=a.chartValues;d?G=In(e,l[0]):re.length===1&&(G=re[0].name);let N=e.title?.trim()||xt(a.chartTitle,{measure:G,dimension:J}),se;if(An(e,s)?.semanticRole==="date"&&m.length>1&&ms(e)){let q="";c.forEach(C=>{let I=String(C[s]??"");I>q&&(q=I)});let F=m.findIndex(C=>C.key===Mn(q));F>=0&&(se=F)}return{type:o,title:N,xAxisTitle:J,yAxisTitle:G,categories:P,series:re,omittedSeriesCount:O,inProgressIndex:se,..._&&f?{comparison:f,comparisonNote:us(f)}:{},locale:i,labels:a,summary:Ys(e,o,P,re,O,a,i)}},rr=[{value:"sum",label:"Total"},{value:"avg",label:"Average"},{value:"min",label:"Minimum"},{value:"max",label:"Maximum"},{value:"count",label:"Total count"},{value:"count_distinct",label:"Unique count"}],Zs={sum:"aggregationSum",avg:"aggregationAvg",min:"aggregationMin",max:"aggregationMax",count:"aggregationCount",count_distinct:"aggregationCountDistinct"},Js=(e,t=ma)=>String(t[Zs[e]]),Ci=(e,t)=>{let n=e.columnMetadata?.find(a=>a.key===t)?.allowedAggregations;return n?.length?rr.filter(a=>n.includes(a.value)):[...rr]},Xs=(e,t,n)=>{let a=Si(e);if(!a||!Ti(e,a,$i(e)).includes(t)||!Ci(e,t).some(o=>o.value===n))return;let i=rr.find(o=>o.value===n)?.label;if(i)return`Using the same approved data, filters, and period as "${e.title?.trim()||e.label?.trim()||"the previous chart"}", calculate ${i.toLowerCase()} of ${In(e,t)} for each ${In(e,a)}. Return a chart and show a table if this app permits it.`},Qs=(e,t=ma)=>{if(e.presentation==="table"||e.presentation==="kpi")return[];let n=ar(e);if(!n)return[];let a=[{type:"line",label:t.chartLine,hint:t.chartLineHint},{type:"bar",label:t.chartBar,hint:t.chartBarHint}];return n.series.length>1&&a.push({type:"stacked_bar",label:t.chartStackedBar,hint:t.chartStackedBarHint}),a},ec=e=>t=>{let n=e.inProgressIndex??-1,a=(Array.isArray(t)?t:[t]).filter(s=>{if(!s||typeof s!="object")return!1;let c=String(s.seriesId??"").startsWith("in-progress:"),u=s.dataIndex,l=s.value;return c?u===n:!(u===n&&l==null)}),i=String(a[0]?.axisValueLabel??a[0]?.name??""),o=s=>s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");return[i?`<strong>${o(i)}</strong>`:"",...a.map(s=>{let c=e.series[Math.floor(Number(s.seriesIndex)/2)]??e.series[0];return`${String(s.marker??"")}${o(String(s.seriesName??""))}: ${o(tn(s.value,c?.valueColumn,void 0,!1,e.locale))}`})].filter(Boolean).join("<br/>")},tc=e=>t=>{let n=(Array.isArray(t)?t:[t]).filter(s=>!!s&&typeof s=="object"),a=s=>s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),i=String(n[0]?.axisValueLabel??n[0]?.name??""),o=n.flatMap(s=>{let c=e.series[Number(s.seriesIndex)]??e.series[0],u=c?.points?.[Number(s.dataIndex)],l=d=>tn(d,c?.valueColumn,void 0,!1,e.locale);return[`${String(s.marker??"")}${a(String(s.seriesName??""))}: ${a(l(s.value))}`,...ps(e.comparison,u,l).map(d=>`<span style="opacity:.75">${a(d)}</span>`)]});return[i?`<strong>${a(i)}</strong>`:"",...o].filter(Boolean).join("<br/>")},nc=(e,{expanded:t=!1,reducedMotion:n=!1,theme:a=en,zoomWindow:i=ln(e.categories.length)}={})=>{let o=e.series.length>1||e.type==="line"&&(e.inProgressIndex??0)>0,s=e.type==="stacked_bar",c=e.categories.length>2,u=Cn(i,e.categories.length);return{animation:!n,animationDuration:n?0:260,aria:{enabled:!0,decal:{show:!0},label:{description:`${e.title}. ${e.summary}`}},backgroundColor:"transparent",color:a.colors,textStyle:{color:a.text,fontFamily:"inherit"},grid:{top:o?t?48:42:14,right:12,bottom:t?18:10,left:10,containLabel:!0},legend:{show:o,type:"scroll",top:0,left:"center",itemWidth:12,itemHeight:8,textStyle:{color:a.muted,fontSize:t?11:10}},tooltip:{trigger:"axis",...e.type==="line"&&(e.inProgressIndex??0)>0?{formatter:ec(e)}:e.comparison?{formatter:tc(e)}:{},triggerOn:"mousemove|click",confine:!0,backgroundColor:a.surface,borderColor:a.border,borderWidth:1,textStyle:{color:a.text,fontSize:12},axisPointer:{type:"line",lineStyle:{color:a.muted,opacity:.5}}},dataZoom:c?[{id:vi,type:"inside",xAxisIndex:0,startValue:u.startIndex,endValue:u.endIndex,minValueSpan:1,filterMode:"filter",disabled:!0}]:void 0,xAxis:{type:"category",data:e.categories,name:e.xAxisTitle,nameLocation:"middle",nameGap:t?38:32,nameTextStyle:{color:a.muted,fontSize:t?11:10},axisLine:{lineStyle:{color:a.border}},axisTick:{show:!1},axisLabel:{color:a.muted,fontSize:t?11:9,hideOverlap:!0,interval:"auto",rotate:!t&&e.categories.length>5?28:0,formatter:l=>l.length>(t?18:11)?`${l.slice(0,t?16:9)}…`:l}},yAxis:{type:"value",name:e.yAxisTitle,nameLocation:"middle",nameGap:t?52:44,nameTextStyle:{color:a.muted,fontSize:t?11:10},axisLabel:{color:a.muted,fontSize:t?11:9,formatter:l=>tn(l,e.series[0]?.valueColumn,void 0,!0,e.locale)},axisLine:{show:!1},axisTick:{show:!1},splitNumber:4,splitLine:{lineStyle:{color:a.border,opacity:.75}}},series:e.series.flatMap((l,d)=>{let p=e.inProgressIndex??-1,h={type:e.type==="line"?"line":"bar",name:l.name,data:l.values,stack:s?"total":void 0,connectNulls:!1,showSymbol:e.type==="line"&&e.categories.length<=18,symbol:"circle",symbolSize:t?7:6,smooth:!1,maxBarWidth:t?38:28,lineStyle:e.type==="line"?{width:t?3:2.5}:void 0,itemStyle:e.type==="line"?{borderColor:a.background,borderWidth:2}:{borderRadius:s?0:[4,4,0,0]},emphasis:{focus:"series"},tooltip:{valueFormatter:_=>tn(_,l.valueColumn,void 0,!1,e.locale)}};if(p<0)return[h];let f=a.colors[d%a.colors.length];return e.type==="line"?p===0?[h]:[{...h,lineStyle:{...h.lineStyle,color:f},itemStyle:{...h.itemStyle,color:f},data:l.values.map((_,x)=>x===p?null:_)},{...h,id:`in-progress:${d}`,name:e.labels.inProgressLegend||gs,showSymbol:!0,symbol:"emptyCircle",lineStyle:{width:t?3:2.5,type:"dashed",color:f,opacity:.6},itemStyle:{color:f,opacity:.6},data:l.values.map((_,x)=>x===p||x===p-1?_:null)}]:[{...h,data:l.values.map((_,x)=>x===p?{value:_,itemStyle:{opacity:.45,borderType:"dashed",borderWidth:1.5,borderColor:f}}:_)}]})}},ac=e=>{let t=getComputedStyle(e),n=(c,u)=>{for(let l of c){let d=t.getPropertyValue(l).trim();if(d)return d}return u},[a,i,o,s]=en.colors;return{background:n(["--rv-bg","--cf-bg"],en.background),border:n(["--rv-border","--cf-border"],en.border),muted:n(["--rv-muted","--cf-muted"],en.muted),surface:n(["--rv-surface","--cf-surface"],en.surface),text:n(["--rv-text","--cf-text"],en.text),colors:[n(["--rv-chart-1","--rv-accent","--cf-accent"],a),n(["--rv-chart-2"],i),n(["--rv-chart-3"],o),n(["--rv-chart-4"],s)]}},rc=["data-theme","data-color-scheme","class","style"],ic=(e,t)=>{let n=[];if(typeof matchMedia<"u"){let a=matchMedia("(prefers-color-scheme: dark)");a.addEventListener?.("change",t),n.push(()=>a.removeEventListener?.("change",t))}if(typeof MutationObserver<"u"){let a=new MutationObserver(t),i=e;for(;i;){i instanceof Element&&a.observe(i,{attributes:!0,attributeFilter:rc});let o=i.parentNode;i=o instanceof ShadowRoot?o.host:o}n.push(()=>a.disconnect())}return()=>n.forEach(a=>a())},oc=({model:e,expanded:t=!1,classPrefix:n="cf"})=>{let a=R(null),i=R(null),[o,s]=S(()=>({model:e,window:ln(e.categories.length)})),[c,u]=S(!1),l=o.model===e?Cn(o.window,e.categories.length):ln(e.categories.length),d=R(l);d.current=l;let p=G=>{let N=Cn(G,e.categories.length);d.current=N,s({model:e,window:N}),i.current?.dispatchAction({type:"dataZoom",dataZoomId:vi,startValue:N.startIndex,endValue:N.endIndex})},[h,f]=S(!1),[_,x]=S(0),[w,v]=S(0);X(()=>{let G=a.current;if(G)return ic(G,()=>v(N=>N+1))},[]),X(()=>{let G=a.current;if(!G)return;let N=!1,se=null;return Vs().then(({init:q})=>{if(N||!G.isConnected||!bi&&typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("jsdom"))return;let F=q(G,null,{renderer:"canvas",devicePixelRatio:Math.min(window.devicePixelRatio||1,2)});i.current=F;let C=()=>{F.resize(),x(Math.round(G.clientWidth/40))},I=typeof ResizeObserver>"u"?null:new ResizeObserver(C);I?.observe(G),I||window.addEventListener("resize",C,{passive:!0}),se=()=>{I?.disconnect(),I||window.removeEventListener("resize",C),F.dispose(),i.current=null},f(!0)}).catch(()=>{N||u(!0)}),()=>{N=!0,se?.()}},[]),X(()=>{let G=a.current,N=i.current;if(!G||!N)return;let se=typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;N.setOption(Ns(nc(e,{expanded:t,reducedMotion:se,theme:ac(G),zoomWindow:d.current}),G.clientWidth),{lazyUpdate:!0,notMerge:!0}),N.resize()},[t,e,h,w,_]);let m=e.labels,T=!c&&e.categories.length>2,P=l.endIndex-l.startIndex+1,O=l.startIndex===0&&l.endIndex===e.categories.length-1,re=T&&P>2,J=T&&!O;return r(de,{children:[r("div",{ref:a,class:`${n}-analytics-echart${t?" is-expanded":""}`,role:"img","aria-label":`${e.title}. ${e.summary}`,"data-chart-status":c?"fallback":"ready",children:c?r("span",{class:`${n}-analytics-echart__fallback`,children:e.summary}):null}),e.comparisonNote?r("p",{class:`${n}-analytics-comparison-note`,"data-comparison-note":!0,style:"margin:4px 2px 0;font-size:11px;color:var(--rv-muted,#5b7186)",children:e.comparisonNote}):null,T?r("div",{class:`${n}-analytics-zoom`,children:[r("span",{class:`${n}-analytics-zoom__range`,"aria-live":"polite","aria-atomic":"true",children:Hs(e.categories,l,m)}),r("div",{class:`${n}-analytics-zoom__controls`,role:"group","aria-label":m.zoomControls,children:[r("button",{type:"button","aria-label":m.zoomOut,title:m.zoomOut,disabled:!J,onClick:()=>p(yi(d.current,"out",e.categories.length)),children:"−"}),r("button",{type:"button",class:`${n}-analytics-zoom__reset`,"aria-label":m.zoomReset,title:m.zoomReset,disabled:O,onClick:()=>p(ln(e.categories.length)),children:m.zoomResetShort}),r("button",{type:"button","aria-label":m.zoomIn,title:m.zoomIn,disabled:!re,onClick:()=>p(yi(d.current,"in",e.categories.length)),children:"+"})]})]}):null]})},En=e=>{let t=e.replaceAll("_"," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim();return t?`${t.charAt(0).toUpperCase()}${t.slice(1)}`:"Value"},Mi=(e,t)=>(t?.length?t:Object.keys(e[0]??{})).map(n=>typeof n=="string"?{key:n,label:En(n)}:{...n,label:n.label?.trim()||En(n.key)}),ir=(e,t,n,a={})=>mi(e,n,{...a,locale:t??a.locale}),Ai=e=>{let t=String(e??"");return/[",\r\n]/.test(t)?`"${t.replaceAll('"','""')}"`:t},sc=(e,t)=>{let n=Mi(e,t);return[n.map(a=>Ai(a.label)).join(","),...e.map(a=>n.map(i=>Ai(a[i.key])).join(","))].join(`\r
2
+ `)},Ii=({label:e,options:t,value:n,onChange:a,classPrefix:i})=>{let o=R(null),s=R(null),[c,u]=S(n),[l,d]=S(!1);X(()=>u(n),[n]);let p=f=>`${i}-${f}`,h=f=>{u(f),o.current&&(o.current.dataset.value=f,o.current.open=!1,o.current.querySelector("summary")?.focus()),a?.(f)};return r("details",{ref:o,"data-result-popover":!0,"data-result-select":!0,"data-value":c,class:p("sdk-select"),onToggle:f=>{let _=f.currentTarget.open;d(_);let x=s.current;if(x){if(x.setAttribute("popover","manual"),!_){typeof x.hidePopover=="function"&&x.matches(":popover-open")&&x.hidePopover();return}typeof x.showPopover=="function"&&!x.matches(":popover-open")&&x.showPopover(),requestAnimationFrame(()=>{if(!o.current?.open||!x.isConnected)return;let w=o.current.querySelector("summary").getBoundingClientRect(),v=Math.max(w.width,Math.min(220,innerWidth-24)),m=Math.min(x.scrollHeight,240);x.style.width=`${v}px`,x.style.left=`${Math.max(12,Math.min(w.left,innerWidth-v-12))}px`,x.style.top=`${w.bottom+m+6<=innerHeight-12?w.bottom+6:Math.max(12,w.top-m-6)}px`})}},children:[r("summary",{class:p("sdk-select-trigger"),role:"combobox","aria-label":e,"aria-haspopup":"listbox","aria-expanded":l,children:[r("span",{children:t.find(([f])=>f===c)?.[1]??c}),r("span",{"aria-hidden":"true",children:"⌄"})]}),r("div",{ref:s,class:p("sdk-select-list"),role:"listbox","aria-label":e,popover:"manual",children:t.map(([f,_])=>r("button",{type:"button",role:"option","aria-selected":f===c,onClick:()=>h(f),children:_},f))})]})},cc=(e,t,n)=>{let a=n.value.trim();if(!a)return!0;let i=String(e??""),o=typeof e=="number"?e:NaN,s=Number(a),c=!Number.isNaN(o)&&!Number.isNaN(s)?o-s:i.localeCompare(a,void 0,{numeric:!0,sensitivity:"base"});switch(n.operator){case"equals":return c===0;case"not_equals":return c!==0;case"gt":return c>0;case"gte":return c>=0;case"lt":return c<0;case"lte":return c<=0;default:return i.toLocaleLowerCase().includes(a.toLocaleLowerCase())||t.toLocaleLowerCase().includes(a.toLocaleLowerCase())}},lc=({rows:e,columns:t,maxRows:n=100,locale:a,format:i,expanded:o=!1,classPrefix:s="cr",pageSize:c=10})=>{let u=qe(()=>Mi(e,t),[t,e]),l=u.map($=>$.key).join("\0"),[d,p]=S(()=>u.map($=>$.key)),[h,f]=S(""),[_,x]=S(),[w,v]=S("asc"),[m,T]=S({}),[P,O]=S(),[re,J]=S([]),[G,N]=S({}),[se,q]=S(()=>u.map($=>$.key)),[F,C]=S(!1),[I,ce]=S([]),[te,ue]=S("table"),[le,z]=S(1),[ne,He]=S(c),y=R(null);X(()=>{let $=U=>{let Y=U.composedPath();y.current?.querySelectorAll("details[data-result-popover][open]").forEach(Q=>{Y.includes(Q)||(Q.open=!1)})},j=U=>{let Y=[...y.current?.querySelectorAll("details[data-result-popover][open]")??[]].at(-1);U.key!=="Escape"||!Y||(Y.open=!1,Y.querySelector("summary")?.focus(),U.preventDefault())};return document.addEventListener("pointerdown",$),document.addEventListener("keydown",j),()=>{document.removeEventListener("pointerdown",$),document.removeEventListener("keydown",j)}},[]),X(()=>{p(u.map($=>$.key)),x(void 0),T({}),O(void 0),J([]),N({}),q(u.map($=>$.key)),ce([]),z(1)},[l]);let V=se.map($=>u.find(j=>j.key===$)).filter($=>!!($&&d.includes($.key))),we=qe(()=>{let $=h.toLocaleLowerCase(a),j=e.map((U,Y)=>({row:U,index:Y})).filter(({row:U})=>V.some(Y=>ir(U[Y.key],a,Y,i).toLocaleLowerCase(a).includes($))&&Object.entries(m).every(([Y,Q])=>{let $e=u.find(Me=>Me.key===Y);return cc(U[Y],ir(U[Y],a,$e,i),Q)}));return _?j.sort((U,Y)=>{let Q=U.row[_],$e=Y.row[_],Me=typeof Q=="number"?Q:NaN,et=typeof $e=="number"?$e:NaN,Je=!Number.isNaN(Me)&&!Number.isNaN(et)?Me-et:String(Q??"").localeCompare(String($e??""),a,{numeric:!0,sensitivity:"base"});return w==="asc"?Je:-Je}):j},[V,m,i,a,h,u,e,w,_]),oe=we.slice(0,Math.max(1,n)),_e=Math.max(1,Math.ceil(oe.length/ne)),he=Math.min(le,_e),Ge=o?oe:oe.slice((he-1)*ne,he*ne),ke=Ge.length>0&&Ge.every(({index:$})=>I.includes($)),K=$=>`${s}-${$}`,Ne=()=>{p(u.map($=>$.key)),q(u.map($=>$.key)),N({}),x(void 0),v("asc"),T({}),O(void 0),J([]),C(!1),f(""),ce([]),ue("table"),z(1)};if(e.length===0||u.length===0)return r("div",{class:K("table-note"),children:"No rows returned."});let Ze=$=>{let j=new Set(Ge.map(({index:U})=>U));ce(U=>$?[...new Set([...U,...j])]:U.filter(Y=>!j.has(Y)))};return r("section",{ref:y,class:K("data-table"),children:[r("div",{class:K("table-fields"),children:[r("strong",{children:"Fields"}),r("div",{class:K("field-list"),children:u.map($=>r("span",{class:K("field-chip"),children:$.label},$.key))}),r("span",{class:K("table-field-count"),children:[e.length.toLocaleString(a)," rows"]})]}),r("div",{class:K("table-controls"),children:[r("label",{class:K("table-search"),children:[r("span",{"aria-hidden":"true",children:"⌕"}),r("input",{type:"search",value:h,placeholder:"Search this result...","aria-label":"Search this result",onInput:$=>{f($.currentTarget.value.trim()),z(1)}})]}),r("div",{class:K("table-modes"),role:"group","aria-label":"Table display mode",children:["table","matrix"].map($=>r("button",{type:"button",class:`${K("segment")}${te===$?" is-active":""}`,"aria-pressed":te===$,onClick:()=>ue($),children:$==="table"?"Table":"Matrix"},$))})]}),r("div",{class:K("table-column-bar"),children:[r("details",{"data-result-popover":!0,class:K("column-picker"),children:[r("summary",{children:"Columns"}),r("div",{class:K("column-menu"),children:se.map(($,j)=>{let U=u.find(Y=>Y.key===$);return U?r("div",{class:K("column-picker-row"),children:[r("label",{children:[r("input",{type:"checkbox",checked:d.includes(U.key),onChange:Y=>{let Q=Y.currentTarget.checked;p($e=>Q?[...new Set([...$e,U.key])]:$e.length>1?$e.filter(Me=>Me!==U.key):$e)}}),r("span",{children:G[U.key]||U.label})]}),r("button",{type:"button","aria-label":`Move ${U.label} left`,disabled:j===0,onClick:()=>q(Y=>{let Q=[...Y];return[Q[j-1],Q[j]]=[Q[j],Q[j-1]],Q}),children:"↑"}),r("button",{type:"button","aria-label":`Move ${U.label} right`,disabled:j===se.length-1,onClick:()=>q(Y=>{let Q=[...Y];return[Q[j+1],Q[j]]=[Q[j],Q[j+1]],Q}),children:"↓"})]},U.key):null})})]}),r("button",{type:"button",class:K("table-view-button"),"aria-pressed":F,onClick:()=>C($=>!$),children:F?"Comfortable rows":"Compact rows"}),r("button",{type:"button",class:K("table-view-button"),onClick:Ne,children:"Reset view"})]}),Object.keys(m).length?r("div",{class:K("table-filter-bar"),children:Object.entries(m).map(([$,j])=>{let U=u.find(Y=>Y.key===$);return r("button",{type:"button",class:K("table-filter-chip"),"aria-label":`Clear ${U?.label??$} filter`,onClick:()=>T(Y=>{let Q={...Y};return delete Q[$],Q}),children:[G[$]||U?.label||$," ",j.operator.replaceAll("_"," ")," ",j.value," ×"]},$)})}):null,r("div",{class:K("table-wrap"),role:"region","aria-label":"Scrollable result table",tabIndex:0,children:r("table",{class:`${K("table")}${te==="matrix"?" is-matrix":""}${F?" is-compact":""}`,children:[r("caption",{class:K("visually-hidden"),children:["Result table with ",we.length," ",we.length===1?"row":"rows"]}),r("thead",{children:r("tr",{children:[r("th",{class:K("select-cell"),children:r("input",{type:"checkbox","aria-label":"Select all visible rows",checked:ke,onChange:$=>Ze($.currentTarget.checked)})}),V.map($=>r("th",{scope:"col",class:P===$.key?"is-pinned":void 0,style:P===$.key?{left:"34px"}:void 0,"aria-sort":_===$.key?w==="asc"?"ascending":"descending":"none",children:[r("button",{type:"button",class:K("table-sort"),"aria-label":`Sort by ${$.label}`,onClick:()=>{_===$.key?v(j=>j==="asc"?"desc":"asc"):(x($.key),v("asc")),z(1)},children:[r("span",{children:G[$.key]||$.label}),r("span",{class:K("sort-direction"),"aria-hidden":"true",children:_===$.key?w==="asc"?"↑":"↓":"↕"})]}),r("details",{"data-result-popover":!0,class:K("table-column-menu"),onToggle:j=>{let U=j.currentTarget,Y=U.querySelector(`.${K("table-column-panel")}`);if(Y?.setAttribute("popover","manual"),!U.open){Y&&typeof Y.hidePopover=="function"&&Y.matches(":popover-open")&&Y.hidePopover(),U.querySelectorAll("details[data-result-select][open]").forEach(Q=>{Q.open=!1});return}y.current?.querySelectorAll("details[data-result-popover][open]").forEach(Q=>{Q!==U&&!U.contains(Q)&&(Q.open=!1)}),Y&&typeof Y.showPopover=="function"&&!Y.matches(":popover-open")&&Y.showPopover(),requestAnimationFrame(()=>{if(!U.open||!U.isConnected)return;let Q=U.querySelector("summary")?.getBoundingClientRect();if(!Q||!Y)return;let{width:$e,height:Me}=Y.getBoundingClientRect(),et=Q.bottom+Me+5<=innerHeight-12?Q.bottom+5:Q.top-Me-5;Y.style.left=`${Math.max(12,Math.min(Q.right-$e,innerWidth-$e-12))}px`,Y.style.top=`${Math.max(12,Math.min(et,innerHeight-Me-12))}px`})},children:[r("summary",{"aria-label":`Actions for ${$.label}`,children:"⋯"}),r("div",{class:K("table-column-panel"),popover:"manual",children:[r("strong",{children:G[$.key]||$.label}),r("button",{type:"button",onClick:()=>{x($.key),v("asc"),z(1)},children:"Sort ascending"}),r("button",{type:"button",onClick:()=>{x($.key),v("desc"),z(1)},children:"Sort descending"}),r("span",{children:"Filter values"}),r(Ii,{classPrefix:s,label:`Filter operator for ${$.label}`,value:m[$.key]?.operator??"contains",options:[["contains","Contains"],["equals","Equals"],["not_equals","Does not equal"],["gt","Greater than"],["gte","At least"],["lt","Less than"],["lte","At most"]]}),r("input",{type:"text","aria-label":`Filter value for ${$.label}`,defaultValue:m[$.key]?.value??"",placeholder:"Enter a value"}),r("button",{type:"button",onClick:j=>{let U=j.currentTarget.parentElement,Y=U.querySelector('input[aria-label^="Filter value"]').value.trim(),Q=U.querySelector("[data-result-select]").dataset.value;T($e=>{let Me={...$e};return Y?Me[$.key]={operator:Q,value:Y}:delete Me[$.key],Me}),z(1),j.currentTarget.closest("details").open=!1},children:"Apply filter"}),r("button",{type:"button",onClick:j=>{O(U=>U===$.key?void 0:$.key),q(U=>[$.key,...U.filter(Y=>Y!==$.key)]),j.currentTarget.closest("details").open=!1},children:P===$.key?"Unpin column":"Pin column"}),r("button",{type:"button",onClick:j=>{J(U=>U.includes($.key)?U.filter(Y=>Y!==$.key):[...U,$.key]),j.currentTarget.closest("details").open=!1},children:re.includes($.key)?"Do not wrap text":"Wrap text"}),r("input",{type:"text","aria-label":`Display name for ${$.label}`,defaultValue:G[$.key]||$.label,maxLength:80}),r("button",{type:"button",onClick:j=>{let U=j.currentTarget.parentElement.querySelector('input[aria-label^="Display name"]').value.trim();N(Y=>({...Y,[$.key]:U||$.label||$.key})),j.currentTarget.closest("details").open=!1},children:"Apply display name"})]})]})]},$.key))]})}),r("tbody",{children:Ge.map(({row:$,index:j})=>r("tr",{class:I.includes(j)?"is-selected":void 0,children:[r("td",{class:K("select-cell"),children:r("input",{type:"checkbox","aria-label":`Select row ${j+1}`,checked:I.includes(j),onChange:U=>ce(Y=>U.currentTarget.checked?[...new Set([...Y,j])]:Y.filter(Q=>Q!==j))})}),V.map(U=>r("td",{class:`${re.includes(U.key)?"is-wrapped":""} ${P===U.key?"is-pinned":""}`.trim(),style:P===U.key?{left:"34px"}:void 0,children:ir($[U.key],a,U,i)},U.key))]},j))})]})}),r("div",{class:K("table-summary"),children:[r("span",{children:oe.length?`${((he-1)*ne+1).toLocaleString(a)}-${Math.min(he*ne,oe.length).toLocaleString(a)} of ${we.length.toLocaleString(a)}`:`0 of ${we.length.toLocaleString(a)}`}),o?r("span",{children:e.length>n?`First ${n.toLocaleString(a)} rows available`:"All returned rows loaded"}):r("div",{class:K("table-pagination"),"aria-label":"Table pagination",children:[r("label",{children:[r("span",{children:"Rows"}),r(Ii,{classPrefix:s,label:"Rows per page",value:String(ne),options:[["10","10"],["25","25"],["50","50"]],onChange:$=>{He(Number($)),z(1)}})]}),r("button",{type:"button","aria-label":"Previous page",disabled:he<=1,onClick:()=>z($=>Math.max(1,$-1)),children:"‹"}),r("span",{children:[he," / ",_e]}),r("button",{type:"button","aria-label":"Next page",disabled:he>=_e,onClick:()=>z($=>Math.min(_e,$+1)),children:"›"})]})]})]})},dc=(e,t,n)=>{let a=er(t),i=[],o=e.reportingPeriod?.label?.trim();o&&i.push({label:a.aboutPeriod,value:o});let s=e.rowCount??e.rows?.length;typeof s=="number"&&i.push({label:a.aboutResults,value:xt(s===1?a.rowOne:a.rowMany,{count:s})});let c=e.explanation?.checkedAt??e.freshness?.answeredAt,u=e.explanation?.timezone??e.timezone??e.reportingPeriod?.timezone;if(c){let d=new Date(c),p=c;if(!Number.isNaN(d.getTime()))try{p=new Intl.DateTimeFormat(n,{dateStyle:"medium",timeStyle:"short",...u?{timeZone:u}:{}}).format(d)}catch{p=d.toLocaleString(n)}i.push({label:a.aboutChecked,value:p})}u&&i.push({label:a.aboutTimezone,value:u});let l=e.explanation?.dataFreshness?.status??e.freshness?.status;return l&&l!=="unknown"&&i.push({label:a.aboutSourceData,value:l.replaceAll("_"," ")}),e.appliedFilters?.length&&i.push({label:a.aboutFilters,value:xt(a.filtersApplied,{count:e.appliedFilters.length})}),i},Ei=e=>e.columns?.length?e.columns:Object.keys(e.rows?.[0]??{}),uc=e=>{let t=e.rows??[],n=e.currency?.code&&!e.currency.isMixed?e.currency.code:void 0;return Ei(e).map(a=>{let i=e.columnMetadata?.find(s=>s.key===a);if(!i)return{key:a,label:En(a)};let o=i.dataType==="date"||i.dataType==="datetime"||i.semanticRole==="date";return{key:a,label:i.label,dataType:i.dataType,semanticRole:i.semanticRole,currencyCode:i.currencyCode||(i.dataType==="currency"?n:void 0),formatPattern:i.formatPattern,grain:o?i.grain??e.periodComparison?.grain??di(t.map(s=>s[a])):void 0}})},pc=(e,t)=>{let n=e.rows?.[0]??{};return e.chartRecommendation?.valueFields?.[0]??e.valueFields?.[0]??e.value??e.columnMetadata?.find(a=>a.semanticRole==="measure"&&a.key in n)?.key??t.find(a=>$n(n[a])!==null)??t[1]??t[0]},fc=(e,t,n="analytics-result.csv")=>{if(typeof document>"u"||e.length===0)return;let a=sc(t,e),i=URL.createObjectURL(new Blob([a],{type:"text/csv;charset=utf-8"})),o=document.createElement("a");o.href=i,o.download=n,o.click(),URL.revokeObjectURL(i)},dn=new Set,zi=e=>{let t=e.composedPath();dn.forEach(n=>{n.isOpen()&&!n.contains(t)&&n.close(!1)})},Ni=e=>{if(e.key==="Escape"){for(let t of dn)if(t.isOpen()){t.close(!0),e.preventDefault();return}}},hc=e=>(dn.size===0&&typeof document<"u"&&(document.addEventListener("pointerdown",zi),document.addEventListener("keydown",Ni)),dn.add(e),()=>{dn.delete(e),dn.size===0&&typeof document<"u"&&(document.removeEventListener("pointerdown",zi),document.removeEventListener("keydown",Ni))}),ga=({children:e,size:t=15})=>r("svg",{viewBox:"0 0 24 24",width:t,height:t,fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false",children:e}),mc=()=>r(ga,{children:r("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})}),gc=()=>r(ga,{children:r("path",{d:"M18 6 6 18M6 6l12 12"})}),Ri=()=>r(ga,{size:13,children:r("path",{d:"m6 9 6 6 6-6"})}),bc=()=>r(ga,{size:13,children:r("path",{d:"m5 12 5 5L20 7"})}),Li=({type:e,className:t})=>r("svg",{viewBox:"0 0 32 32","aria-hidden":"true",class:t,fill:"none",children:[r("path",{d:"M6 26h21M6 7v19",stroke:"var(--rv-muted)","stroke-width":"1.4","stroke-linecap":"round"}),e==="line"?r("path",{d:"M8 21c4-7 7 2 11-6 2.5-5 4.5-2 7-7",stroke:"var(--rv-chart-2)","stroke-width":"2.1","stroke-linecap":"round","stroke-linejoin":"round"}):e==="stacked_bar"?r(de,{children:[9,15,21].map((n,a)=>r("g",{children:[r("rect",{x:n,y:18-a*2,width:"4",height:8+a*2,fill:"var(--rv-chart-2)",rx:"0.6"}),r("rect",{x:n,y:13-a,width:"4",height:"5",fill:"var(--rv-chart-3)",rx:"0.6"}),r("rect",{x:n,y:9-a,width:"4",height:"4",fill:"var(--rv-chart-1)",rx:"0.6"})]},n))}):r(de,{children:[r("rect",{x:"9",y:"18",width:"4",height:"8",fill:"var(--rv-chart-2)",rx:"0.7"}),r("rect",{x:"15",y:"13",width:"4",height:"13",fill:"var(--rv-chart-2)",rx:"0.7"}),r("rect",{x:"21",y:"8",width:"4",height:"18",fill:"var(--rv-chart-2)",rx:"0.7"})]})]}),Di=e=>{let[t,n]=S(!1),a=R(null),i=R(null),o=R(t);return o.current=t,X(()=>hc({isOpen:()=>o.current,contains:s=>!!(a.current&&s.includes(a.current)||i.current&&s.includes(i.current)),close:s=>{n(!1),s&&a.current?.focus()}}),[]),Sn(()=>{if(!t)return;let s=()=>{let c=a.current,u=i.current;if(!c||!u)return;u.style.left="0px",u.style.top="0px";let l=u.getBoundingClientRect(),d=c.getBoundingClientRect(),p=document.documentElement.clientWidth||window.innerWidth,h=document.documentElement.clientHeight||window.innerHeight,f=getComputedStyle(c).direction==="rtl",_=e==="end"===f?d.left:d.right-l.width;_=Math.max(8,Math.min(_,p-l.width-8));let x=d.bottom+7;x+l.height>h-8&&d.top-7-l.height>8&&(x=d.top-7-l.height),u.style.left=`${_-l.left}px`,u.style.top=`${x-l.top}px`};return s(),window.addEventListener("resize",s),window.addEventListener("scroll",s,!0),i.current?.querySelector('[aria-selected="true"], button')?.focus({preventScroll:!0}),()=>{window.removeEventListener("resize",s),window.removeEventListener("scroll",s,!0)}},[t,e]),{open:t,setOpen:n,triggerRef:a,layerRef:i}},vc=({visualization:e,field:t,prefix:n,labels:a,locale:i,headerTitle:o})=>{let s=e.rows??[],c=e.columnMetadata?.find(v=>v.key===t),u=t?s[0]?.[t]:void 0,l=$n(u),d=v=>tn(v,c,e,!1,i),p=l===null?String(u??a.noValue):d(l),h=e.periodComparison,f=!h?.measureField||h.measureField===t,_=t?$n(s[1]?.[t]):null,x=l!==null&&h&&f?Nr(h,{value:l,status:"observed",label:h.currentPeriod?.label},{value:_??h.previousFullValue??h.previousToDateValue,status:"observed",label:h.previousPeriod?.label},{format:d,locale:i}):void 0,w=c?.label??(t?En(t):a.currentValue);return r("section",{class:`${n}-analytics-kpi`,"aria-label":o??w,"data-testid":"analytics-kpi",children:[r("div",{class:`${n}-analytics-kpi__label`,children:w}),r("div",{class:`${n}-analytics-kpi__value`,children:p}),x?r(de,{children:[r("div",{class:`${n}-analytics-kpi__change is-${x.tone}`,"data-comparison-basis":x.basis,title:x.title,children:[r("span",{children:x.label}),x.copy?r("span",{class:`${n}-analytics-kpi__copy`,children:x.copy}):null]}),x.secondary?r("div",{class:`${n}-analytics-kpi__secondary`,children:x.secondary}):null]}):null]})},xc=({visualization:e,classPrefix:t,labels:n,locale:a,expanded:i=!1,onExpand:o,onClose:s,expandControlId:c,onFollowUp:u,onDownload:l,headerActions:d,leading:p,children:h,dataToggle:f,cardRef:_,maxTableRows:x=100})=>{let w=qe(()=>er(n),[n]),v=qe(()=>ar(e,void 0,{labels:w,locale:a}),[e,w,a]),[m,T]=S(v?.type);X(()=>T(v?.type),[v]);let[P,O]=S(!1),re=qe(()=>Qs(e,w),[e,w]),J=qe(()=>ar(e,m,{labels:w,locale:a}),[e,m,w,a]),G=m??J?.type??v?.type,N=re.find(K=>K.type===G),se=[...new Set(J?.series.map(K=>K.field)??[])],q=Di("end"),F=Di("start"),C=e.rows??[],I=Ei(e),ce=qe(()=>hs(e),[e]),te=qe(()=>uc(ce),[ce]),ue=qe(()=>({locale:a,timezone:e.timezone||e.periodComparison?.timezone,yes:w.yes,no:w.no}),[a,e.timezone,e.periodComparison?.timezone,w]),le=dc(e,w,a),z=l===!1||!e.downloadAvailable?null:()=>(l??fc)(I,C),ne=le.length?r("details",{class:`${t}-analytics-inspect`,children:[r("summary",{children:w.aboutResult}),r("dl",{children:le.map(K=>r("div",{children:[r("dt",{children:K.label}),r("dd",{children:K.value})]},K.label))})]}):null,He=(()=>{let K=e.freshness?.answeredAt,Ne=K?new Date(K):null;return!Ne||Number.isNaN(Ne.getTime())?w.liveData:xt(w.updatedAt,{time:new Intl.DateTimeFormat(a,{hour:"numeric",minute:"2-digit"}).format(Ne)})})(),y=e.rowCount??C.length,V=e.appliedFilters?.length??0,we=r("div",{class:`${t}-analytics-meta`,"data-testid":"analytics-result-meta",role:"group","aria-label":w.resultDetails,children:[r("span",{children:[r("span",{"aria-hidden":"true",class:`${t}-analytics-meta__dot`}),He]}),e.reportingPeriod?.label?r("span",{children:e.reportingPeriod.label}):null,r("span",{children:xt(y===1?w.rowOne:w.rowMany,{count:y})}),V>0?r("span",{children:xt(V===1?w.filtersOne:w.filtersMany,{count:V})}):null]}),oe=(K,Ne,Ze,$=w.expandChart)=>r("div",{class:`${t}-analytics-result`,children:[r("section",{ref:_,class:`${t}-analytics-visualization${i?" is-expanded":""}`,"aria-label":K,children:[r("div",{class:`${t}-analytics-visualization__header`,children:[r("div",{children:[r("div",{class:`${t}-analytics-visualization__title`,children:K}),we]}),r("div",{class:`${t}-analytics-visualization__actions`,children:[Ze,d,i&&s?r("button",{type:"button",class:`${t}-analytics-visualization__close`,"aria-label":w.restoreView,title:w.restoreView,onClick:s,children:r(gc,{})}):o&&e.expandable!==!1?r("button",{type:"button",class:`${t}-analytics-visualization__expand`,"aria-label":$,title:$,"data-visualization-message":c,onClick:o,children:r(mc,{})}):null]})]}),p,Ne,ne,h]}),r("div",{class:`${t}-analytics-layer`,children:[u?r("div",{ref:F.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:"fixed"},role:"menu","aria-label":w.aggregate,hidden:!F.open,children:se.flatMap(j=>Ci(e,j).map(U=>{let Y=e.columnMetadata?.find(Q=>Q.key===j)?.label??En(j);return r("button",{type:"button",role:"menuitem",onClick:()=>{let Q=Xs(e,j,U.value);Q&&u(Q),F.setOpen(!1)},children:r("span",{class:`${t}-analytics-chart-picker__copy`,children:[r("strong",{children:[Js(U.value,w)," · ",Y]}),r("small",{children:w.aggregateCharge})]})},`${j}:${U.value}`)}))}):null,r("div",{ref:q.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:"fixed"},role:"listbox","aria-label":w.chartType,hidden:!q.open,children:re.map(j=>{let U=j.type===G;return r("button",{type:"button",role:"option","aria-selected":U,class:U?"is-selected":"",onClick:()=>{T(j.type),q.setOpen(!1),q.triggerRef.current?.focus()},children:[r("span",{class:`${t}-analytics-chart-picker__icon`,children:r(Li,{type:j.type,className:`${t}-chart-type-icon`})}),r("span",{class:`${t}-analytics-chart-picker__copy`,children:[r("strong",{children:j.label}),r("small",{children:j.hint})]}),U?r(bc,{}):null]},j.type)})})]})]}),_e=r(lc,{rows:ce.rows??C,columns:te,maxRows:x,expanded:i,classPrefix:t,locale:a,format:ue}),he=()=>e.tableAvailable===!1||I.length===0?null:oe(e.title?.trim()||w.resultDetails,r(de,{children:_e}),z?r("button",{type:"button",class:`${t}-analytics-visualization__download`,onClick:z,children:w.download}):null,w.expandTable);if(C.length===0)return r(de,{children:[p,r("section",{class:`${t}-analytics-empty`,role:"status","data-testid":"analytics-empty-state",children:[r("p",{children:w.noMatchTitle}),r("p",{children:w.noMatchBody})]}),ne,h]});if(e.presentation==="table"||!e.presentation&&e.type==="table")return he()??r(de,{children:h});let Ge=f&&e.tableAvailable!==!1?r("button",{type:"button",class:`${t}-analytics-visualization__download`,"aria-expanded":P,onClick:()=>O(K=>{let Ne=!K;return f.onToggle?.(Ne),Ne}),children:P?w.hideData:w.viewData}):null,ke=P?r("div",{class:`${t}-analytics-data`,children:_e}):null;return e.presentation==="kpi"||!e.presentation&&e.type==="kpi"?oe(w.liveMetric,r(de,{children:[r(vc,{visualization:e,field:pc(e,I),prefix:t,labels:w,locale:a}),Ge,ke]})):J?oe(J.title,r(de,{children:[r(oc,{model:J,expanded:i,classPrefix:t}),z?r("button",{type:"button",class:`${t}-analytics-visualization__download`,onClick:z,children:w.downloadData}):null,Ge,ke]}),r(de,{children:[u?r("div",{class:`${t}-analytics-chart-picker ${t}-analytics-chart-picker--aggregation`,children:r("button",{type:"button",ref:F.triggerRef,"aria-haspopup":"menu","aria-expanded":F.open,"aria-label":w.aggregate,title:w.aggregateTitle,onClick:()=>{q.setOpen(!1),F.setOpen(!F.open)},children:[r("span",{class:`${t}-analytics-chart-picker__current`,children:r("span",{children:w.aggregate})}),r(Ri,{})]})}):null,re.length>1?r("div",{class:`${t}-analytics-chart-picker`,children:r("button",{type:"button",ref:q.triggerRef,"aria-haspopup":"listbox","aria-expanded":q.open,"aria-label":w.chooseChartType,title:w.chooseChartType,onClick:()=>{F.setOpen(!1),q.setOpen(!q.open)},children:[r("span",{class:`${t}-analytics-chart-picker__current`,children:[r(Li,{type:G??J.type,className:`${t}-chart-type-icon`}),r("span",{children:N?.label??w.chartFallback})]}),r(Ri,{})]})}):null]})):he()??r(de,{children:h})},yc=["#2563eb","#b45309","#7c3aed"],_c=["#60a5fa","#fbbf24","#a78bfa"],wc=(e,t)=>{let n=`.${e}-analytics-visualization`,a=`.${e}-analytics-result`,i=`.${e}-analytics-chart-picker`,o=`.${e}-analytics-kpi`;return`
3
3
  ${a}{
4
4
  display:contents;
5
5
  --rv-bg:${t.bg};--rv-surface:${t.surface};--rv-surface-2:${t.surface2};--rv-text:${t.text};
@@ -69,14 +69,14 @@ ${n}.is-expanded .${e}-analytics-echart{height:auto;min-height:310px;flex:1}
69
69
  .${e}-analytics-zoom__controls button:focus-visible{position:relative;z-index:1;outline:2px solid var(--rv-accent);outline-offset:-2px}
70
70
  .${e}-analytics-zoom__controls button:disabled{cursor:not-allowed;opacity:.38}
71
71
  .${e}-analytics-zoom__controls .${e}-analytics-zoom__reset{min-width:56px;padding:0 10px;font-size:10px;font-weight:700}
72
- `},yc=(e,t)=>{if(typeof MutationObserver>"u")return()=>{};let n=e.scrollHeight,a=0,i=()=>{a=0;let s=e.scrollHeight,c=s>n,d=t.isAtBottom();n=s,c&&(d?(e.scrollTop=e.scrollHeight,t.onFollow?.()):t.onUnseen?.())},o=new MutationObserver(()=>{a||(a=typeof requestAnimationFrame=="function"?requestAnimationFrame(i):setTimeout(i,0))});return o.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>{o.disconnect(),a&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(a)}};class un extends Error{constructor(n,a,i){super(a);q(this,"status");q(this,"retryAfterSeconds");this.status=n,this.retryAfterSeconds=i,this.name="ApiError"}}const ir=()=>({agentName:"Accurix",greeting:"Hi! 👋 How can I help you today?",widgetModule:"chat",assistantMediaKind:"image",soundEnabled:!0,voiceOutputEnabled:!1,talkbackMode:"text",allowVoiceInput:!1,memoryEnabled:!0,memoryRetentionDays:30,memoryMessageCap:50,availableActions:[]}),_c="Sara is an AI assistant; answers may be imperfect.",wc="Accurix is an AI assistant; answers may be imperfect.",Li=e=>{typeof console>"u"||console.warn(`[centrinfo-widget] Could not load saved widget configuration from the API (${e}). Showing default widget chrome. Check data-token, data-api-base, CORS, and backend availability.`)},or=(e,t={})=>{const a=e.disclaimerText?.trim()?.toLowerCase(),i=t.agentName?.trim()||e.agentName?.trim()||"Accurix",o=t.agentAvatarUrl?.trim()||e.agentAvatarUrl?.trim();return{...e,allowVoiceInput:!!(e.allowVoiceInput&&e.talkbackMode&&e.talkbackMode!=="text"),voiceOutputEnabled:!!(e.voiceOutputEnabled&&e.talkbackMode&&e.talkbackMode!=="text"),agentName:i,agentAvatarUrl:o||void 0,disclaimerText:a===_c.toLowerCase()||a?.includes("sara is an ai assistant")?wc:e.disclaimerText}},kc=15e3,Sc=6e4,$c=12e4,Tc=["/transcribe","/speak","/attachments","/stream"],Cc=["/book-demo","/schedule-callback"],Ac=e=>{const t=e.split("?")[0]??e;return Cc.some(n=>t.includes(`/public-chat${n}`))?$c:Tc.some(n=>t.includes(`/public-chat${n}`))||t.endsWith("/public-chat")?Sc:kc},Mc=e=>{const t=e.headers?.get?.("Retry-After"),n=t?Number(t):NaN;return Number.isFinite(n)&&n>=0?n:void 0},Ic=e=>{try{const t=e.split(".")[1];if(!t)return null;const n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),a=JSON.parse(n).exp;return typeof a=="number"&&Number.isFinite(a)?a*1e3:null}catch{return null}};class Ec{constructor(t,n,a,i,o={},s,c,d="floating"){q(this,"baseUrl");q(this,"token");q(this,"gifApiKey");q(this,"analyticsContextToken");q(this,"bootstrapOverrides");q(this,"identityToken");q(this,"identityTokenProvider");q(this,"chatSurface");q(this,"cachedIdentity",null);q(this,"identityFlight",null);this.baseUrl=t,this.token=n,this.gifApiKey=a,this.analyticsContextToken=i,this.bootstrapOverrides=o,this.identityToken=s,this.identityTokenProvider=c,this.chatSurface=d}async currentIdentityToken(){if(!this.identityTokenProvider)return this.identityToken;const t=this.cachedIdentity;return t&&Date.now()<t.refreshAt?t.token:(this.identityFlight??(this.identityFlight=(async()=>{try{const n=(await this.identityTokenProvider()??"").trim();this.identityToken=n||void 0;const a=n?Ic(n):null;return this.cachedIdentity=n&&a!==null?{token:n,refreshAt:a-6e4}:null,this.identityToken}finally{this.identityFlight=null}})()),this.identityFlight)}async fetchT(t,n={}){const a=new AbortController;let i=!1;const o=setTimeout(()=>{i=!0,a.abort()},Ac(t)),s=n.signal,c=()=>a.abort();s?.aborted?a.abort():s?.addEventListener("abort",c,{once:!0});try{return await fetch(t,{...n,signal:a.signal})}catch(d){throw i&&!s?.aborted?new un(408,"The request took too long. Please try again."):d}finally{clearTimeout(o),s?.removeEventListener("abort",c)}}headers(t=!0){const n={Authorization:`Bearer ${this.token}`};return t&&(n["Content-Type"]="application/json"),n}async json(t){let n;try{n=await t.json()}catch{n=void 0}if(!t.ok){const a=Nc(n)??`request failed (${t.status})`;throw new un(t.status,a,Mc(t))}return n?.data??n}async bootstrap(){try{const t=await this.fetchT(`${this.baseUrl}/public-chat/bootstrap`,{headers:this.headers(!1)});if(!t.ok)return Li(`bootstrap request failed with ${t.status}`),or(ir(),this.bootstrapOverrides);const n=await this.json(t);return or({...ir(),...n},this.bootstrapOverrides)}catch(t){return Li(t instanceof Error?t.message:"bootstrap request failed"),or(ir(),this.bootstrapOverrides)}}async history(){const t=await this.currentIdentityToken();if(!t)return{conversations:[]};const n=await this.fetchT(`${this.baseUrl}/public-chat/history`,{method:"POST",headers:this.headers(),body:JSON.stringify({identityToken:t,surface:this.chatSurface})}),a=await this.json(n);return{activeSessionId:a.activeSessionId,conversations:Array.isArray(a.conversations)?a.conversations:[]}}async stream(t,n,a){const i=await this.currentIdentityToken(),o=await this.fetchT(`${this.baseUrl}/public-chat/stream`,{method:"POST",headers:this.headers(),body:JSON.stringify({question:t,sessionId:n,clientMessageId:a.clientMessageId,attachmentId:a.attachmentId,attachmentIds:a.attachmentIds,voicePlaybackRequested:!!a.voicePlaybackRequested,analyticsContextToken:this.analyticsContextToken,identityToken:i,surface:this.chatSurface}),signal:a.signal});return!o.ok||!o.body?((o.status===429||o.status===401)&&await this.json(o),this.send(t,n,a)):Rc(o.body,a)}async liveEvents(t,n){const a=`sessionId=${encodeURIComponent(t)}&after=${encodeURIComponent(n)}`,i=await this.fetchT(`${this.baseUrl}/public-chat/live-events?${a}`,{headers:this.headers(!1)}),o=await this.json(i);return{mode:o.mode??"ai",assignedAgentName:o.assignedAgentName,agentTyping:!!o.agentTyping,agentTypingName:o.agentTypingName,conversationEnded:!!o.conversationEnded,events:o.events??[]}}async typing(t,n){try{const a=await this.fetchT(`${this.baseUrl}/public-chat/typing`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:t,isTyping:n})});if(!a.ok)try{await a.text()}catch{}}catch{}}async presence(t){try{await this.fetchT(`${this.baseUrl}/public-chat/presence`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:t})})}catch{}}async send(t,n,a){const i=await this.currentIdentityToken(),o=await this.fetchT(`${this.baseUrl}/public-chat`,{method:"POST",headers:this.headers(),body:JSON.stringify({question:t,sessionId:n,clientMessageId:a.clientMessageId,attachmentId:a.attachmentId,attachmentIds:a.attachmentIds,voicePlaybackRequested:!!a.voicePlaybackRequested,analyticsContextToken:this.analyticsContextToken,identityToken:i,surface:this.chatSurface}),signal:a.signal}),s=await this.json(o);return a.onChunk(s.answer??""),{answer:s.answer??"",sources:s.sources??[],suggestedReplies:s.suggestedReplies??[],availableActions:s.availableActions??[],actions:s.actions??[],selectedAction:s.selectedAction,handoffOffered:s.handoffOffered??!1,requestedContactFields:Di(s.requestedContactFields),conversationEnded:s.conversationEnded??!1,liveMode:s.liveMode,assignedAgentName:s.assignedAgentName,audioBase64:s.audioBase64,mimeType:s.mimeType,visualization:s.visualization,artifacts:s.artifacts}}async action(t,n,a){const i=a?.trim()||(t==="contact-support"?"inquiry":t),o=await this.fetchT(`${this.baseUrl}/public-chat/${i}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)}),s=await this.json(o);return{ok:!0,note:s?.note,receipt:s?.receipt,booking:s?.booking,caseReference:s?.caseReference||void 0,inquiryId:s?.inquiryId||s?.inquiry?.id||void 0}}async confirmHostedBooking(t){const n=await this.fetchT(`${this.baseUrl}/public-chat/book-demo/confirm`,{method:"POST",headers:this.headers(),body:JSON.stringify(t)}),a=await this.json(n);if(!a?.booking)throw new Error("Calendar booking confirmation was unavailable.");return{...a.booking,receipt:a.receipt}}async speak(t){const n=await this.fetchT(`${this.baseUrl}/public-chat/speak`,{method:"POST",headers:this.headers(),body:JSON.stringify({text:t})}),a=await this.json(n);return{providerReady:!!a.providerReady,message:a.message,audioBase64:a.audioBase64,mimeType:a.mimeType}}async identify(t,n){if(!(!t||!n))try{const a=await this.fetchT(`${this.baseUrl}/public-chat/identify`,{method:"POST",headers:this.headers(),body:JSON.stringify(zc(t,n))});if(!a.ok)try{await a.text()}catch{}}catch{}}async transcribe(t,n,a,i){const o=await this.fetchT(`${this.baseUrl}/public-chat/transcribe`,{method:"POST",headers:this.headers(),body:JSON.stringify({audioBase64:t,mimeType:n,languageHint:a,durationSeconds:i})});return(await this.json(o)).text??""}async transcribeAudio(t,n,a,i){const o=new FormData;o.append("audio",t,"voice-recording"),o.append("mimeType",n||t.type||"audio/webm"),a&&o.append("languageHint",a),i!==void 0&&Number.isFinite(i)&&o.append("durationSeconds",String(i));const s=await this.fetchT(`${this.baseUrl}/public-chat/transcribe`,{method:"POST",headers:this.headers(!1),body:o});return(await this.json(s)).text??""}async endConversation(t){try{const n=await this.fetchT(`${this.baseUrl}/public-chat/end`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:t})});if(!n.ok)try{await n.text()}catch{}}catch{}}async sendFeedback(t){try{const n=await this.fetchT(`${this.baseUrl}/public-chat/feedback`,{method:"POST",headers:this.headers(),body:JSON.stringify(t)});if(!n.ok)try{await n.text()}catch{}}catch{}}async sendExplanationFeedback(t){const n=await this.fetchT(`${this.baseUrl}/public-chat/explanation-feedback`,{method:"POST",headers:this.headers(),body:JSON.stringify(t)});await this.json(n)}async fetchExplanation(t,n,a="widget",i){const o=await this.fetchT(`${this.baseUrl}/public-chat/analytics-explanations/${encodeURIComponent(t)}?sessionId=${encodeURIComponent(n)}&surface=${a}`,{method:"GET",headers:this.headers(!1),signal:i});return this.explanationJob(o,t)}async retryExplanation(t,n,a="widget"){const i=await this.fetchT(`${this.baseUrl}/public-chat/analytics-explanations/${encodeURIComponent(t)}/retry`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:n,surface:a})});return this.explanationJob(i,t)}async explanationJob(t,n){return t.status===404||t.status===410?{status:"failed",explanationId:n,retryAvailable:!1}:this.json(t)}async uploadAttachment(t,n,a,i,o){const s=await this.fetchT(`${this.baseUrl}/public-chat/attachments`,{method:"POST",headers:this.headers(),body:JSON.stringify({fileBase64:t,mimeType:n,filename:a,sessionId:i,analyze:o})});return this.json(s)}async fetchAttachment(t,n){const a=await this.fetchT(`${this.baseUrl}/public-chat/attachments/${encodeURIComponent(t)}?sessionId=${encodeURIComponent(n)}`,{headers:this.headers(!1)});if(!a.ok)throw new un(a.status,"This file is no longer available.");return a.blob()}async demoSlots(t,n){const a=`from=${encodeURIComponent(t)}&to=${encodeURIComponent(n)}`,i=await this.fetchT(`${this.baseUrl}/public-chat/demo-slots?${a}`,{headers:this.headers(!1)});if(!i.ok){const s=new Error("Calendar availability is temporarily unavailable.");throw s.status=i.status,s}const o=await this.json(i);return{status:o?.status,reason:o?.reason,timezone:o?.timezone,slotDurationMinutes:o?.slotDurationMinutes,available:o?.available,taken:o?.taken??[],busy:o?.busy??[]}}async searchGifs(t){if(!this.gifApiKey)return[];const a=`https://tenor.googleapis.com/v2/search?q=${encodeURIComponent(t.trim()||"trending")}&key=${this.gifApiKey}&limit=24&media_filter=tinygif,gif&contentfilter=high`;try{const i=await this.fetchT(a,{});return i.ok?((await i.json()).results??[]).map(s=>({id:s.id,url:s.media_formats?.gif?.url??s.media_formats?.tinygif?.url??"",preview:s.media_formats?.tinygif?.url??s.media_formats?.gif?.url??"",alt:s.content_description||"GIF"})).filter(s=>s.url):[]}catch{return[]}}}const zc=(e,t)=>{const n={...t.customAttributes??{},...t.metadata??{}};t.createdAt!==void 0&&(n.createdAt=t.createdAt),t.avatarUrl&&(n.avatarUrl=t.avatarUrl),t.company&&(n.company=t.company);const a={sessionId:e},i=t.externalId??t.userId;return i&&(a.externalId=i),t.email&&(a.email=t.email),t.firstName&&(a.firstName=t.firstName),t.lastName&&(a.lastName=t.lastName),t.name&&(a.name=t.name),t.phone&&(a.phone=t.phone),Object.keys(n).length>0&&(a.metadata=n),a},Nc=e=>{const t=e?.message;if(Array.isArray(t))return t.join(", ");if(typeof t=="string")return t},Rc=async(e,t)=>{const n=e.getReader(),a=new TextDecoder,i={answer:"",sources:[],suggestedReplies:[],availableActions:[],handoffOffered:!1,requestedContactFields:[],conversationEnded:!1};let o="";for(;;){const{done:s,value:c}=await n.read();if(s)break;o+=a.decode(c,{stream:!0});let d;for(;(d=o.indexOf(`
72
+ `},kc=(e,t)=>{if(typeof MutationObserver>"u")return()=>{};let n=e.scrollHeight,a=0,i=()=>{a=0;let s=e.scrollHeight,c=s>n,u=t.isAtBottom();n=s,c&&(u?(e.scrollTop=e.scrollHeight,t.onFollow?.()):t.onUnseen?.())},o=new MutationObserver(()=>{a||(a=typeof requestAnimationFrame=="function"?requestAnimationFrame(i):setTimeout(i,0))});return o.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>{o.disconnect(),a&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(a)}};class un extends Error{constructor(n,a,i){super(a);B(this,"status");B(this,"retryAfterSeconds");this.status=n,this.retryAfterSeconds=i,this.name="ApiError"}}const or=()=>({agentName:"Accurix",greeting:"Hi! 👋 How can I help you today?",widgetModule:"chat",assistantMediaKind:"image",soundEnabled:!0,voiceOutputEnabled:!1,talkbackMode:"text",allowVoiceInput:!1,memoryEnabled:!0,memoryRetentionDays:30,memoryMessageCap:50,availableActions:[]}),Sc="Sara is an AI assistant; answers may be imperfect.",$c="Accurix is an AI assistant; answers may be imperfect.",Pi=e=>{typeof console>"u"||console.warn(`[centrinfo-widget] Could not load saved widget configuration from the API (${e}). Showing default widget chrome. Check data-token, data-api-base, CORS, and backend availability.`)},sr=(e,t={})=>{const a=e.disclaimerText?.trim()?.toLowerCase(),i=t.agentName?.trim()||e.agentName?.trim()||"Accurix",o=t.agentAvatarUrl?.trim()||e.agentAvatarUrl?.trim();return{...e,allowVoiceInput:!!(e.allowVoiceInput&&e.talkbackMode&&e.talkbackMode!=="text"),voiceOutputEnabled:!!(e.voiceOutputEnabled&&e.talkbackMode&&e.talkbackMode!=="text"),agentName:i,agentAvatarUrl:o||void 0,disclaimerText:a===Sc.toLowerCase()||a?.includes("sara is an ai assistant")?$c:e.disclaimerText}},Tc=15e3,Cc=6e4,Mc=12e4,Ac=["/transcribe","/speak","/attachments","/stream"],Ic=["/book-demo","/schedule-callback"],Ec=e=>{const t=e.split("?")[0]??e;return Ic.some(n=>t.includes(`/public-chat${n}`))?Mc:Ac.some(n=>t.includes(`/public-chat${n}`))||t.endsWith("/public-chat")?Cc:Tc},zc=e=>{const t=e.headers?.get?.("Retry-After"),n=t?Number(t):NaN;return Number.isFinite(n)&&n>=0?n:void 0},Nc=e=>{try{const t=e.split(".")[1];if(!t)return null;const n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),a=JSON.parse(n).exp;return typeof a=="number"&&Number.isFinite(a)?a*1e3:null}catch{return null}};class Rc{constructor(t,n,a,i,o={},s,c,u="floating"){B(this,"baseUrl");B(this,"token");B(this,"gifApiKey");B(this,"analyticsContextToken");B(this,"bootstrapOverrides");B(this,"identityToken");B(this,"identityTokenProvider");B(this,"chatSurface");B(this,"cachedIdentity",null);B(this,"identityFlight",null);this.baseUrl=t,this.token=n,this.gifApiKey=a,this.analyticsContextToken=i,this.bootstrapOverrides=o,this.identityToken=s,this.identityTokenProvider=c,this.chatSurface=u}async currentIdentityToken(){if(!this.identityTokenProvider)return this.identityToken;const t=this.cachedIdentity;return t&&Date.now()<t.refreshAt?t.token:(this.identityFlight??(this.identityFlight=(async()=>{try{const n=(await this.identityTokenProvider()??"").trim();this.identityToken=n||void 0;const a=n?Nc(n):null;return this.cachedIdentity=n&&a!==null?{token:n,refreshAt:a-6e4}:null,this.identityToken}finally{this.identityFlight=null}})()),this.identityFlight)}async fetchT(t,n={}){const a=new AbortController;let i=!1;const o=setTimeout(()=>{i=!0,a.abort()},Ec(t)),s=n.signal,c=()=>a.abort();s?.aborted?a.abort():s?.addEventListener("abort",c,{once:!0});try{return await fetch(t,{...n,signal:a.signal})}catch(u){throw i&&!s?.aborted?new un(408,"The request took too long. Please try again."):u}finally{clearTimeout(o),s?.removeEventListener("abort",c)}}headers(t=!0){const n={Authorization:`Bearer ${this.token}`};return t&&(n["Content-Type"]="application/json"),n}async json(t){let n;try{n=await t.json()}catch{n=void 0}if(!t.ok){const a=Dc(n)??`request failed (${t.status})`;throw new un(t.status,a,zc(t))}return n?.data??n}async bootstrap(){try{const t=await this.fetchT(`${this.baseUrl}/public-chat/bootstrap`,{headers:this.headers(!1)});if(!t.ok)return Pi(`bootstrap request failed with ${t.status}`),sr(or(),this.bootstrapOverrides);const n=await this.json(t);return sr({...or(),...n},this.bootstrapOverrides)}catch(t){return Pi(t instanceof Error?t.message:"bootstrap request failed"),sr(or(),this.bootstrapOverrides)}}async history(){const t=await this.currentIdentityToken();if(!t)return{conversations:[]};const n=await this.fetchT(`${this.baseUrl}/public-chat/history`,{method:"POST",headers:this.headers(),body:JSON.stringify({identityToken:t,surface:this.chatSurface})}),a=await this.json(n);return{activeSessionId:a.activeSessionId,conversations:Array.isArray(a.conversations)?a.conversations:[]}}async stream(t,n,a){const i=await this.currentIdentityToken(),o=await this.fetchT(`${this.baseUrl}/public-chat/stream`,{method:"POST",headers:this.headers(),body:JSON.stringify({question:t,sessionId:n,clientMessageId:a.clientMessageId,attachmentId:a.attachmentId,attachmentIds:a.attachmentIds,voicePlaybackRequested:!!a.voicePlaybackRequested,analyticsContextToken:this.analyticsContextToken,identityToken:i,surface:this.chatSurface}),signal:a.signal});return!o.ok||!o.body?((o.status===429||o.status===401)&&await this.json(o),this.send(t,n,a)):Pc(o.body,a)}async liveEvents(t,n){const a=`sessionId=${encodeURIComponent(t)}&after=${encodeURIComponent(n)}`,i=await this.fetchT(`${this.baseUrl}/public-chat/live-events?${a}`,{headers:this.headers(!1)}),o=await this.json(i);return{mode:o.mode??"ai",assignedAgentName:o.assignedAgentName,agentTyping:!!o.agentTyping,agentTypingName:o.agentTypingName,conversationEnded:!!o.conversationEnded,events:o.events??[]}}async typing(t,n){try{const a=await this.fetchT(`${this.baseUrl}/public-chat/typing`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:t,isTyping:n})});if(!a.ok)try{await a.text()}catch{}}catch{}}async presence(t){try{await this.fetchT(`${this.baseUrl}/public-chat/presence`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:t})})}catch{}}async send(t,n,a){const i=await this.currentIdentityToken(),o=await this.fetchT(`${this.baseUrl}/public-chat`,{method:"POST",headers:this.headers(),body:JSON.stringify({question:t,sessionId:n,clientMessageId:a.clientMessageId,attachmentId:a.attachmentId,attachmentIds:a.attachmentIds,voicePlaybackRequested:!!a.voicePlaybackRequested,analyticsContextToken:this.analyticsContextToken,identityToken:i,surface:this.chatSurface}),signal:a.signal}),s=await this.json(o);return a.onChunk(s.answer??""),{answer:s.answer??"",sources:s.sources??[],suggestedReplies:s.suggestedReplies??[],availableActions:s.availableActions??[],actions:s.actions??[],selectedAction:s.selectedAction,handoffOffered:s.handoffOffered??!1,requestedContactFields:Oi(s.requestedContactFields),conversationEnded:s.conversationEnded??!1,liveMode:s.liveMode,assignedAgentName:s.assignedAgentName,audioBase64:s.audioBase64,mimeType:s.mimeType,visualization:s.visualization,artifacts:s.artifacts}}async action(t,n,a){const i=a?.trim()||(t==="contact-support"?"inquiry":t),o=await this.fetchT(`${this.baseUrl}/public-chat/${i}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)}),s=await this.json(o);return{ok:!0,note:s?.note,receipt:s?.receipt,booking:s?.booking,caseReference:s?.caseReference||void 0,inquiryId:s?.inquiryId||s?.inquiry?.id||void 0}}async confirmHostedBooking(t){const n=await this.fetchT(`${this.baseUrl}/public-chat/book-demo/confirm`,{method:"POST",headers:this.headers(),body:JSON.stringify(t)}),a=await this.json(n);if(!a?.booking)throw new Error("Calendar booking confirmation was unavailable.");return{...a.booking,receipt:a.receipt}}async speak(t){const n=await this.fetchT(`${this.baseUrl}/public-chat/speak`,{method:"POST",headers:this.headers(),body:JSON.stringify({text:t})}),a=await this.json(n);return{providerReady:!!a.providerReady,message:a.message,audioBase64:a.audioBase64,mimeType:a.mimeType}}async identify(t,n){if(!(!t||!n))try{const a=await this.fetchT(`${this.baseUrl}/public-chat/identify`,{method:"POST",headers:this.headers(),body:JSON.stringify(Lc(t,n))});if(!a.ok)try{await a.text()}catch{}}catch{}}async transcribe(t,n,a,i){const o=await this.fetchT(`${this.baseUrl}/public-chat/transcribe`,{method:"POST",headers:this.headers(),body:JSON.stringify({audioBase64:t,mimeType:n,languageHint:a,durationSeconds:i})});return(await this.json(o)).text??""}async transcribeAudio(t,n,a,i){const o=new FormData;o.append("audio",t,"voice-recording"),o.append("mimeType",n||t.type||"audio/webm"),a&&o.append("languageHint",a),i!==void 0&&Number.isFinite(i)&&o.append("durationSeconds",String(i));const s=await this.fetchT(`${this.baseUrl}/public-chat/transcribe`,{method:"POST",headers:this.headers(!1),body:o});return(await this.json(s)).text??""}async endConversation(t){try{const n=await this.fetchT(`${this.baseUrl}/public-chat/end`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:t})});if(!n.ok)try{await n.text()}catch{}}catch{}}async sendFeedback(t){try{const n=await this.fetchT(`${this.baseUrl}/public-chat/feedback`,{method:"POST",headers:this.headers(),body:JSON.stringify(t)});if(!n.ok)try{await n.text()}catch{}}catch{}}async sendExplanationFeedback(t){const n=await this.fetchT(`${this.baseUrl}/public-chat/explanation-feedback`,{method:"POST",headers:this.headers(),body:JSON.stringify(t)});await this.json(n)}async fetchExplanation(t,n,a="widget",i){const o=await this.fetchT(`${this.baseUrl}/public-chat/analytics-explanations/${encodeURIComponent(t)}?sessionId=${encodeURIComponent(n)}&surface=${a}`,{method:"GET",headers:this.headers(!1),signal:i});return this.explanationJob(o,t)}async retryExplanation(t,n,a="widget"){const i=await this.fetchT(`${this.baseUrl}/public-chat/analytics-explanations/${encodeURIComponent(t)}/retry`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:n,surface:a})});return this.explanationJob(i,t)}async explanationJob(t,n){return t.status===404||t.status===410?{status:"failed",explanationId:n,retryAvailable:!1}:this.json(t)}async uploadAttachment(t,n,a,i,o){const s=await this.fetchT(`${this.baseUrl}/public-chat/attachments`,{method:"POST",headers:this.headers(),body:JSON.stringify({fileBase64:t,mimeType:n,filename:a,sessionId:i,analyze:o})});return this.json(s)}async fetchAttachment(t,n){const a=await this.fetchT(`${this.baseUrl}/public-chat/attachments/${encodeURIComponent(t)}?sessionId=${encodeURIComponent(n)}`,{headers:this.headers(!1)});if(!a.ok)throw new un(a.status,"This file is no longer available.");return a.blob()}async demoSlots(t,n){const a=`from=${encodeURIComponent(t)}&to=${encodeURIComponent(n)}`,i=await this.fetchT(`${this.baseUrl}/public-chat/demo-slots?${a}`,{headers:this.headers(!1)});if(!i.ok){const s=new Error("Calendar availability is temporarily unavailable.");throw s.status=i.status,s}const o=await this.json(i);return{status:o?.status,reason:o?.reason,timezone:o?.timezone,slotDurationMinutes:o?.slotDurationMinutes,available:o?.available,taken:o?.taken??[],busy:o?.busy??[]}}async searchGifs(t){if(!this.gifApiKey)return[];const a=`https://tenor.googleapis.com/v2/search?q=${encodeURIComponent(t.trim()||"trending")}&key=${this.gifApiKey}&limit=24&media_filter=tinygif,gif&contentfilter=high`;try{const i=await this.fetchT(a,{});return i.ok?((await i.json()).results??[]).map(s=>({id:s.id,url:s.media_formats?.gif?.url??s.media_formats?.tinygif?.url??"",preview:s.media_formats?.tinygif?.url??s.media_formats?.gif?.url??"",alt:s.content_description||"GIF"})).filter(s=>s.url):[]}catch{return[]}}}const Lc=(e,t)=>{const n={...t.customAttributes??{},...t.metadata??{}};t.createdAt!==void 0&&(n.createdAt=t.createdAt),t.avatarUrl&&(n.avatarUrl=t.avatarUrl),t.company&&(n.company=t.company);const a={sessionId:e},i=t.externalId??t.userId;return i&&(a.externalId=i),t.email&&(a.email=t.email),t.firstName&&(a.firstName=t.firstName),t.lastName&&(a.lastName=t.lastName),t.name&&(a.name=t.name),t.phone&&(a.phone=t.phone),Object.keys(n).length>0&&(a.metadata=n),a},Dc=e=>{const t=e?.message;if(Array.isArray(t))return t.join(", ");if(typeof t=="string")return t},Pc=async(e,t)=>{const n=e.getReader(),a=new TextDecoder,i={answer:"",sources:[],suggestedReplies:[],availableActions:[],handoffOffered:!1,requestedContactFields:[],conversationEnded:!1};let o="";for(;;){const{done:s,value:c}=await n.read();if(s)break;o+=a.decode(c,{stream:!0});let u;for(;(u=o.indexOf(`
73
73
 
74
- `))!==-1;){const l=o.slice(0,d);o=o.slice(d+2);const u=Lc(l);if(u){if(u.event==="error")throw new un(502,u.data?.message??"stream error");if(u.event==="chunk"&&typeof u.data?.text=="string")i.answer+=u.data.text,t.onChunk(u.data.text);else if(u.event==="reset")i.answer="",t.onReset?.();else if(u.event==="final"&&u.data)typeof u.data.answer=="string"&&(i.answer=u.data.answer),i.sources=u.data.sources??[],i.suggestedReplies=u.data.suggestedReplies??[],i.availableActions=u.data.availableActions??[],i.actions=u.data.actions??[],i.selectedAction=u.data.selectedAction,i.handoffOffered=!!u.data.handoffOffered,i.requestedContactFields=Di(u.data.requestedContactFields),i.conversationEnded=!!u.data.conversationEnded,i.liveMode=u.data.liveMode,i.assignedAgentName=u.data.assignedAgentName,i.visualization=u.data.visualization,i.artifacts=u.data.artifacts,i.audioBase64=u.data.audioBase64,i.mimeType=u.data.mimeType,t.onTextReady?.();else if(u.event==="audio"&&u.data)typeof u.data.seq=="number"?(i.liveAudio=!0,t.onAudioSegment?.({seq:u.data.seq,audioBase64:u.data.audioBase64??"",mimeType:u.data.mimeType,text:typeof u.data.text=="string"?u.data.text:void 0})):(i.audioBase64=u.data.audioBase64,i.mimeType=u.data.mimeType);else if(u.event==="done")return i}}}return i},Lc=e=>{let t="message";const n=[];for(const a of e.split(`
74
+ `))!==-1;){const l=o.slice(0,u);o=o.slice(u+2);const d=Oc(l);if(d){if(d.event==="error")throw new un(502,d.data?.message??"stream error");if(d.event==="chunk"&&typeof d.data?.text=="string")i.answer+=d.data.text,t.onChunk(d.data.text);else if(d.event==="reset")i.answer="",t.onReset?.();else if(d.event==="final"&&d.data)typeof d.data.answer=="string"&&(i.answer=d.data.answer),i.sources=d.data.sources??[],i.suggestedReplies=d.data.suggestedReplies??[],i.availableActions=d.data.availableActions??[],i.actions=d.data.actions??[],i.selectedAction=d.data.selectedAction,i.handoffOffered=!!d.data.handoffOffered,i.requestedContactFields=Oi(d.data.requestedContactFields),i.conversationEnded=!!d.data.conversationEnded,i.liveMode=d.data.liveMode,i.assignedAgentName=d.data.assignedAgentName,i.visualization=d.data.visualization,i.artifacts=d.data.artifacts,i.audioBase64=d.data.audioBase64,i.mimeType=d.data.mimeType,t.onTextReady?.();else if(d.event==="audio"&&d.data)typeof d.data.seq=="number"?(i.liveAudio=!0,t.onAudioSegment?.({seq:d.data.seq,audioBase64:d.data.audioBase64??"",mimeType:d.data.mimeType,text:typeof d.data.text=="string"?d.data.text:void 0})):(i.audioBase64=d.data.audioBase64,i.mimeType=d.data.mimeType);else if(d.event==="done")return i}}}return i},Oc=e=>{let t="message";const n=[];for(const a of e.split(`
75
75
  `))a.startsWith("event:")?t=a.slice(6).trim():a.startsWith("data:")&&n.push(a.slice(5).trim());if(n.length===0)return{event:t};try{return{event:t,data:JSON.parse(n.join(`
76
- `))}}catch{return{event:t}}},Di=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[];let sr=()=>Promise.resolve().then(()=>Fo);const Dc=e=>{sr=e},Pi=e=>new Ec(e.apiBaseUrl,e.token,e.gifApiKey,e.analyticsContextToken,{agentName:e.agentName,agentAvatarUrl:e.agentAvatarUrl},e.identityToken,e.getIdentityToken,e.chatSurface),Oi=e=>{const t=n=>(...a)=>e().then(i=>i[n].apply(i,a));return{bootstrap:t("bootstrap"),history:t("history"),stream:t("stream"),liveEvents:t("liveEvents"),presence:t("presence"),typing:t("typing"),action:t("action"),speak:t("speak"),transcribe:t("transcribe"),searchGifs:t("searchGifs"),demoSlots:t("demoSlots"),identify:t("identify"),endConversation:t("endConversation"),sendFeedback:t("sendFeedback"),sendExplanationFeedback:t("sendExplanationFeedback"),uploadAttachment:t("uploadAttachment")}},Pc=e=>e.demo?Oi(async()=>new(await sr()).MockTransport):e.preview?Oi(async()=>{const{PreviewTransport:t}=await sr();return new t(Pi(e),e.strings)}):Pi(e),cr=16e3;class Oc{constructor(t){q(this,"ratio");q(this,"position",0);q(this,"carry",[]);this.ratio=t/cr}process(t){if(this.ratio===1)return t.slice();const n=this.carry.length?Float32Array.from([...this.carry,...t]):t,a=[];let i=this.position;for(;i+this.ratio<=n.length;){const s=Math.floor(i),c=Math.min(n.length,Math.floor(i+this.ratio));let d=0;for(let l=s;l<c;l+=1)d+=n[l]??0;a.push(c>s?d/(c-s):0),i+=this.ratio}const o=Math.floor(i);return this.carry=Array.from(n.subarray(o)),this.position=i-o,Float32Array.from(a)}}const Fc=(e,t=cr)=>{const n=e.reduce((c,d)=>c+d.length,0),a=new ArrayBuffer(44+n*2),i=new DataView(a),o=(c,d)=>{for(let l=0;l<d.length;l+=1)i.setUint8(c+l,d.charCodeAt(l))};o(0,"RIFF"),i.setUint32(4,36+n*2,!0),o(8,"WAVE"),o(12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),o(36,"data"),i.setUint32(40,n*2,!0);let s=44;for(const c of e)for(let d=0;d<c.length;d+=1){const l=Math.max(-1,Math.min(1,c[d]??0));i.setInt16(s,l<0?l*32768:l*32767,!0),s+=2}return new Blob([a],{type:"audio/wav"})},Fi=e=>e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(t=>t.length>1),Uc=(e,t)=>{const n=Fi(e);if(n.length===0||!t.trim())return!1;const a=new Set(Fi(t));return n.filter(i=>a.has(i)).length/n.length>=.7},Ui=e=>{const t=e.replace(/```[\s\S]*?```/g,"").split(`
76
+ `))}}catch{return{event:t}}},Oi=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[];let cr=()=>Promise.resolve().then(()=>Vo);const Fc=e=>{cr=e},Fi=e=>new Rc(e.apiBaseUrl,e.token,e.gifApiKey,e.analyticsContextToken,{agentName:e.agentName,agentAvatarUrl:e.agentAvatarUrl},e.identityToken,e.getIdentityToken,e.chatSurface),Ui=e=>{const t=n=>(...a)=>e().then(i=>i[n].apply(i,a));return{bootstrap:t("bootstrap"),history:t("history"),stream:t("stream"),liveEvents:t("liveEvents"),presence:t("presence"),typing:t("typing"),action:t("action"),speak:t("speak"),transcribe:t("transcribe"),searchGifs:t("searchGifs"),demoSlots:t("demoSlots"),identify:t("identify"),endConversation:t("endConversation"),sendFeedback:t("sendFeedback"),sendExplanationFeedback:t("sendExplanationFeedback"),uploadAttachment:t("uploadAttachment")}},Uc=e=>e.demo?Ui(async()=>new(await cr()).MockTransport):e.preview?Ui(async()=>{const{PreviewTransport:t}=await cr();return new t(Fi(e),e.strings)}):Fi(e),lr=16e3;class Bc{constructor(t){B(this,"ratio");B(this,"position",0);B(this,"carry",[]);this.ratio=t/lr}process(t){if(this.ratio===1)return t.slice();const n=this.carry.length?Float32Array.from([...this.carry,...t]):t,a=[];let i=this.position;for(;i+this.ratio<=n.length;){const s=Math.floor(i),c=Math.min(n.length,Math.floor(i+this.ratio));let u=0;for(let l=s;l<c;l+=1)u+=n[l]??0;a.push(c>s?u/(c-s):0),i+=this.ratio}const o=Math.floor(i);return this.carry=Array.from(n.subarray(o)),this.position=i-o,Float32Array.from(a)}}const qc=(e,t=lr)=>{const n=e.reduce((c,u)=>c+u.length,0),a=new ArrayBuffer(44+n*2),i=new DataView(a),o=(c,u)=>{for(let l=0;l<u.length;l+=1)i.setUint8(c+l,u.charCodeAt(l))};o(0,"RIFF"),i.setUint32(4,36+n*2,!0),o(8,"WAVE"),o(12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),o(36,"data"),i.setUint32(40,n*2,!0);let s=44;for(const c of e)for(let u=0;u<c.length;u+=1){const l=Math.max(-1,Math.min(1,c[u]??0));i.setInt16(s,l<0?l*32768:l*32767,!0),s+=2}return new Blob([a],{type:"audio/wav"})},Bi=e=>e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(t=>t.length>1),Vc=(e,t)=>{const n=Bi(e);if(n.length===0||!t.trim())return!1;const a=new Set(Bi(t));return n.filter(i=>a.has(i)).length/n.length>=.7},qi=e=>{const t=e.replace(/```[\s\S]*?```/g,"").split(`
77
77
  `),n=new Set;for(let a=1;a<t.length;a+=1){const i=t[a]?.trim().replace(/^\|/,"").replace(/\|$/,"");if(!(!t[a-1]?.includes("|")||!i||!i.split("|").every(o=>/^\s*:?-{3,}:?\s*$/.test(o)))){n.add(a-1),n.add(a);for(let o=a+1;o<t.length&&t[o]?.includes("|");o+=1)n.add(o)}}return t.filter((a,i)=>!n.has(i)).join(`
78
- `).trim()},Bc=(e,t)=>{const n=t?.explanation,a=[n?.summary?.trim()||n?.headline?.trim(),n?.businessMeaning?.trim(),...n?.limitations??[]].filter(o=>!!o?.trim()),i=a.length?[...new Set(a)].join(`
79
- `):e;return Ui(i)||(i.trim()?"The detailed results are available in the chat.":"")},Bi=300,qc=()=>{const e=globalThis;if(e.__voiceDebug)return!0;try{return e.localStorage?.getItem("accurix.voiceDebug")==="1"}catch{return!1}};class Vc{constructor(t=()=>Date.now()){q(this,"now");q(this,"entries",[]);q(this,"startedAt");this.now=t,this.startedAt=t(),globalThis.__accurixVoiceLog=()=>this.list()}add(t,n){const a={at:Math.round(this.now()-this.startedAt),event:t,detail:n};this.entries.push(a),this.entries.length>Bi&&this.entries.splice(0,this.entries.length-Bi),qc()&&console.debug(`VOICEDBG ${t} ${n?JSON.stringify(n):""}`)}list(){return this.entries.slice()}}const lr=cr/50,st=20,jc=500,Hc=120,Wc=300,Gc=280,Kc=600,Yc=300,Zc=12e3,Jc=25e3,Xc=300,Qc=2e4,el=60,tl=400,nl=250,dr=8e-4,al=.1,rl=2.8,il=1.8,ol=.006,sl=.004,cl=1.8,ll=1.4,dl=2e3,ul=2e3;class pl{constructor(t){q(this,"options");q(this,"endSilenceMs");q(this,"pending",new Float32Array(0));q(this,"levels",[]);q(this,"framesSinceFloor",0);q(this,"floor",dr*4);q(this,"recentSpeech",[]);q(this,"preroll",[]);q(this,"silentMs",0);q(this,"inputSilent",!1);q(this,"outputActive",!1);q(this,"turns",[]);q(this,"nextTurnId",1);this.options=t,this.endSilenceMs=t.endSilenceMs??ul}get hearing(){return this.current()?.capturing??!1}get processing(){return this.turns.some(t=>!t.capturing&&!t.cancelled)}feed(t){let n=t;this.pending.length&&(n=new Float32Array(this.pending.length+t.length),n.set(this.pending),n.set(t,this.pending.length));let a=0;for(;a+lr<=n.length;)this.frame(n.slice(a,a+lr)),a+=lr;this.pending=n.slice(a)}setOutputActive(t){this.outputActive!==t&&(this.outputActive=t,this.options.log.add("output",{active:t}))}finishTurn(){const t=this.current();t&&(t.capturing?this.endTurn(t,"done"):t.closed||(t.closed=!0,t.endedBy="done",this.options.log.add("turn-done",{turn:t.id})))}reset(t){for(const n of this.turns)n.cancelled=!0;this.turns.length&&this.options.log.add("turns-dropped",{reason:t,count:this.turns.length}),this.turns=[],this.preroll=[],this.recentSpeech=[],this.pending=new Float32Array(0),this.options.onChange()}current(){return this.turns[this.turns.length-1]}frame(t){let n=0,a=0;for(let p=0;p<t.length;p+=1){const m=t[p]??0;n+=m*m,a=Math.max(a,Math.abs(m))}const i=Math.sqrt(n/t.length);this.trackInputSilence(a);const o=this.current();!o?.capturing&&!this.outputActive&&this.trackFloor(i);const s=this.outputActive,c=Math.max(ol,this.floor*rl)*(s?cl:1),d=Math.max(sl,this.floor*il)*(s?ll:1),l=i>=c,u=i>=d;if(!o?.capturing){for(this.preroll.push(t);this.preroll.length*st>jc;)this.preroll.shift();this.recentSpeech.push(l);const p=(s?Kc:Wc)/st;for(;this.recentSpeech.length>p;)this.recentSpeech.shift();const m=this.recentSpeech.filter(Boolean).length*st;m>=(s?Gc:Hc)&&this.beginCapture(m);return}o.chunk.push(t),o.chunkMs+=st,o.durationMs+=st,l&&(o.voicedMs+=st,o.chunkVoicedMs+=st),o.quietMs=u?0:o.quietMs+st,s&&(o.overlappedOutput=!0),o.quietMs>=this.endSilenceMs?this.endTurn(o,"silence"):(o.chunkMs>=Jc||o.chunkMs>=Zc&&o.quietMs>=Xc||o.chunkMs>=Qc&&o.quietMs>=el)&&this.cutChunk(o)}trackFloor(t){if(this.levels.push(t),this.levels.length>nl&&this.levels.shift(),this.framesSinceFloor+=1,this.framesSinceFloor<10&&this.levels.length>10)return;this.framesSinceFloor=0;const n=this.levels.slice().sort((a,i)=>a-i);this.floor=Math.max(dr,n[Math.floor(n.length*al)]??dr)}trackInputSilence(t){this.silentMs=t===0?this.silentMs+st:0;const n=this.silentMs>=dl;n!==this.inputSilent&&(this.inputSilent=n,this.options.log.add("input-silent",{silent:n}),this.options.onInputSilent?.(n))}beginCapture(t){const n=this.current();let a;n&&!n.capturing&&!n.closed?(a=n,a.capturing=!0,this.options.log.add("turn-resumed",{turn:a.id})):(a={id:this.nextTurnId++,capturing:!0,closed:!1,endedBy:"silence",chunk:[],chunkMs:0,chunkVoicedMs:0,quietMs:0,voicedMs:0,durationMs:0,overlappedOutput:this.outputActive,results:[],chunkCount:0,cancelled:!1},this.turns.push(a),this.options.log.add("turn-start",{turn:a.id,overOutput:this.outputActive}),this.options.listener.speechStart?.({turnId:a.id,overlappedOutput:this.outputActive})),a.chunk.push(...this.preroll),a.chunkMs+=this.preroll.length*st,a.durationMs+=this.preroll.length*st,a.voicedMs+=t,a.chunkVoicedMs+=t,a.quietMs=0,this.preroll=[],this.recentSpeech=[],this.options.onChange()}endTurn(t,n){const a=Math.max(0,Math.floor((t.quietMs-tl)/st));if(a>0&&(t.chunk.splice(t.chunk.length-Math.min(a,t.chunk.length)),t.chunkMs=t.chunk.length*st),t.capturing=!1,t.endedBy=n,n==="done"&&(t.closed=!0),this.options.log.add("turn-end",{turn:t.id,by:n,ms:t.durationMs,voicedMs:t.voicedMs}),t.chunkCount===0&&t.voicedMs<Yc){this.turns=this.turns.filter(i=>i!==t),this.options.log.add("turn-noise",{turn:t.id,reason:"too-short"}),this.options.listener.noise?.({id:t.id,reason:"too-short",overlappedOutput:t.overlappedOutput}),this.options.onChange();return}this.cutChunk(t),this.options.onChange(),this.settle()}cutChunk(t){if(t.chunk.length===0)return;const n=t.chunk,a=t.chunkCount;t.chunkCount+=1,t.results[a]=void 0,t.chunk=[];const i=n.length*st,o=t.chunkVoicedMs;if(t.chunkMs=0,t.chunkVoicedMs=0,o===0&&a>0){t.results[a]="";return}this.options.log.add("chunk",{turn:t.id,index:a,ms:i}),this.options.transcribe({audio:Fc(n),mimeType:"audio/wav",durationSeconds:i/1e3,turnId:t.id,chunkIndex:a}).then(s=>(s??"").trim(),()=>null).then(s=>{if(t.cancelled)return;t.results[a]=s,this.options.log.add("chunk-text",{turn:t.id,index:a,chars:s===null?-1:s.length});const c=[];for(const d of t.results){if(d===void 0)break;d&&c.push(d)}c.length&&this.options.listener.partial?.({turnId:t.id,text:c.join(" ")}),this.settle()})}settle(){for(;this.turns.length;){const t=this.turns[0];if(!t||t.capturing||t.results.some(o=>o===void 0))return;this.turns.shift();const n=t.results.filter(o=>typeof o=="string"&&o!==""),a=t.results.every(o=>o===null),i=n.join(" ").replace(/\s+/g," ").trim();if(i)this.options.log.add("turn",{turn:t.id,chars:i.length,by:t.endedBy}),this.options.listener.turn?.({id:t.id,text:i,durationMs:t.durationMs,endedBy:t.endedBy,overlappedOutput:t.overlappedOutput});else{const o=a?"transcribe-failed":"empty-transcript";this.options.log.add("turn-noise",{turn:t.id,reason:o}),this.options.listener.noise?.({id:t.id,reason:o,overlappedOutput:t.overlappedOutput})}this.options.onChange()}}}const fl=2048,hl=[300,1e3,2500],ml=()=>typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof globalThis.AudioContext=="function",gl=e=>{const t=e?.name;return t==="NotAllowedError"||t==="SecurityError"?"permission-denied":t==="NotFoundError"||t==="OverconstrainedError"?"no-device":"error"};class qi{constructor(t){q(this,"options");q(this,"log",new Vc);q(this,"turns");q(this,"mic","off");q(this,"reason");q(this,"muted",!1);q(this,"inputSilent",!1);q(this,"stream",null);q(this,"context",null);q(this,"source",null);q(this,"processor",null);q(this,"sink",null);q(this,"downsampler",null);q(this,"deviceId");q(this,"generation",0);q(this,"recoveryAttempt",0);q(this,"recoveryTimer",null);q(this,"lastSnapshot","");q(this,"groupId");q(this,"onTrackEnded",()=>{this.log.add("track-ended"),this.recover("track-ended")});q(this,"onTrackMuteChange",()=>{const t=this.stream?.getAudioTracks()[0];this.log.add("track-mute-change",{muted:!!t?.muted}),this.refreshMic()});q(this,"onContextState",()=>{const t=this.context?.state;this.log.add("audio-state",{state:t}),(t==="suspended"||t==="interrupted")&&this.context?.resume().catch(()=>{}),this.refreshMic()});q(this,"onDeviceChange",()=>{this.checkDevices()});this.options=t,this.deviceId=t.deviceId,this.turns=new pl({transcribe:t.transcribe,listener:t.listener,log:this.log,endSilenceMs:t.endSilenceMs,onChange:()=>this.publish(),onInputSilent:n=>{this.inputSilent=n,this.publish()}})}get snapshot(){let t=this.mic,n=this.reason;return t==="listening"&&this.inputSilent&&(t="unavailable",n="input-silent"),t==="listening"&&this.turns.hearing&&(t="hearing"),{mic:t,processing:this.turns.processing,reason:t==="unavailable"?n:void 0}}get active(){return this.mic!=="off"}async start(){this.mic==="off"&&(this.log.add("start"),this.mediaDevices()?.addEventListener("devicechange",this.onDeviceChange),await this.open("start"))}stop(t="stopped"){this.mic!=="off"&&(this.log.add("stop",{reason:t}),this.generation+=1,this.clearRecovery(),this.mediaDevices()?.removeEventListener("devicechange",this.onDeviceChange),this.turns.reset(t),this.close(),this.context?.close().catch(()=>{}),this.context=null,this.setMic("off"))}setMuted(t){if(!(this.muted===t||this.mic==="off")){this.muted=t,this.log.add(t?"mute":"unmute");for(const n of this.stream?.getAudioTracks()??[])n.enabled=!t;t?(this.turns.reset("muted"),this.setMic("muted")):this.refreshMic()}}finishTurn(){this.log.add("done-pressed"),this.turns.finishTurn()}setOutputActive(t){this.turns.setOutputActive(t)}async selectDevice(t){t!==this.deviceId&&(this.deviceId=t,this.mic!=="off"&&(this.log.add("device-selected"),this.turns.reset("device-selected"),this.close(),await this.open("device-selected")))}mediaDevices(){return this.options.media?.mediaDevices??(typeof navigator<"u"?navigator.mediaDevices:void 0)}async open(t){const n=++this.generation;this.setMic("starting");const a=this.options.media?.getUserMedia??(ml()?o=>navigator.mediaDevices.getUserMedia(o):null);if(!a){this.unavailable("unsupported");return}let i;try{i=await a({audio:{...this.deviceId?{deviceId:{exact:this.deviceId}}:{},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1}})}catch(o){if(n!==this.generation)return;const s=gl(o);if(this.log.add("mic-open-failed",{why:t,reason:s}),s==="no-device"&&this.deviceId){this.deviceId=void 0,await this.open("default-device");return}this.unavailable(s);return}if(n!==this.generation){i.getTracks().forEach(o=>o.stop());return}try{this.connect(i)}catch(o){this.log.add("audio-setup-failed",{message:String(o?.name??"error")}),i.getTracks().forEach(s=>s.stop()),this.unavailable("error");return}this.recoveryAttempt=0,this.groupId=i.getAudioTracks()[0]?.getSettings?.().groupId,this.log.add("mic-open",{why:t}),this.refreshMic()}connect(t){this.stream=t;for(const a of t.getAudioTracks())a.enabled=!this.muted,a.addEventListener("ended",this.onTrackEnded),a.addEventListener("mute",this.onTrackMuteChange),a.addEventListener("unmute",this.onTrackMuteChange);const n=this.context??this.options.media?.createAudioContext?.()??new globalThis.AudioContext;this.context||(this.context=n,n.addEventListener("statechange",this.onContextState)),n.state==="suspended"&&n.resume().catch(()=>{}),this.downsampler=new Oc(n.sampleRate),this.source=n.createMediaStreamSource(t),this.processor=n.createScriptProcessor(fl,1,1),this.sink=n.createGain(),this.sink.gain.value=0,this.processor.onaudioprocess=a=>{if(this.muted||!this.downsampler)return;const i=this.downsampler.process(a.inputBuffer.getChannelData(0));if(this.turns.feed(i),this.options.listener.level&&i.length){let o=0;for(const s of i)o+=s*s;this.options.listener.level(Math.sqrt(o/i.length))}},this.source.connect(this.processor),this.processor.connect(this.sink),this.sink.connect(n.destination)}close(){this.processor&&(this.processor.onaudioprocess=null),this.source?.disconnect(),this.processor?.disconnect(),this.sink?.disconnect(),this.source=null,this.processor=null,this.sink=null;for(const t of this.stream?.getTracks()??[])t.removeEventListener("ended",this.onTrackEnded),t.removeEventListener("mute",this.onTrackMuteChange),t.removeEventListener("unmute",this.onTrackMuteChange),t.stop();this.stream=null,this.inputSilent=!1}refreshMic(){if(this.mic==="off")return;if(this.muted)return this.setMic("muted");const t=this.stream?.getAudioTracks()[0];if(!t||t.readyState!=="live")return this.unavailable("device-lost");if(t.muted)return this.unavailable("track-muted");if(this.context&&this.context.state!=="running")return this.unavailable("audio-suspended");this.reason=void 0,this.setMic("listening")}unavailable(t){this.reason=t,this.setMic("unavailable")}setMic(t){this.mic!==t&&this.log.add("mic",{state:t,reason:t==="unavailable"?this.reason:void 0}),this.mic=t,this.publish()}publish(){const t=this.snapshot,n=JSON.stringify(t);n!==this.lastSnapshot&&(this.lastSnapshot=n,this.options.listener.state?.(t))}recover(t){if(this.mic==="off"||this.recoveryTimer)return;const n=hl[this.recoveryAttempt];if(this.turns.reset(t),this.close(),n===void 0){this.log.add("mic-recovery-gave-up",{why:t}),this.unavailable("device-lost");return}this.recoveryAttempt+=1,this.unavailable("device-lost"),this.log.add("mic-recovering",{why:t,attempt:this.recoveryAttempt}),this.recoveryTimer=setTimeout(()=>{this.recoveryTimer=null,this.mic!=="off"&&this.open(t)},n)}clearRecovery(){this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,this.recoveryAttempt=0}async checkDevices(){const t=this.stream?.getAudioTracks()[0];if(!t||t.readyState!=="live"){this.log.add("device-change",{live:!1}),this.recover("device-change");return}let n=[];try{n=(await this.mediaDevices()?.enumerateDevices()??[]).filter(s=>s.kind==="audioinput")}catch{return}const a=n.some(s=>!this.groupId||s.groupId===this.groupId),i=n.find(s=>s.deviceId==="default"),o=!this.deviceId&&i!==void 0&&this.groupId!==void 0&&i.groupId!==this.groupId;this.log.add("device-change",{live:!0,ours:a,defaultMoved:o}),(!a||o)&&this.recover("device-change")}}const ur=e=>!!(e?.headline?.trim()||e?.summary?.trim()),bl=(e,t={})=>{const n=e?.explanation??void 0,a=e?.businessAnalysis?.explanation??void 0,i=[t.requested??void 0,n?.source==="ai_grounded"?n:void 0,a,n];for(const o of i)if(o&&ur(o))return o;return t.fallback?.()},xt={eyebrow:"Answer from your data",provenanceAI:"AI-assisted · evidence checked",provenanceGoverned:"Based on current values",comparison:"Comparison",conclusions:"What we can conclude",whyItMatters:"Why it matters",limits:"Important limits",investigate:"Investigate further",evidenceList:"Evidence checked",causes:"Possible causes",causesHint:"Not proven causes",howToCheck:"How to check:",recommendations:"Recommended next steps",watch:"Watch:",outlook:"Outlook",followUps:"Ask a follow-up",sourceNoteAI:"AI-assisted wording, checked against the live values shown here.",sourceNoteGoverned:"Based only on the live values shown here.",evidence:"Evidence",evidenceMetric:"Metric",evidencePeriod:"Period",evidenceTimezone:"Timezone",evidenceFilters:"Filters",evidenceValue:"Value",evidenceStatus:"Status",evidenceSource:"Source",evidenceChecked:"Checked",openSource:"Open source",closeEvidence:"Close evidence details",citationLabel:"Show evidence",sourceCard:"This card",sourceSupportingQuery:"Supporting query",feedbackPrompt:"Was this explanation helpful?",feedbackHelpful:"Helpful explanation",feedbackNotHelpful:"Unhelpful explanation",feedbackReasonsPrompt:"What went wrong? (optional)",feedbackCommentPlaceholder:"Anything else? (optional)",feedbackSubmit:"Send feedback",feedbackThanks:"Thanks for the feedback.",feedbackUndo:"Undo",feedbackError:"Feedback could not be saved. Try again.",notComparable:"Not comparable yet",basicExplanation:"Basic explanation",preparingDetailed:"Preparing a detailed explanation…",detailedReady:"Detailed explanation ready.",detailedUnavailable:"A detailed explanation is not available right now.",detailedRetry:"Try again",region:"Explanation",inProgress:"in progress",expand:"Expand explanation",collapse:"Collapse explanation",reasonWrongNumbers:"Wrong numbers",reasonMissingComparison:"Missing comparison",reasonUnclear:"Unclear",reasonTooLong:"Too long"},Vi=[{id:"wrong_numbers",label:"Wrong numbers"},{id:"missing_comparison",label:"Missing comparison"},{id:"unclear",label:"Unclear"},{id:"too_long",label:"Too long"}],pr=500,vl=e=>e==="ai_grounded"||e==="rag_deterministic_analysis",ji=e=>{switch(e){case"confirmed_zero":return"confirmed 0";case"empty_bucket":case"unconfirmed_zero":return"no records yet";case"missing":return"missing";default:return""}},Hi=e=>{switch(e){case"confirmed_zero":return"confirmed";case"empty_bucket":case"unconfirmed_zero":return"caution";case"missing":return"missing";default:return"neutral"}},xl=e=>{const t=(e??"").trim().toLowerCase().replaceAll("-","_");return t==="low"||t==="low_quality"?"Low-confidence forecast":t==="medium"||t==="directional"?"Directional forecast":t==="high"||t==="validated"||t==="trusted"?"Validated forecast":"Forecast estimate"},Wi=/^\d{4}-\d{2}-\d{2}$/,ga=(e,t,n,a)=>{try{return new Intl.DateTimeFormat(t,a?{...n,timeZone:a}:n).format(e)}catch{return new Intl.DateTimeFormat(t,n).format(e)}},Gi=(e,t)=>ga(e,"en-CA",{year:"numeric",month:"2-digit",day:"2-digit"},t),Ki=(e,t={})=>{const n=e?.trim();if(!n)return"";const a=new Date(n);if(Number.isNaN(a.getTime()))return"";const i={hour:"2-digit",minute:"2-digit",hour12:!1},o=Gi(a,t.timezone)===Gi(t.now??new Date,t.timezone);return ga(a,t.locale,o?i:{...i,month:"short",day:"numeric"},t.timezone)},yl=(e,t={})=>{const n=e.timezone?.trim(),a=Ki(e.checkedAt,{...t,timezone:n});return[n?`Times in ${n}`:"",a?`Checked ${a}`:""].filter(Boolean).join(" · ")},Yi=(e,t,n)=>{const a=e?.trim();if(!a)return"";if(Wi.test(a)){const o=new Date(`${a}T00:00:00Z`);return Number.isNaN(o.getTime())?a:ga(o,t,{day:"numeric",month:"short",year:"numeric"},"UTC")}const i=new Date(a);return Number.isNaN(i.getTime())?a:ga(i,t,{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1},n)},_l=(e,t={})=>{if(!e)return"";const n=e.timezone?.trim()||t.timezone?.trim(),a=Yi(e.start,t.locale,n),i=Yi(e.end,t.locale,n);return a&&i?`${a} – ${i} (end not included)`:a?`From ${a}`:i?`Before ${i}`:""},wl=(e,t,n)=>{if(!e)return{label:"Updated",description:"Source freshness is unavailable.",tone:"neutral"};if(e.status==="current")return{label:"Fresh",description:"Source data is current.",tone:"success"};if(e.status==="no_data")return{label:"No source data",description:"No source data is available for this period or an earlier period.",tone:"neutral"};if(e.status!=="delayed")return{label:"Updated",description:"Source freshness is unavailable.",tone:"neutral"};const a=s=>{if(!s)return"";const c=Wi.test(s)?new Date(`${s}T00:00:00`):new Date(s);return Number.isNaN(c.getTime())?"":new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(c)},i=a(e.dataAsOf),o=a(t);return{label:`${o?`Checked ${o} · `:""}Latest record${i?` ${i}`:""}`,description:`Latest matching record${i?`: ${i}`:" date is unavailable"}. An older record alone does not prove a source delay.`,tone:"neutral"}},Je=(e,t)=>t(String(e??"").replace(/\s+/g," ").trim()).trim(),Zi=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e.toLocaleString(t):"",kl=e=>{const t=[];return e?.liveboardTileId?.trim()&&t.push({kind:"liveboard_tile",id:e.liveboardTileId.trim()}),e?.insightId?.trim()&&t.push({kind:"insight",id:e.insightId.trim()}),e?.queryRunId?.trim()&&t.push({kind:"query_run",id:e.queryRunId.trim()}),t},Sl=(e,t={})=>{const{locale:n}=t,a={...xt,...t.copy},i=t.cleanText??(y=>y),o=e.timezone?.trim()||void 0,s=new Map;for(const y of e.evidenceItems??[])y?.id?.trim()&&!s.has(y.id.trim())&&s.set(y.id.trim(),y);const c=[],d={},l=y=>{const D=y?.trim();if(!D)return;const S=d[D];if(S)return{id:D,index:S.index};const O=s.get(D);if(!O)return;const ue=O.valueStatus,oe=ji(ue)||(ue==="observed"?"observed":""),Fe=O.source?.kind,_e={id:D,index:c.length+1,text:Je(O.text,i),...O.metric?.trim()?{metric:O.metric.trim()}:{},...O.period?.label?.trim()?{periodLabel:O.period.label.trim()}:{},...(()=>{const Te=_l(O.period,{locale:n,timezone:o});return Te?{periodRange:Te}:{}})(),...O.period?.timezone?.trim()||o?{timezone:O.period?.timezone?.trim()||o}:{},...O.filters?.length?{filters:O.filters.map(Te=>Te.trim()).filter(Boolean)}:{},...(()=>{const Te=Zi(O.value,n);return Te?{valueText:Te}:{}})(),...oe?{statusLabel:oe}:{},statusTone:Hi(ue),...O.statusReason?.trim()?{statusReason:Je(O.statusReason,i)}:{},...Fe==="card"?{sourceLabel:xt.sourceCard}:Fe==="supporting_query"?{sourceLabel:xt.sourceSupportingQuery}:{},sourceTargets:kl(O.source),...(()=>{const Te=Ki(O.checkedAt??e.checkedAt,{locale:n,timezone:o,now:t.now});return Te?{checkedText:Te}:{}})()};return _e.filters&&_e.filters.length===0&&delete _e.filters,c.push(_e),d[D]=_e,{id:D,index:_e.index}},u=y=>{const D=new Set,S=[];for(const O of y??[]){const ue=l(O);ue&&!D.has(ue.id)&&(D.add(ue.id),S.push(ue))}return S},p=vl(e.source)||e.level==="detailed",m=Je(e.headline,i)||Je(e.summary,i),f={text:m,citations:u(e.headlineEvidenceIds)},_=Je(e.summary,i),h=_&&_!==m?{text:_,citations:u(e.summaryEvidenceIds)}:void 0;if(!h&&_&&e.summaryEvidenceIds?.length)for(const y of u(e.summaryEvidenceIds))f.citations.some(D=>D.id===y.id)||f.citations.push(y);const I=(e.periods??[]).filter(y=>y?.label?.trim()).map(y=>{const D=y.valueStatus,S=ji(D),O=y.valueText?.trim()||Zi(y.value,n)||(D==="missing"?"—":""),ue=S?y.statusReason?.trim()||s.get(y.evidenceId?.trim()??"")?.statusReason?.trim():"",oe=l(y.evidenceId);return{key:y.evidenceId||`${y.label}-${y.start??""}-${y.end??""}`,label:y.label.trim(),valueText:O,...D?{status:D}:{},statusLabel:S,statusTone:Hi(D),inProgress:!!y.inProgress,current:!!y.current,...ue?{reason:Je(ue,i)}:{},...oe?{citation:oe}:{}}}),x=t.maxConclusions??4,g=(e.evidenceStatements??[]).map(y=>({text:Je(y.text,i),citations:u(y.evidenceIds)})).filter(y=>y.text),T=(g.length>0?g:(e.evidence??[]).map(y=>Je(y,i)).filter(Boolean).map(y=>({text:y,citations:[]}))).filter((y,D,S)=>S.findIndex(O=>O.text===y.text)===D).filter(y=>y.text!==f.text&&y.text!==h?.text).slice(0,x),V=Je(e.businessMeaning,i),P=V?{text:V,citations:u(e.businessMeaningEvidenceIds)}:void 0,ee=[],Z=y=>{y.text&&!ee.some(D=>D.text===y.text)&&ee.push(y)},Y=(e.limitations??[]).map(y=>y.toLowerCase());for(const y of I){const D=Y.some(S=>S.includes(y.label.toLowerCase())&&S.includes("in progress"));y.inProgress&&!D&&Z({kind:"in_progress",text:`${y.label} is still in progress, so its total can still change.`,...y.citation?{citation:y.citation}:{}}),(y.status==="empty_bucket"||y.status==="unconfirmed_zero")&&Z({kind:"no_records",text:`${y.label} has no records yet. This is not a confirmed 0${y.reason?`: ${y.reason.replace(/\.$/,"")}`:""}.`,...y.citation?{citation:y.citation}:{}}),y.status==="missing"&&Z({kind:"missing",text:`${y.label} is missing${y.reason?`: ${y.reason.replace(/\.$/,"")}`:""}.`,...y.citation?{citation:y.citation}:{}})}e.currentPeriodInProgress&&!I.some(y=>y.inProgress)&&Z({kind:"in_progress",text:"The current period is still in progress, so its total can still change."});for(const y of e.missing??[]){if(!y?.label?.trim()||!y.reason?.trim())continue;const D=l(y.evidenceId);Z({kind:"missing",text:$l(y),...D?{citation:D}:{}})}(e.dataFreshness?.status==="delayed"||e.dataFreshness?.status==="no_data")&&Z({kind:"freshness",text:wl(e.dataFreshness,e.checkedAt,n).description});for(const y of e.limitations??[]){const D=Je(y,i);D&&Z({kind:"limitation",text:D})}const z=(e.possibleDrivers??[]).map(y=>({title:Je(y.hypothesis,i),howToCheck:Je(y.howToCheck,i),citations:u(y.evidenceIds)})).filter(y=>y.title).slice(0,t.maxCauses??3),te=(e.recommendations??[]).map(y=>({title:Je(y.action,i),why:Je(y.why,i),...y.successMetric?.trim()?{watch:Je(y.successMetric,i)}:{},citations:u(y.evidenceIds)})).filter(y=>y.title).slice(0,t.maxRecommendations??3),U=Je(e.forecast?.text,i),B=U?{badge:xl(e.forecast?.qualityStatus),text:U,...e.forecast?.limitations?.trim()?{note:Je(e.forecast.limitations,i)}:{}}:void 0,A=(e.followUps??[]).map(y=>Je(y,i)).filter(Boolean).filter((y,D,S)=>S.indexOf(y)===D).slice(0,t.maxFollowUps??4);for(const y of s.keys())l(y);const N=Je(e.conversationalPreface,i);return{...e.explanationId?.trim()?{explanationId:e.explanationId.trim()}:{},ai:p,lead:{eyebrow:a.eyebrow,provenance:p?a.provenanceAI:e.level==="basic"?a.basicExplanation:a.provenanceGoverned,...N?{preface:N}:{},headline:f,...h?{summary:h}:{}},comparison:I,conclusions:T,...P?{businessMeaning:P}:{},limits:ee,checkedLine:yl(e,{locale:n,now:t.now}),investigate:{causes:z,recommendations:te,...B?{outlook:B}:{},followUps:A},hasInvestigate:z.length>0||te.length>0||!!B||A.length>0||c.length>0,evidence:c,evidenceById:d,sourceNote:p?a.sourceNoteAI:a.sourceNoteGoverned}},$l=e=>`${e.label.trim()} could not be established: ${e.reason.trim()}`,Tl=e=>`[${e.index}]`,Cl=(e,t)=>{const n={...xt,...t},a=[];e.metric&&a.push({key:"metric",label:n.evidenceMetric,value:e.metric});const i=[e.periodLabel,e.periodRange].filter(Boolean).join(" · ");i&&a.push({key:"period",label:n.evidencePeriod,value:i}),e.timezone&&a.push({key:"timezone",label:n.evidenceTimezone,value:e.timezone}),e.filters?.length&&a.push({key:"filters",label:n.evidenceFilters,value:e.filters.join("; ")});const o=[e.valueText,e.statusLabel].filter(Boolean).join(" · ");return o&&a.push({key:"value",label:n.evidenceValue,value:o}),e.statusReason&&a.push({key:"reason",label:n.evidenceStatus,value:e.statusReason}),e.sourceLabel&&a.push({key:"source",label:n.evidenceSource,value:e.sourceLabel}),e.checkedText&&a.push({key:"checked",label:n.evidenceChecked,value:e.checkedText}),a},Al=e=>{const t=new Set(Vi.map(i=>i.id)),n=Array.from(e.comment??"").map(i=>{const o=i.charCodeAt(0);return o<32||o>=127&&o<=159?" ":i}).join("").replace(/\s+/g," ").trim(),a=e.rating==="down"?[...new Set(e.reasons??[])].filter(i=>t.has(i)).slice(0,4):[];return{explanationId:e.explanationId,rating:e.rating,...a.length?{reasons:a}:{},...e.rating!=="clear"&&n?{comment:Array.from(n).slice(0,pr).join("")}:{},...e.modelId?{modelId:e.modelId}:{},...typeof e.modelVersion=="number"&&e.modelVersion>0?{modelVersion:e.modelVersion}:{}}},Ml=(e,t)=>{const n=`.${e}-xp`;return`
78
+ `).trim()},Hc=(e,t)=>{const n=t?.explanation,a=[n?.summary?.trim()||n?.headline?.trim(),n?.businessMeaning?.trim(),...n?.limitations??[]].filter(o=>!!o?.trim()),i=a.length?[...new Set(a)].join(`
79
+ `):e;return qi(i)||(i.trim()?"The detailed results are available in the chat.":"")},Vi=300,jc=()=>{const e=globalThis;if(e.__voiceDebug)return!0;try{return e.localStorage?.getItem("accurix.voiceDebug")==="1"}catch{return!1}};class Wc{constructor(t=()=>Date.now()){B(this,"now");B(this,"entries",[]);B(this,"startedAt");this.now=t,this.startedAt=t(),globalThis.__accurixVoiceLog=()=>this.list()}add(t,n){const a={at:Math.round(this.now()-this.startedAt),event:t,detail:n};this.entries.push(a),this.entries.length>Vi&&this.entries.splice(0,this.entries.length-Vi),jc()&&console.debug(`VOICEDBG ${t} ${n?JSON.stringify(n):""}`)}list(){return this.entries.slice()}}const dr=lr/50,st=20,Gc=500,Kc=120,Yc=300,Zc=280,Jc=600,Xc=300,Qc=12e3,el=25e3,tl=300,nl=2e4,al=60,rl=400,il=250,ur=8e-4,ol=.1,sl=2.8,cl=1.8,ll=.006,dl=.004,ul=1.8,pl=1.4,fl=2e3,hl=2e3;class ml{constructor(t){B(this,"options");B(this,"endSilenceMs");B(this,"pending",new Float32Array(0));B(this,"levels",[]);B(this,"framesSinceFloor",0);B(this,"floor",ur*4);B(this,"recentSpeech",[]);B(this,"preroll",[]);B(this,"silentMs",0);B(this,"inputSilent",!1);B(this,"outputActive",!1);B(this,"turns",[]);B(this,"nextTurnId",1);this.options=t,this.endSilenceMs=t.endSilenceMs??hl}get hearing(){return this.current()?.capturing??!1}get processing(){return this.turns.some(t=>!t.capturing&&!t.cancelled)}feed(t){let n=t;this.pending.length&&(n=new Float32Array(this.pending.length+t.length),n.set(this.pending),n.set(t,this.pending.length));let a=0;for(;a+dr<=n.length;)this.frame(n.slice(a,a+dr)),a+=dr;this.pending=n.slice(a)}setOutputActive(t){this.outputActive!==t&&(this.outputActive=t,this.options.log.add("output",{active:t}))}finishTurn(){const t=this.current();t&&(t.capturing?this.endTurn(t,"done"):t.closed||(t.closed=!0,t.endedBy="done",this.options.log.add("turn-done",{turn:t.id})))}reset(t){for(const n of this.turns)n.cancelled=!0;this.turns.length&&this.options.log.add("turns-dropped",{reason:t,count:this.turns.length}),this.turns=[],this.preroll=[],this.recentSpeech=[],this.pending=new Float32Array(0),this.options.onChange()}current(){return this.turns[this.turns.length-1]}frame(t){let n=0,a=0;for(let p=0;p<t.length;p+=1){const h=t[p]??0;n+=h*h,a=Math.max(a,Math.abs(h))}const i=Math.sqrt(n/t.length);this.trackInputSilence(a);const o=this.current();!o?.capturing&&!this.outputActive&&this.trackFloor(i);const s=this.outputActive,c=Math.max(ll,this.floor*sl)*(s?ul:1),u=Math.max(dl,this.floor*cl)*(s?pl:1),l=i>=c,d=i>=u;if(!o?.capturing){for(this.preroll.push(t);this.preroll.length*st>Gc;)this.preroll.shift();this.recentSpeech.push(l);const p=(s?Jc:Yc)/st;for(;this.recentSpeech.length>p;)this.recentSpeech.shift();const h=this.recentSpeech.filter(Boolean).length*st;h>=(s?Zc:Kc)&&this.beginCapture(h);return}o.chunk.push(t),o.chunkMs+=st,o.durationMs+=st,l&&(o.voicedMs+=st,o.chunkVoicedMs+=st),o.quietMs=d?0:o.quietMs+st,s&&(o.overlappedOutput=!0),o.quietMs>=this.endSilenceMs?this.endTurn(o,"silence"):(o.chunkMs>=el||o.chunkMs>=Qc&&o.quietMs>=tl||o.chunkMs>=nl&&o.quietMs>=al)&&this.cutChunk(o)}trackFloor(t){if(this.levels.push(t),this.levels.length>il&&this.levels.shift(),this.framesSinceFloor+=1,this.framesSinceFloor<10&&this.levels.length>10)return;this.framesSinceFloor=0;const n=this.levels.slice().sort((a,i)=>a-i);this.floor=Math.max(ur,n[Math.floor(n.length*ol)]??ur)}trackInputSilence(t){this.silentMs=t===0?this.silentMs+st:0;const n=this.silentMs>=fl;n!==this.inputSilent&&(this.inputSilent=n,this.options.log.add("input-silent",{silent:n}),this.options.onInputSilent?.(n))}beginCapture(t){const n=this.current();let a;n&&!n.capturing&&!n.closed?(a=n,a.capturing=!0,this.options.log.add("turn-resumed",{turn:a.id})):(a={id:this.nextTurnId++,capturing:!0,closed:!1,endedBy:"silence",chunk:[],chunkMs:0,chunkVoicedMs:0,quietMs:0,voicedMs:0,durationMs:0,overlappedOutput:this.outputActive,results:[],chunkCount:0,cancelled:!1},this.turns.push(a),this.options.log.add("turn-start",{turn:a.id,overOutput:this.outputActive}),this.options.listener.speechStart?.({turnId:a.id,overlappedOutput:this.outputActive})),a.chunk.push(...this.preroll),a.chunkMs+=this.preroll.length*st,a.durationMs+=this.preroll.length*st,a.voicedMs+=t,a.chunkVoicedMs+=t,a.quietMs=0,this.preroll=[],this.recentSpeech=[],this.options.onChange()}endTurn(t,n){const a=Math.max(0,Math.floor((t.quietMs-rl)/st));if(a>0&&(t.chunk.splice(t.chunk.length-Math.min(a,t.chunk.length)),t.chunkMs=t.chunk.length*st),t.capturing=!1,t.endedBy=n,n==="done"&&(t.closed=!0),this.options.log.add("turn-end",{turn:t.id,by:n,ms:t.durationMs,voicedMs:t.voicedMs}),t.chunkCount===0&&t.voicedMs<Xc){this.turns=this.turns.filter(i=>i!==t),this.options.log.add("turn-noise",{turn:t.id,reason:"too-short"}),this.options.listener.noise?.({id:t.id,reason:"too-short",overlappedOutput:t.overlappedOutput}),this.options.onChange();return}this.cutChunk(t),this.options.onChange(),this.settle()}cutChunk(t){if(t.chunk.length===0)return;const n=t.chunk,a=t.chunkCount;t.chunkCount+=1,t.results[a]=void 0,t.chunk=[];const i=n.length*st,o=t.chunkVoicedMs;if(t.chunkMs=0,t.chunkVoicedMs=0,o===0&&a>0){t.results[a]="";return}this.options.log.add("chunk",{turn:t.id,index:a,ms:i}),this.options.transcribe({audio:qc(n),mimeType:"audio/wav",durationSeconds:i/1e3,turnId:t.id,chunkIndex:a}).then(s=>(s??"").trim(),()=>null).then(s=>{if(t.cancelled)return;t.results[a]=s,this.options.log.add("chunk-text",{turn:t.id,index:a,chars:s===null?-1:s.length});const c=[];for(const u of t.results){if(u===void 0)break;u&&c.push(u)}c.length&&this.options.listener.partial?.({turnId:t.id,text:c.join(" ")}),this.settle()})}settle(){for(;this.turns.length;){const t=this.turns[0];if(!t||t.capturing||t.results.some(o=>o===void 0))return;this.turns.shift();const n=t.results.filter(o=>typeof o=="string"&&o!==""),a=t.results.every(o=>o===null),i=n.join(" ").replace(/\s+/g," ").trim();if(i)this.options.log.add("turn",{turn:t.id,chars:i.length,by:t.endedBy}),this.options.listener.turn?.({id:t.id,text:i,durationMs:t.durationMs,endedBy:t.endedBy,overlappedOutput:t.overlappedOutput});else{const o=a?"transcribe-failed":"empty-transcript";this.options.log.add("turn-noise",{turn:t.id,reason:o}),this.options.listener.noise?.({id:t.id,reason:o,overlappedOutput:t.overlappedOutput})}this.options.onChange()}}}const gl=2048,bl=[300,1e3,2500],vl=()=>typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof globalThis.AudioContext=="function",xl=e=>{const t=e?.name;return t==="NotAllowedError"||t==="SecurityError"?"permission-denied":t==="NotFoundError"||t==="OverconstrainedError"?"no-device":"error"};class Hi{constructor(t){B(this,"options");B(this,"log",new Wc);B(this,"turns");B(this,"mic","off");B(this,"reason");B(this,"muted",!1);B(this,"inputSilent",!1);B(this,"stream",null);B(this,"context",null);B(this,"source",null);B(this,"processor",null);B(this,"sink",null);B(this,"downsampler",null);B(this,"deviceId");B(this,"generation",0);B(this,"recoveryAttempt",0);B(this,"recoveryTimer",null);B(this,"lastSnapshot","");B(this,"groupId");B(this,"onTrackEnded",()=>{this.log.add("track-ended"),this.recover("track-ended")});B(this,"onTrackMuteChange",()=>{const t=this.stream?.getAudioTracks()[0];this.log.add("track-mute-change",{muted:!!t?.muted}),this.refreshMic()});B(this,"onContextState",()=>{const t=this.context?.state;this.log.add("audio-state",{state:t}),(t==="suspended"||t==="interrupted")&&this.context?.resume().catch(()=>{}),this.refreshMic()});B(this,"onDeviceChange",()=>{this.checkDevices()});this.options=t,this.deviceId=t.deviceId,this.turns=new ml({transcribe:t.transcribe,listener:t.listener,log:this.log,endSilenceMs:t.endSilenceMs,onChange:()=>this.publish(),onInputSilent:n=>{this.inputSilent=n,this.publish()}})}get snapshot(){let t=this.mic,n=this.reason;return t==="listening"&&this.inputSilent&&(t="unavailable",n="input-silent"),t==="listening"&&this.turns.hearing&&(t="hearing"),{mic:t,processing:this.turns.processing,reason:t==="unavailable"?n:void 0}}get active(){return this.mic!=="off"}async start(){this.mic==="off"&&(this.log.add("start"),this.mediaDevices()?.addEventListener("devicechange",this.onDeviceChange),await this.open("start"))}stop(t="stopped"){this.mic!=="off"&&(this.log.add("stop",{reason:t}),this.generation+=1,this.clearRecovery(),this.mediaDevices()?.removeEventListener("devicechange",this.onDeviceChange),this.turns.reset(t),this.close(),this.context?.close().catch(()=>{}),this.context=null,this.setMic("off"))}setMuted(t){if(!(this.muted===t||this.mic==="off")){this.muted=t,this.log.add(t?"mute":"unmute");for(const n of this.stream?.getAudioTracks()??[])n.enabled=!t;t?(this.turns.reset("muted"),this.setMic("muted")):this.refreshMic()}}finishTurn(){this.log.add("done-pressed"),this.turns.finishTurn()}setOutputActive(t){this.turns.setOutputActive(t)}async selectDevice(t){t!==this.deviceId&&(this.deviceId=t,this.mic!=="off"&&(this.log.add("device-selected"),this.turns.reset("device-selected"),this.close(),await this.open("device-selected")))}mediaDevices(){return this.options.media?.mediaDevices??(typeof navigator<"u"?navigator.mediaDevices:void 0)}async open(t){const n=++this.generation;this.setMic("starting");const a=this.options.media?.getUserMedia??(vl()?o=>navigator.mediaDevices.getUserMedia(o):null);if(!a){this.unavailable("unsupported");return}let i;try{i=await a({audio:{...this.deviceId?{deviceId:{exact:this.deviceId}}:{},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1}})}catch(o){if(n!==this.generation)return;const s=xl(o);if(this.log.add("mic-open-failed",{why:t,reason:s}),s==="no-device"&&this.deviceId){this.deviceId=void 0,await this.open("default-device");return}this.unavailable(s);return}if(n!==this.generation){i.getTracks().forEach(o=>o.stop());return}try{this.connect(i)}catch(o){this.log.add("audio-setup-failed",{message:String(o?.name??"error")}),i.getTracks().forEach(s=>s.stop()),this.unavailable("error");return}this.recoveryAttempt=0,this.groupId=i.getAudioTracks()[0]?.getSettings?.().groupId,this.log.add("mic-open",{why:t}),this.refreshMic()}connect(t){this.stream=t;for(const a of t.getAudioTracks())a.enabled=!this.muted,a.addEventListener("ended",this.onTrackEnded),a.addEventListener("mute",this.onTrackMuteChange),a.addEventListener("unmute",this.onTrackMuteChange);const n=this.context??this.options.media?.createAudioContext?.()??new globalThis.AudioContext;this.context||(this.context=n,n.addEventListener("statechange",this.onContextState)),n.state==="suspended"&&n.resume().catch(()=>{}),this.downsampler=new Bc(n.sampleRate),this.source=n.createMediaStreamSource(t),this.processor=n.createScriptProcessor(gl,1,1),this.sink=n.createGain(),this.sink.gain.value=0,this.processor.onaudioprocess=a=>{if(this.muted||!this.downsampler)return;const i=this.downsampler.process(a.inputBuffer.getChannelData(0));if(this.turns.feed(i),this.options.listener.level&&i.length){let o=0;for(const s of i)o+=s*s;this.options.listener.level(Math.sqrt(o/i.length))}},this.source.connect(this.processor),this.processor.connect(this.sink),this.sink.connect(n.destination)}close(){this.processor&&(this.processor.onaudioprocess=null),this.source?.disconnect(),this.processor?.disconnect(),this.sink?.disconnect(),this.source=null,this.processor=null,this.sink=null;for(const t of this.stream?.getTracks()??[])t.removeEventListener("ended",this.onTrackEnded),t.removeEventListener("mute",this.onTrackMuteChange),t.removeEventListener("unmute",this.onTrackMuteChange),t.stop();this.stream=null,this.inputSilent=!1}refreshMic(){if(this.mic==="off")return;if(this.muted)return this.setMic("muted");const t=this.stream?.getAudioTracks()[0];if(!t||t.readyState!=="live")return this.unavailable("device-lost");if(t.muted)return this.unavailable("track-muted");if(this.context&&this.context.state!=="running")return this.unavailable("audio-suspended");this.reason=void 0,this.setMic("listening")}unavailable(t){this.reason=t,this.setMic("unavailable")}setMic(t){this.mic!==t&&this.log.add("mic",{state:t,reason:t==="unavailable"?this.reason:void 0}),this.mic=t,this.publish()}publish(){const t=this.snapshot,n=JSON.stringify(t);n!==this.lastSnapshot&&(this.lastSnapshot=n,this.options.listener.state?.(t))}recover(t){if(this.mic==="off"||this.recoveryTimer)return;const n=bl[this.recoveryAttempt];if(this.turns.reset(t),this.close(),n===void 0){this.log.add("mic-recovery-gave-up",{why:t}),this.unavailable("device-lost");return}this.recoveryAttempt+=1,this.unavailable("device-lost"),this.log.add("mic-recovering",{why:t,attempt:this.recoveryAttempt}),this.recoveryTimer=setTimeout(()=>{this.recoveryTimer=null,this.mic!=="off"&&this.open(t)},n)}clearRecovery(){this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,this.recoveryAttempt=0}async checkDevices(){const t=this.stream?.getAudioTracks()[0];if(!t||t.readyState!=="live"){this.log.add("device-change",{live:!1}),this.recover("device-change");return}let n=[];try{n=(await this.mediaDevices()?.enumerateDevices()??[]).filter(s=>s.kind==="audioinput")}catch{return}const a=n.some(s=>!this.groupId||s.groupId===this.groupId),i=n.find(s=>s.deviceId==="default"),o=!this.deviceId&&i!==void 0&&this.groupId!==void 0&&i.groupId!==this.groupId;this.log.add("device-change",{live:!0,ours:a,defaultMoved:o}),(!a||o)&&this.recover("device-change")}}const pr=e=>!!(e?.headline?.trim()||e?.summary?.trim()),yl=(e,t={})=>{const n=e?.explanation??void 0,a=e?.businessAnalysis?.explanation??void 0,i=[t.requested??void 0,n?.source==="ai_grounded"?n:void 0,a,n];for(const o of i)if(o&&pr(o))return o;return t.fallback?.()},ht={eyebrow:"Answer from your data",provenanceAI:"AI-assisted · evidence checked",provenanceCalculated:"Calculated results",provenanceGoverned:"Based on current values",comparison:"Comparison",conclusions:"What we can conclude",whyItMatters:"Why it matters",limits:"Important limits",investigate:"Investigate further",evidenceList:"Supporting evidence",causes:"Possible causes",causesHint:"Not proven causes",howToCheck:"How to check:",recommendations:"Recommended next steps",watch:"Watch:",outlook:"Outlook",followUps:"Ask a follow-up",sourceNoteAI:"AI-assisted wording, checked against the live values shown here.",sourceNoteCalculated:"AI-assisted wording based on calculated results.",sourceNoteGoverned:"Based only on the live values shown here.",evidence:"Evidence",evidenceMetric:"Metric",evidencePeriod:"Period",evidenceTimezone:"Timezone",evidenceFilters:"Filters",evidenceValue:"Value",evidenceStatus:"Status",evidenceSource:"Source",evidenceChecked:"Checked",openSource:"Open source",closeEvidence:"Close evidence details",citationLabel:"Show evidence",sourceCard:"This card",sourceSupportingQuery:"Supporting query",feedbackPrompt:"Was this explanation helpful?",feedbackHelpful:"Helpful explanation",feedbackNotHelpful:"Unhelpful explanation",feedbackReasonsPrompt:"What went wrong? (optional)",feedbackCommentPlaceholder:"Anything else? (optional)",feedbackSubmit:"Send feedback",feedbackThanks:"Thanks for the feedback.",feedbackUndo:"Undo",feedbackError:"Feedback could not be saved. Try again.",notComparable:"Not comparable yet",basicExplanation:"Basic explanation",preparingDetailed:"Preparing a detailed explanation…",stillWorkingDetailed:"Still working on the detailed explanation…",detailedReady:"Detailed explanation ready.",detailedUnavailable:"A detailed explanation is not available right now.",detailedRetry:"Try again",region:"Explanation",drivers:"What is driving it",driversHint:"Measured association, not proof of cause",anomalies:"Unusual values",supplementaryFindings:"Also in the data",frameworks:"General guidance, not from your data",dataGaps:"Missing data",segment:"Segment:",tasks:"Tasks",inProgress:"in progress",expand:"Expand explanation",collapse:"Collapse explanation",reasonWrongNumbers:"Wrong numbers",reasonMissingComparison:"Missing comparison",reasonUnclear:"Unclear",reasonTooLong:"Too long"},ji=[{id:"wrong_numbers",label:"Wrong numbers"},{id:"missing_comparison",label:"Missing comparison"},{id:"unclear",label:"Unclear"},{id:"too_long",label:"Too long"}],fr=500,Wi=e=>e==="ai_grounded"||e==="rag_deterministic_analysis",_l=(e,t={})=>{const n={...ht,...t};return Wi(e.source)||e.level==="detailed"?e.answerComplete===!0?n.provenanceAI:n.provenanceCalculated:e.level==="basic"?n.basicExplanation:n.provenanceGoverned},Gi=e=>{switch(e){case"confirmed_zero":return"confirmed 0";case"empty_bucket":case"unconfirmed_zero":return"no records yet";case"missing":return"missing";default:return""}},Ki=e=>{switch(e){case"confirmed_zero":return"confirmed";case"empty_bucket":case"unconfirmed_zero":return"caution";case"missing":return"missing";default:return"neutral"}},wl=e=>{const t=(e??"").trim().toLowerCase().replaceAll("-","_");return t==="low"||t==="low_quality"?"Low-confidence forecast":t==="medium"||t==="directional"?"Directional forecast":t==="high"||t==="validated"||t==="trusted"?"Validated forecast":"Forecast estimate"},Yi=/^\d{4}-\d{2}-\d{2}$/,ba=(e,t,n,a)=>{try{return new Intl.DateTimeFormat(t,a?{...n,timeZone:a}:n).format(e)}catch{return new Intl.DateTimeFormat(t,n).format(e)}},Zi=(e,t)=>ba(e,"en-CA",{year:"numeric",month:"2-digit",day:"2-digit"},t),Ji=(e,t={})=>{const n=e?.trim();if(!n)return"";const a=new Date(n);if(Number.isNaN(a.getTime()))return"";const i={hour:"2-digit",minute:"2-digit",hour12:!1},o=Zi(a,t.timezone)===Zi(t.now??new Date,t.timezone);return ba(a,t.locale,o?i:{...i,month:"short",day:"numeric"},t.timezone)},kl=(e,t={})=>{const n=e.timezone?.trim(),a=Ji(e.checkedAt,{...t,timezone:n});return[n?`Times in ${n}`:"",a?`Checked ${a}`:""].filter(Boolean).join(" · ")},Xi=(e,t,n)=>{const a=e?.trim();if(!a)return"";if(Yi.test(a)){const o=new Date(`${a}T00:00:00Z`);return Number.isNaN(o.getTime())?a:ba(o,t,{day:"numeric",month:"short",year:"numeric"},"UTC")}const i=new Date(a);return Number.isNaN(i.getTime())?a:ba(i,t,{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1},n)},Sl=(e,t={})=>{if(!e)return"";const n=e.timezone?.trim()||t.timezone?.trim(),a=Xi(e.start,t.locale,n),i=Xi(e.end,t.locale,n);return a&&i?`${a} – ${i} (end not included)`:a?`From ${a}`:i?`Before ${i}`:""},$l=(e,t,n)=>{if(!e)return{label:"Updated",description:"Source freshness is unavailable.",tone:"neutral"};if(e.status==="current")return{label:"Fresh",description:"Source data is current.",tone:"success"};if(e.status==="no_data")return{label:"No source data",description:"No source data is available for this period or an earlier period.",tone:"neutral"};if(e.status!=="delayed")return{label:"Updated",description:"Source freshness is unavailable.",tone:"neutral"};const a=s=>{if(!s)return"";const c=Yi.test(s)?new Date(`${s}T00:00:00`):new Date(s);return Number.isNaN(c.getTime())?"":new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(c)},i=a(e.dataAsOf),o=a(t);return{label:`${o?`Checked ${o} · `:""}Latest record${i?` ${i}`:""}`,description:`Latest matching record${i?`: ${i}`:" date is unavailable"}. An older record alone does not prove a source delay.`,tone:"neutral"}},Pe=(e,t)=>t(String(e??"").replace(/\s+/g," ").trim()).trim(),Qi=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e.toLocaleString(t):"",Tl=e=>{const t=[];return e?.liveboardTileId?.trim()&&t.push({kind:"liveboard_tile",id:e.liveboardTileId.trim()}),e?.insightId?.trim()&&t.push({kind:"insight",id:e.insightId.trim()}),e?.queryRunId?.trim()&&t.push({kind:"query_run",id:e.queryRunId.trim()}),t},Cl=["summary","headline","in summary","in short","overall","in brief","key finding","answer"],eo=e=>{const t=String(e??"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim(),n=Cl.find(a=>t.startsWith(`${a} `));return n?t.slice(n.length+1):t},zn=(e,t)=>{const n=eo(e),a=eo(t);return!n||!a?!1:n===a||n.startsWith(`${a} `)||a.startsWith(`${n} `)},Ml=(e,t={})=>{const{locale:n}=t,a={...ht,...t.copy},i=t.cleanText??(y=>y),o=e.timezone?.trim()||void 0,s=new Map;for(const y of e.evidenceItems??[])y?.id?.trim()&&!s.has(y.id.trim())&&s.set(y.id.trim(),y);const c=[],u={},l=y=>{const V=y?.trim();if(!V)return;const we=u[V];if(we)return{id:V,index:we.index};const oe=s.get(V);if(!oe)return;const _e=oe.valueStatus,he=Gi(_e)||(_e==="observed"?"observed":""),Ge=oe.source?.kind,ke={id:V,index:c.length+1,text:Pe(oe.text,i),...oe.metric?.trim()?{metric:oe.metric.trim()}:{},...oe.period?.label?.trim()?{periodLabel:oe.period.label.trim()}:{},...(()=>{const K=Sl(oe.period,{locale:n,timezone:o});return K?{periodRange:K}:{}})(),...oe.period?.timezone?.trim()||o?{timezone:oe.period?.timezone?.trim()||o}:{},...oe.filters?.length?{filters:oe.filters.map(K=>K.trim()).filter(Boolean)}:{},...(()=>{const K=Qi(oe.value,n);return K?{valueText:K}:{}})(),...he?{statusLabel:he}:{},statusTone:Ki(_e),...oe.statusReason?.trim()?{statusReason:Pe(oe.statusReason,i)}:{},...Ge==="card"?{sourceLabel:ht.sourceCard}:Ge==="supporting_query"?{sourceLabel:ht.sourceSupportingQuery}:{},sourceTargets:Tl(oe.source),...(()=>{const K=Ji(oe.checkedAt??e.checkedAt,{locale:n,timezone:o,now:t.now});return K?{checkedText:K}:{}})()};return ke.filters&&ke.filters.length===0&&delete ke.filters,c.push(ke),u[V]=ke,{id:V,index:ke.index}},d=y=>{const V=new Set,we=[];for(const oe of y??[]){const _e=l(oe);_e&&!V.has(_e.id)&&(V.add(_e.id),we.push(_e))}return we},p=Wi(e.source)||e.level==="detailed",h=Pe(e.headline,i)||Pe(e.summary,i),f={text:h,citations:d(e.headlineEvidenceIds)},_=Pe(e.summary,i),x=_&&!zn(_,h)?{text:_,citations:d(e.summaryEvidenceIds)}:void 0;if(!x&&_&&e.summaryEvidenceIds?.length)for(const y of d(e.summaryEvidenceIds))f.citations.some(V=>V.id===y.id)||f.citations.push(y);const w=(e.periods??[]).filter(y=>y?.label?.trim()).map(y=>{const V=y.valueStatus,we=Gi(V),oe=y.valueText?.trim()||Qi(y.value,n)||(V==="missing"?"—":""),_e=we?y.statusReason?.trim()||s.get(y.evidenceId?.trim()??"")?.statusReason?.trim():"",he=l(y.evidenceId);return{key:y.evidenceId||`${y.label}-${y.start??""}-${y.end??""}`,label:y.label.trim(),valueText:oe,...V?{status:V}:{},statusLabel:we,statusTone:Ki(V),inProgress:!!y.inProgress,current:!!y.current,..._e?{reason:Pe(_e,i)}:{},...he?{citation:he}:{}}}),v=t.maxConclusions??4,m=(e.evidenceStatements??[]).map(y=>({text:Pe(y.text,i),citations:d(y.evidenceIds)})).filter(y=>y.text),T=(m.length>0?m:(e.evidence??[]).map(y=>Pe(y,i)).filter(Boolean).map(y=>({text:y,citations:[]}))).filter((y,V,we)=>we.findIndex(oe=>zn(oe.text,y.text))===V).filter(y=>!zn(y.text,f.text)&&!(x&&zn(y.text,x.text))).slice(0,v),P=[f.text,x?.text??"",...T.map(y=>y.text)],O=y=>!!y&&!P.some(V=>zn(V,y)),re=[];for(const y of e.drivers??[]){const V=Pe(y?.text,i);O(V)&&(re.push({text:V,basis:y.basis?.trim()||"other",citations:d(y.evidenceIds)}),P.push(V))}const J=[];for(const y of e.anomalies??[]){const V=Pe(y?.text,i);O(V)&&(J.push({text:V,citations:d(y.evidenceIds)}),P.push(V))}const G=[];for(const y of e.supplementaryFindings??[]){const V=Pe(y,i);O(V)&&(G.push(V),P.push(V))}const N=(e.dataGaps??[]).map(y=>({concept:Pe(y?.concept,i),text:Pe(y?.text,i)})).filter(y=>y.text),se=(e.frameworks??[]).map(y=>({name:Pe(y?.name,i),guidance:Pe(y?.guidance,i),fields:(y?.fieldMapping??[]).filter(V=>V.status==="available"&&V.field?.trim()).map(V=>`${V.concept.trim()} → ${String(V.field).trim()}`),missing:(y?.fieldMapping??[]).filter(V=>V.status==="missing"&&V.concept?.trim()).map(V=>V.concept.trim())})).filter(y=>y.guidance).slice(0,3),q=Pe(e.businessMeaning,i),F=q?{text:q,citations:d(e.businessMeaningEvidenceIds)}:void 0,C=[],I=y=>{y.text&&!C.some(V=>V.text===y.text)&&C.push(y)},ce=(e.limitations??[]).map(y=>y.toLowerCase());for(const y of w){const V=ce.some(we=>we.includes(y.label.toLowerCase())&&we.includes("in progress"));y.inProgress&&!V&&I({kind:"in_progress",text:`${y.label} is still in progress, so its total can still change.`,...y.citation?{citation:y.citation}:{}}),(y.status==="empty_bucket"||y.status==="unconfirmed_zero")&&I({kind:"no_records",text:`${y.label} has no records yet. This is not a confirmed 0${y.reason?`: ${y.reason.replace(/\.$/,"")}`:""}.`,...y.citation?{citation:y.citation}:{}}),y.status==="missing"&&I({kind:"missing",text:`${y.label} is missing${y.reason?`: ${y.reason.replace(/\.$/,"")}`:""}.`,...y.citation?{citation:y.citation}:{}})}e.currentPeriodInProgress&&!w.some(y=>y.inProgress)&&I({kind:"in_progress",text:"The current period is still in progress, so its total can still change."});for(const y of e.missing??[]){if(!y?.label?.trim()||!y.reason?.trim())continue;const V=l(y.evidenceId);I({kind:"missing",text:Al(y),...V?{citation:V}:{}})}(e.dataFreshness?.status==="delayed"||e.dataFreshness?.status==="no_data")&&I({kind:"freshness",text:$l(e.dataFreshness,e.checkedAt,n).description});for(const y of e.limitations??[]){const V=Pe(y,i);V&&I({kind:"limitation",text:V})}const te=(e.possibleDrivers??[]).map(y=>({title:Pe(y.hypothesis,i),howToCheck:Pe(y.howToCheck,i),citations:d(y.evidenceIds)})).filter(y=>y.title).slice(0,t.maxCauses??3),ue=(e.recommendations??[]).map(y=>({title:Pe(y.action,i),why:Pe(y.why,i),...y.successMetric?.trim()?{watch:Pe(y.successMetric,i)}:{},...y.segment?.trim()?{segment:Pe(y.segment,i)}:{},citations:d(y.evidenceIds)})).filter(y=>y.title).slice(0,t.maxRecommendations??3),le=Pe(e.forecast?.text,i),z=le?{badge:wl(e.forecast?.qualityStatus),text:le,...e.forecast?.limitations?.trim()?{note:Pe(e.forecast.limitations,i)}:{}}:void 0,ne=(e.followUps??[]).map(y=>Pe(y,i)).filter(Boolean).filter((y,V,we)=>we.indexOf(y)===V).slice(0,t.maxFollowUps??4);for(const y of s.keys())l(y);const He=Pe(e.conversationalPreface,i);return{...e.explanationId?.trim()?{explanationId:e.explanationId.trim()}:{},ai:p,lead:{eyebrow:a.eyebrow,provenance:_l(e,a),...He?{preface:He}:{},headline:f,...x?{summary:x}:{}},comparison:w,conclusions:T,...F?{businessMeaning:F}:{},drivers:re,anomalies:J,supplementaryFindings:G,dataGaps:N,limits:C,checkedLine:kl(e,{locale:n,now:t.now}),investigate:{causes:te,recommendations:ue,...z?{outlook:z}:{},followUps:ne,frameworks:se},hasInvestigate:te.length>0||ue.length>0||!!z||ne.length>0||se.length>0||c.length>0,evidence:c,evidenceById:u,sourceNote:p?e.answerComplete===!0?a.sourceNoteAI:a.sourceNoteCalculated:a.sourceNoteGoverned}},Al=e=>`${e.label.trim()} could not be established: ${e.reason.trim()}`,Il=e=>`[${e.index}]`,El=(e,t)=>{const n={...ht,...t},a=[];e.metric&&a.push({key:"metric",label:n.evidenceMetric,value:e.metric});const i=[e.periodLabel,e.periodRange].filter(Boolean).join(" · ");i&&a.push({key:"period",label:n.evidencePeriod,value:i}),e.timezone&&a.push({key:"timezone",label:n.evidenceTimezone,value:e.timezone}),e.filters?.length&&a.push({key:"filters",label:n.evidenceFilters,value:e.filters.join("; ")});const o=[e.valueText,e.statusLabel].filter(Boolean).join(" · ");return o&&a.push({key:"value",label:n.evidenceValue,value:o}),e.statusReason&&a.push({key:"reason",label:n.evidenceStatus,value:e.statusReason}),e.sourceLabel&&a.push({key:"source",label:n.evidenceSource,value:e.sourceLabel}),e.checkedText&&a.push({key:"checked",label:n.evidenceChecked,value:e.checkedText}),a},zl=e=>{const t=new Set(ji.map(i=>i.id)),n=Array.from(e.comment??"").map(i=>{const o=i.charCodeAt(0);return o<32||o>=127&&o<=159?" ":i}).join("").replace(/\s+/g," ").trim(),a=e.rating==="down"?[...new Set(e.reasons??[])].filter(i=>t.has(i)).slice(0,4):[];return{explanationId:e.explanationId,rating:e.rating,...a.length?{reasons:a}:{},...e.rating!=="clear"&&n?{comment:Array.from(n).slice(0,fr).join("")}:{},...e.modelId?{modelId:e.modelId}:{},...typeof e.modelVersion=="number"&&e.modelVersion>0?{modelVersion:e.modelVersion}:{}}},Nl=(e,t)=>{const n=`.${e}-xp`;return`
80
80
  ${n}{display:grid;gap:12px;color:${t.text};font-size:13px;line-height:1.55;min-width:0}
81
81
  ${n} h3,${n} h4,${n} p,${n} ul,${n} ol,${n} dl,${n} dd{margin:0}
82
82
  ${n} ul,${n} ol{padding:0;list-style:none}
@@ -160,16 +160,16 @@ ${n}__reason[aria-pressed="true"]{border-color:${t.accent};background:color-mix(
160
160
  ${n}__comment{width:100%;box-sizing:border-box;min-height:56px;resize:vertical;border:1px solid ${t.border};border-radius:8px;background:${t.surface};color:${t.text};font:inherit;font-size:12px;padding:8px}
161
161
  ${n}__feedback-note{color:${t.muted};font-size:12px}
162
162
  ${n}__feedback-error{color:${t.danger};font-size:12px}
163
- `};class Il{constructor(t,n,a,i={}){q(this,"explanationId");q(this,"submit");q(this,"onChange");q(this,"context");q(this,"state",{phase:"idle",reasons:[],comment:""});this.explanationId=t,this.submit=n,this.onChange=a,this.context=i}set(t){this.state={...this.state,...t},this.onChange(this.state)}async save(t,n){const a=this.state;this.set({phase:"saving",error:void 0});try{await this.submit(Al({explanationId:this.explanationId,...this.context,...t})),this.set({...n,error:void 0})}catch{this.set({phase:a.phase==="details"?"details":"error",rating:a.rating,error:xt.feedbackError})}}vote(t){return this.state.phase==="saving"?Promise.resolve():this.save({rating:t},t==="up"?{phase:"done",rating:t,reasons:[],comment:""}:{phase:"details",rating:t})}toggleReason(t){const n=this.state.reasons.includes(t)?this.state.reasons.filter(a=>a!==t):[...this.state.reasons,t];this.set({reasons:n})}setComment(t){this.set({comment:Array.from(t).slice(0,pr).join("")})}send(){return this.state.phase==="saving"?Promise.resolve():this.save({rating:"down",reasons:this.state.reasons,comment:this.state.comment},{phase:"done",rating:"down"})}undo(){return this.state.phase==="saving"?Promise.resolve():this.save({rating:"clear"},{phase:"idle",rating:void 0,reasons:[],comment:""})}}const Ji={delaysMs:[1e3,2e3,4e3],capMs:45e3},fr=e=>e==="pending"||e==="ready"||e==="failed"?e:"not_requested",El=e=>fr(e?.aiExplanation?.status);class zl{constructor(t,n,a,i={}){q(this,"transport");q(this,"onChange");q(this,"state");q(this,"handle");q(this,"disposed",!1);q(this,"generation",0);q(this,"attempt",0);q(this,"startedAt",0);q(this,"delays");q(this,"capMs");q(this,"now");q(this,"schedule");q(this,"cancelTimer");q(this,"isVisible");q(this,"onSettled");q(this,"inFlight",null);q(this,"pausedAt",null);q(this,"onVisibilityChange",()=>{this.disposed||this.pausedAt===null||!this.isVisible()||(this.startedAt+=this.now()-this.pausedAt,this.pausedAt=null,this.queue())});this.transport=n,this.onChange=a,this.delays=i.delaysMs?.length?i.delaysMs:Ji.delaysMs,this.capMs=i.capMs??Ji.capMs,this.now=i.now??(()=>Date.now()),this.schedule=i.schedule??((c,d)=>setTimeout(c,d)),this.cancelTimer=i.cancel??(c=>clearTimeout(c)),this.isVisible=i.isVisible??(()=>typeof document>"u"||document.visibilityState!=="hidden"),this.onSettled=i.onSettled;const o=El(t),s=o==="pending"&&!n?"not_requested":o;this.state={status:s,explanation:t,retryAvailable:s==="failed"&&this.canRetry(t.aiExplanation?.retryAvailable),retrying:!1,announcement:""}}get explanationId(){return this.state.explanation.aiExplanation?.explanationId||this.state.explanation.explanationId||""}canRetry(t){return!!this.transport?.retry&&t!==!1}set(t){if(this.disposed)return;const n=this.state.status;this.state={...this.state,...t},this.onChange(this.state);const a=this.state.status;a!==n&&(a==="ready"||a==="failed"||a==="not_requested")&&this.onSettled?.(a)}start(){this.state.status!=="pending"||!this.explanationId||(this.disposed=!1,this.startedAt=this.now(),this.attempt=0,typeof document<"u"&&document.addEventListener("visibilitychange",this.onVisibilityChange),this.queue())}queue(){if(this.disposed)return;if(!this.isVisible()){this.pausedAt??(this.pausedAt=this.now());return}const t=this.now()-this.startedAt;if(t>=this.capMs){this.fail(!0);return}const n=this.delays[Math.min(this.attempt,this.delays.length-1)]??4e3;this.attempt+=1;const a=this.generation;this.handle=this.schedule(()=>{this.pollOnce(a)},Math.min(n,Math.max(0,this.capMs-t)))}async pollOnce(t){if(this.disposed||t!==this.generation||!this.transport)return;if(!this.isVisible()){this.pausedAt??(this.pausedAt=this.now());return}const n=new AbortController;this.inFlight=n;try{const a=await this.transport.poll(this.explanationId,n.signal);if(this.disposed||t!==this.generation)return;this.apply(a)}catch{if(this.disposed||t!==this.generation)return;this.queue()}finally{this.inFlight===n&&(this.inFlight=null)}}apply(t){const n=fr(t.status);if(this.applyBasicUpdate(t,n),n==="ready"&&t.explanation&&ur(t.explanation)){this.set({status:"ready",explanation:t.explanation,retryAvailable:!1,retrying:!1,announcement:xt.detailedReady});return}if(n==="pending"){this.state.status!=="pending"&&this.set({status:"pending",retrying:!1,announcement:""}),this.queue();return}if(n==="not_requested"){this.set({status:"not_requested",retryAvailable:!1,retrying:!1,announcement:""});return}this.fail(this.canRetry(t.retryAvailable))}applyBasicUpdate(t,n){const a=t.basic;if(!a||n==="ready"||this.state.status==="ready"||!ur(a))return;const i=this.state.explanation;a.headline===i.headline&&a.summary===i.summary||this.set({explanation:{...a,explanationId:i.explanationId??a.explanationId,aiExplanation:i.aiExplanation,level:i.level}})}fail(t){this.generation+=1,this.set({status:"failed",retryAvailable:t&&this.canRetry(!0),retrying:!1,announcement:xt.detailedUnavailable})}async retry(){if(!this.transport?.retry||this.state.retrying||this.state.status==="ready")return;const t=this.explanationId;if(!t)return;this.generation+=1;const n=this.generation;this.set({retrying:!0,announcement:""});try{const a=await this.transport.retry(t);if(this.disposed||n!==this.generation)return;if(fr(a.status)==="pending"){this.set({status:"pending",retrying:!1,retryAvailable:!1,announcement:xt.preparingDetailed}),this.startedAt=this.now(),this.attempt=0,this.queue();return}this.apply(a)}catch{if(this.disposed||n!==this.generation)return;this.set({status:"failed",retrying:!1,retryAvailable:!1,announcement:xt.detailedUnavailable})}}dispose(){this.disposed=!0,this.generation+=1,this.inFlight?.abort(),this.inFlight=null,this.handle!==void 0&&this.cancelTimer(this.handle),typeof document<"u"&&document.removeEventListener("visibilitychange",this.onVisibilityChange)}}const Xi=Ha(xt),zn=()=>Ga(Xi),Nl=(e,t)=>{const n=R(t);n.current=t;const a=R(()=>{}),i=e.aiExplanation?.explanationId??e.explanationId??"",o=e.aiExplanation?.status==="pending"?"pending":"settled",s=Be(()=>{const u=n.current,p=u?{poll:(m,f)=>n.current.poll(m,f),...u.retry?{retry:(m,f)=>n.current.retry(m,f)}:{}}:void 0;return new zl(e,p,m=>a.current(m),{onSettled:m=>n.current?.settled?.(i,m)})},[i,o,!!t]),[c,d]=$(s.state);return X(()=>(a.current=d,d(s.state),s.start(),()=>s.dispose()),[s]),[c.status==="ready"?c:{...c,explanation:e},s]},Rl=({prefix:e,state:t,onRetry:n})=>{const a=zn();return r("div",{class:`${e}-xp__ai`,"data-ai-status":t.status,children:[t.status==="pending"?r("p",{class:`${e}-xp__ai-note`,children:a.preparingDetailed}):null,t.status==="failed"?r("p",{class:`${e}-xp__ai-note`,children:[a.detailedUnavailable,t.retryAvailable?r("button",{type:"button",class:`${e}-xp__ai-retry`,disabled:t.retrying,onClick:n,children:a.detailedRetry}):null]}):null,r("span",{class:`${e}-xp__sr`,role:"status","aria-live":"polite",children:t.announcement})]})},Ll=({citations:e,step:t,prefix:n,active:a,onToggle:i,evidenceById:o})=>{const s=zn();return e.length===0?null:r(se,{children:e.map(c=>{const d=a?.id===c.id&&a.step===t;return r("button",{type:"button",class:`${n}-xp__cite`,"data-evidence-id":c.id,"aria-expanded":d,"aria-label":`${s.citationLabel} ${c.index}: ${o[c.id]?.text??""}`.trim(),onClick:l=>i(c.id,t,l.currentTarget),children:Tl(c).slice(1,-1)},c.id)})})},Dl=(e,t)=>e.sourceTargets.find(n=>t?t(n):!0),Pl=({evidence:e,prefix:t,onClose:n,onOpenSource:a,canOpenSource:i})=>{const o=zn(),s=R(null);X(()=>{s.current?.focus()},[e.id]);const c=a?Dl(e,i):void 0;return r("div",{ref:s,class:`${t}-xp__evidence-panel`,role:"region",tabIndex:-1,"aria-label":`${o.evidence} ${e.index}`,"data-testid":"analytics-explanation-evidence",onKeyDown:d=>{d.key==="Escape"&&(d.stopPropagation(),n())},children:[r("div",{class:`${t}-xp__evidence-head`,children:[r("p",{class:`${t}-xp__evidence-text`,children:["[",e.index,"] ",e.text]}),r("button",{type:"button",class:`${t}-xp__close`,"aria-label":o.closeEvidence,onClick:n,children:"×"})]}),r("dl",{class:`${t}-xp__evidence-rows`,children:Cl(e,o).map(d=>r("div",{style:{display:"contents"},"data-row":d.key,children:[r("dt",{children:d.label}),r("dd",{children:d.value})]},d.key))}),c&&a?r("div",{class:`${t}-xp__evidence-actions`,children:r("button",{type:"button",class:`${t}-xp__button`,onClick:()=>a(c,e),children:o.openSource})}):null]})},Qi=({down:e})=>r("svg",{viewBox:"0 0 24 24",width:"15",height:"15",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false",style:e?{transform:"scaleY(-1)"}:void 0,children:r("path",{d:"M7 10v11H3V10h4Zm0 0 4-7a2 2 0 0 1 2 2v4h6a2 2 0 0 1 2 2.3l-1.2 7A2 2 0 0 1 17.8 21H7"})}),Ol=(e,t,n)=>t==="wrong_numbers"?e.reasonWrongNumbers:t==="missing_comparison"?e.reasonMissingComparison:t==="unclear"?e.reasonUnclear:t==="too_long"?e.reasonTooLong:n,Fl=({prefix:e,explanationId:t,submit:n,context:a})=>{const i=zn(),[o,s]=$({phase:"idle",reasons:[],comment:""}),c=Be(()=>new Il(t,n,s,a),[t]),d=o.phase==="saving";return r("div",{class:`${e}-xp__feedback`,"data-testid":"analytics-explanation-feedback",children:[o.phase==="done"?r("div",{class:`${e}-xp__feedback-row`,role:"status",children:[r("span",{class:`${e}-xp__feedback-note`,children:i.feedbackThanks}),r("button",{type:"button",class:`${e}-xp__button`,onClick:()=>{c.undo()},children:i.feedbackUndo})]}):r("div",{class:`${e}-xp__feedback-row`,children:[r("span",{class:`${e}-xp__feedback-label`,children:i.feedbackPrompt}),r("button",{type:"button",class:`${e}-xp__vote`,"aria-label":i.feedbackHelpful,"aria-pressed":o.rating==="up",disabled:d,onClick:()=>{c.vote("up")},children:r(Qi,{down:!1})}),r("button",{type:"button",class:`${e}-xp__vote`,"aria-label":i.feedbackNotHelpful,"aria-pressed":o.rating==="down",disabled:d,onClick:()=>{c.vote("down")},children:r(Qi,{down:!0})})]}),o.phase==="details"||d&&o.rating==="down"?r("form",{class:`${e}-xp__feedback-form`,onSubmit:l=>{l.preventDefault(),c.send()},children:[r("fieldset",{class:`${e}-xp__reasons`,children:[r("legend",{children:i.feedbackReasonsPrompt}),Vi.map(l=>r("button",{type:"button",class:`${e}-xp__reason`,"aria-pressed":o.reasons.includes(l.id),onClick:()=>c.toggleReason(l.id),children:Ol(i,l.id,l.label)},l.id))]}),r("textarea",{class:`${e}-xp__comment`,"aria-label":i.feedbackCommentPlaceholder,placeholder:i.feedbackCommentPlaceholder,maxLength:pr,value:o.comment,onInput:l=>c.setComment(l.currentTarget.value)}),r("div",{class:`${e}-xp__feedback-row`,children:r("button",{type:"submit",class:`${e}-xp__button is-primary`,disabled:d,children:i.feedbackSubmit})})]}):null,o.error?r("p",{class:`${e}-xp__feedback-error`,role:"alert",children:o.error}):null]})},eo=({aiTransport:e,...t})=>{const[n,a]=Nl(t.explanation,e),i=Ul(t.explanation),o=Be(()=>({...xt,...t.copy}),[t.copy]);return r(Xi.Provider,{value:o,children:r(Bl,{...t,explanation:n.explanation,aiStatus:i?r(Rl,{prefix:t.classPrefix,state:n,onRetry:()=>{a.retry()}}):null})})},Ul=e=>!!(e.aiExplanation&&e.aiExplanation.status!=="not_requested"),Bl=({explanation:e,aiStatus:t,classPrefix:n,showLead:a=!0,investigateOpen:i=!1,onFollowUp:o,onOpenSource:s,canOpenSource:c,onFeedback:d,feedbackContext:l,onExpand:u,onCollapse:p,expanded:m=!1,...f})=>{const _=zn(),h=R(null),I=R(null),x=R(!1),g=()=>{const A=h.current,N=A?.getRootNode(),y=N&&"activeElement"in N?N.activeElement:null;return!!(A&&y&&A.contains(y))},T=Be(()=>(x.current=g(),Sl(e,{...f,copy:_})),[e,f.locale,f.cleanText,_]),[V,P]=$(),ee=R(null);Sn(()=>{!V||T.evidenceById[V.id]&&h.current?.querySelector('[data-testid="analytics-explanation-evidence"]')||(P(void 0),x.current&&!g()&&(I.current??h.current)?.focus())},[T]);const Z=(A,N,y)=>{ee.current=y,P(D=>D?.id===A&&D.step===N?void 0:{id:A,step:N})},Y=()=>{P(void 0);const A=ee.current;A?.isConnected?A.focus():(I.current??h.current)?.focus()},z=(A,N)=>r(Ll,{citations:A,step:N,prefix:n,active:V,onToggle:Z,evidenceById:T.evidenceById}),te=A=>{if(!V||V.step!==A)return null;const N=T.evidenceById[V.id];return N?r(Pl,{evidence:N,prefix:n,onClose:Y,onOpenSource:s,canOpenSource:c}):null},U=(A,N)=>r(se,{children:[A.text,z(A.citations,N)]}),{investigate:B}=T;return r("section",{ref:h,class:`${n}-xp${m?" is-expanded":""}${u||p?" has-expand":""}`,"data-testid":"analytics-explanation","aria-label":_.region,tabIndex:-1,children:[m&&p?r("button",{type:"button",class:`${n}-xp__expand`,"aria-label":_.collapse,title:_.collapse,onClick:p,children:"×"}):u?r("button",{type:"button",class:`${n}-xp__expand`,"aria-label":_.expand,title:_.expand,"data-testid":"analytics-explanation-expand",onClick:u,children:"⤢"}):null,a?r("div",{class:`${n}-xp__lead`,"data-step":"lead",children:[T.lead.preface?r("p",{class:`${n}-xp__preface`,children:T.lead.preface}):null,r("div",{class:`${n}-xp__meta`,children:[r("span",{class:`${n}-xp__eyebrow`,children:T.lead.eyebrow}),r("span",{class:`${n}-xp__provenance`,children:T.lead.provenance})]}),r("h3",{class:`${n}-xp__headline`,ref:I,tabIndex:-1,children:U(T.lead.headline,"lead")}),T.lead.summary?r("p",{class:`${n}-xp__summary`,children:U(T.lead.summary,"lead")}):null,te("lead")]}):null,t,T.comparison.length>0?r("section",{class:`${n}-xp__step`,"data-step":"comparison",children:[r("h4",{class:`${n}-xp__title`,children:_.comparison}),r("ul",{class:`${n}-xp__periods`,children:T.comparison.map(A=>r("li",{class:`${n}-xp__period`,"data-status":A.status??"observed",children:[r("span",{class:`${n}-xp__period-label`,children:A.label}),A.valueText?r("span",{class:`${n}-xp__period-value`,children:A.valueText}):null,A.statusLabel?r("span",{class:`${n}-xp__chip is-${A.statusTone}`,children:A.statusLabel}):null,A.inProgress?r("span",{class:`${n}-xp__chip is-progress`,children:_.inProgress}):null,A.citation?z([A.citation],"comparison"):null,A.reason?r("small",{class:`${n}-xp__period-reason`,children:A.reason}):null]},A.key))}),te("comparison")]}):null,T.conclusions.length>0||T.businessMeaning?r("section",{class:`${n}-xp__step`,"data-step":"conclusions",children:[r("h4",{class:`${n}-xp__title`,children:_.conclusions}),T.conclusions.length>0?r("ul",{class:`${n}-xp__list`,children:T.conclusions.map(A=>r("li",{children:U(A,"conclusions")},A.text))}):null,T.businessMeaning?r("p",{class:`${n}-xp__meaning`,children:[r("strong",{children:[_.whyItMatters,": "]}),U(T.businessMeaning,"conclusions")]}):null,te("conclusions")]}):null,T.limits.length>0?r("section",{class:`${n}-xp__step`,"data-step":"limits",children:[r("h4",{class:`${n}-xp__title`,children:_.limits}),r("ul",{class:`${n}-xp__list ${n}-xp__limits`,children:T.limits.map(A=>r("li",{"data-kind":A.kind,children:[A.text,A.citation?z([A.citation],"limits"):null]},A.text))}),te("limits")]}):null,T.checkedLine?r("p",{class:`${n}-xp__checked`,"data-step":"checked",children:T.checkedLine}):null,T.hasInvestigate?r("details",{class:`${n}-xp__investigate`,"data-step":"investigate",open:i,children:[r("summary",{children:_.investigate}),r("div",{class:`${n}-xp__investigate-body`,children:[B.causes.length>0?r("div",{class:`${n}-xp__group`,children:[r("div",{class:`${n}-xp__group-head`,children:[r("h4",{class:`${n}-xp__title`,children:_.causes}),r("span",{class:`${n}-xp__hint`,children:_.causesHint})]}),B.causes.map(A=>r("article",{class:`${n}-xp__card`,children:[r("p",{class:`${n}-xp__card-title`,children:[A.title,z(A.citations,"investigate")]}),A.howToCheck?r("p",{class:`${n}-xp__card-body`,children:[_.howToCheck," ",A.howToCheck]}):null]},A.title))]}):null,B.recommendations.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:_.recommendations}),B.recommendations.map(A=>r("article",{class:`${n}-xp__card`,children:[r("p",{class:`${n}-xp__card-title`,children:[A.title,z(A.citations,"investigate")]}),A.why?r("p",{class:`${n}-xp__card-body`,children:A.why}):null,A.watch?r("p",{class:`${n}-xp__card-body`,children:[_.watch," ",A.watch]}):null]},A.title))]}):null,B.outlook?r("div",{class:`${n}-xp__group`,children:[r("div",{class:`${n}-xp__group-head`,children:[r("h4",{class:`${n}-xp__title`,children:_.outlook}),r("span",{class:`${n}-xp__hint`,children:B.outlook.badge})]}),r("p",{class:`${n}-xp__card-body`,children:B.outlook.text}),B.outlook.note?r("p",{class:`${n}-xp__card-body`,children:B.outlook.note}):null]}):null,o&&B.followUps.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:_.followUps}),r("div",{class:`${n}-xp__questions`,children:B.followUps.map(A=>r("button",{type:"button",class:`${n}-xp__question`,onClick:()=>o(A),children:A},A))})]}):null,T.evidence.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:_.evidenceList}),r("ul",{class:`${n}-xp__list`,children:T.evidence.map(A=>r("li",{children:[A.text,z([{id:A.id,index:A.index}],"investigate")]},A.id))})]}):null,te("investigate")]})]}):null,r("p",{class:`${n}-xp__source`,children:T.sourceNote}),d&&T.explanationId?r(Fl,{prefix:n,explanationId:T.explanationId,submit:d,context:l}):null]})},ql=[{name:"Smileys",emojis:["😀","😃","😄","😁","😅","😂","🤣","😊","😇","🙂","🙃","😉","😌","😍","🥰","😘","😋","😛","😜","🤪","🤗","🤭","🤔","🤐","😐","😶","😏","🙄","😴","🥳","😎","🤓","🥺","😢","😭","😤","😠","🤯","😬","😱","🤩","🥱"]},{name:"Gestures",emojis:["👍","👎","👌","🤌","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","👇","✋","🖐️","👋","🤝","🙏","💪","👏","🙌","👐","🤲","🫶"]},{name:"Hearts & symbols",emojis:["❤️","🧡","💛","💚","💙","💜","🖤","🤍","💔","❣️","💕","💖","💘","💝","✨","⭐","🌟","💫","🔥","🎉","🎊","✅","❌","⚡","💯","🚀"]},{name:"Animals & nature",emojis:["🐶","🐱","🦊","🐻","🐼","🐨","🦁","🐮","🐸","🐵","🐧","🦄","🐝","🦋","🐢","🐬","🌷","🌸","🌹","🌻","🌳","🍀"]},{name:"Food & drink",emojis:["🍎","🍌","🍉","🍓","🍒","🥑","🍔","🍟","🍕","🌮","🍿","🍩","🍪","🎂","☕","🍵","🍺","🥂","🍷"]},{name:"Objects & travel",emojis:["🚀","✈️","🚗","🏠","📦","📱","💻","⌚","📷","💡","🔑","🎁","📌","✏️","📝","📞","📧","💰","📈","⏰","🔔","🎯","🏆","🎮","🎵","💬","👀"]}],ba={"contact-support":{title:"Contact support",submit:"Request support",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"},{key:"subject",label:"Subject",kind:"text",required:!0},{key:"message",label:"Message",kind:"textarea",required:!0,placeholder:"Describe what you need help with."}]},inquiry:{title:"Leave a message",submit:"Send message",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"},{key:"message",label:"Message",kind:"textarea",required:!0,placeholder:"How can we help?"}]},contact:{title:"Share your details",submit:"Save",fields:[{key:"name",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"email",label:"Email",kind:"email",required:!0,identity:"email"},{key:"phone",label:"Phone",kind:"tel",required:!0,identity:"phone"}]},"book-demo":{title:"Book a demo",submit:"Request demo",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"},{key:"preferredAt",label:"Preferred time",kind:"text",placeholder:"e.g. Thursday 3pm"},{key:"notes",label:"Notes",kind:"textarea",placeholder:"Anything we should know?"}]},"request-callback":{title:"Request a callback",submit:"Request callback",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorPhone",label:"Phone number",kind:"tel",required:!0,identity:"phone"},{key:"topic",label:"Topic",kind:"text",placeholder:"What should we call about?"}]},"schedule-callback":{title:"Schedule a callback",submit:"Schedule callback",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorPhone",label:"Phone number",kind:"tel",required:!0,identity:"phone"},{key:"topic",label:"Topic",kind:"text",placeholder:"What should we call about?"}]},"subscribe-newsletter":{title:"Subscribe",submit:"Subscribe",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"}]}},hr={openChat:"Open chat",closeChat:"Close chat",closeHistory:"Close conversation history",unreadMessage:"1 unread message",unreadMessages:"{count} unread messages",muteSounds:"Mute sounds",unmuteSounds:"Unmute sounds",statusOnline:"Online · replies instantly",statusOffline:"Away · leave a message",liveSupport:"Live support",reconnectSupport:"Reconnect to support",reconnectPrompt:"I can bring a teammate back into this chat.",waitingForTeam:"AI helping · team notified",assistantName:"Assistant",chatName:"Chat",welcomeLabel:"{name} welcome",welcomeEyebrow:"Ready when you are",welcomePrompt:"Ask a question, leave a message, or book a demo.",agentTyping:"{name} is typing…",expandedAnalyticsResult:"Expanded analytics result",privacyAndData:"Privacy and local data",muteMicrophone:"Mute microphone",unmuteMicrophone:"Unmute microphone",chooseMicrophone:"Choose microphone",defaultMicrophone:"Default microphone",microphone:"Microphone",talkNow:"Talk now",expandView:"Expand view",exitExpandedView:"Exit expanded view",minimizeVoiceChat:"Minimize voice chat",endVoiceChat:"End voice chat",restoreVoiceChat:"Restore voice chat",reopenVoiceChat:"Reopen voice chat with {name}",voiceConnecting:"Connecting…",voiceListening:"Listening…",voiceHearing:"Hearing you…",voiceUnavailable:"Can’t hear you — check your microphone.",voiceProcessing:"Transcribing…",voiceSpeaking:"Speaking…",voiceNoise:"No clear speech heard. Move closer to the mic and try again.",voiceMisunderstood:"Could not transcribe that. Please try again or type your message.",voiceDenied:"Microphone unavailable. Allow access or type your message.",composerPlaceholder:"Type your message…",send:"Send message",emoji:"Emoji",gifs:"GIFs",attachFile:"Attach a file",recordVoice:"Record a voice message",stopRecording:"Stop recording",actionTestMode:"Test mode",stop:"Stop",copy:"Copy",copied:"Copied",retry:"Retry",clearChat:"Clear conversation",clearChatConfirm:"Clear this conversation?",clearChatConfirmBody:"This clears the messages on this device and starts a fresh chat.",clearConfirmCta:"Clear chat",endChat:"End conversation",endChatConfirm:"End this conversation?",endChatConfirmBody:"You won't be able to send more messages in this chat, but you can start a new one anytime.",endConfirmCta:"End conversation",conversationEnded:"This conversation has ended.",startNewChat:"Start a new conversation",pastConversations:"Past conversations",viewingPast:"Viewing a past conversation (read-only)",backToChat:"Back to current chat",historyEnded:"ended",feedbackHelpful:"Helpful",feedbackNotHelpful:"Not helpful",feedbackAnswerPrompt:"Was this answer helpful?",feedbackThanks:"Thanks for the feedback",csatPrompt:"How was this chat?",feedbackCommentPlaceholder:"What went wrong? (optional)",feedbackSend:"Send",cancel:"Cancel",newMessages:"New messages",poweredBy:"Powered by",searchGifs:"Search GIFs…",searchingGifs:"Searching…",noGifs:"No GIFs found",assistantTyping:"Assistant is typing",emptyReply:"Sorry, I couldn't generate a reply.",errorGeneric:"Something went wrong reaching the assistant. Please try again.",errorRateLimit:"You’re sending messages a little fast — give it a second and try again.",resultExpired:"This result is not stored on this device. Ask again to see it.",attaching:"Reading file…",attachTooLarge:"That file is too large (max 5 MB).",attachFailed:"Could not attach that file. Check its type and try again.",attachPreviewTitle:"Preview of {name}",attachOpen:"Preview {name}",attachDownload:"Download",attachPreviewClose:"Close preview",attachPreviewLoading:"Loading file…",attachPreviewFailed:"This file can’t be shown right now. It may have expired.",attachPreviewUnsupported:"This file can’t be previewed here. Download it to open it.",attachAnalysisFailed:"Saved for the team; AI could not read it.",removeAttachment:"Remove attachment",attachLimit:"You can attach up to {count} files to one message.",attachedFiles:"Attached files",removeAttachmentNamed:"Remove {name}",dropFileHere:"Drop the file here",clearDeviceData:"Clear conversations from this device",clearDeviceDataBody:"This removes locally stored conversations and visitor details from this browser. It cannot be undone.",clearDeviceDataCta:"Clear this device",handoffTitle:"Want our team to follow up?",handoffName:"Name (optional)",handoffEmail:"Your email",handoffNotify:"Notify the team",sending:"Sending…",handoffShared:"I’ve shared this with our team — they’ll get back to you at {email}.",formThanks:"Thanks! We’ll be in touch.",caseReference:"Reference: {reference}",formError:"Something went wrong — please try again.",actionContactOptions:"Contact options",actionGetInTouch:"Get in touch",actionMore:"+{count} more",actionNeedHelp:"Need help?",actionChoose:"Choose what you want to do",actionFooter:"We’ll ask for your full name and the best email or phone so the team can reach you.",actionCategorySupport:"Support",actionCategorySales:"Talk to sales",actionCategoryMarketing:"Stay in touch",actionClose:"Close",actionAs:"as {identity}",bookingPickTime:"What time works best?",bookingPickDay:"Pick a day",bookingPickTimeLabel:"Pick a time",bookingDuration:"{count}-minute demo",bookingCallbackDuration:"{count}-minute callback",bookingTimezone:"Times shown in {timezone}",bookingSchedulerFallback:"the scheduler",bookingCheckingAvailability:"Checking calendar availability…",bookingNoSlots:"No available times were found in this booking window.",bookingAvailabilityUnavailable:"Calendar availability is temporarily unavailable. Please try again shortly.",bookingEarlierToday:"Earlier today",bookingCalendarBusy:"Busy on the calendar",bookingAlreadyBooked:"Already booked",bookingNotOffered:"Not offered by the calendar",bookingRequested:"Demo requested for {when}. The team will follow up.",bookingVerificationPending:"We received your request for {when}, but could not verify the calendar booking. The team will check it. Please do not book this time again.",bookingCallbackRequested:"Callback requested for {when}.",bookingCallbackConfirmed:"Your callback is scheduled for {when}.",bookingConfirmed:"Your demo is booked for {when}.",bookingSlotTaken:"That time was just taken — please pick another.",bookingViaProvider:"Pick a time that works for you on {provider}.",bookingOpenScheduler:"Open the scheduler",bookingLinkOpened:"Opening the scheduler — pick a time that suits you. 📅",bookingScheduled:"Your demo is booked. Your booking details are saved in this chat.",bookingBackToChat:"Back to chat",bookingOpenNewTab:"Open in new tab",bookingCloseScheduler:"Close scheduler",bookingLoadingScheduler:"Loading scheduler…",bookingMeetingLink:"Meeting link",bookingManageLink:"Manage booking",bookingCheckingDetails:"Getting your meeting link…",bookingDetailsUnavailable:"We could not verify the booking details yet. Try checking again here; please do not book the same time twice.",bookingUnverifiedLink:"View unverified calendar record",bookingRetryDetails:"Retry",previewReply:"👋 This is a preview — replies here are samples. Publish the widget on your site to chat with the live AI.",previewActionNote:"Preview — nothing was actually sent. This works for real once you publish.",previewBanner:"Preview — sample replies, no AI"},qe=(e,t)=>e.replace(/\{(\w+)\}/g,(n,a)=>t[a]??""),Nn=(e,t,n)=>!t||e.includes(t)?e:`${e} ${qe(n.caseReference,{reference:t})}`,Vl=e=>e?{...hr,...e}:hr,to=Ha(hr),jl=to.Provider,no=Ha(void 0),Hl=no.Provider,mr=()=>Ga(no),Wl=new Set(["ar","he","iw","fa","ur","ps","sd","ug","yi","dv","ckb"]),Gl=(e,t)=>{if(t==="ltr"||t==="rtl")return t;const n=(e??"").trim().toLowerCase().split(/[-_]/)[0]??"";return Wl.has(n)?"rtl":"ltr"},ct=()=>Ga(to),nn=[["AF","Afghanistan","93"],["AL","Albania","355"],["DZ","Algeria","213"],["AS","American Samoa","1684"],["AD","Andorra","376"],["AO","Angola","244"],["AI","Anguilla","1264"],["AG","Antigua and Barbuda","1268"],["AR","Argentina","54"],["AM","Armenia","374"],["AW","Aruba","297"],["AU","Australia","61"],["AT","Austria","43"],["AZ","Azerbaijan","994"],["BS","Bahamas","1242"],["BH","Bahrain","973"],["BD","Bangladesh","880"],["BB","Barbados","1246"],["BY","Belarus","375"],["BE","Belgium","32"],["BZ","Belize","501"],["BJ","Benin","229"],["BM","Bermuda","1441"],["BT","Bhutan","975"],["BO","Bolivia","591"],["BA","Bosnia and Herzegovina","387"],["BW","Botswana","267"],["BR","Brazil","55"],["BN","Brunei","673"],["BG","Bulgaria","359"],["BF","Burkina Faso","226"],["BI","Burundi","257"],["CV","Cabo Verde","238"],["KH","Cambodia","855"],["CM","Cameroon","237"],["CA","Canada","1"],["KY","Cayman Islands","1345"],["CF","Central African Republic","236"],["TD","Chad","235"],["CL","Chile","56"],["CN","China","86"],["CO","Colombia","57"],["KM","Comoros","269"],["CG","Congo","242"],["CD","Congo, Democratic Republic","243"],["CK","Cook Islands","682"],["CR","Costa Rica","506"],["CI","Cote d'Ivoire","225"],["HR","Croatia","385"],["CU","Cuba","53"],["CW","Curacao","599"],["CY","Cyprus","357"],["CZ","Czechia","420"],["DK","Denmark","45"],["DJ","Djibouti","253"],["DM","Dominica","1767"],["DO","Dominican Republic","1809"],["EC","Ecuador","593"],["EG","Egypt","20"],["SV","El Salvador","503"],["GQ","Equatorial Guinea","240"],["ER","Eritrea","291"],["EE","Estonia","372"],["SZ","Eswatini","268"],["ET","Ethiopia","251"],["FO","Faroe Islands","298"],["FJ","Fiji","679"],["FI","Finland","358"],["FR","France","33"],["GF","French Guiana","594"],["PF","French Polynesia","689"],["GA","Gabon","241"],["GM","Gambia","220"],["GE","Georgia","995"],["DE","Germany","49"],["GH","Ghana","233"],["GI","Gibraltar","350"],["GR","Greece","30"],["GL","Greenland","299"],["GD","Grenada","1473"],["GP","Guadeloupe","590"],["GU","Guam","1671"],["GT","Guatemala","502"],["GG","Guernsey","44"],["GN","Guinea","224"],["GW","Guinea-Bissau","245"],["GY","Guyana","592"],["HT","Haiti","509"],["HN","Honduras","504"],["HK","Hong Kong","852"],["HU","Hungary","36"],["IS","Iceland","354"],["IN","India","91"],["ID","Indonesia","62"],["IR","Iran","98"],["IQ","Iraq","964"],["IE","Ireland","353"],["IM","Isle of Man","44"],["IL","Israel","972"],["IT","Italy","39"],["JM","Jamaica","1876"],["JP","Japan","81"],["JE","Jersey","44"],["JO","Jordan","962"],["KZ","Kazakhstan","7"],["KE","Kenya","254"],["KI","Kiribati","686"],["XK","Kosovo","383"],["KW","Kuwait","965"],["KG","Kyrgyzstan","996"],["LA","Laos","856"],["LV","Latvia","371"],["LB","Lebanon","961"],["LS","Lesotho","266"],["LR","Liberia","231"],["LY","Libya","218"],["LI","Liechtenstein","423"],["LT","Lithuania","370"],["LU","Luxembourg","352"],["MO","Macao","853"],["MG","Madagascar","261"],["MW","Malawi","265"],["MY","Malaysia","60"],["MV","Maldives","960"],["ML","Mali","223"],["MT","Malta","356"],["MH","Marshall Islands","692"],["MQ","Martinique","596"],["MR","Mauritania","222"],["MU","Mauritius","230"],["MX","Mexico","52"],["FM","Micronesia","691"],["MD","Moldova","373"],["MC","Monaco","377"],["MN","Mongolia","976"],["ME","Montenegro","382"],["MS","Montserrat","1664"],["MA","Morocco","212"],["MZ","Mozambique","258"],["MM","Myanmar","95"],["NA","Namibia","264"],["NR","Nauru","674"],["NP","Nepal","977"],["NL","Netherlands","31"],["NC","New Caledonia","687"],["NZ","New Zealand","64"],["NI","Nicaragua","505"],["NE","Niger","227"],["NG","Nigeria","234"],["NU","Niue","683"],["KP","North Korea","850"],["MK","North Macedonia","389"],["MP","Northern Mariana Islands","1670"],["NO","Norway","47"],["OM","Oman","968"],["PK","Pakistan","92"],["PW","Palau","680"],["PS","Palestine","970"],["PA","Panama","507"],["PG","Papua New Guinea","675"],["PY","Paraguay","595"],["PE","Peru","51"],["PH","Philippines","63"],["PL","Poland","48"],["PT","Portugal","351"],["PR","Puerto Rico","1787"],["QA","Qatar","974"],["RE","Reunion","262"],["RO","Romania","40"],["RU","Russia","7"],["RW","Rwanda","250"],["KN","Saint Kitts and Nevis","1869"],["LC","Saint Lucia","1758"],["VC","Saint Vincent and the Grenadines","1784"],["WS","Samoa","685"],["SM","San Marino","378"],["ST","Sao Tome and Principe","239"],["SA","Saudi Arabia","966"],["SN","Senegal","221"],["RS","Serbia","381"],["SC","Seychelles","248"],["SL","Sierra Leone","232"],["SG","Singapore","65"],["SK","Slovakia","421"],["SI","Slovenia","386"],["SB","Solomon Islands","677"],["SO","Somalia","252"],["ZA","South Africa","27"],["KR","South Korea","82"],["SS","South Sudan","211"],["ES","Spain","34"],["LK","Sri Lanka","94"],["SD","Sudan","249"],["SR","Suriname","597"],["SE","Sweden","46"],["CH","Switzerland","41"],["SY","Syria","963"],["TW","Taiwan","886"],["TJ","Tajikistan","992"],["TZ","Tanzania","255"],["TH","Thailand","66"],["TL","Timor-Leste","670"],["TG","Togo","228"],["TO","Tonga","676"],["TT","Trinidad and Tobago","1868"],["TN","Tunisia","216"],["TR","Turkey","90"],["TM","Turkmenistan","993"],["TC","Turks and Caicos Islands","1649"],["TV","Tuvalu","688"],["UG","Uganda","256"],["UA","Ukraine","380"],["AE","United Arab Emirates","971"],["GB","United Kingdom","44"],["US","United States","1"],["UY","Uruguay","598"],["UZ","Uzbekistan","998"],["VU","Vanuatu","678"],["VA","Vatican City","39"],["VE","Venezuela","58"],["VN","Vietnam","84"],["VG","Virgin Islands, British","1284"],["VI","Virgin Islands, U.S.","1340"],["YE","Yemen","967"],["ZM","Zambia","260"],["ZW","Zimbabwe","263"]].map(([e,t,n])=>({iso:e,name:t,dial:n})),ao=e=>[...e.toUpperCase()].map(t=>String.fromCodePoint(127397+t.charCodeAt(0))).join(""),Kl=()=>{let e="";try{if(Intl.DateTimeFormat().resolvedOptions().timeZone==="Africa/Lagos"&&(e="NG"),!e){const t=navigator.languages?.[0]||navigator.language;e=new Intl.Locale(t).region||""}}catch{e=""}return nn.find(t=>t.iso===e)??nn.find(t=>t.iso==="US")},Yl=e=>{const t=Kl(),n=e?.trim()??"";if(!n.startsWith("+"))return{country:t,national:n.replace(/\D/g,"")};const a=n.replace(/\D/g,""),i=[...nn].sort((o,s)=>s.dial.length-o.dial.length).find(o=>a.startsWith(o.dial))??t;return{country:i,national:a.slice(i.dial.length)}},ro=(e,t)=>{const n=t.replace(/\D/g,"").replace(/^0+/,"");return n?`+${e.dial}${n}`:""},Zl=e=>{const t=e.replace(/\D/g,"");return e.startsWith("+")&&t.length>=8&&t.length<=15},$e=(e,t)=>r("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",...t,children:e}),Jl=e=>r("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...e,children:r("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M5 3.25h14A3.75 3.75 0 0 1 22.75 7v6A3.75 3.75 0 0 1 19 16.75h-7.19l-4.26 3.84A.75.75 0 0 1 6.25 20v-3.32A3.75 3.75 0 0 1 2.25 13V7A3.75 3.75 0 0 1 6 3.25Zm3 7.75a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Zm4 0a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Zm4 0a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Z"})}),pn=e=>$e(r("path",{d:"m6 9 6 6 6-6"}),e),Xl=e=>$e(r(se,{children:[r("path",{d:"m22 2-7 20-4-9-9-4Z"}),r("path",{d:"M22 2 11 13"})]}),e),Rn=e=>$e(r(se,{children:[r("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),r("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),r("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),e),Ql=e=>$e(r(se,{children:[r("path",{d:"M9 9v1a3 3 0 0 0 4.24 2.73"}),r("path",{d:"M15 5.5V5a3 3 0 0 0-5.94-.6"}),r("path",{d:"M19 10v2a7 7 0 0 1-9.9 6.36"}),r("path",{d:"M5 10v2a6.98 6.98 0 0 0 1.11 3.79"}),r("line",{x1:"12",y1:"19",x2:"12",y2:"22"}),r("line",{x1:"2",y1:"2",x2:"22",y2:"22"})]}),e),Ln=e=>$e(r(se,{children:[r("path",{d:"M15 3h6v6"}),r("path",{d:"M10 14 21 3"}),r("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]}),e),ed=e=>$e(r(se,{children:[r("rect",{x:"3",y:"4",width:"18",height:"18",rx:"2"}),r("line",{x1:"16",y1:"2",x2:"16",y2:"6"}),r("line",{x1:"8",y1:"2",x2:"8",y2:"6"}),r("line",{x1:"3",y1:"10",x2:"21",y2:"10"})]}),e),gr=e=>$e(r(se,{children:[r("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),r("path",{d:"m22 7-10 5L2 7"})]}),e),td=e=>$e(r("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z"}),e),io=e=>$e(r(se,{children:[r("path",{d:"M4 14v-2a8 8 0 0 1 16 0v2"}),r("path",{d:"M18 19h-2"}),r("rect",{x:"3",y:"13",width:"4",height:"6",rx:"2"}),r("rect",{x:"17",y:"13",width:"4",height:"6",rx:"2"})]}),e),nd=e=>$e(r(se,{children:[r("path",{d:"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4Z"}),r("path",{d:"M8 9h8M8 13h5"})]}),e),ad=e=>$e(r(se,{children:[r("path",{d:"M3 4h18M4 4v12h16V4M12 16v5M8 21h8"}),r("path",{d:"m8 12 2.5-2.5 2 2L16 8"})]}),e),rd=e=>$e(r(se,{children:[r("path",{d:"M15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6"}),r("path",{d:"M3 9h12M7 2v4M12 2v4"}),r("circle",{cx:"17",cy:"17",r:"4"}),r("path",{d:"M17 15v2l1.5 1"})]}),e),id=e=>$e(r(se,{children:[r("path",{d:"M4 4h16v16H5a3 3 0 0 1-3-3V6"}),r("path",{d:"M8 8h8M8 12h8M8 16h5"})]}),e),od=e=>$e(r(se,{children:[r("circle",{cx:"12",cy:"12",r:"9"}),r("path",{d:"M8.5 14.5a4 4 0 0 0 7 0"}),r("line",{x1:"9",y1:"9.5",x2:"9.01",y2:"9.5"}),r("line",{x1:"15",y1:"9.5",x2:"15.01",y2:"9.5"})]}),e),Dn=e=>$e(r(se,{children:[r("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),e),sd=e=>$e(r(se,{children:[r("path",{d:"M11 5 6 9H2v6h4l5 4z"}),r("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),r("path",{d:"M19 5a9 9 0 0 1 0 14"})]}),e),cd=e=>$e(r(se,{children:[r("path",{d:"M11 5 6 9H2v6h4l5 4z"}),r("line",{x1:"22",y1:"9",x2:"16",y2:"15"}),r("line",{x1:"16",y1:"9",x2:"22",y2:"15"})]}),e),fn=e=>$e(r("path",{d:"M20 6 9 17l-5-5"}),e),ld=e=>$e(r(se,{children:[r("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),r("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),e),dd=e=>$e(r(se,{children:[r("path",{d:"M1 4v6h6"}),r("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"})]}),e),ud=e=>$e(r("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"}),e),va=e=>$e(r("path",{d:"M21.44 11.05 12.25 20.24a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"}),e),br=e=>$e(r(se,{children:[r("path",{d:"M18.36 6.64a9 9 0 1 1-12.73 0"}),r("line",{x1:"12",y1:"2",x2:"12",y2:"12"})]}),e),pd=e=>$e(r(se,{children:[r("circle",{cx:"12",cy:"12",r:"9"}),r("path",{d:"M12 7v5l3 2"})]}),e),oo=e=>$e(r(se,{children:[r("path",{d:"M7 10v12"}),r("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),e),so=e=>$e(r(se,{children:[r("path",{d:"M17 14V2"}),r("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),e),fd=e=>$e(r(se,{children:[r("path",{d:"M15 3h6v6"}),r("path",{d:"M9 21H3v-6"}),r("path",{d:"M21 3l-7 7"}),r("path",{d:"M3 21l7-7"})]}),e),hd=e=>$e(r(se,{children:[r("path",{d:"M9 3v6H3"}),r("path",{d:"M15 21v-6h6"}),r("path",{d:"M9 9 2 2"}),r("path",{d:"M15 15l7 7"})]}),e),md=e=>$e(r(se,{children:[r("rect",{x:"3",y:"4",width:"18",height:"14",rx:"2"}),r("rect",{x:"11",y:"11",width:"8",height:"6",rx:"1",fill:"currentColor",stroke:"none"})]}),e),gd=e=>$e(r(se,{children:[r("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2"}),r("path",{d:"M12 15V9"}),r("path",{d:"m8.5 12.5 3.5-3.5 3.5 3.5"})]}),e),bd=e=>$e(r(se,{children:[r("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),r("path",{d:"m19 12-7 7-7-7"})]}),e),co=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\(https?:\/\/[^\s)]+\))|(\[[^\]]+\]\([^\s)]+\))|(https?:\/\/[^\s)]+)/g,vd=e=>e.replace(/([^\n])\s+((?:[-*•]|\d+\.)\s+)(?=(?:\*\*[^*\n]{1,80}\*\*|[A-Z][A-Za-z0-9/& -]{1,50}:))/g,`$1
164
- $2`),hn=e=>{const t=[];let n=0,a=0,i;for(co.lastIndex=0;(i=co.exec(e))!==null;){i.index>n&&t.push(e.slice(n,i.index));const o=i[0];if(o.startsWith("`"))t.push(r("code",{class:"cf-md-code",children:o.slice(1,-1)},a++));else if(o.startsWith("**"))t.push(r("strong",{children:o.slice(2,-2)},a++));else if(o.startsWith("[")&&!/\]\(https?:\/\//.test(o))t.push(/^\[([^\]]+)\]/.exec(o)?.[1]??o);else if(o.startsWith("[")){const s=/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/.exec(o),c=s?s[1]:o,d=s?s[2]:"#";t.push(r("a",{href:d,target:"_blank",rel:"noopener noreferrer nofollow",children:c},a++))}else t.push(r("a",{href:o,target:"_blank",rel:"noopener noreferrer nofollow",children:o},a++));n=i.index+o.length}return n<e.length&&t.push(e.slice(n)),t},xd=/^(```|#{1,6}\s|\s*[-*•]\s|\s*\d+\.\s)/,yd=(e,t,n)=>{const a=`cf-md-h cf-md-h--${Math.min(e,6)}`;return e<=2?r("h3",{class:a,children:t},n):e===3?r("h4",{class:a,children:t},n):r("h5",{class:a,children:t},n)},_d=e=>{const t=vd(e.replace(/\r\n/g,`
163
+ `};class Rl{constructor(t,n,a,i={}){B(this,"explanationId");B(this,"submit");B(this,"onChange");B(this,"context");B(this,"state",{phase:"idle",reasons:[],comment:""});this.explanationId=t,this.submit=n,this.onChange=a,this.context=i}set(t){this.state={...this.state,...t},this.onChange(this.state)}async save(t,n){const a=this.state;this.set({phase:"saving",error:void 0});try{await this.submit(zl({explanationId:this.explanationId,...this.context,...t})),this.set({...n,error:void 0})}catch{this.set({phase:a.phase==="details"?"details":"error",rating:a.rating,error:ht.feedbackError})}}vote(t){return this.state.phase==="saving"?Promise.resolve():this.save({rating:t},t==="up"?{phase:"done",rating:t,reasons:[],comment:""}:{phase:"details",rating:t})}toggleReason(t){const n=this.state.reasons.includes(t)?this.state.reasons.filter(a=>a!==t):[...this.state.reasons,t];this.set({reasons:n})}setComment(t){this.set({comment:Array.from(t).slice(0,fr).join("")})}send(){return this.state.phase==="saving"?Promise.resolve():this.save({rating:"down",reasons:this.state.reasons,comment:this.state.comment},{phase:"done",rating:"down"})}undo(){return this.state.phase==="saving"?Promise.resolve():this.save({rating:"clear"},{phase:"idle",rating:void 0,reasons:[],comment:""})}}const va={delaysMs:[1e3,2e3,4e3],capMs:45e3,graceMs:5e3,stillWorkingMs:15e3},hr=e=>e==="pending"||e==="ready"||e==="failed"?e:"not_requested",Ll=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e*1e3:0,Dl=e=>hr(e?.aiExplanation?.status);class Pl{constructor(t,n,a,i={}){B(this,"transport");B(this,"onChange");B(this,"state");B(this,"handle");B(this,"disposed",!1);B(this,"generation",0);B(this,"attempt",0);B(this,"startedAt",0);B(this,"delays");B(this,"capMs");B(this,"graceMs");B(this,"stillWorkingMs");B(this,"windowMs",0);B(this,"now");B(this,"schedule");B(this,"cancelTimer");B(this,"isVisible");B(this,"onSettled");B(this,"inFlight",null);B(this,"pausedAt",null);B(this,"onVisibilityChange",()=>{this.disposed||this.pausedAt===null||!this.isVisible()||(this.startedAt+=this.now()-this.pausedAt,this.pausedAt=null,this.queue())});this.transport=n,this.onChange=a,this.delays=i.delaysMs?.length?i.delaysMs:va.delaysMs,this.capMs=i.capMs??va.capMs,this.graceMs=i.graceMs??va.graceMs,this.stillWorkingMs=i.stillWorkingMs??va.stillWorkingMs,this.now=i.now??(()=>Date.now()),this.schedule=i.schedule??((c,u)=>setTimeout(c,u)),this.cancelTimer=i.cancel??(c=>clearTimeout(c)),this.isVisible=i.isVisible??(()=>typeof document>"u"||document.visibilityState!=="hidden"),this.onSettled=i.onSettled;const o=Dl(t),s=o==="pending"&&!n?"not_requested":o;this.state={status:s,explanation:t,retryAvailable:s==="failed"&&this.canRetry(t.aiExplanation?.retryAvailable),retrying:!1,announcement:"",stillWorking:!1}}extendWindow(t){const n=Ll(t);if(n<=0)return;const a=this.now()-this.startedAt;this.windowMs=Math.max(this.windowMs,a+n+this.graceMs)}get explanationId(){return this.state.explanation.aiExplanation?.explanationId||this.state.explanation.explanationId||""}canRetry(t){return!!this.transport?.retry&&t!==!1}set(t){if(this.disposed)return;const n=this.state.status;this.state={...this.state,...t},this.onChange(this.state);const a=this.state.status;a!==n&&(a==="ready"||a==="failed"||a==="not_requested")&&this.onSettled?.(a)}start(){this.state.status!=="pending"||!this.explanationId||(this.disposed=!1,this.startedAt=this.now(),this.attempt=0,this.windowMs=this.capMs,this.extendWindow(this.state.explanation.aiExplanation?.waitSeconds),typeof document<"u"&&document.addEventListener("visibilitychange",this.onVisibilityChange),this.queue())}queue(){if(this.disposed)return;if(!this.isVisible()){this.pausedAt??(this.pausedAt=this.now());return}const t=this.now()-this.startedAt,n=Math.max(this.windowMs,this.capMs);if(t>=n){this.fail(!0);return}!this.state.stillWorking&&this.state.status==="pending"&&t>=this.stillWorkingMs&&this.set({stillWorking:!0});const a=this.delays[Math.min(this.attempt,this.delays.length-1)]??4e3;this.attempt+=1;const i=this.generation;this.handle=this.schedule(()=>{this.pollOnce(i)},Math.min(a,Math.max(0,n-t)))}async pollOnce(t){if(this.disposed||t!==this.generation||!this.transport)return;if(!this.isVisible()){this.pausedAt??(this.pausedAt=this.now());return}const n=new AbortController;this.inFlight=n;try{const a=await this.transport.poll(this.explanationId,n.signal);if(this.disposed||t!==this.generation)return;this.apply(a)}catch{if(this.disposed||t!==this.generation)return;this.queue()}finally{this.inFlight===n&&(this.inFlight=null)}}apply(t){const n=hr(t.status);if(this.applyBasicUpdate(t,n),n==="ready"&&t.explanation&&pr(t.explanation)){this.set({status:"ready",explanation:t.explanation,retryAvailable:!1,retrying:!1,announcement:ht.detailedReady,stillWorking:!1});return}if(n==="pending"){this.extendWindow(t.waitSeconds),this.state.status!=="pending"&&this.set({status:"pending",retrying:!1,announcement:""}),this.queue();return}if(n==="not_requested"){this.set({status:"not_requested",retryAvailable:!1,retrying:!1,announcement:"",stillWorking:!1});return}this.fail(this.canRetry(t.retryAvailable))}applyBasicUpdate(t,n){const a=t.basic;if(!a||n==="ready"||this.state.status==="ready"||!pr(a))return;const i=this.state.explanation;a.headline===i.headline&&a.summary===i.summary||this.set({explanation:{...a,explanationId:i.explanationId??a.explanationId,aiExplanation:i.aiExplanation,level:i.level}})}fail(t){this.generation+=1,this.set({status:"failed",retryAvailable:t&&this.canRetry(!0),retrying:!1,announcement:ht.detailedUnavailable,stillWorking:!1})}async retry(){if(!this.transport?.retry||this.state.retrying||this.state.status==="ready")return;const t=this.explanationId;if(!t)return;this.generation+=1;const n=this.generation;this.set({retrying:!0,announcement:""});try{const a=await this.transport.retry(t);if(this.disposed||n!==this.generation)return;if(hr(a.status)==="pending"){this.set({status:"pending",retrying:!1,retryAvailable:!1,announcement:ht.preparingDetailed,stillWorking:!1}),this.startedAt=this.now(),this.attempt=0,this.windowMs=this.capMs,this.extendWindow(a.waitSeconds),this.queue();return}this.apply(a)}catch{if(this.disposed||n!==this.generation)return;this.set({status:"failed",retrying:!1,retryAvailable:!1,announcement:ht.detailedUnavailable})}}dispose(){this.disposed=!0,this.generation+=1,this.inFlight?.abort(),this.inFlight=null,this.handle!==void 0&&this.cancelTimer(this.handle),typeof document<"u"&&document.removeEventListener("visibilitychange",this.onVisibilityChange)}}const to=Wa(ht),Nn=()=>Ka(to),Ol=(e,t)=>{const n=R(t);n.current=t;const a=R(()=>{}),i=e.aiExplanation?.explanationId??e.explanationId??"",o=e.aiExplanation?.status==="pending"?"pending":"settled",s=qe(()=>{const d=n.current,p=d?{poll:(h,f)=>n.current.poll(h,f),...d.retry?{retry:(h,f)=>n.current.retry(h,f)}:{}}:void 0;return new Pl(e,p,h=>a.current(h),{onSettled:h=>n.current?.settled?.(i,h)})},[i,o,!!t]),[c,u]=S(s.state);return X(()=>(a.current=u,u(s.state),s.start(),()=>s.dispose()),[s]),[c.status==="ready"?c:{...c,explanation:e},s]},Fl=({prefix:e,state:t,onRetry:n})=>{const a=Nn();return r("div",{class:`${e}-xp__ai`,"data-ai-status":t.status,role:"status","aria-live":"polite","aria-atomic":"true",children:[t.status==="pending"?r("p",{class:`${e}-xp__ai-note`,children:t.stillWorking?a.stillWorkingDetailed:a.preparingDetailed}):null,t.status==="failed"?r("p",{class:`${e}-xp__ai-note`,children:[a.detailedUnavailable,t.retryAvailable?r("button",{type:"button",class:`${e}-xp__ai-retry`,disabled:t.retrying,onClick:n,children:a.detailedRetry}):null]}):null,t.status==="ready"&&t.announcement?r("span",{class:`${e}-xp__sr`,children:t.announcement}):null]})},Ul=({citations:e,step:t,prefix:n,active:a,onToggle:i,evidenceById:o})=>{const s=Nn();return e.length===0?null:r(de,{children:e.map(c=>{const u=a?.id===c.id&&a.step===t;return r("button",{type:"button",class:`${n}-xp__cite`,"data-evidence-id":c.id,"aria-expanded":u,"aria-label":`${s.citationLabel} ${c.index}: ${o[c.id]?.text??""}`.trim(),onClick:l=>i(c.id,t,l.currentTarget),children:Il(c).slice(1,-1)},c.id)})})},Bl=(e,t)=>e.sourceTargets.find(n=>t?t(n):!0),ql=({evidence:e,prefix:t,onClose:n,onOpenSource:a,canOpenSource:i})=>{const o=Nn(),s=R(null);X(()=>{s.current?.focus()},[e.id]);const c=a?Bl(e,i):void 0;return r("div",{ref:s,class:`${t}-xp__evidence-panel`,role:"region",tabIndex:-1,"aria-label":`${o.evidence} ${e.index}`,"data-testid":"analytics-explanation-evidence",onKeyDown:u=>{u.key==="Escape"&&(u.stopPropagation(),n())},children:[r("div",{class:`${t}-xp__evidence-head`,children:[r("p",{class:`${t}-xp__evidence-text`,children:["[",e.index,"] ",e.text]}),r("button",{type:"button",class:`${t}-xp__close`,"aria-label":o.closeEvidence,onClick:n,children:"×"})]}),r("dl",{class:`${t}-xp__evidence-rows`,children:El(e,o).map(u=>r("div",{style:{display:"contents"},"data-row":u.key,children:[r("dt",{children:u.label}),r("dd",{children:u.value})]},u.key))}),c&&a?r("div",{class:`${t}-xp__evidence-actions`,children:r("button",{type:"button",class:`${t}-xp__button`,onClick:()=>a(c,e),children:o.openSource})}):null]})},no=({down:e})=>r("svg",{viewBox:"0 0 24 24",width:"15",height:"15",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false",style:e?{transform:"scaleY(-1)"}:void 0,children:r("path",{d:"M7 10v11H3V10h4Zm0 0 4-7a2 2 0 0 1 2 2v4h6a2 2 0 0 1 2 2.3l-1.2 7A2 2 0 0 1 17.8 21H7"})}),Vl=(e,t,n)=>t==="wrong_numbers"?e.reasonWrongNumbers:t==="missing_comparison"?e.reasonMissingComparison:t==="unclear"?e.reasonUnclear:t==="too_long"?e.reasonTooLong:n,Hl=({prefix:e,explanationId:t,submit:n,context:a})=>{const i=Nn(),[o,s]=S({phase:"idle",reasons:[],comment:""}),c=qe(()=>new Rl(t,n,s,a),[t]),u=o.phase==="saving";return r("div",{class:`${e}-xp__feedback`,"data-testid":"analytics-explanation-feedback",children:[o.phase==="done"?r("div",{class:`${e}-xp__feedback-row`,role:"status",children:[r("span",{class:`${e}-xp__feedback-note`,children:i.feedbackThanks}),r("button",{type:"button",class:`${e}-xp__button`,onClick:()=>{c.undo()},children:i.feedbackUndo})]}):r("div",{class:`${e}-xp__feedback-row`,children:[r("span",{class:`${e}-xp__feedback-label`,children:i.feedbackPrompt}),r("button",{type:"button",class:`${e}-xp__vote`,"aria-label":i.feedbackHelpful,"aria-pressed":o.rating==="up",disabled:u,onClick:()=>{c.vote("up")},children:r(no,{down:!1})}),r("button",{type:"button",class:`${e}-xp__vote`,"aria-label":i.feedbackNotHelpful,"aria-pressed":o.rating==="down",disabled:u,onClick:()=>{c.vote("down")},children:r(no,{down:!0})})]}),o.phase==="details"||u&&o.rating==="down"?r("form",{class:`${e}-xp__feedback-form`,onSubmit:l=>{l.preventDefault(),c.send()},children:[r("fieldset",{class:`${e}-xp__reasons`,children:[r("legend",{children:i.feedbackReasonsPrompt}),ji.map(l=>r("button",{type:"button",class:`${e}-xp__reason`,"aria-pressed":o.reasons.includes(l.id),onClick:()=>c.toggleReason(l.id),children:Vl(i,l.id,l.label)},l.id))]}),r("textarea",{class:`${e}-xp__comment`,"aria-label":i.feedbackCommentPlaceholder,placeholder:i.feedbackCommentPlaceholder,maxLength:fr,value:o.comment,onInput:l=>c.setComment(l.currentTarget.value)}),r("div",{class:`${e}-xp__feedback-row`,children:r("button",{type:"submit",class:`${e}-xp__button is-primary`,disabled:u,children:i.feedbackSubmit})})]}):null,o.error?r("p",{class:`${e}-xp__feedback-error`,role:"alert",children:o.error}):null]})},ao=({aiTransport:e,...t})=>{const[n,a]=Ol(t.explanation,e),i=jl(t.explanation),o=qe(()=>({...ht,...t.copy}),[t.copy]);return r(to.Provider,{value:o,children:r(Wl,{...t,explanation:n.explanation,aiStatus:i?r(Fl,{prefix:t.classPrefix,state:n,onRetry:()=>{a.retry()}}):null})})},jl=e=>!!(e.aiExplanation&&e.aiExplanation.status!=="not_requested"),Wl=({explanation:e,aiStatus:t,classPrefix:n,showLead:a=!0,investigateOpen:i=!1,onFollowUp:o,onOpenSource:s,canOpenSource:c,onFeedback:u,feedbackContext:l,onExpand:d,onCollapse:p,expanded:h=!1,...f})=>{const _=Nn(),x=R(null),w=R(null),v=R(!1),m=()=>{const C=x.current,I=C?.getRootNode(),ce=I&&"activeElement"in I?I.activeElement:null;return!!(C&&ce&&C.contains(ce))},T=qe(()=>(v.current=m(),Ml(e,{...f,copy:_})),[e,f.locale,f.cleanText,_]),[P,O]=S(),re=R(null);Sn(()=>{!P||T.evidenceById[P.id]&&x.current?.querySelector('[data-testid="analytics-explanation-evidence"]')||(O(void 0),v.current&&!m()&&(w.current??x.current)?.focus())},[T]);const J=(C,I,ce)=>{re.current=ce,O(te=>te?.id===C&&te.step===I?void 0:{id:C,step:I})},G=()=>{O(void 0);const C=re.current;C?.isConnected?C.focus():(w.current??x.current)?.focus()},N=(C,I)=>r(Ul,{citations:C,step:I,prefix:n,active:P,onToggle:J,evidenceById:T.evidenceById}),se=C=>{if(!P||P.step!==C)return null;const I=T.evidenceById[P.id];return I?r(ql,{evidence:I,prefix:n,onClose:G,onOpenSource:s,canOpenSource:c}):null},q=(C,I)=>r(de,{children:[C.text,N(C.citations,I)]}),{investigate:F}=T;return r("section",{ref:x,class:`${n}-xp${h?" is-expanded":""}${d||p?" has-expand":""}`,"data-testid":"analytics-explanation","aria-label":_.region,tabIndex:-1,children:[h&&p?r("button",{type:"button",class:`${n}-xp__expand`,"aria-label":_.collapse,title:_.collapse,onClick:p,children:"×"}):d?r("button",{type:"button",class:`${n}-xp__expand`,"aria-label":_.expand,title:_.expand,"data-testid":"analytics-explanation-expand",onClick:d,children:"⤢"}):null,a?r("div",{class:`${n}-xp__lead`,"data-step":"lead",children:[T.lead.preface?r("p",{class:`${n}-xp__preface`,children:T.lead.preface}):null,r("div",{class:`${n}-xp__meta`,children:[r("span",{class:`${n}-xp__eyebrow`,children:T.lead.eyebrow}),r("span",{class:`${n}-xp__provenance`,children:T.lead.provenance})]}),r("h3",{class:`${n}-xp__headline`,ref:w,tabIndex:-1,children:q(T.lead.headline,"lead")}),T.lead.summary?r("p",{class:`${n}-xp__summary`,children:q(T.lead.summary,"lead")}):null,se("lead")]}):null,t,T.comparison.length>0?r("section",{class:`${n}-xp__step`,"data-step":"comparison",children:[r("h4",{class:`${n}-xp__title`,children:_.comparison}),r("ul",{class:`${n}-xp__periods`,children:T.comparison.map(C=>r("li",{class:`${n}-xp__period`,"data-status":C.status??"observed",children:[r("span",{class:`${n}-xp__period-label`,children:C.label}),C.valueText?r("span",{class:`${n}-xp__period-value`,children:C.valueText}):null,C.statusLabel?r("span",{class:`${n}-xp__chip is-${C.statusTone}`,children:C.statusLabel}):null,C.inProgress?r("span",{class:`${n}-xp__chip is-progress`,children:_.inProgress}):null,C.citation?N([C.citation],"comparison"):null,C.reason?r("small",{class:`${n}-xp__period-reason`,children:C.reason}):null]},C.key))}),se("comparison")]}):null,T.conclusions.length>0||T.businessMeaning?r("section",{class:`${n}-xp__step`,"data-step":"conclusions",children:[r("h4",{class:`${n}-xp__title`,children:_.conclusions}),T.conclusions.length>0?r("ul",{class:`${n}-xp__list`,children:T.conclusions.map(C=>r("li",{children:q(C,"conclusions")},C.text))}):null,T.businessMeaning?r("p",{class:`${n}-xp__meaning`,children:[r("strong",{children:[_.whyItMatters,": "]}),q(T.businessMeaning,"conclusions")]}):null,se("conclusions")]}):null,T.limits.length>0?r("section",{class:`${n}-xp__step`,"data-step":"limits",children:[r("h4",{class:`${n}-xp__title`,children:_.limits}),r("ul",{class:`${n}-xp__list ${n}-xp__limits`,children:T.limits.map(C=>r("li",{"data-kind":C.kind,children:[C.text,C.citation?N([C.citation],"limits"):null]},C.text))}),se("limits")]}):null,T.checkedLine?r("p",{class:`${n}-xp__checked`,"data-step":"checked",children:T.checkedLine}):null,T.hasInvestigate?r("details",{class:`${n}-xp__investigate`,"data-step":"investigate",open:i,children:[r("summary",{children:_.investigate}),r("div",{class:`${n}-xp__investigate-body`,children:[F.causes.length>0?r("div",{class:`${n}-xp__group`,children:[r("div",{class:`${n}-xp__group-head`,children:[r("h4",{class:`${n}-xp__title`,children:_.causes}),r("span",{class:`${n}-xp__hint`,children:_.causesHint})]}),F.causes.map(C=>r("article",{class:`${n}-xp__card`,children:[r("p",{class:`${n}-xp__card-title`,children:[C.title,N(C.citations,"investigate")]}),C.howToCheck?r("p",{class:`${n}-xp__card-body`,children:[_.howToCheck," ",C.howToCheck]}):null]},C.title))]}):null,F.recommendations.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:_.recommendations}),F.recommendations.map(C=>r("article",{class:`${n}-xp__card`,children:[r("p",{class:`${n}-xp__card-title`,children:[C.title,N(C.citations,"investigate")]}),C.why?r("p",{class:`${n}-xp__card-body`,children:C.why}):null,C.watch?r("p",{class:`${n}-xp__card-body`,children:[_.watch," ",C.watch]}):null]},C.title))]}):null,F.outlook?r("div",{class:`${n}-xp__group`,children:[r("div",{class:`${n}-xp__group-head`,children:[r("h4",{class:`${n}-xp__title`,children:_.outlook}),r("span",{class:`${n}-xp__hint`,children:F.outlook.badge})]}),r("p",{class:`${n}-xp__card-body`,children:F.outlook.text}),F.outlook.note?r("p",{class:`${n}-xp__card-body`,children:F.outlook.note}):null]}):null,o&&F.followUps.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:_.followUps}),r("div",{class:`${n}-xp__questions`,children:F.followUps.map(C=>r("button",{type:"button",class:`${n}-xp__question`,onClick:()=>o(C),children:C},C))})]}):null,T.evidence.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:_.evidenceList}),r("ul",{class:`${n}-xp__list`,children:T.evidence.map(C=>r("li",{children:[C.text,N([{id:C.id,index:C.index}],"investigate")]},C.id))})]}):null,se("investigate")]})]}):null,r("p",{class:`${n}-xp__source`,children:T.sourceNote}),u&&T.explanationId?r(Hl,{prefix:n,explanationId:T.explanationId,submit:u,context:l}):null]})},Gl=[{name:"Smileys",emojis:["😀","😃","😄","😁","😅","😂","🤣","😊","😇","🙂","🙃","😉","😌","😍","🥰","😘","😋","😛","😜","🤪","🤗","🤭","🤔","🤐","😐","😶","😏","🙄","😴","🥳","😎","🤓","🥺","😢","😭","😤","😠","🤯","😬","😱","🤩","🥱"]},{name:"Gestures",emojis:["👍","👎","👌","🤌","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","👇","✋","🖐️","👋","🤝","🙏","💪","👏","🙌","👐","🤲","🫶"]},{name:"Hearts & symbols",emojis:["❤️","🧡","💛","💚","💙","💜","🖤","🤍","💔","❣️","💕","💖","💘","💝","✨","⭐","🌟","💫","🔥","🎉","🎊","✅","❌","⚡","💯","🚀"]},{name:"Animals & nature",emojis:["🐶","🐱","🦊","🐻","🐼","🐨","🦁","🐮","🐸","🐵","🐧","🦄","🐝","🦋","🐢","🐬","🌷","🌸","🌹","🌻","🌳","🍀"]},{name:"Food & drink",emojis:["🍎","🍌","🍉","🍓","🍒","🥑","🍔","🍟","🍕","🌮","🍿","🍩","🍪","🎂","☕","🍵","🍺","🥂","🍷"]},{name:"Objects & travel",emojis:["🚀","✈️","🚗","🏠","📦","📱","💻","⌚","📷","💡","🔑","🎁","📌","✏️","📝","📞","📧","💰","📈","⏰","🔔","🎯","🏆","🎮","🎵","💬","👀"]}],xa={"contact-support":{title:"Contact support",submit:"Request support",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"},{key:"subject",label:"Subject",kind:"text",required:!0},{key:"message",label:"Message",kind:"textarea",required:!0,placeholder:"Describe what you need help with."}]},inquiry:{title:"Leave a message",submit:"Send message",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"},{key:"message",label:"Message",kind:"textarea",required:!0,placeholder:"How can we help?"}]},contact:{title:"Share your details",submit:"Save",fields:[{key:"name",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"email",label:"Email",kind:"email",required:!0,identity:"email"},{key:"phone",label:"Phone",kind:"tel",required:!0,identity:"phone"}]},"book-demo":{title:"Book a demo",submit:"Request demo",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"},{key:"preferredAt",label:"Preferred time",kind:"text",placeholder:"e.g. Thursday 3pm"},{key:"notes",label:"Notes",kind:"textarea",placeholder:"Anything we should know?"}]},"request-callback":{title:"Request a callback",submit:"Request callback",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorPhone",label:"Phone number",kind:"tel",required:!0,identity:"phone"},{key:"topic",label:"Topic",kind:"text",placeholder:"What should we call about?"}]},"schedule-callback":{title:"Schedule a callback",submit:"Schedule callback",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorPhone",label:"Phone number",kind:"tel",required:!0,identity:"phone"},{key:"topic",label:"Topic",kind:"text",placeholder:"What should we call about?"}]},"subscribe-newsletter":{title:"Subscribe",submit:"Subscribe",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"}]}},mr={openChat:"Open chat",closeChat:"Close chat",closeHistory:"Close conversation history",unreadMessage:"1 unread message",unreadMessages:"{count} unread messages",muteSounds:"Mute sounds",unmuteSounds:"Unmute sounds",statusOnline:"Online · replies instantly",statusOffline:"Away · leave a message",liveSupport:"Live support",reconnectSupport:"Reconnect to support",reconnectPrompt:"I can bring a teammate back into this chat.",waitingForTeam:"AI helping · team notified",assistantName:"Assistant",chatName:"Chat",welcomeLabel:"{name} welcome",welcomeEyebrow:"Ready when you are",welcomePrompt:"Ask a question, leave a message, or book a demo.",agentTyping:"{name} is typing…",expandedAnalyticsResult:"Expanded analytics result",privacyAndData:"Privacy and local data",muteMicrophone:"Mute microphone",unmuteMicrophone:"Unmute microphone",chooseMicrophone:"Choose microphone",defaultMicrophone:"Default microphone",microphone:"Microphone",talkNow:"Talk now",expandView:"Expand view",exitExpandedView:"Exit expanded view",minimizeVoiceChat:"Minimize voice chat",endVoiceChat:"End voice chat",restoreVoiceChat:"Restore voice chat",reopenVoiceChat:"Reopen voice chat with {name}",voiceConnecting:"Connecting…",voiceListening:"Listening…",voiceHearing:"Hearing you…",voiceUnavailable:"Can’t hear you — check your microphone.",voiceProcessing:"Transcribing…",voiceSpeaking:"Speaking…",voiceNoise:"No clear speech heard. Move closer to the mic and try again.",voiceMisunderstood:"Could not transcribe that. Please try again or type your message.",voiceDenied:"Microphone unavailable. Allow access or type your message.",composerPlaceholder:"Type your message…",send:"Send message",emoji:"Emoji",gifs:"GIFs",attachFile:"Attach a file",recordVoice:"Record a voice message",stopRecording:"Stop recording",actionTestMode:"Test mode",stop:"Stop",copy:"Copy",copied:"Copied",retry:"Retry",clearChat:"Clear conversation",clearChatConfirm:"Clear this conversation?",clearChatConfirmBody:"This clears the messages on this device and starts a fresh chat.",clearConfirmCta:"Clear chat",endChat:"End conversation",endChatConfirm:"End this conversation?",endChatConfirmBody:"You won't be able to send more messages in this chat, but you can start a new one anytime.",endConfirmCta:"End conversation",conversationEnded:"This conversation has ended.",startNewChat:"Start a new conversation",pastConversations:"Past conversations",viewingPast:"Viewing a past conversation (read-only)",backToChat:"Back to current chat",historyEnded:"ended",feedbackHelpful:"Helpful",feedbackNotHelpful:"Not helpful",feedbackAnswerPrompt:"Was this answer helpful?",feedbackThanks:"Thanks for the feedback",csatPrompt:"How was this chat?",feedbackCommentPlaceholder:"What went wrong? (optional)",feedbackSend:"Send",cancel:"Cancel",newMessages:"New messages",poweredBy:"Powered by",searchGifs:"Search GIFs…",searchingGifs:"Searching…",noGifs:"No GIFs found",assistantTyping:"Assistant is typing",emptyReply:"Sorry, I couldn't generate a reply.",errorGeneric:"Something went wrong reaching the assistant. Please try again.",errorRateLimit:"You’re sending messages a little fast — give it a second and try again.",resultExpired:"This result is not stored on this device. Ask again to see it.",attaching:"Reading file…",attachTooLarge:"That file is too large (max 5 MB).",attachFailed:"Could not attach that file. Check its type and try again.",attachPreviewTitle:"Preview of {name}",attachOpen:"Preview {name}",attachDownload:"Download",attachPreviewClose:"Close preview",attachPreviewLoading:"Loading file…",attachPreviewFailed:"This file can’t be shown right now. It may have expired.",attachPreviewUnsupported:"This file can’t be previewed here. Download it to open it.",attachAnalysisFailed:"Saved for the team; AI could not read it.",removeAttachment:"Remove attachment",attachLimit:"You can attach up to {count} files to one message.",attachedFiles:"Attached files",removeAttachmentNamed:"Remove {name}",dropFileHere:"Drop the file here",clearDeviceData:"Clear conversations from this device",clearDeviceDataBody:"This removes locally stored conversations and visitor details from this browser. It cannot be undone.",clearDeviceDataCta:"Clear this device",handoffTitle:"Want our team to follow up?",handoffName:"Name (optional)",handoffEmail:"Your email",handoffNotify:"Notify the team",sending:"Sending…",handoffShared:"I’ve shared this with our team — they’ll get back to you at {email}.",formThanks:"Thanks! We’ll be in touch.",caseReference:"Reference: {reference}",formError:"Something went wrong — please try again.",actionContactOptions:"Contact options",actionGetInTouch:"Get in touch",actionMore:"+{count} more",actionNeedHelp:"Need help?",actionChoose:"Choose what you want to do",actionFooter:"We’ll ask for your full name and the best email or phone so the team can reach you.",actionCategorySupport:"Support",actionCategorySales:"Talk to sales",actionCategoryMarketing:"Stay in touch",actionClose:"Close",actionAs:"as {identity}",bookingPickTime:"What time works best?",bookingPickDay:"Pick a day",bookingPickTimeLabel:"Pick a time",bookingDuration:"{count}-minute demo",bookingCallbackDuration:"{count}-minute callback",bookingTimezone:"Times shown in {timezone}",bookingSchedulerFallback:"the scheduler",bookingCheckingAvailability:"Checking calendar availability…",bookingNoSlots:"No available times were found in this booking window.",bookingAvailabilityUnavailable:"Calendar availability is temporarily unavailable. Please try again shortly.",bookingEarlierToday:"Earlier today",bookingCalendarBusy:"Busy on the calendar",bookingAlreadyBooked:"Already booked",bookingNotOffered:"Not offered by the calendar",bookingRequested:"Demo requested for {when}. The team will follow up.",bookingVerificationPending:"We received your request for {when}, but could not verify the calendar booking. The team will check it. Please do not book this time again.",bookingCallbackRequested:"Callback requested for {when}.",bookingCallbackConfirmed:"Your callback is scheduled for {when}.",bookingConfirmed:"Your demo is booked for {when}.",bookingSlotTaken:"That time was just taken — please pick another.",bookingViaProvider:"Pick a time that works for you on {provider}.",bookingOpenScheduler:"Open the scheduler",bookingLinkOpened:"Opening the scheduler — pick a time that suits you. 📅",bookingScheduled:"Your demo is booked. Your booking details are saved in this chat.",bookingBackToChat:"Back to chat",bookingOpenNewTab:"Open in new tab",bookingCloseScheduler:"Close scheduler",bookingLoadingScheduler:"Loading scheduler…",bookingMeetingLink:"Meeting link",bookingManageLink:"Manage booking",bookingCheckingDetails:"Getting your meeting link…",bookingDetailsUnavailable:"We could not verify the booking details yet. Try checking again here; please do not book the same time twice.",bookingUnverifiedLink:"View unverified calendar record",bookingRetryDetails:"Retry",previewReply:"👋 This is a preview — replies here are samples. Publish the widget on your site to chat with the live AI.",previewActionNote:"Preview — nothing was actually sent. This works for real once you publish.",previewBanner:"Preview — sample replies, no AI"},Ve=(e,t)=>e.replace(/\{(\w+)\}/g,(n,a)=>t[a]??""),Rn=(e,t,n)=>!t||e.includes(t)?e:`${e} ${Ve(n.caseReference,{reference:t})}`,Kl=e=>e?{...mr,...e}:mr,ro=Wa(mr),Yl=ro.Provider,io=Wa(void 0),Zl=io.Provider,gr=()=>Ka(io),Jl=new Set(["ar","he","iw","fa","ur","ps","sd","ug","yi","dv","ckb"]),Xl=(e,t)=>{if(t==="ltr"||t==="rtl")return t;const n=(e??"").trim().toLowerCase().split(/[-_]/)[0]??"";return Jl.has(n)?"rtl":"ltr"},ct=()=>Ka(ro),nn=[["AF","Afghanistan","93"],["AL","Albania","355"],["DZ","Algeria","213"],["AS","American Samoa","1684"],["AD","Andorra","376"],["AO","Angola","244"],["AI","Anguilla","1264"],["AG","Antigua and Barbuda","1268"],["AR","Argentina","54"],["AM","Armenia","374"],["AW","Aruba","297"],["AU","Australia","61"],["AT","Austria","43"],["AZ","Azerbaijan","994"],["BS","Bahamas","1242"],["BH","Bahrain","973"],["BD","Bangladesh","880"],["BB","Barbados","1246"],["BY","Belarus","375"],["BE","Belgium","32"],["BZ","Belize","501"],["BJ","Benin","229"],["BM","Bermuda","1441"],["BT","Bhutan","975"],["BO","Bolivia","591"],["BA","Bosnia and Herzegovina","387"],["BW","Botswana","267"],["BR","Brazil","55"],["BN","Brunei","673"],["BG","Bulgaria","359"],["BF","Burkina Faso","226"],["BI","Burundi","257"],["CV","Cabo Verde","238"],["KH","Cambodia","855"],["CM","Cameroon","237"],["CA","Canada","1"],["KY","Cayman Islands","1345"],["CF","Central African Republic","236"],["TD","Chad","235"],["CL","Chile","56"],["CN","China","86"],["CO","Colombia","57"],["KM","Comoros","269"],["CG","Congo","242"],["CD","Congo, Democratic Republic","243"],["CK","Cook Islands","682"],["CR","Costa Rica","506"],["CI","Cote d'Ivoire","225"],["HR","Croatia","385"],["CU","Cuba","53"],["CW","Curacao","599"],["CY","Cyprus","357"],["CZ","Czechia","420"],["DK","Denmark","45"],["DJ","Djibouti","253"],["DM","Dominica","1767"],["DO","Dominican Republic","1809"],["EC","Ecuador","593"],["EG","Egypt","20"],["SV","El Salvador","503"],["GQ","Equatorial Guinea","240"],["ER","Eritrea","291"],["EE","Estonia","372"],["SZ","Eswatini","268"],["ET","Ethiopia","251"],["FO","Faroe Islands","298"],["FJ","Fiji","679"],["FI","Finland","358"],["FR","France","33"],["GF","French Guiana","594"],["PF","French Polynesia","689"],["GA","Gabon","241"],["GM","Gambia","220"],["GE","Georgia","995"],["DE","Germany","49"],["GH","Ghana","233"],["GI","Gibraltar","350"],["GR","Greece","30"],["GL","Greenland","299"],["GD","Grenada","1473"],["GP","Guadeloupe","590"],["GU","Guam","1671"],["GT","Guatemala","502"],["GG","Guernsey","44"],["GN","Guinea","224"],["GW","Guinea-Bissau","245"],["GY","Guyana","592"],["HT","Haiti","509"],["HN","Honduras","504"],["HK","Hong Kong","852"],["HU","Hungary","36"],["IS","Iceland","354"],["IN","India","91"],["ID","Indonesia","62"],["IR","Iran","98"],["IQ","Iraq","964"],["IE","Ireland","353"],["IM","Isle of Man","44"],["IL","Israel","972"],["IT","Italy","39"],["JM","Jamaica","1876"],["JP","Japan","81"],["JE","Jersey","44"],["JO","Jordan","962"],["KZ","Kazakhstan","7"],["KE","Kenya","254"],["KI","Kiribati","686"],["XK","Kosovo","383"],["KW","Kuwait","965"],["KG","Kyrgyzstan","996"],["LA","Laos","856"],["LV","Latvia","371"],["LB","Lebanon","961"],["LS","Lesotho","266"],["LR","Liberia","231"],["LY","Libya","218"],["LI","Liechtenstein","423"],["LT","Lithuania","370"],["LU","Luxembourg","352"],["MO","Macao","853"],["MG","Madagascar","261"],["MW","Malawi","265"],["MY","Malaysia","60"],["MV","Maldives","960"],["ML","Mali","223"],["MT","Malta","356"],["MH","Marshall Islands","692"],["MQ","Martinique","596"],["MR","Mauritania","222"],["MU","Mauritius","230"],["MX","Mexico","52"],["FM","Micronesia","691"],["MD","Moldova","373"],["MC","Monaco","377"],["MN","Mongolia","976"],["ME","Montenegro","382"],["MS","Montserrat","1664"],["MA","Morocco","212"],["MZ","Mozambique","258"],["MM","Myanmar","95"],["NA","Namibia","264"],["NR","Nauru","674"],["NP","Nepal","977"],["NL","Netherlands","31"],["NC","New Caledonia","687"],["NZ","New Zealand","64"],["NI","Nicaragua","505"],["NE","Niger","227"],["NG","Nigeria","234"],["NU","Niue","683"],["KP","North Korea","850"],["MK","North Macedonia","389"],["MP","Northern Mariana Islands","1670"],["NO","Norway","47"],["OM","Oman","968"],["PK","Pakistan","92"],["PW","Palau","680"],["PS","Palestine","970"],["PA","Panama","507"],["PG","Papua New Guinea","675"],["PY","Paraguay","595"],["PE","Peru","51"],["PH","Philippines","63"],["PL","Poland","48"],["PT","Portugal","351"],["PR","Puerto Rico","1787"],["QA","Qatar","974"],["RE","Reunion","262"],["RO","Romania","40"],["RU","Russia","7"],["RW","Rwanda","250"],["KN","Saint Kitts and Nevis","1869"],["LC","Saint Lucia","1758"],["VC","Saint Vincent and the Grenadines","1784"],["WS","Samoa","685"],["SM","San Marino","378"],["ST","Sao Tome and Principe","239"],["SA","Saudi Arabia","966"],["SN","Senegal","221"],["RS","Serbia","381"],["SC","Seychelles","248"],["SL","Sierra Leone","232"],["SG","Singapore","65"],["SK","Slovakia","421"],["SI","Slovenia","386"],["SB","Solomon Islands","677"],["SO","Somalia","252"],["ZA","South Africa","27"],["KR","South Korea","82"],["SS","South Sudan","211"],["ES","Spain","34"],["LK","Sri Lanka","94"],["SD","Sudan","249"],["SR","Suriname","597"],["SE","Sweden","46"],["CH","Switzerland","41"],["SY","Syria","963"],["TW","Taiwan","886"],["TJ","Tajikistan","992"],["TZ","Tanzania","255"],["TH","Thailand","66"],["TL","Timor-Leste","670"],["TG","Togo","228"],["TO","Tonga","676"],["TT","Trinidad and Tobago","1868"],["TN","Tunisia","216"],["TR","Turkey","90"],["TM","Turkmenistan","993"],["TC","Turks and Caicos Islands","1649"],["TV","Tuvalu","688"],["UG","Uganda","256"],["UA","Ukraine","380"],["AE","United Arab Emirates","971"],["GB","United Kingdom","44"],["US","United States","1"],["UY","Uruguay","598"],["UZ","Uzbekistan","998"],["VU","Vanuatu","678"],["VA","Vatican City","39"],["VE","Venezuela","58"],["VN","Vietnam","84"],["VG","Virgin Islands, British","1284"],["VI","Virgin Islands, U.S.","1340"],["YE","Yemen","967"],["ZM","Zambia","260"],["ZW","Zimbabwe","263"]].map(([e,t,n])=>({iso:e,name:t,dial:n})),oo=e=>[...e.toUpperCase()].map(t=>String.fromCodePoint(127397+t.charCodeAt(0))).join(""),Ql=()=>{let e="";try{if(Intl.DateTimeFormat().resolvedOptions().timeZone==="Africa/Lagos"&&(e="NG"),!e){const t=navigator.languages?.[0]||navigator.language;e=new Intl.Locale(t).region||""}}catch{e=""}return nn.find(t=>t.iso===e)??nn.find(t=>t.iso==="US")},ed=e=>{const t=Ql(),n=e?.trim()??"";if(!n.startsWith("+"))return{country:t,national:n.replace(/\D/g,"")};const a=n.replace(/\D/g,""),i=[...nn].sort((o,s)=>s.dial.length-o.dial.length).find(o=>a.startsWith(o.dial))??t;return{country:i,national:a.slice(i.dial.length)}},so=(e,t)=>{const n=t.replace(/\D/g,"").replace(/^0+/,"");return n?`+${e.dial}${n}`:""},td=e=>{const t=e.replace(/\D/g,"");return e.startsWith("+")&&t.length>=8&&t.length<=15},Ae=(e,t)=>r("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",...t,children:e}),nd=e=>r("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...e,children:r("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M5 3.25h14A3.75 3.75 0 0 1 22.75 7v6A3.75 3.75 0 0 1 19 16.75h-7.19l-4.26 3.84A.75.75 0 0 1 6.25 20v-3.32A3.75 3.75 0 0 1 2.25 13V7A3.75 3.75 0 0 1 6 3.25Zm3 7.75a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Zm4 0a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Zm4 0a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Z"})}),pn=e=>Ae(r("path",{d:"m6 9 6 6 6-6"}),e),ad=e=>Ae(r(de,{children:[r("path",{d:"m22 2-7 20-4-9-9-4Z"}),r("path",{d:"M22 2 11 13"})]}),e),Ln=e=>Ae(r(de,{children:[r("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),r("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),r("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),e),rd=e=>Ae(r(de,{children:[r("path",{d:"M9 9v1a3 3 0 0 0 4.24 2.73"}),r("path",{d:"M15 5.5V5a3 3 0 0 0-5.94-.6"}),r("path",{d:"M19 10v2a7 7 0 0 1-9.9 6.36"}),r("path",{d:"M5 10v2a6.98 6.98 0 0 0 1.11 3.79"}),r("line",{x1:"12",y1:"19",x2:"12",y2:"22"}),r("line",{x1:"2",y1:"2",x2:"22",y2:"22"})]}),e),Dn=e=>Ae(r(de,{children:[r("path",{d:"M15 3h6v6"}),r("path",{d:"M10 14 21 3"}),r("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]}),e),id=e=>Ae(r(de,{children:[r("rect",{x:"3",y:"4",width:"18",height:"18",rx:"2"}),r("line",{x1:"16",y1:"2",x2:"16",y2:"6"}),r("line",{x1:"8",y1:"2",x2:"8",y2:"6"}),r("line",{x1:"3",y1:"10",x2:"21",y2:"10"})]}),e),br=e=>Ae(r(de,{children:[r("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),r("path",{d:"m22 7-10 5L2 7"})]}),e),od=e=>Ae(r("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z"}),e),co=e=>Ae(r(de,{children:[r("path",{d:"M4 14v-2a8 8 0 0 1 16 0v2"}),r("path",{d:"M18 19h-2"}),r("rect",{x:"3",y:"13",width:"4",height:"6",rx:"2"}),r("rect",{x:"17",y:"13",width:"4",height:"6",rx:"2"})]}),e),sd=e=>Ae(r(de,{children:[r("path",{d:"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4Z"}),r("path",{d:"M8 9h8M8 13h5"})]}),e),cd=e=>Ae(r(de,{children:[r("path",{d:"M3 4h18M4 4v12h16V4M12 16v5M8 21h8"}),r("path",{d:"m8 12 2.5-2.5 2 2L16 8"})]}),e),ld=e=>Ae(r(de,{children:[r("path",{d:"M15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6"}),r("path",{d:"M3 9h12M7 2v4M12 2v4"}),r("circle",{cx:"17",cy:"17",r:"4"}),r("path",{d:"M17 15v2l1.5 1"})]}),e),dd=e=>Ae(r(de,{children:[r("path",{d:"M4 4h16v16H5a3 3 0 0 1-3-3V6"}),r("path",{d:"M8 8h8M8 12h8M8 16h5"})]}),e),ud=e=>Ae(r(de,{children:[r("circle",{cx:"12",cy:"12",r:"9"}),r("path",{d:"M8.5 14.5a4 4 0 0 0 7 0"}),r("line",{x1:"9",y1:"9.5",x2:"9.01",y2:"9.5"}),r("line",{x1:"15",y1:"9.5",x2:"15.01",y2:"9.5"})]}),e),Pn=e=>Ae(r(de,{children:[r("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),e),pd=e=>Ae(r(de,{children:[r("path",{d:"M11 5 6 9H2v6h4l5 4z"}),r("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),r("path",{d:"M19 5a9 9 0 0 1 0 14"})]}),e),fd=e=>Ae(r(de,{children:[r("path",{d:"M11 5 6 9H2v6h4l5 4z"}),r("line",{x1:"22",y1:"9",x2:"16",y2:"15"}),r("line",{x1:"16",y1:"9",x2:"22",y2:"15"})]}),e),fn=e=>Ae(r("path",{d:"M20 6 9 17l-5-5"}),e),hd=e=>Ae(r(de,{children:[r("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),r("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),e),md=e=>Ae(r(de,{children:[r("path",{d:"M1 4v6h6"}),r("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"})]}),e),gd=e=>Ae(r("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"}),e),ya=e=>Ae(r("path",{d:"M21.44 11.05 12.25 20.24a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"}),e),vr=e=>Ae(r(de,{children:[r("path",{d:"M18.36 6.64a9 9 0 1 1-12.73 0"}),r("line",{x1:"12",y1:"2",x2:"12",y2:"12"})]}),e),bd=e=>Ae(r(de,{children:[r("circle",{cx:"12",cy:"12",r:"9"}),r("path",{d:"M12 7v5l3 2"})]}),e),lo=e=>Ae(r(de,{children:[r("path",{d:"M7 10v12"}),r("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),e),uo=e=>Ae(r(de,{children:[r("path",{d:"M17 14V2"}),r("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),e),vd=e=>Ae(r(de,{children:[r("path",{d:"M15 3h6v6"}),r("path",{d:"M9 21H3v-6"}),r("path",{d:"M21 3l-7 7"}),r("path",{d:"M3 21l7-7"})]}),e),xd=e=>Ae(r(de,{children:[r("path",{d:"M9 3v6H3"}),r("path",{d:"M15 21v-6h6"}),r("path",{d:"M9 9 2 2"}),r("path",{d:"M15 15l7 7"})]}),e),yd=e=>Ae(r(de,{children:[r("rect",{x:"3",y:"4",width:"18",height:"14",rx:"2"}),r("rect",{x:"11",y:"11",width:"8",height:"6",rx:"1",fill:"currentColor",stroke:"none"})]}),e),_d=e=>Ae(r(de,{children:[r("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2"}),r("path",{d:"M12 15V9"}),r("path",{d:"m8.5 12.5 3.5-3.5 3.5 3.5"})]}),e),wd=e=>Ae(r(de,{children:[r("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),r("path",{d:"m19 12-7 7-7-7"})]}),e),po=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\(https?:\/\/[^\s)]+\))|(\[[^\]]+\]\([^\s)]+\))|(https?:\/\/[^\s)]+)/g,kd=e=>e.replace(/([^\n])\s+((?:[-*•]|\d+\.)\s+)(?=(?:\*\*[^*\n]{1,80}\*\*|[A-Z][A-Za-z0-9/& -]{1,50}:))/g,`$1
164
+ $2`),hn=e=>{const t=[];let n=0,a=0,i;for(po.lastIndex=0;(i=po.exec(e))!==null;){i.index>n&&t.push(e.slice(n,i.index));const o=i[0];if(o.startsWith("`"))t.push(r("code",{class:"cf-md-code",children:o.slice(1,-1)},a++));else if(o.startsWith("**"))t.push(r("strong",{children:o.slice(2,-2)},a++));else if(o.startsWith("[")&&!/\]\(https?:\/\//.test(o))t.push(/^\[([^\]]+)\]/.exec(o)?.[1]??o);else if(o.startsWith("[")){const s=/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/.exec(o),c=s?s[1]:o,u=s?s[2]:"#";t.push(r("a",{href:u,target:"_blank",rel:"noopener noreferrer nofollow",children:c},a++))}else t.push(r("a",{href:o,target:"_blank",rel:"noopener noreferrer nofollow",children:o},a++));n=i.index+o.length}return n<e.length&&t.push(e.slice(n)),t},Sd=/^(```|#{1,6}\s|\s*[-*•]\s|\s*\d+\.\s)/,$d=(e,t,n)=>{const a=`cf-md-h cf-md-h--${Math.min(e,6)}`;return e<=2?r("h3",{class:a,children:t},n):e===3?r("h4",{class:a,children:t},n):r("h5",{class:a,children:t},n)},Td=e=>{const t=kd(e.replace(/\r\n/g,`
165
165
  `)).split(`
166
- `),n=[];let a=0,i=0;for(;i<t.length;){const o=t[i];if(o.trim().startsWith("```")){const u=[];for(i++;i<t.length&&!t[i].trim().startsWith("```");)u.push(t[i]),i++;i++,n.push(r("pre",{class:"cf-md-pre",children:r("code",{children:u.join(`
167
- `)})},a++));continue}if(o.trim()===""){i++;continue}const s=/^(#{1,6})\s+(.*)$/.exec(o);if(s){n.push(yd(s[1].length,hn(s[2]),a++)),i++;continue}if(/^\s*[-*•]\s+/.test(o)){const u=[];for(;i<t.length&&/^\s*[-*•]\s+/.test(t[i]);)u.push(r("li",{children:hn(t[i].replace(/^\s*[-*•]\s+/,""))},u.length)),i++;n.push(r("ul",{class:"cf-md-list",children:u},a++));continue}if(/^\s*\d+\.\s+/.test(o)){const u=[];for(;i<t.length&&/^\s*\d+\.\s+/.test(t[i]);)u.push(r("li",{children:hn(t[i].replace(/^\s*\d+\.\s+/,""))},u.length)),i++;n.push(r("ol",{class:"cf-md-list",children:u},a++));continue}const c=[o];for(i++;i<t.length&&t[i].trim()!==""&&!xd.test(t[i]);)c.push(t[i]),i++;const d=c.join(" ");if(/:\s*$/.test(d)&&i<t.length&&/^(?:\s*[-*•]\s+|\s*\d+\.\s+)/.test(t[i])){const u=/^(.*[.!?])\s+([^.!?]{2,120}:)$/.exec(d);u&&n.push(r("p",{children:hn(u[1])},a++)),n.push(r("p",{class:"cf-md-list-intro",children:hn(u?.[2]??d)},a++))}else n.push(r("p",{children:hn(d)},a++))}return n},xa=e=>bl(e),lo=()=>{const e=R(null);return X(()=>{const t=requestAnimationFrame(()=>e.current?.scrollIntoView?.({block:"end"}));return()=>cancelAnimationFrame(t)},[]),e},wd=e=>e.trim().split(/\s+/).slice(0,2).map(t=>t[0]?.toUpperCase()??"").join("")||"🤖",Pn=e=>{const t=e?.avatarId?.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-");return t?` cf-avatar-preset--${t}`:""},kd={"support-guide":"SG","sales-host":"SH","calm-advisor":"CA","technical-guide":"TG","school-desk":"SD","front-office":"FO"},ya=e=>{const t=e?.avatarId?.trim().toLowerCase();return t&&kd[t]||(e?wd(e.agentName):"·")},uo=({persona:e,small:t,hideWhenMissing:n})=>{const a=t?"cf-msg__avatar":"cf-header__avatar",i=e?.agentAvatarUrl?.trim();return i?r("span",{class:a,children:r("img",{src:i,alt:""})}):n?null:r("span",{class:`${a}${Pn(e)}`,children:ya(e)})},Sd=()=>{const e=ct(),[t,n]=$(0),a=["Understanding your question","Checking approved information","Preparing your answer"];return X(()=>{const i=[window.setTimeout(()=>n(1),1800),window.setTimeout(()=>n(2),5e3)];return()=>i.forEach(o=>window.clearTimeout(o))},[]),r("div",{class:"cf-msg__bubble cf-typing","aria-label":e.assistantTyping,children:[r("span",{class:"cf-typing__label","aria-live":"polite",children:a[t]}),r("span",{class:"cf-typing__dot"}),r("span",{class:"cf-typing__dot"}),r("span",{class:"cf-typing__dot"})]})},$d=3,Td=({msg:e})=>{if(!e.sources||e.sources.length===0)return null;const t=new Set,n=[];for(const o of e.sources){const s=(o.url||o.title||"").toLowerCase();!s||t.has(s)||o.url&&e.content.includes(o.url)||(t.add(s),n.push(o))}if(n.length===0)return null;const a=n.slice(0,$d),i=n.length-a.length;return r("div",{class:"cf-sources",children:[a.map((o,s)=>o.url?r("a",{class:"cf-source",href:o.url,target:"_blank",rel:"noopener noreferrer nofollow",title:o.title||o.url,children:[r(Ln,{}),r("span",{children:o.title||o.url})]},s):r("span",{class:"cf-source",title:o.title,children:[r(Ln,{}),r("span",{children:o.title})]},s)),i>0&&r("span",{class:"cf-source cf-source--more",children:["+",i," more"]})]})},Cd=({replies:e,onPick:t})=>e&&e.length>0?r("div",{class:"cf-chips",children:e.map((n,a)=>r("button",{type:"button",class:"cf-chip",onClick:()=>t(n),children:n},a))}):null,Ad=({persona:e,starters:t,onPick:n,onFocusComposer:a,speaking:i,voiceState:o="idle",replyPending:s=!1,pinned:c=!1,muted:d=!1,onToggleMute:l,onEndCall:u,onTalkNow:p,showTalkNow:m=!1,micLevel:f=0,theaterMode:_=!1,onToggleTheater:h,onMinimize:I,audioDevices:x=[],selectedAudioDeviceId:g="",onSelectAudioDevice:T,connectingOnly:V=!1})=>{if(!e)return null;const P=!!(e.allowVoiceInput&&e.talkbackMode&&e.talkbackMode!=="text");if(!(P||e.widgetModule==="assistant"))return null;const Z=e.agentAvatarUrl?.trim()||"",Y=e.assistantMediaUrl?.trim()||Z,z=e.assistantMediaKind==="video"&&!!Y,te=t.slice(0,3),U=o!=="idle",B=o!=="idle"?"End voice chat":`Speak with ${e.agentName}`,A=c&&P&&!U&&!i,N=o==="connecting"||o==="processing"||U&&s,y=["cf-assistant-card__stage","cf-assistant-card__stage--local",U?"is-live":"",N?"is-thinking":"",mn(o)&&!d?"is-listening":"",i||o==="speaking"?"is-speaking":"",d?"is-muted":""].filter(Boolean).join(" "),D=mn(o)&&!d?{"--cf-listen":String(Math.max(.18,Math.min(1,f*8)))}:void 0,S=N&&r("span",{class:"cf-call-ripple","aria-hidden":"true",children:[r("span",{}),r("span",{}),r("span",{})]});if(V)return r("div",{class:"cf-assistant-card cf-assistant-card--connecting","aria-live":"polite",children:[r("div",{class:"cf-assistant-card__connecting-avatar",children:[Z?r("img",{src:Z,alt:""}):r("span",{class:`cf-assistant-card__connecting-face${Pn(e)}`,children:ya(e)}),S]}),r("div",{class:"cf-assistant-card__connecting-copy",children:[r("span",{class:"cf-assistant-card__connecting-eyebrow",children:e.agentName}),r("strong",{children:"Connecting with the AI…"})]})]});const O=U&&u&&r(au,{voiceState:o,muted:d,onToggleMute:l??(()=>{}),onEndCall:u,onTalkNow:p??(()=>{}),showTalkNow:m,micLevel:f,theaterMode:_,onToggleTheater:h??(()=>{}),onMinimize:I??(()=>{}),audioDevices:x,selectedAudioDeviceId:g,onSelectAudioDevice:T??(()=>{})});return A?r("div",{class:"cf-assistant-card cf-assistant-card--pinned cf-assistant-card--compact",children:r("button",{type:"button",class:"cf-assistant-card__compact-speak",onClick:a,children:[Z?r("span",{class:"cf-assistant-card__compact-avatar",children:r("img",{src:Z,alt:""})}):null,r("span",{class:"cf-assistant-card__compact-mic","aria-hidden":"true",children:r(Rn,{})}),r("span",{class:"cf-assistant-card__compact-label",children:B})]})}):r("div",{class:`cf-assistant-card ${c?"cf-assistant-card--pinned":""} ${i?"is-speaking":""}`,children:[(Y||P)&&r("div",{class:y,style:D,children:[r("div",{class:`cf-assistant-card__media ${Y?"cf-assistant-card__media--uploaded":"cf-assistant-card__media--generated"}${Pn(e)}`,children:[z?r("video",{src:Y,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):Y?r("img",{src:Y,alt:""}):r("div",{class:`cf-assistant-card__avatar-stage${Pn(e)}`,children:r("div",{class:"cf-assistant-card__face",children:[r("span",{class:"cf-assistant-card__initials",children:ya(e)}),r("span",{class:"cf-assistant-card__eye cf-assistant-card__eye--left"}),r("span",{class:"cf-assistant-card__eye cf-assistant-card__eye--right"}),r("span",{class:"cf-assistant-card__mouth"})]})}),Y&&!z&&r("span",{class:"cf-assistant-card__mouth cf-assistant-card__mouth--overlay"}),r("span",{class:"cf-avatar-aura cf-avatar-aura--one","aria-hidden":"true"}),r("span",{class:"cf-avatar-aura cf-avatar-aura--two","aria-hidden":"true"}),r("span",{class:"cf-avatar-listen-ring","aria-hidden":"true"}),r("span",{class:"cf-avatar-wave","aria-hidden":"true",children:[r("span",{}),r("span",{}),r("span",{}),r("span",{})]})]}),S,U&&r("span",{class:"cf-call-status",role:"status","aria-live":"polite",children:xr(o)}),P&&(O||r("button",{type:"button",class:"cf-assistant-card__speak",onClick:a,children:[r(Rn,{}),B]}))]}),!c&&r(se,{children:[e.agentDescription?r("p",{class:"cf-assistant-card__copy",children:e.agentDescription}):r("p",{class:"cf-assistant-card__copy",children:e.greeting}),te.length>0&&r("div",{class:"cf-assistant-card__chips",children:te.map(ue=>r("button",{type:"button",class:"cf-assistant-card__chip",onClick:()=>n(ue),children:ue},ue))}),e.disclaimerText||e.assistantPrivacyUrl?r("p",{class:"cf-assistant-card__privacy",children:[e.disclaimerText||"This chat may be recorded for quality and support.",e.assistantPrivacyUrl?r(se,{children:[" ",r("a",{href:e.assistantPrivacyUrl,target:"_blank",rel:"noopener noreferrer nofollow",children:"Privacy Policy"})]}):null]}):null]})]})},Md={calendar:ed,"calendar-clock":rd,headset:io,mail:gr,message:nd,newsletter:id,phone:td,presentation:ad,lifebuoy:io},Id=e=>Md[e]??gr,Ed=e=>{if(e.id==="public_contact_support")return"contact-support";switch(e.endpoint){case"book-demo":return"book-demo";case"request-callback":return"request-callback";case"schedule-callback":return"schedule-callback";case"subscribe-newsletter":return"subscribe-newsletter";case"contact":return"contact";default:return"inquiry"}},zd={public_contact_support:{label:"Contact support",description:"Send your request to the support team.",category:"support",icon:"headset",endpoint:"inquiry"},public_submit_inquiry:{label:"Leave a message",description:"Send your question and contact details.",category:"support",icon:"message",endpoint:"inquiry"},public_book_demo:{label:"Book a demo",description:"Request a demo from the team.",category:"sales",icon:"presentation",endpoint:"book-demo"},public_request_callback:{label:"Request a callback",description:"Ask the next available sales teammate to call you.",category:"sales",icon:"phone",endpoint:"request-callback"},public_schedule_callback:{label:"Schedule a callback",description:"Choose an available date and time for a call.",category:"sales",icon:"calendar-clock",endpoint:"schedule-callback"},public_subscribe_newsletter:{label:"Subscribe",description:"Get product updates.",category:"marketing",icon:"newsletter",endpoint:"subscribe-newsletter"}},Nd=(e,t,n={})=>Array.isArray(e)?e.filter(a=>a.readiness!=="unavailable").map(a=>po(a,n[a.id])):(t??[]).flatMap(a=>{const i=zd[a];if(!i)return[];const o=Ed({...i,id:a}),s=ba[o];return[{...i,id:a,presentation:o==="book-demo"||o==="schedule-callback"?"booking":"form",formTitle:s.title,submitLabel:s.submit,fields:s.fields,delivery:"",prompt:"",shortLabel:i.label.toLowerCase(),enabled:!0,readiness:"available",legacyFallback:!0}]}).map(a=>po(a,n[a.id])),po=(e,t)=>{if(!t)return e;const n=t.fields??{};return{...e,...Object.fromEntries(Object.entries(t).filter(([a,i])=>a!=="fields"&&i!==void 0)),fields:e.fields.map(a=>({...a,...n[a.key]}))}},Rd=(e,t)=>{const n=e.map(a=>a.label);return n.length===0?t.actionGetInTouch:n.length<=3?n.join(", "):`${n.slice(0,2).join(", ")} ${qe(t.actionMore,{count:String(n.length-2)})}`},fo=({label:e,required:t,value:n,onInput:a})=>{const i=Be(()=>Yl(n),[]),[o,s]=$(i.country.iso),[c,d]=$(i.national),[l,u]=$(!1),[p,m]=$(""),f=R(null),_=nn.find(x=>x.iso===o)??i.country,h=Be(()=>{const x=p.trim().toLowerCase().replace(/^\+/,"");return x?nn.filter(g=>g.name.toLowerCase().includes(x)||g.iso.toLowerCase().includes(x)||g.dial.includes(x)):nn},[p]);X(()=>{if(!l)return;const x=T=>{f.current&&!T.composedPath().includes(f.current)&&u(!1)},g=T=>{T.key==="Escape"&&u(!1)};return document.addEventListener("pointerdown",x),document.addEventListener("keydown",g),()=>{document.removeEventListener("pointerdown",x),document.removeEventListener("keydown",g)}},[l]);const I=x=>{const g=nn.find(T=>T.iso===x)??_;s(g.iso),u(!1),m(""),a(ro(g,c))};return r("div",{class:"cf-phone",role:"group","aria-label":`${e}${t?" *":""}`,ref:f,children:[r("span",{class:"cf-phone__label",children:[e,t?" *":""]}),r("div",{class:"cf-phone__control",children:[r("button",{type:"button",class:"cf-phone__country","aria-label":`${_.name}, +${_.dial}. Choose country and calling code`,"aria-haspopup":"listbox","aria-expanded":l,onClick:()=>u(x=>!x),children:[r("span",{"aria-hidden":"true",children:ao(_.iso)}),r("span",{class:"cf-phone__country-code",children:["+",_.dial]}),r(pn,{})]}),r("input",{class:"cf-phone__input",type:"tel",inputMode:"numeric",pattern:"[0-9]*",autoComplete:"tel-national",maxLength:15,placeholder:"8028509941",value:c,"aria-label":e,onInput:x=>{const g=x.target,T=g.value.replace(/\D/g,"");g.value=T,d(T),a(ro(_,T))}})]}),l?r("div",{class:"cf-phone__menu",children:[r("input",{class:"cf-phone__search",type:"search",placeholder:"Search country or code","aria-label":"Search countries",value:p,autoFocus:!0,onInput:x=>m(x.target.value)}),r("div",{class:"cf-phone__options",role:"listbox","aria-label":"Countries",children:h.length>0?h.map(x=>r("button",{type:"button",class:`cf-phone__option ${x.iso===_.iso?"is-selected":""}`,role:"option","aria-selected":x.iso===_.iso,onClick:()=>I(x.iso),children:[r("span",{"aria-hidden":"true",children:ao(x.iso)}),r("span",{class:"cf-phone__option-name",children:x.name}),r("span",{class:"cf-phone__option-code",children:["+",x.dial]})]},x.iso)):r("div",{class:"cf-phone__empty",children:"No countries found"})})]}):null]})},Ld=({field:e,value:t,onInput:n})=>{if(e.kind==="tel")return r(fo,{label:e.label,required:e.required,value:t,onInput:n});const a=e.placeholder??e.label,i={class:"cf-form__input",placeholder:e.required?`${a} *`:a,value:t,"aria-label":e.label,onInput:o=>n(o.target.value)};return e.kind==="textarea"?r("textarea",{rows:2,...i}):r("input",{type:e.kind,...i})},Dd=({spec:e,visitor:t,onSubmit:n,onCancel:a})=>{const i=ct(),o=lo(),[s,c]=$(()=>{const x={};for(const g of e.fields)g.identity&&t[g.identity]&&(x[g.key]=t[g.identity]);return x}),[d,l]=$("idle"),[u,p]=$(""),m=x=>!!(x.identity&&t[x.identity]?.trim()),f=e.fields.filter(x=>!m(x)),_=f.every(x=>!x.required||(s[x.key]?.trim()??"")!==""),h=t.email||t.name||"",I=async()=>{if(!_||d==="submitting")return;l("submitting");const x={},g={};for(const T of e.fields){const V=s[T.key]?.trim();V&&(x[T.key]=V,T.identity&&(g[T.identity]=V))}try{const T=await n(x,g);p(Nn(T.note||i.formThanks,T.caseReference,i)),l("done")}catch{l("error")}};return d==="done"?r("div",{class:"cf-form cf-form--done",children:[r(fn,{}),r("span",{children:u})]}):r("div",{class:"cf-form",ref:o,children:[f.length===0&&h&&r("div",{class:"cf-form__as",children:qe(i.actionAs,{identity:h})}),f.map(x=>r(Ld,{field:x,value:s[x.key]??"",onInput:g=>c(T=>({...T,[x.key]:g}))},x.key)),d==="error"&&r("div",{class:"cf-form__err",children:i.formError}),r("div",{class:"cf-form__actions",children:[a&&r("button",{type:"button",class:"cf-form__cancel",onClick:a,children:i.cancel}),r("button",{type:"button",class:"cf-form__submit",disabled:!_||d==="submitting",onClick:I,children:d==="submitting"?i.sending:e.submit})]})]})},ho=e=>String(e).padStart(2,"0"),Pd=()=>{const e=[];for(let t=9;t<=17;t++)e.push(`${ho(t)}:00`),e.push(`${ho(t)}:30`);return e},Od=e=>{const t=new Date;return t.setHours(0,0,0,0),Array.from({length:e},(n,a)=>{const i=new Date(t);return i.setDate(t.getDate()+a),i})},Fd=(e,t)=>{const[n,a]=t.split(":").map(Number),i=new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,a??0);try{return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",timeZoneName:"short"}).format(i)}catch{return`${e.toDateString()} ${t}`}},Lt=(e,t)=>{const[n,a]=t.split(":").map(Number);return new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,a??0)},Ud=(e,t)=>{const n=Lt(e,t);try{return new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(n)}catch{return t}},_a=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{return""}},mo=(e,t)=>{try{const n=new URL(e);return n.searchParams.set("embed_type","Inline"),globalThis.location?.hostname&&n.searchParams.set("embed_domain",globalThis.location.hostname),t.name?.trim()&&n.searchParams.set("name",t.name.trim()),t.email?.trim()&&n.searchParams.set("email",t.email.trim()),n.toString()}catch{return e}},Bd=(e,t)=>{if(!t?.contentWindow||e.source!==t.contentWindow)return!1;try{const n=new URL(e.origin).hostname;if(n!=="calendly.com"&&!n.endsWith(".calendly.com"))return!1}catch{return!1}return!!(e.data&&typeof e.data=="object"&&typeof e.data.event=="string")},qd=({actionId:e,fields:t=ba["book-demo"].fields,visitor:n,onSubmit:a,onCancel:i,onDemoSlots:o,onConfirmHostedBooking:s,scheduler:c,title:d,submitLabel:l})=>{const u=e==="public_schedule_callback",p=u?ba["schedule-callback"]:ba["book-demo"],m=d?.trim()||p.title,f=ct(),_=lo(),h=!!(!u&&c?.connected&&c.provider==="calendly"),I=h?f.bookingOpenScheduler:l?.trim()||p.submit,x=!!(c?.connected&&c.mode==="event"&&!h&&(c.availability===void 0||c.availability.calendarIds.length>0)),g=Math.min(60,Math.max(1,c?.availability?.bookingWindowDays??14)),T=Be(()=>Od(g),[g]),[V,P]=$(null),[ee,Z]=$(x?"loading":"request_only"),[Y,z]=$(c?.availability?.slotDurationMinutes??30),[te,U]=$(_a()||c?.availability?.timezone||""),B=Be(()=>x?ee!=="available"||V===null?[]:[...new Set([...V].map(Q=>{const he=new Date(Q);return`${String(he.getHours()).padStart(2,"0")}:${String(he.getMinutes()).padStart(2,"0")}`}))].sort():Pd(),[V,ee,x]),A=Be(()=>{const Q=Date.now();for(let he=0;he<T.length;he++)if(B.some(we=>Lt(T[he],we).getTime()>Q))return he;return 0},[T,B]),[N,y]=$(A),[D,S]=$(null),[O,ue]=$(n.name??""),[oe,Fe]=$(n.email??""),[_e,Te]=$(n.phone??""),[Le,Ie]=$(""),[Ce,ve]=$("idle"),[Xe,ge]=$(""),[ie,He]=$(!1),[We,k]=$(""),[K,j]=$("scheduler"),[G,ne]=$(null),[ye,Se]=$("idle"),[et,Ye]=$(""),[tt,at]=$(""),[M,pe]=$(""),de=R(null),fe=async(Q,he,we)=>{Se("loading");try{const ce=await s?.(Q,he,we);if(!ce?.confirmed)throw new Error("booking confirmation unavailable");const be=ce?.meetingUrl||ce?.eventLink||"",wt=ce?.rescheduleUrl||ce?.cancelUrl||"";k(be||wt),j(be?"meeting":"manage"),Se("idle"),He(!1),ge(Nn(f.bookingScheduled,tt,f))}catch{Se("error"),He(!0),ge(f.bookingDetailsUnavailable)}};X(()=>{if(!et)return;const Q=he=>{if(!Bd(he,de.current)||he.data.event!=="calendly.event_scheduled")return;const we=he.data.payload,ce=we?.event?.uri?.trim()||"",be=we?.invitee?.uri?.trim()||"";M&&ce&&be?(ne({eventUri:ce,inviteeUri:be}),fe(M,ce,be),ge(f.bookingCheckingDetails)):(Se("error"),He(!0),ge(f.bookingDetailsUnavailable)),Ye(""),ve("done")};return window.addEventListener("message",Q),()=>window.removeEventListener("message",Q)},[s,tt,M,et,f]),X(()=>{if(!x||ee!=="available"||V===null)return;const Q=T.findIndex(he=>B.some(we=>V.has(Lt(he,we).getTime())));Q>=0&&y(Q)},[V,ee,T,x,B]);const Oe=!!(!u&&c?.connected&&(c.mode==="link"||c.provider==="calendly")),Ge=async()=>{if(Ce==="submitting"||Ce==="scheduling"||!n.name?.trim()&&!O.trim()||!n.email?.trim()&&!oe.trim())return;ve("submitting");const Q={};oe.trim()&&(Q.email=oe.trim()),O.trim()&&(Q.name=O.trim());try{const he=await a({...oe.trim()?{visitorEmail:oe.trim()}:{},...O.trim()?{visitorName:O.trim()}:{}},Q),we=he.booking?.schedulingLink||c?.bookingLink||"";if(!we){ve("error");return}k(we),j("scheduler"),at(he.caseReference||""),pe(he.inquiryId||""),Ye(mo(we,{name:O.trim()||n.name,email:oe.trim()||n.email})),ve("scheduling")}catch{ve("error")}},[ht,pt]=$(new Set),[yt,Dt]=$([]),[_t,Vn]=$(0),[an,rt]=$(!1);X(()=>{if(!o)return;let Q=!0;const he=new Date,we=new Date;return we.setDate(we.getDate()+g+1),o(he.toISOString(),we.toISOString()).then(ce=>{if(Q)if(pt(new Set(ce.taken.map(be=>Date.parse(be)).filter(be=>!Number.isNaN(be)))),Dt(ce.busy.map(be=>[Date.parse(be.start),Date.parse(be.end)]).filter(([be,wt])=>!Number.isNaN(be)&&!Number.isNaN(wt))),z(ce.slotDurationMinutes??30),U(_a()||ce.timezone||""),x){if(ce.status!=="available"||!Array.isArray(ce.available)){P(null),Z("unavailable");return}P(new Set(ce.available.map(be=>Date.parse(be)).filter(be=>!Number.isNaN(be)))),Z("available")}else Z(ce.status??"request_only")}).catch(()=>{!Q||!x||(P(null),Z("unavailable"))}),()=>{Q=!1}},[g,x,o,_t]);const Pt=!!n.email?.trim(),bn=!!n.name?.trim(),jt=!!n.phone?.trim(),mt=_e,Ht=!!D&&(!x||ee==="available")&&(bn||O.trim()!=="")&&(u?jt||Zl(mt):Pt||oe.trim()!==""),Ot=(u?n.phone||n.name:n.email||n.name)||"",gt=Q=>t.find(he=>he.key===Q),dt=gt("visitorName")?.label||p.fields.find(Q=>Q.key==="visitorName").label,Qe=gt("visitorEmail")?.label||f.handoffEmail,Ft=gt("visitorPhone"),it=gt("topic"),Ut=Q=>ht.has(Lt(T[N],Q).getTime()),Wt=Q=>Lt(T[N],Q).getTime()<=Date.now(),jn=Y*60*1e3,Hn=Q=>{const he=Lt(T[N],Q).getTime(),we=he+jn;return yt.some(([ce,be])=>he<be&&we>ce)},Wn=Q=>!x||V?.has(Lt(T[N],Q).getTime())===!0,Gn=async()=>{if(!Ht||Ce==="submitting"||!D)return;ve("submitting"),rt(!1);const Q=Lt(T[N],D),he=Fd(T[N],D),we={};O.trim()&&(we.name=O.trim()),u?mt&&(we.phone=mt):oe.trim()&&(we.email=oe.trim());try{const ce=await a(u?{bestTime:he,slotAt:Q.toISOString(),visitorTimezone:_a()||"UTC",...mt?{visitorPhone:mt}:{},...O.trim()?{visitorName:O.trim()}:{},...Le.trim()?{topic:Le.trim()}:{}}:{preferredAt:he,slotAt:Q.toISOString(),visitorTimezone:_a()||"UTC",...oe.trim()?{visitorEmail:oe.trim()}:{},...O.trim()?{visitorName:O.trim()}:{}},we);if(!u&&ce.booking?.mode==="link"&&ce.booking.schedulingLink?.trim()){const be=ce.booking.schedulingLink.trim();k(be),at(ce.caseReference||""),pe(ce.inquiryId||""),Ye(mo(be,{name:O.trim()||n.name,email:oe.trim()||n.email})),ve("scheduling");return}if(ce.booking?.confirmed)ge(Nn(ce.note||qe(u?f.bookingCallbackConfirmed:f.bookingConfirmed,{when:he}),ce.caseReference,f)),k(ce.booking.meetingUrl||ce.booking.rescheduleUrl||ce.booking.cancelUrl||ce.booking.eventLink||""),j(ce.booking.meetingUrl||ce.booking.eventLink?"meeting":"manage");else if(ce.booking?.verificationPending){He(!0);const be=ce.booking.eventLink||ce.booking.meetingUrl||"";/^https?:\/\//i.test(be)&&(k(be),j("unverified")),ge(Nn(ce.note||qe(f.bookingVerificationPending,{when:he}),ce.caseReference,f))}else ge(Nn(ce.note||qe(u?f.bookingCallbackRequested:f.bookingRequested,{when:he}),ce.caseReference,f));ve("done")}catch(ce){ce?.status===409?(pt(be=>new Set(be).add(Q.getTime())),S(null),rt(!0),Vn(be=>be+1),ve("idle")):ve("error")}},Tt=()=>{Ye(""),ve("idle"),i?.()};return Ce==="scheduling"&&et?r("div",{class:"cf-scheduler-overlay",role:"dialog","aria-modal":"true","aria-label":m,children:[r("header",{class:"cf-scheduler-overlay__head",children:[r("button",{type:"button",class:"cf-scheduler-overlay__back",onClick:Tt,children:f.bookingBackToChat}),r("strong",{children:m}),r("div",{class:"cf-scheduler-overlay__tools",children:[r("a",{href:We,target:"_blank",rel:"noopener noreferrer",children:[f.bookingOpenNewTab," ",r(Ln,{})]}),r("button",{type:"button","aria-label":f.bookingCloseScheduler,onClick:Tt,children:r(Dn,{})})]})]}),r("div",{class:"cf-scheduler-overlay__body",children:[r("div",{class:"cf-scheduler-overlay__loading",children:f.bookingLoadingScheduler}),r("iframe",{ref:de,class:"cf-scheduler-overlay__frame",src:et,title:m,allow:"camera; microphone; fullscreen; payment"})]})]}):Ce==="done"?r("div",{class:`cf-form cf-form--done${ie?" cf-form--pending":""}`,role:ie?"alert":"status",children:[!ie&&r(fn,{}),r("span",{children:Xe}),ye==="loading"&&r("span",{role:"status",children:f.bookingCheckingDetails}),ye==="error"&&r("div",{class:"cf-booking__receipt-error",role:"alert",children:[r("span",{children:f.bookingDetailsUnavailable}),G&&M&&s&&r("button",{type:"button",class:"cf-booking__back",onClick:()=>{fe(M,G.eventUri,G.inviteeUri)},children:f.bookingRetryDetails})]}),We&&r("a",{class:"cf-booking__link",href:We,target:"_blank",rel:"noopener noreferrer",children:[K==="meeting"?f.bookingMeetingLink:K==="manage"?f.bookingManageLink:K==="unverified"?f.bookingUnverifiedLink:f.bookingOpenScheduler," ",r(Ln,{}),r("span",{class:"cf-booking__url",children:We})]}),i&&r("button",{type:"button",class:"cf-booking__back",onClick:i,children:f.bookingBackToChat})]}):Oe?r("div",{class:"cf-form cf-booking",ref:_,children:[r("div",{class:"cf-booking__hint",children:qe(f.bookingViaProvider,{provider:c?.label??f.bookingSchedulerFallback})}),Pt?Ot?r("div",{class:"cf-form__as",children:qe(f.actionAs,{identity:Ot})}):null:r(se,{children:[!n.name?.trim()&&r("input",{class:"cf-form__input",type:"text",placeholder:`${dt} *`,value:O,"aria-label":dt,onInput:Q=>ue(Q.target.value)}),r("input",{class:"cf-form__input",type:"email",placeholder:`${Qe} *`,value:oe,"aria-label":Qe,onInput:Q=>Fe(Q.target.value)})]}),Ce==="error"&&r("div",{class:"cf-form__err",children:f.formError}),r("div",{class:"cf-form__actions",children:[i&&r("button",{type:"button",class:"cf-form__cancel",onClick:i,children:f.cancel}),r("button",{type:"button",class:"cf-form__submit",disabled:Ce==="submitting"||!n.name?.trim()&&O.trim()===""||!Pt&&oe.trim()==="",onClick:Ge,children:Ce==="submitting"?f.sending:f.bookingOpenScheduler})]})]}):r("div",{class:"cf-form cf-booking",ref:_,children:[r("div",{class:"cf-booking__hint",children:[f.bookingPickTime," ·"," ",r("span",{class:"cf-booking__dur",children:qe(u?f.bookingCallbackDuration:f.bookingDuration,{count:String(Y)})}),te?r("span",{class:"cf-booking__timezone",children:qe(f.bookingTimezone,{timezone:te})}):null]}),x&&ee==="loading"?r("div",{class:"cf-booking__state",role:"status",children:f.bookingCheckingAvailability}):null,x&&ee==="unavailable"?r("div",{class:"cf-form__err",role:"alert",children:f.bookingAvailabilityUnavailable}):null,x&&ee==="available"&&B.length===0?r("div",{class:"cf-booking__state",role:"status",children:f.bookingNoSlots}):null,B.length>0?r("div",{class:"cf-booking__dates",role:"tablist","aria-label":f.bookingPickDay,children:T.map((Q,he)=>r("button",{type:"button",role:"tab","aria-selected":he===N,disabled:x&&ee==="available"&&!B.some(we=>V?.has(Lt(Q,we).getTime())),class:`cf-booking__date ${he===N?"is-selected":""}`,onClick:()=>{y(he),S(null)},children:[r("span",{class:"cf-booking__dow",children:Q.toLocaleDateString(void 0,{weekday:"short"})}),r("span",{class:"cf-booking__dom",children:Q.getDate()})]},he))}):null,B.length>0?r("div",{class:"cf-booking__slots",role:"listbox","aria-label":f.bookingPickTimeLabel,children:B.map(Q=>{const he=Wt(Q),we=Hn(Q),ce=Ut(Q),be=Wn(Q),wt=ce||he||we||!be;return r("button",{type:"button",role:"option","aria-selected":D===Q,disabled:wt,title:he?f.bookingEarlierToday:we?f.bookingCalendarBusy:ce?f.bookingAlreadyBooked:be?void 0:f.bookingNotOffered,class:`cf-booking__slot ${D===Q?"is-selected":""} ${wt?"is-taken":""}`,onClick:()=>S(Q),children:Ud(T[N],Q)},Q)})}):null,an&&r("div",{class:"cf-form__err",children:f.bookingSlotTaken}),Ot?r("div",{class:"cf-form__as",children:qe(f.actionAs,{identity:Ot})}):null,!bn&&r("input",{class:"cf-form__input",type:"text",placeholder:`${dt} *`,value:O,"aria-label":dt,onInput:Q=>ue(Q.target.value)}),u&&!jt&&r(fo,{label:Ft?.label??"Phone number",required:!0,value:_e,onInput:Te}),u&&it?r("input",{class:"cf-form__input",type:"text",placeholder:it.placeholder||it.label,value:Le,"aria-label":it.label,onInput:Q=>Ie(Q.target.value)}):null,!u&&!Pt&&r(se,{children:r("input",{class:"cf-form__input",type:"email",placeholder:`${Qe} *`,value:oe,"aria-label":Qe,onInput:Q=>Fe(Q.target.value)})}),Ce==="error"&&r("div",{class:"cf-form__err",children:f.formError}),r("div",{class:"cf-form__actions",children:[i&&r("button",{type:"button",class:"cf-form__cancel",onClick:i,children:f.cancel}),r("button",{type:"button",class:"cf-form__submit",disabled:!Ht||Ce==="submitting",onClick:Gn,children:Ce==="submitting"?f.sending:I})]})]})},go=({actions:e,descriptors:t,visitor:n,onSubmitForm:a,onDemoSlots:i,onConfirmHostedBooking:o,scheduler:s,exclude:c=[],openAction:d,showTrigger:l=!0,translations:u={},onClose:p})=>{const m=ct(),[f,_]=$(null),[h,I]=$(!1),x=R(null),g=R(null),T=R(!1),V=R(null),P=R(void 0),ee=R(!1),Z=Be(()=>`cf-actions-${Math.random().toString(36).slice(2,9)}`,[]),Y=Be(()=>Nd(t,e,u).filter(N=>!c.includes(N.id)&&!c.includes(N.endpoint)),[t,e,c,u]);X(()=>{if(!d){P.current=void 0;return}P.current!==d&&Y.some(N=>N.id===d)&&(P.current=d,ee.current=!0,_(d),I(!0))},[d,Y]);const z=f?Y.find(N=>N.id===f):void 0,te=F(()=>{if(p){p();return}T.current=!0,V.current=x.current||g.current?.closest(".cf-panel")?.querySelector(".cf-footer-actions .cf-action-trigger, .cf-textarea")||null,ee.current=!1,_(null),I(!1)},[p]),U=F(()=>{ee.current?te():p?p():_(null)},[p,te]);Sn(()=>{h||!T.current||(T.current=!1,V.current?.focus(),V.current=null)},[h]);const B=R({drawerOpen:h,activeId:f});if(B.current={drawerOpen:h,activeId:f},X(()=>{const N=y=>{if(y.key!=="Escape")return;const{drawerOpen:D,activeId:S}=B.current;!D&&!S||(y.stopPropagation(),S?U():te())};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[U,te]),X(()=>{if(!h)return;const N=g.current;if(!N)return;N.querySelector("button, input, textarea, select")?.focus({preventScroll:!0});let y;const D=()=>{cancelAnimationFrame(y),y=requestAnimationFrame(()=>N.scrollIntoView?.({block:"nearest"}))};D();const S=N.closest(".cf-body")&&typeof ResizeObserver=="function"?new ResizeObserver(D):null;return S?.observe(N),()=>{cancelAnimationFrame(y),S?.disconnect()}},[h,f]),Y.length===0||!l&&!h)return null;const A=h?z?r("div",{ref:g,id:Z,class:"cf-action-drawer is-open",role:"dialog","aria-modal":"false","aria-label":z.formTitle||z.label,children:[r("div",{class:"cf-action-drawer__handle","aria-hidden":"true"}),r("div",{class:"cf-action-drawer__head",children:[r("div",{children:[r("strong",{children:z.formTitle||z.label}),z.legacyFallback?r("small",{class:"cf-action-test-mode",children:m.actionTestMode}):null]}),r("button",{type:"button",class:"cf-action-drawer__close","aria-label":m.actionClose,onClick:U,children:r(Dn,{})})]}),z.readiness==="degraded"&&z.readinessNote?r("p",{class:"cf-action-drawer__note cf-action-drawer__note--warn",role:"status",children:z.readinessNote}):null,z.presentation==="booking"||z.endpoint==="book-demo"||z.endpoint==="schedule-callback"?r(qd,{actionId:z.id,fields:z.fields,visitor:n,title:z.formTitle,submitLabel:z.submitLabel,onCancel:U,onSubmit:(N,y)=>a(z.id,N,y,z.endpoint),onDemoSlots:i,onConfirmHostedBooking:o,scheduler:s}):r(Dd,{spec:{title:z.formTitle||z.label,submit:z.submitLabel,fields:z.endpoint==="request-callback"?z.fields.filter(N=>N.key!=="bestTime"):z.fields},visitor:n,onCancel:U,onSubmit:(N,y)=>a(z.id,N,y,z.endpoint)})]}):r("div",{ref:g,id:Z,class:"cf-action-drawer cf-action-drawer--menu",role:"dialog","aria-modal":"false","aria-label":m.actionChoose,children:[r("div",{class:"cf-action-drawer__handle","aria-hidden":"true"}),r("div",{class:"cf-action-drawer__head",children:[r("div",{children:[r("span",{class:"cf-action-drawer__eyebrow",children:m.actionNeedHelp}),r("strong",{children:m.actionChoose})]}),r("button",{type:"button",class:"cf-action-drawer__close","aria-label":m.actionClose,onClick:te,children:r(Dn,{})})]}),r("div",{class:"cf-action-drawer__grid",children:Y.map(N=>{const y=Id(N.icon);return r("button",{type:"button",class:"cf-action-card",onClick:()=>{ee.current=!1,_(N.id)},children:[r("span",{class:`cf-action-card__icon cf-action-card__icon--${N.category}`,children:r(y,{})}),r("span",{class:"cf-action-card__copy",children:[r("strong",{children:N.label}),N.legacyFallback?r("small",{class:"cf-action-test-mode",children:m.actionTestMode}):null,r("small",{children:N.description}),N.readiness==="degraded"&&N.readinessNote?r("small",{class:"cf-action-card__warn",children:N.readinessNote}):null]}),r(pn,{})]},N.id)})}),r("p",{class:"cf-action-drawer__note",children:m.actionFooter})]}):null;return r("div",{class:"cf-action-shell",children:[l&&r("button",{ref:x,type:"button",class:"cf-action-trigger",hidden:h,"aria-expanded":h,"aria-controls":Z,onClick:()=>h?te():I(!0),children:[r("span",{class:"cf-action-trigger__icon",children:r(gr,{})}),r("span",{class:"cf-action-trigger__copy",children:[r("strong",{children:m.actionContactOptions}),r("small",{children:Rd(Y,m)})]}),r(pn,{})]}),A]})},Vd=({hasEmail:e,visitor:t,question:n,onSubmitForm:a})=>{const i=ct(),[o,s]=$(!1),[c,d]=$(!1),[l,u]=$(t.name??""),[p,m]=$(t.email??"");if(e)return r("div",{class:"cf-handoff cf-handoff--done",children:[r(fn,{}),r("span",{children:"We’ve alerted the team. If someone is available, they can continue here."})]});if(o){const _=t.email||p;return r("div",{class:"cf-handoff cf-handoff--done",children:[r(fn,{}),r("span",{children:qe(i.handoffShared,{email:_})})]})}const f=async()=>{if(!(!p.trim()||c)){d(!0);try{await a("inquiry",{visitorEmail:p.trim(),...l.trim()?{visitorName:l.trim()}:{},message:n||"I had a question the assistant couldn’t answer.",subject:"Help request from chat"},{email:p.trim(),name:l.trim()||void 0}),s(!0)}catch{d(!1)}}};return r("div",{class:"cf-handoff",children:[r("div",{class:"cf-handoff__title",children:i.handoffTitle}),r("input",{class:"cf-form__input",type:"text",placeholder:i.handoffName,value:l,"aria-label":i.handoffName,onInput:_=>u(_.target.value)}),r("input",{class:"cf-form__input",type:"email",placeholder:`${i.handoffEmail} *`,value:p,"aria-label":i.handoffEmail,onInput:_=>m(_.target.value)}),r("button",{type:"button",class:"cf-form__submit",disabled:!p.trim()||c,onClick:f,children:c?i.sending:i.handoffNotify})]})},jd=({text:e})=>{const t=ct(),[n,a]=$(!1);return r("button",{type:"button",class:"cf-tool",onClick:async()=>{try{await navigator.clipboard.writeText(e),a(!0),setTimeout(()=>a(!1),1500)}catch{}},"aria-label":t.copy,children:[n?r(fn,{}):r(ld,{}),n?t.copied:t.copy]})},Hd=({items:e,onPick:t})=>e.length===0?null:r("div",{class:"cf-starters",children:e.map((n,a)=>r("button",{type:"button",class:"cf-starter",onClick:()=>t(n),children:n},a))}),Wd=({items:e})=>{const t=e.filter(n=>n.label.trim()&&n.url.trim()).slice(0,4);return t.length===0?null:r("div",{class:"cf-featured-links",children:t.map((n,a)=>r("a",{class:"cf-featured-link",href:n.url,target:"_blank",rel:"noopener noreferrer nofollow",title:n.label,children:[r(Ln,{}),r("span",{children:n.label})]},`${n.url}-${a}`))})},Gd=({msg:e,onRate:t})=>{const n=ct(),[a,i]=$(!1),[o,s]=$(""),c=e.feedback,d=()=>{t(e.id,"up"),i(!1)},l=()=>{t(e.id,"down"),i(!0)},u=()=>{t(e.id,"down",o.trim()),i(!1)};return r("div",{class:"cf-feedback",children:[r("div",{class:"cf-feedback__row",children:[r("span",{class:"cf-feedback__label",children:n.feedbackAnswerPrompt}),r("button",{type:"button",class:`cf-feedback__btn ${c==="up"?"is-active":""}`,"aria-label":`${n.feedbackHelpful} answer`,"aria-pressed":c==="up",onClick:d,children:r(oo,{})}),r("button",{type:"button",class:`cf-feedback__btn ${c==="down"?"is-active":""}`,"aria-label":`${n.feedbackNotHelpful} answer`,"aria-pressed":c==="down",onClick:l,children:r(so,{})}),c&&!a&&r("span",{class:"cf-feedback__thanks",children:n.feedbackThanks})]}),a&&c==="down"&&r("div",{class:"cf-feedback__comment",children:[r("textarea",{class:"cf-feedback__input",rows:2,placeholder:n.feedbackCommentPlaceholder,value:o,onInput:p=>s(p.target.value)}),r("button",{type:"button",class:"cf-feedback__send",onClick:u,children:n.feedbackSend})]})]})},bo=e=>e.attachments??(e.attachmentName?[{id:e.attachmentId,name:e.attachmentName}]:[]),Kd=({msg:e,persona:t,isLast:n,visitor:a,hasEmail:i,lastQuestion:o,showActions:s,onPickReply:c,onSubmitForm:d,onDemoSlots:l,onConfirmHostedBooking:u,onRetry:p,ratable:m,onRate:f,onExpandVisualization:_,onExpandExplanation:h,onReconnect:I,onOpenAttachment:x,onExplanationFeedback:g,explanationTransport:T,onOpenAnalyticsSource:V})=>{const P=ct(),ee=mr(),Z=e.role==="user",Y=e.liveEventType??"",z=e.content.trim().toLowerCase(),te=Y==="handoff_queued"||Y==="agent_joined"||Y==="agent_left"||Y==="ai_handback"||Y==="conversation_ended"||z.includes("joined the chat")||z.includes("left the chat")||z.includes("support agents will be with you"),U=e.role==="system"||te,B=e.requestedContactFields?.includes("email")===!0,A=n&&!Z&&!U&&!e.reconnectOffer&&!!(e.handoffOffered||B),N=A&&!i?["inquiry"]:[],y=!e.pending&&!e.streaming,D=[...e.artifacts??[],...e.visualization&&!(e.artifacts??[]).some(S=>S.type==="visualization")?[{type:"visualization",visualization:e.visualization}]:[]];return U?r("div",{class:"cf-msg cf-msg--system",children:r("div",{class:"cf-system-event",children:[r("div",{class:"cf-system-event__mark","aria-hidden":"true"}),r("div",{class:"cf-system-event__text",children:e.content}),I&&r("button",{type:"button",class:"cf-system-event__action",onClick:I,children:P.reconnectSupport}),e.createdAt&&r("div",{class:"cf-system-event__time",children:new Date(e.createdAt).toLocaleString(void 0,{day:"2-digit",month:"short",year:"numeric",hour:"numeric",minute:"2-digit"})})]})}):r("div",{class:`cf-msg cf-msg--${Z?"user":"agent"}`,children:[!Z&&r(uo,{persona:t,small:!0}),r("div",{class:`cf-msg__col${!Z&&s?" cf-msg__col--actions":""}`,children:[e.pending&&e.content===""?r(Sd,{}):e.imageUrl?r("div",{class:"cf-msg__bubble cf-msg__bubble--media",children:[r("img",{class:"cf-msg__media",src:e.imageUrl,alt:"GIF"}),e.content&&r("span",{class:"cf-msg__caption",children:e.content})]}):r("div",{class:"cf-msg__bubble",children:[Z?e.content:_d(e.content),e.streaming&&r("span",{class:"cf-caret","aria-hidden":"true"})]}),Z?null:D.map((S,O)=>S.type==="visualization"&&S.visualization?r(vo,{visualization:S.visualization,onFollowUp:c,onExpand:_?()=>_(e.id):void 0,expandControlId:e.id},`visualization-${O}`):S.type==="image"&&(S.data||S.uri?.startsWith("https://"))&&["image/png","image/jpeg","image/webp"].includes(S.mimeType??"")?r("figure",{class:"cf-artifact",children:[S.title?r("figcaption",{children:S.title}):null,r("img",{src:S.uri||`data:${S.mimeType};base64,${S.data}`,alt:S.altText||S.caption||S.title||"Tool result"}),S.caption&&S.caption!==S.title?r("p",{children:S.caption}):null]},`image-${O}`):S.type==="video"&&S.uri?.startsWith("https://")&&(S.mimeType??"").startsWith("video/")?r("figure",{class:"cf-artifact",children:[S.title?r("figcaption",{children:S.title}):null,r("video",{controls:!0,preload:"metadata",playsInline:!0,src:S.uri}),S.caption&&S.caption!==S.title?r("p",{children:S.caption}):null]},`video-${O}`):S.type==="resource_link"&&S.uri?.startsWith("https://")?r("a",{class:"cf-artifact-link",href:S.uri,target:"_blank",rel:"noopener noreferrer nofollow",children:[r("strong",{children:S.title||S.name||"Open result"}),S.caption?r("span",{children:S.caption}):null]},`link-${O}`):null),!Z&&e.resultExpired&&!e.visualization?r("p",{class:"cf-analytics-expired","data-testid":"analytics-result-expired",children:[e.resultExpired.title?r("strong",{children:[e.resultExpired.title,". "]}):null,P.resultExpired]}):null,!Z&&e.visualization&&xa(e.visualization)?r("div",{class:"cf-analytics-explanation","data-testid":"inline-analytics-explanation","data-explanation-message":e.id,children:r(eo,{classPrefix:"cf",copy:P.analytics?.explanation,locale:ee,onExpand:h?()=>h(e.id):void 0,explanation:xa(e.visualization),onFollowUp:c,onFeedback:g,aiTransport:T,canOpenSource:S=>!!V&&(S.kind==="liveboard_tile"||S.kind==="insight"),onOpenSource:V?S=>{(S.kind==="liveboard_tile"||S.kind==="insight")&&V({kind:S.kind,id:S.id,...e.visualization?.appliedFilters?.length?{appliedFilters:e.visualization.appliedFilters}:{}})}:void 0,maxFollowUps:3,showLead:(()=>{const S=xa(e.visualization).headline?.trim().toLocaleLowerCase();return!S||!e.content.toLocaleLowerCase().includes(S)})()})}):null,Z&&bo(e).length>0&&r("div",{class:"cf-attach-row cf-attach-row--sent",children:bo(e).map((S,O)=>x?r("button",{type:"button",class:"cf-attach-chip cf-attach-chip--open",title:qe(P.attachOpen,{name:S.name}),"aria-label":qe(P.attachOpen,{name:S.name}),onClick:()=>x(e,S,O),children:[r(va,{}),r("span",{children:S.name})]},`${S.id??S.name}-${O}`):r("div",{class:"cf-attach-chip",title:S.name,children:[r(va,{}),r("span",{children:S.name})]},`${S.id??S.name}-${O}`))}),!Z&&r(se,{children:[y&&(e.error||e.content)&&r("div",{class:"cf-msg__actions",children:[r("div",{class:"cf-msg__tools",children:e.error?r("button",{type:"button",class:"cf-tool",onClick:()=>p(e.id,e.retryText??""),children:[r(dd,{}),P.retry]}):r(jd,{text:e.content})}),m&&!e.error&&e.content?r(Gd,{msg:e,onRate:f}):null]}),r(Td,{msg:e}),n&&r(Cd,{replies:e.suggestedReplies,onPick:c}),A&&r(Vd,{hasEmail:i,visitor:a,question:o,onSubmitForm:d}),s&&r(go,{showTrigger:!1,actions:e.availableActions,descriptors:e.actions,openAction:e.selectedAction,visitor:a,onSubmitForm:d,onDemoSlots:l,onConfirmHostedBooking:u,scheduler:t?.scheduler,exclude:N})]})]})]})},Yd=({visualization:e,onClose:t,onFollowUp:n,onFeedback:a,transport:i,onOpenSource:o})=>{const s=ct(),c=mr(),d=xa(e);return d?r("div",{class:"cf-analytics-explanation is-expanded","data-testid":"expanded-analytics-explanation",children:r(eo,{classPrefix:"cf",explanation:d,copy:s.analytics?.explanation,locale:c,expanded:!0,onCollapse:t,onFollowUp:n,onFeedback:a,aiTransport:i,canOpenSource:l=>!!o&&(l.kind==="liveboard_tile"||l.kind==="insight"),onOpenSource:o?l=>{(l.kind==="liveboard_tile"||l.kind==="insight")&&o({kind:l.kind,id:l.id,...e.appliedFilters?.length?{appliedFilters:e.appliedFilters}:{}})}:void 0})}):null},vo=({visualization:e,expanded:t=!1,onExpand:n,onClose:a,onFollowUp:i,expandControlId:o})=>{const s=ct(),c=mr();return r(gc,{visualization:e,classPrefix:"cf",labels:s.analytics,locale:c,expanded:t,onExpand:n,onClose:a,onFollowUp:i,expandControlId:o})},xo=e=>new Promise((t,n)=>{const a=new FileReader;a.onload=()=>t(String(a.result).split(",")[1]??""),a.onerror=n,a.readAsDataURL(e)}),Zd=({onPick:e})=>r("div",{class:"cf-picker cf-emoji",children:ql.map(t=>r("div",{class:"cf-emoji__group",children:[r("div",{class:"cf-emoji__label",children:t.name}),r("div",{class:"cf-emoji__grid",children:t.emojis.map((n,a)=>r("button",{type:"button",class:"cf-emoji__btn",onClick:()=>e(n),"aria-label":n,children:n},a))})]},t.name))}),Jd=({onSearch:e,onPick:t})=>{const n=ct(),[a,i]=$(""),[o,s]=$([]),[c,d]=$(!0);return X(()=>{let l=!0;d(!0);const u=setTimeout(()=>{e(a).then(p=>l&&(s(p),d(!1))).catch(()=>l&&(s([]),d(!1)))},300);return()=>{l=!1,clearTimeout(u)}},[a,e]),r("div",{class:"cf-picker cf-gif",children:[r("input",{class:"cf-gif__search",placeholder:n.searchGifs,value:a,"aria-label":n.searchGifs,onInput:l=>i(l.target.value)}),r("div",{class:"cf-gif__grid",children:c?r("div",{class:"cf-gif__hint",children:n.searchingGifs}):o.length===0?r("div",{class:"cf-gif__hint",children:n.noGifs}):o.map(l=>r("button",{type:"button",class:"cf-gif__item",onClick:()=>t(l.url),"aria-label":l.alt,children:r("img",{src:l.preview,alt:l.alt,loading:"lazy"})},l.id))}),r("div",{class:"cf-gif__powered",children:"via Tenor"})]})},Xd=5*1024*1024,vr=5,Qd="image/png,image/jpeg,image/webp,image/gif,application/pdf",eu=15e3,mn=e=>e==="listening"||e==="hearing",xr=e=>{switch(e){case"connecting":return"Connecting with AI…";case"listening":return"Listening now — go ahead.";case"hearing":return"Hearing you…";case"unavailable":return"I can’t hear you — check your microphone.";case"speaking":return"AI is speaking — talk to interrupt.";case"processing":return"Working on it — keep talking to add more.";case"noise":return"I couldn't hear clear words. Try again closer to the mic.";case"misunderstood":return"I didn't understand that. Please try again.";case"denied":return"Microphone access is blocked. Allow the mic or type your question.";case"muted":return"Muted — tap the mic to unmute.";case"timeout":return"Didn't hear anything for a while — ending the call.";default:return""}},tu=.004,yo=({muted:e,listening:t,micLevel:n,onToggleMute:a})=>{const i=t&&n>=tu;return r("button",{type:"button",class:`cf-call-btn ${e?"is-muted":""} ${t?"is-listening":""} ${i?"is-hot":""}`,"aria-label":e?"Unmute microphone":"Mute microphone","aria-pressed":e,onClick:a,style:t?{"--cf-wave":String(Math.max(.2,Math.min(1,n*6)))}:void 0,children:e?r(Ql,{}):r(Rn,{})})},nu=({audioDevices:e,selectedAudioDeviceId:t,onSelectAudioDevice:n})=>{const[a,i]=$(!1),[o,s]=$(null),c=R(null);X(()=>{if(!a)return;const l=u=>{c.current&&!u.composedPath().includes(c.current)&&i(!1)};return document.addEventListener("pointerdown",l),()=>document.removeEventListener("pointerdown",l)},[a]),Sn(()=>{if(!a){s(null);return}const l=c.current;if(!l)return;let u=new DOMRect(0,0,window.innerWidth,window.innerHeight);for(let I=l.parentElement;I;I=I.parentElement){const x=getComputedStyle(I);if(x.overflow!=="visible"||x.overflowY!=="visible"){u=I.getBoundingClientRect();break}}const p=l.getBoundingClientRect(),m=8,f=u.bottom-p.bottom-m*2,_=p.top-u.top-m*2,h=_>f;s({up:h,maxHeight:Math.max(72,Math.floor(h?_:f))})},[a]);const d=[{deviceId:"",label:"Default microphone"},...e];return r("div",{class:"cf-call-more",ref:c,children:[r("button",{type:"button",class:"cf-call-btn cf-call-btn--microphones","aria-label":"Choose microphone","aria-expanded":a,onClick:()=>i(l=>!l),children:r(pn,{})}),a&&r("div",{class:`cf-call-menu${o?.up?" cf-call-menu--up":""}`,role:"menu",style:o?{maxHeight:`${o.maxHeight}px`}:{visibility:"hidden"},children:[r("div",{class:"cf-call-menu__label",children:"Microphone"}),d.map(l=>r("button",{type:"button",role:"menuitemradio","aria-checked":l.deviceId===t,class:`cf-call-menu__item ${l.deviceId===t?"is-active":""}`,onClick:()=>{n(l.deviceId),i(!1)},children:[l.deviceId===t?r(fn,{}):r("span",{class:"cf-call-menu__spacer"}),r("span",{children:l.label})]},l.deviceId))]})]})},au=({voiceState:e,muted:t,onToggleMute:n,onEndCall:a,onTalkNow:i,showTalkNow:o,micLevel:s,theaterMode:c,onToggleTheater:d,onMinimize:l,audioDevices:u,selectedAudioDeviceId:p,onSelectAudioDevice:m})=>r("div",{class:"cf-call-controls",children:[r(yo,{muted:t,listening:mn(e)&&!t,micLevel:s,onToggleMute:n}),r(nu,{audioDevices:u,selectedAudioDeviceId:p,onSelectAudioDevice:m}),o&&r("button",{type:"button",class:"cf-call-btn cf-call-btn--talk","aria-label":"Talk now",onClick:i,children:r(Rn,{})}),r("button",{type:"button",class:"cf-call-btn","aria-label":c?"Exit expanded view":"Expand view","aria-pressed":c,onClick:d,children:c?r(hd,{}):r(fd,{})}),r("button",{type:"button",class:"cf-call-btn","aria-label":"Minimize voice chat",onClick:l,children:r(md,{})}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--end","aria-label":"End voice chat",onClick:a,children:r(br,{})})]}),ru=({persona:e,voiceState:t,muted:n,onToggleMute:a,onEndCall:i,micLevel:o,onExpand:s})=>{const c=m=>m.stopPropagation(),d=e?.assistantMediaUrl?.trim()||e?.agentAvatarUrl?.trim()||"",l=e?.assistantMediaKind==="video"&&!!d,u=e?.agentName||"Assistant",p=["cf-floating-call-card",mn(t)&&!n?"is-listening":"",t==="speaking"?"is-speaking":"",t==="processing"||t==="connecting"?"is-thinking":"",n?"is-muted":""].filter(Boolean).join(" ");return r("div",{class:p,style:mn(t)&&!n?{"--cf-listen":String(Math.max(.18,Math.min(1,o*8)))}:void 0,role:"button",tabIndex:0,"aria-label":`Reopen voice chat with ${u}`,onClick:s,onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),s())},children:[r("div",{class:"cf-floating-call-card__media","aria-hidden":"true",children:d?l?r("video",{src:d,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):r("img",{src:d,alt:""}):r("div",{class:`cf-floating-call-card__avatar${Pn(e)}`,children:[r("span",{children:ya(e)}),r("span",{class:"cf-floating-call-card__eye cf-floating-call-card__eye--left"}),r("span",{class:"cf-floating-call-card__eye cf-floating-call-card__eye--right"}),r("span",{class:"cf-floating-call-card__mouth"})]})}),r("div",{class:"cf-floating-call-card__shade","aria-hidden":"true"}),r("span",{class:"cf-floating-call-card__status",role:"status","aria-live":"polite",children:xr(t)}),r("div",{class:"cf-floating-call-card__controls",onClick:c,onKeyDown:c,role:"presentation",children:[r(yo,{muted:n,listening:mn(t)&&!n,micLevel:o,onToggleMute:a}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--restore","aria-label":"Restore voice chat",onClick:m=>{c(m),s()},children:r(gd,{})}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--end","aria-label":"End voice chat",onClick:m=>{c(m),i()},children:r(br,{})})]})]})},iu=(e,t)=>{switch(e){case"connecting":return t.voiceConnecting;case"listening":return t.voiceListening;case"hearing":return t.voiceHearing;case"unavailable":return t.voiceUnavailable;case"processing":return t.voiceProcessing;case"speaking":return t.voiceSpeaking;case"noise":return t.voiceNoise;case"misunderstood":return t.voiceMisunderstood;case"denied":return t.voiceDenied;default:return xr(e)}},ou=({draftStore:e,onSend:t,onSendGif:n,onTyping:a,disabled:i,allowVoice:o,onTranscribe:s,gifEnabled:c,onSearchGifs:d,allowAttach:l,analyzeAttachments:u=!0,onUpload:p,voiceStartSignal:m=0,onVoiceStateChange:f,onPreviewAttachment:_})=>{const h=ct(),[I,x]=$(()=>e.value),g=M=>{const pe=typeof M=="function"?M(I):M;e.value=pe,x(pe)},[T,V]=$(!1),[P,ee]=$(!1),[Z,Y]=$("idle"),[z,te]=$("none"),[U,B]=$([]),A=R([]);A.current=U;const N=R(0),[y,D]=$(!1),[S,O]=$(!1),[ue,oe]=$(""),Fe=R(null),_e=R(null),Te=R(null),Le=R(0),Ie=R(null),Ce=R(void 0),ve=M=>{Y(M),f?.(M)},Xe=()=>{Ce.current&&window.clearTimeout(Ce.current),Ce.current=void 0};X(()=>{const M=Fe.current;M&&(M.style.height="auto",M.style.height=`${Math.min(M.scrollHeight,110)}px`)},[I]),X(()=>()=>{for(const M of A.current)M.previewUrl&&URL.revokeObjectURL(M.previewUrl)},[]);const ge=M=>{B(pe=>{const de=pe.find(fe=>fe.key===M);return de?.previewUrl&&URL.revokeObjectURL(de.previewUrl),pe.filter(fe=>fe.key!==M)})},ie=()=>B([]);X(()=>{if(z==="none")return;const M=pe=>{_e.current&&!pe.composedPath().includes(_e.current)&&te("none")};return document.addEventListener("pointerdown",M),()=>document.removeEventListener("pointerdown",M)},[z]);const He=M=>te(pe=>pe===M?"none":M),We=M=>{const pe=Fe.current;if(!pe){g(Oe=>Oe+M);return}const de=pe.selectionStart??I.length,fe=pe.selectionEnd??I.length;g(I.slice(0,de)+M+I.slice(fe)),requestAnimationFrame(()=>{pe.focus();const Oe=de+M.length;pe.setSelectionRange(Oe,Oe)})},k=M=>{te("none"),n(M)},K=async M=>{if(M.length===0)return;oe("");const pe=Le.current,de=vr-A.current.length-N.current;if(de<=0){oe(qe(h.attachLimit,{count:String(vr)}));return}const fe=M.slice(0,de);N.current+=fe.length,D(!0);for(const Oe of fe){if(pe!==Le.current)break;try{await j(Oe,pe)}finally{pe===Le.current&&(N.current-=1,D(N.current>0))}}pe===Le.current&&M.length>fe.length&&oe(qe(h.attachLimit,{count:String(vr)}))},j=async(M,pe)=>{if(M.size>Xd){oe(h.attachTooLarge);return}if(!p){oe(h.attachFailed);return}try{const de=await xo(M);if(pe!==Le.current)return;const fe=await p(de,M.type||"application/octet-stream",M.name,u);if(pe!==Le.current)return;const Oe={key:`${fe.id||M.name}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,id:fe.id,analysisFailed:fe.analysisFailed,name:M.name,text:fe.text,mimeType:M.type||"application/octet-stream",size:M.size,previewUrl:M.type.startsWith("image/")?URL.createObjectURL(M):void 0,file:M};B(Ge=>[...Ge,Oe])}catch(de){if(pe!==Le.current)return;de instanceof un&&de.status===413?oe(h.attachTooLarge):de instanceof un&&[400,415,503].includes(de.status)?oe(de.message):oe(h.attachFailed)}},G=async M=>{const pe=M.target,de=Array.from(pe.files??[]);pe.value="",await K(de)},ne=()=>{Le.current+=1,N.current=0,D(!1),oe("")},ye=(!!I.trim()||U.length>0)&&!i&&!y&&!P,Se=()=>{ye&&(t(I,U.length>0?{attachments:U.map(M=>({id:M.id,name:M.name,text:M.text,file:M.file}))}:void 0),a?.(!1),g(""),ie(),oe(""))},et=M=>{const pe=M.trim();if(!pe||i){ve("misunderstood");return}const de=I.trim(),fe=de?`${de} ${pe}`:pe;t(fe),a?.(!1),g(""),ie(),oe(""),ve("idle")},Ye=M=>{if(M.key==="Enter"&&!M.shiftKey){if(i)return;M.preventDefault(),Se()}else M.key==="Escape"&&z!=="none"&&(M.preventDefault(),M.stopPropagation(),te("none"))},tt=()=>{Xe(),Ie.current?.stop("dictation-ended"),Ie.current=null,V(!1),ee(!1)},at=async()=>{const M=Ie.current;if(M){const{mic:fe,processing:Oe}=M.snapshot;fe==="hearing"||Oe?M.finishTurn():(tt(),ve("idle"));return}const pe=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||void 0;ve("connecting");const de=new qi({transcribe:async({audio:fe,mimeType:Oe,durationSeconds:Ge})=>s(await xo(fe),Oe,pe,Ge),listener:{state:({mic:fe,processing:Oe,reason:Ge})=>{if(Ie.current===de){if(fe==="unavailable"){if(Ge==="permission-denied"||Ge==="unsupported"||Ge==="no-device"||Ge==="error"){tt(),ve("denied");return}ve("unavailable");return}V(fe==="listening"||fe==="hearing"),ee(Oe),fe==="starting"?ve("connecting"):Oe&&fe!=="hearing"?ve("processing"):fe==="hearing"?ve("hearing"):fe==="listening"&&ve("listening")}},speechStart:()=>Xe(),turn:fe=>{Ie.current===de&&(tt(),et(fe.text))},noise:fe=>{Ie.current===de&&(tt(),ve(fe.reason==="transcribe-failed"?"misunderstood":"noise"))}}});Ie.current=de,Ce.current=window.setTimeout(()=>{Ie.current===de&&(tt(),ve("noise"))},eu),await de.start()};return X(()=>{!m||!o||i||T||P||at()},[m]),X(()=>()=>{Xe(),Ie.current?.stop("unmounted"),Ie.current=null},[]),r("div",{class:`cf-composer ${S?"is-dragging":""}`,ref:_e,onDragEnter:M=>{l&&(M.preventDefault(),O(!0))},onDragOver:M=>{l&&M.preventDefault()},onDragLeave:M=>{M.currentTarget===M.target&&O(!1)},onDrop:M=>{l&&(M.preventDefault(),O(!1),K(Array.from(M.dataTransfer?.files??[])))},children:[z==="emoji"&&r(Zd,{onPick:We}),z==="gif"&&r(Jd,{onSearch:d,onPick:k}),(U.length>0||y||ue)&&r("div",{class:"cf-attach-row",role:"list","aria-label":h.attachedFiles,children:[U.map(M=>r("span",{class:"cf-attach-chip",role:"listitem",title:M.name,children:[r("button",{type:"button",class:"cf-attach-open","aria-label":qe(h.attachOpen,{name:M.name}),disabled:!_,onClick:()=>_?.(M.file,M.name),children:[M.previewUrl?r("img",{class:"cf-attach-preview",src:M.previewUrl,alt:""}):r(va,{}),r("span",{class:"cf-attach-copy",children:[r("span",{children:M.name}),r("small",{children:M.analysisFailed?h.attachAnalysisFailed:`${Math.max(1,Math.ceil(M.size/1024))} KB`})]})]}),r("button",{type:"button",class:"cf-attach-x","aria-label":qe(h.removeAttachmentNamed,{name:M.name}),onClick:()=>ge(M.key),children:r(Dn,{})})]},M.key)),y&&r("span",{class:"cf-attach-status",children:[r("span",{children:h.attaching}),r("button",{type:"button",onClick:ne,children:h.cancel})]}),ue&&!y&&r("span",{class:"cf-attach-status cf-attach-status--err",children:ue})]}),Z!=="idle"&&r("div",{class:"cf-voice-state","aria-live":"polite",children:[r("span",{class:`cf-voice-state__dot ${T?"is-live":""}`}),iu(Z,h)]}),r("div",{class:"cf-composer__field",children:[r("button",{type:"button",class:`cf-iconbtn ${z==="emoji"?"is-active":""}`,"aria-label":h.emoji,"aria-pressed":z==="emoji",onClick:()=>He("emoji"),children:z==="emoji"?r(Dn,{}):r(od,{})}),c&&r("button",{type:"button",class:`cf-iconbtn cf-gifbtn ${z==="gif"?"is-active":""}`,"aria-label":h.gifs,"aria-pressed":z==="gif",onClick:()=>He("gif"),children:r("span",{class:"cf-gif-label",children:"GIF"})}),l&&r(se,{children:[r("input",{ref:Te,type:"file",class:"cf-file-input",accept:Qd,multiple:!0,onChange:G,tabIndex:-1,"aria-hidden":"true"}),r("button",{type:"button",class:"cf-iconbtn","aria-label":h.attachFile,disabled:y,onClick:()=>Te.current?.click(),children:r(va,{})})]}),r("textarea",{ref:Fe,class:"cf-textarea",rows:1,placeholder:h.composerPlaceholder,value:I,"aria-label":h.composerPlaceholder,"aria-busy":i,onInput:M=>{const pe=M.target.value;g(pe),a?.(!!pe.trim())},onPaste:M=>{const pe=Array.from(M.clipboardData?.files??[]);!l||pe.length===0||(M.preventDefault(),K(pe))},onKeyDown:Ye}),o&&r("button",{type:"button",class:`cf-iconbtn cf-mic ${T?"is-recording":""}`,"aria-label":T?h.stopRecording:h.recordVoice,"aria-pressed":T,disabled:P||i,onClick:at,children:r(Rn,{})}),r("button",{type:"button",class:"cf-send","aria-label":h.send,disabled:!ye,onClick:Se,children:r(Xl,{})})]})]})},su=e=>e.replace(/\[[^\]]{0,60}\]/g," ").replace(/\(([^)]{0,60})\)/g,(t,n)=>_o.has(n.trim().toLowerCase().replace(/[.!?,…]+$/,"").replace(/\s+/g," "))?" ":t).replace(/\*[^*]{0,60}\*/g," ").replace(/\s+/g," ").trim(),_o=new Set(["background noise","engine noise","noise","inaudible","unintelligible","silence","no speech","static","music","laughter","applause","wind","breathing","click","clicks","clicking","mouse click","mouse clicks","beep","beeps","beeping","tap","taps","tapping","typing","keyboard typing","cough","coughing","sigh","hmm","mm","mmm","uh","um","ah","oh"]),cu=/^\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?(?:\s*(?:-|–|—|to|-->)\s*\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?)?$/,lu=e=>{const t=e.trim().toLowerCase().replace(/[()[\]*]/g," ").replace(/[.!?,…]+$/,"").replace(/\s+/g," ").trim();return!t||/^(?:sh+\s*)+$/.test(t)||cu.test(t)?!0:_o.has(t)},du=e=>{const t=e.trim().toLowerCase().replace(/\s+/g," ");return t?/^(?:transcribe|transcription|transcribed text)[.!:]*$/.test(t)?!0:t.includes("transcribe this audio recording verbatim")||t.includes("preserve the spoken language and any code-switching")||t.includes("output only the transcribed text, no commentary"):!1};let wo=!0,On=null;const uu=e=>{wo=e},pu=()=>{const e=typeof window<"u"?window.AudioContext??window.webkitAudioContext:void 0;if(!e)return null;if(!On)try{On=new e}catch{return null}return On.state==="suspended"&&On.resume(),On},Fn=(e,t,n,a,i,o)=>{const s=e.createOscillator(),c=e.createGain();s.type=i,s.frequency.setValueAtTime(t,n),s.connect(c),c.connect(e.destination),c.gain.setValueAtTime(1e-4,n),c.gain.exponentialRampToValueAtTime(o,n+.012),c.gain.exponentialRampToValueAtTime(1e-4,n+a),s.start(n),s.stop(n+a+.03)},gn=e=>{if(!wo)return;const t=pu();if(!t)return;const n=t.currentTime;try{e==="open"?(Fn(t,523,n,.12,"sine",.05),Fn(t,784,n+.08,.16,"sine",.05)):e==="send"?Fn(t,660,n,.08,"triangle",.04):e==="receive"&&(Fn(t,880,n,.1,"sine",.045),Fn(t,1175,n+.09,.14,"sine",.045))}catch{}},fu=e=>e.startsWith("image/")?"image":e==="application/pdf"?"pdf":"other",hu=({state:e,onClose:t})=>{const n=ct(),a=R(null);X(()=>{a.current?.focus();const o=s=>{s.key==="Escape"&&(s.stopPropagation(),t())};return document.addEventListener("keydown",o,!0),()=>document.removeEventListener("keydown",o,!0)},[t]);const i=e.status==="ready"?fu(e.mimeType):"other";return r("div",{class:"cf-preview",role:"dialog","aria-modal":"true","aria-label":qe(n.attachPreviewTitle,{name:e.name}),onClick:o=>{o.target===o.currentTarget&&t()},children:r("div",{class:"cf-preview__frame",children:[r("div",{class:"cf-preview__bar",children:[r("span",{class:"cf-preview__name",title:e.name,children:e.name}),e.status==="ready"&&r("a",{class:"cf-preview__btn",href:e.url,download:e.name,children:n.attachDownload}),r("button",{ref:a,type:"button",class:"cf-preview__btn cf-preview__close","aria-label":n.attachPreviewClose,onClick:t,children:"✕"})]}),r("div",{class:"cf-preview__body",children:[e.status==="loading"&&r("p",{class:"cf-preview__note",children:n.attachPreviewLoading}),e.status==="error"&&r("p",{class:"cf-preview__note",children:n.attachPreviewFailed}),e.status==="ready"&&i==="image"&&r("img",{class:"cf-preview__image",src:e.url,alt:e.name}),e.status==="ready"&&i==="pdf"&&r("iframe",{class:"cf-preview__pdf",src:e.url,title:e.name}),e.status==="ready"&&i==="other"&&r("p",{class:"cf-preview__note",children:n.attachPreviewUnsupported})]})]})})},mu=e=>new Promise((t,n)=>{const a=new FileReader;a.onload=()=>t(String(a.result??"").split(",")[1]??""),a.onerror=()=>n(a.error),a.readAsDataURL(e)}),gu=(e,t)=>e?.status===429?t.errorRateLimit:t.errorGeneric,yr=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),wa=(e,t)=>{const n=yr(),a={stage:e,durationMs:Math.max(0,n-t)};try{performance.measure(`centrinfo-widget:${e}`,{start:t,end:n})}catch{}return typeof window<"u"&&typeof CustomEvent<"u"&&window.dispatchEvent(new CustomEvent("centrinfo:performance",{detail:a})),a},bu=/!?\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,vu=/https?:\/\/[^\s)]+/g,ko=e=>Ui(e).replace(bu,"$1").replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/(^|[\s([{])\*([^*\n]{1,120})\*(?=[\s.,;:!?)}\]]|$)/g,"$1$2").replace(/(^|[\s([{])_([^_\n]{1,120})_(?=[\s.,;:!?)}\]]|$)/g,"$1$2").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s{0,3}[-*+]\s+/gm,"").replace(/^\s{0,3}\d+\.\s+/gm,"").replace(/\s+\*/g," ").replace(/\*\s+/g," ").replace(/[*_]{2,}/g,"").replace(vu,t=>t.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/$/,"")).replace(/[ \t]+\n/g,`
166
+ `),n=[];let a=0,i=0;for(;i<t.length;){const o=t[i];if(o.trim().startsWith("```")){const d=[];for(i++;i<t.length&&!t[i].trim().startsWith("```");)d.push(t[i]),i++;i++,n.push(r("pre",{class:"cf-md-pre",children:r("code",{children:d.join(`
167
+ `)})},a++));continue}if(o.trim()===""){i++;continue}const s=/^(#{1,6})\s+(.*)$/.exec(o);if(s){n.push($d(s[1].length,hn(s[2]),a++)),i++;continue}if(/^\s*[-*•]\s+/.test(o)){const d=[];for(;i<t.length&&/^\s*[-*•]\s+/.test(t[i]);)d.push(r("li",{children:hn(t[i].replace(/^\s*[-*•]\s+/,""))},d.length)),i++;n.push(r("ul",{class:"cf-md-list",children:d},a++));continue}if(/^\s*\d+\.\s+/.test(o)){const d=[];for(;i<t.length&&/^\s*\d+\.\s+/.test(t[i]);)d.push(r("li",{children:hn(t[i].replace(/^\s*\d+\.\s+/,""))},d.length)),i++;n.push(r("ol",{class:"cf-md-list",children:d},a++));continue}const c=[o];for(i++;i<t.length&&t[i].trim()!==""&&!Sd.test(t[i]);)c.push(t[i]),i++;const u=c.join(" ");if(/:\s*$/.test(u)&&i<t.length&&/^(?:\s*[-*•]\s+|\s*\d+\.\s+)/.test(t[i])){const d=/^(.*[.!?])\s+([^.!?]{2,120}:)$/.exec(u);d&&n.push(r("p",{children:hn(d[1])},a++)),n.push(r("p",{class:"cf-md-list-intro",children:hn(d?.[2]??u)},a++))}else n.push(r("p",{children:hn(u)},a++))}return n},fo=e=>yl(e),ho=()=>{const e=R(null);return X(()=>{const t=requestAnimationFrame(()=>e.current?.scrollIntoView?.({block:"end"}));return()=>cancelAnimationFrame(t)},[]),e},Cd=e=>e.trim().split(/\s+/).slice(0,2).map(t=>t[0]?.toUpperCase()??"").join("")||"🤖",On=e=>{const t=e?.avatarId?.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-");return t?` cf-avatar-preset--${t}`:""},Md={"support-guide":"SG","sales-host":"SH","calm-advisor":"CA","technical-guide":"TG","school-desk":"SD","front-office":"FO"},_a=e=>{const t=e?.avatarId?.trim().toLowerCase();return t&&Md[t]||(e?Cd(e.agentName):"·")},mo=({persona:e,small:t,hideWhenMissing:n})=>{const a=t?"cf-msg__avatar":"cf-header__avatar",i=e?.agentAvatarUrl?.trim();return i?r("span",{class:a,children:r("img",{src:i,alt:""})}):n?null:r("span",{class:`${a}${On(e)}`,children:_a(e)})},Ad=()=>{const e=ct(),[t,n]=S(0),a=["Understanding your question","Checking approved information","Preparing your answer"];return X(()=>{const i=[window.setTimeout(()=>n(1),1800),window.setTimeout(()=>n(2),5e3)];return()=>i.forEach(o=>window.clearTimeout(o))},[]),r("div",{class:"cf-msg__bubble cf-typing","aria-label":e.assistantTyping,children:[r("span",{class:"cf-typing__label","aria-live":"polite",children:a[t]}),r("span",{class:"cf-typing__dot"}),r("span",{class:"cf-typing__dot"}),r("span",{class:"cf-typing__dot"})]})},Id=3,Ed=({msg:e})=>{if(!e.sources||e.sources.length===0)return null;const t=new Set,n=[];for(const o of e.sources){const s=(o.url||o.title||"").toLowerCase();!s||t.has(s)||o.url&&e.content.includes(o.url)||(t.add(s),n.push(o))}if(n.length===0)return null;const a=n.slice(0,Id),i=n.length-a.length;return r("div",{class:"cf-sources",children:[a.map((o,s)=>o.url?r("a",{class:"cf-source",href:o.url,target:"_blank",rel:"noopener noreferrer nofollow",title:o.title||o.url,children:[r(Dn,{}),r("span",{children:o.title||o.url})]},s):r("span",{class:"cf-source",title:o.title,children:[r(Dn,{}),r("span",{children:o.title})]},s)),i>0&&r("span",{class:"cf-source cf-source--more",children:["+",i," more"]})]})},zd=({replies:e,onPick:t})=>e&&e.length>0?r("div",{class:"cf-chips",children:e.map((n,a)=>r("button",{type:"button",class:"cf-chip",onClick:()=>t(n),children:n},a))}):null,Nd=({persona:e,starters:t,onPick:n,onFocusComposer:a,speaking:i,voiceState:o="idle",replyPending:s=!1,pinned:c=!1,muted:u=!1,onToggleMute:l,onEndCall:d,onTalkNow:p,showTalkNow:h=!1,micLevel:f=0,theaterMode:_=!1,onToggleTheater:x,onMinimize:w,audioDevices:v=[],selectedAudioDeviceId:m="",onSelectAudioDevice:T,connectingOnly:P=!1})=>{if(!e)return null;const O=!!(e.allowVoiceInput&&e.talkbackMode&&e.talkbackMode!=="text");if(!(O||e.widgetModule==="assistant"))return null;const J=e.agentAvatarUrl?.trim()||"",G=e.assistantMediaUrl?.trim()||J,N=e.assistantMediaKind==="video"&&!!G,se=t.slice(0,3),q=o!=="idle",F=o!=="idle"?"End voice chat":`Speak with ${e.agentName}`,C=c&&O&&!q&&!i,I=o==="connecting"||o==="processing"||q&&s,ce=["cf-assistant-card__stage","cf-assistant-card__stage--local",q?"is-live":"",I?"is-thinking":"",mn(o)&&!u?"is-listening":"",i||o==="speaking"?"is-speaking":"",u?"is-muted":""].filter(Boolean).join(" "),te=mn(o)&&!u?{"--cf-listen":String(Math.max(.18,Math.min(1,f*8)))}:void 0,ue=I&&r("span",{class:"cf-call-ripple","aria-hidden":"true",children:[r("span",{}),r("span",{}),r("span",{})]});if(P)return r("div",{class:"cf-assistant-card cf-assistant-card--connecting","aria-live":"polite",children:[r("div",{class:"cf-assistant-card__connecting-avatar",children:[J?r("img",{src:J,alt:""}):r("span",{class:`cf-assistant-card__connecting-face${On(e)}`,children:_a(e)}),ue]}),r("div",{class:"cf-assistant-card__connecting-copy",children:[r("span",{class:"cf-assistant-card__connecting-eyebrow",children:e.agentName}),r("strong",{children:"Connecting with the AI…"})]})]});const le=q&&d&&r(cu,{voiceState:o,muted:u,onToggleMute:l??(()=>{}),onEndCall:d,onTalkNow:p??(()=>{}),showTalkNow:h,micLevel:f,theaterMode:_,onToggleTheater:x??(()=>{}),onMinimize:w??(()=>{}),audioDevices:v,selectedAudioDeviceId:m,onSelectAudioDevice:T??(()=>{})});return C?r("div",{class:"cf-assistant-card cf-assistant-card--pinned cf-assistant-card--compact",children:r("button",{type:"button",class:"cf-assistant-card__compact-speak",onClick:a,children:[J?r("span",{class:"cf-assistant-card__compact-avatar",children:r("img",{src:J,alt:""})}):null,r("span",{class:"cf-assistant-card__compact-mic","aria-hidden":"true",children:r(Ln,{})}),r("span",{class:"cf-assistant-card__compact-label",children:F})]})}):r("div",{class:`cf-assistant-card ${c?"cf-assistant-card--pinned":""} ${i?"is-speaking":""}`,children:[(G||O)&&r("div",{class:ce,style:te,children:[r("div",{class:`cf-assistant-card__media ${G?"cf-assistant-card__media--uploaded":"cf-assistant-card__media--generated"}${On(e)}`,children:[N?r("video",{src:G,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):G?r("img",{src:G,alt:""}):r("div",{class:`cf-assistant-card__avatar-stage${On(e)}`,children:r("div",{class:"cf-assistant-card__face",children:[r("span",{class:"cf-assistant-card__initials",children:_a(e)}),r("span",{class:"cf-assistant-card__eye cf-assistant-card__eye--left"}),r("span",{class:"cf-assistant-card__eye cf-assistant-card__eye--right"}),r("span",{class:"cf-assistant-card__mouth"})]})}),G&&!N&&r("span",{class:"cf-assistant-card__mouth cf-assistant-card__mouth--overlay"}),r("span",{class:"cf-avatar-aura cf-avatar-aura--one","aria-hidden":"true"}),r("span",{class:"cf-avatar-aura cf-avatar-aura--two","aria-hidden":"true"}),r("span",{class:"cf-avatar-listen-ring","aria-hidden":"true"}),r("span",{class:"cf-avatar-wave","aria-hidden":"true",children:[r("span",{}),r("span",{}),r("span",{}),r("span",{})]})]}),ue,q&&r("span",{class:"cf-call-status",role:"status","aria-live":"polite",children:yr(o)}),O&&(le||r("button",{type:"button",class:"cf-assistant-card__speak",onClick:a,children:[r(Ln,{}),F]}))]}),!c&&r(de,{children:[e.agentDescription?r("p",{class:"cf-assistant-card__copy",children:e.agentDescription}):r("p",{class:"cf-assistant-card__copy",children:e.greeting}),se.length>0&&r("div",{class:"cf-assistant-card__chips",children:se.map(z=>r("button",{type:"button",class:"cf-assistant-card__chip",onClick:()=>n(z),children:z},z))}),e.disclaimerText||e.assistantPrivacyUrl?r("p",{class:"cf-assistant-card__privacy",children:[e.disclaimerText||"This chat may be recorded for quality and support.",e.assistantPrivacyUrl?r(de,{children:[" ",r("a",{href:e.assistantPrivacyUrl,target:"_blank",rel:"noopener noreferrer nofollow",children:"Privacy Policy"})]}):null]}):null]})]})},Rd={calendar:id,"calendar-clock":ld,headset:co,mail:br,message:sd,newsletter:dd,phone:od,presentation:cd,lifebuoy:co},Ld=e=>Rd[e]??br,Dd=e=>{if(e.id==="public_contact_support")return"contact-support";switch(e.endpoint){case"book-demo":return"book-demo";case"request-callback":return"request-callback";case"schedule-callback":return"schedule-callback";case"subscribe-newsletter":return"subscribe-newsletter";case"contact":return"contact";default:return"inquiry"}},Pd={public_contact_support:{label:"Contact support",description:"Send your request to the support team.",category:"support",icon:"headset",endpoint:"inquiry"},public_submit_inquiry:{label:"Leave a message",description:"Send your question and contact details.",category:"support",icon:"message",endpoint:"inquiry"},public_book_demo:{label:"Book a demo",description:"Request a demo from the team.",category:"sales",icon:"presentation",endpoint:"book-demo"},public_request_callback:{label:"Request a callback",description:"Ask the next available sales teammate to call you.",category:"sales",icon:"phone",endpoint:"request-callback"},public_schedule_callback:{label:"Schedule a callback",description:"Choose an available date and time for a call.",category:"sales",icon:"calendar-clock",endpoint:"schedule-callback"},public_subscribe_newsletter:{label:"Subscribe",description:"Get product updates.",category:"marketing",icon:"newsletter",endpoint:"subscribe-newsletter"}},Od=(e,t,n={})=>Array.isArray(e)?e.filter(a=>a.readiness!=="unavailable").map(a=>go(a,n[a.id])):(t??[]).flatMap(a=>{const i=Pd[a];if(!i)return[];const o=Dd({...i,id:a}),s=xa[o];return[{...i,id:a,presentation:o==="book-demo"||o==="schedule-callback"?"booking":"form",formTitle:s.title,submitLabel:s.submit,fields:s.fields,delivery:"",prompt:"",shortLabel:i.label.toLowerCase(),enabled:!0,readiness:"available",legacyFallback:!0}]}).map(a=>go(a,n[a.id])),go=(e,t)=>{if(!t)return e;const n=t.fields??{};return{...e,...Object.fromEntries(Object.entries(t).filter(([a,i])=>a!=="fields"&&i!==void 0)),fields:e.fields.map(a=>({...a,...n[a.key]}))}},Fd=(e,t)=>{const n=e.map(a=>a.label);return n.length===0?t.actionGetInTouch:n.length<=3?n.join(", "):`${n.slice(0,2).join(", ")} ${Ve(t.actionMore,{count:String(n.length-2)})}`},bo=({label:e,required:t,value:n,onInput:a})=>{const i=qe(()=>ed(n),[]),[o,s]=S(i.country.iso),[c,u]=S(i.national),[l,d]=S(!1),[p,h]=S(""),f=R(null),_=nn.find(v=>v.iso===o)??i.country,x=qe(()=>{const v=p.trim().toLowerCase().replace(/^\+/,"");return v?nn.filter(m=>m.name.toLowerCase().includes(v)||m.iso.toLowerCase().includes(v)||m.dial.includes(v)):nn},[p]);X(()=>{if(!l)return;const v=T=>{f.current&&!T.composedPath().includes(f.current)&&d(!1)},m=T=>{T.key==="Escape"&&d(!1)};return document.addEventListener("pointerdown",v),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",v),document.removeEventListener("keydown",m)}},[l]);const w=v=>{const m=nn.find(T=>T.iso===v)??_;s(m.iso),d(!1),h(""),a(so(m,c))};return r("div",{class:"cf-phone",role:"group","aria-label":`${e}${t?" *":""}`,ref:f,children:[r("span",{class:"cf-phone__label",children:[e,t?" *":""]}),r("div",{class:"cf-phone__control",children:[r("button",{type:"button",class:"cf-phone__country","aria-label":`${_.name}, +${_.dial}. Choose country and calling code`,"aria-haspopup":"listbox","aria-expanded":l,onClick:()=>d(v=>!v),children:[r("span",{"aria-hidden":"true",children:oo(_.iso)}),r("span",{class:"cf-phone__country-code",children:["+",_.dial]}),r(pn,{})]}),r("input",{class:"cf-phone__input",type:"tel",inputMode:"numeric",pattern:"[0-9]*",autoComplete:"tel-national",maxLength:15,placeholder:"8028509941",value:c,"aria-label":e,onInput:v=>{const m=v.target,T=m.value.replace(/\D/g,"");m.value=T,u(T),a(so(_,T))}})]}),l?r("div",{class:"cf-phone__menu",children:[r("input",{class:"cf-phone__search",type:"search",placeholder:"Search country or code","aria-label":"Search countries",value:p,autoFocus:!0,onInput:v=>h(v.target.value)}),r("div",{class:"cf-phone__options",role:"listbox","aria-label":"Countries",children:x.length>0?x.map(v=>r("button",{type:"button",class:`cf-phone__option ${v.iso===_.iso?"is-selected":""}`,role:"option","aria-selected":v.iso===_.iso,onClick:()=>w(v.iso),children:[r("span",{"aria-hidden":"true",children:oo(v.iso)}),r("span",{class:"cf-phone__option-name",children:v.name}),r("span",{class:"cf-phone__option-code",children:["+",v.dial]})]},v.iso)):r("div",{class:"cf-phone__empty",children:"No countries found"})})]}):null]})},Ud=({field:e,value:t,onInput:n})=>{if(e.kind==="tel")return r(bo,{label:e.label,required:e.required,value:t,onInput:n});const a=e.placeholder??e.label,i={class:"cf-form__input",placeholder:e.required?`${a} *`:a,value:t,"aria-label":e.label,onInput:o=>n(o.target.value)};return e.kind==="textarea"?r("textarea",{rows:2,...i}):r("input",{type:e.kind,...i})},Bd=({spec:e,visitor:t,onSubmit:n,onCancel:a})=>{const i=ct(),o=ho(),[s,c]=S(()=>{const v={};for(const m of e.fields)m.identity&&t[m.identity]&&(v[m.key]=t[m.identity]);return v}),[u,l]=S("idle"),[d,p]=S(""),h=v=>!!(v.identity&&t[v.identity]?.trim()),f=e.fields.filter(v=>!h(v)),_=f.every(v=>!v.required||(s[v.key]?.trim()??"")!==""),x=t.email||t.name||"",w=async()=>{if(!_||u==="submitting")return;l("submitting");const v={},m={};for(const T of e.fields){const P=s[T.key]?.trim();P&&(v[T.key]=P,T.identity&&(m[T.identity]=P))}try{const T=await n(v,m);p(Rn(T.note||i.formThanks,T.caseReference,i)),l("done")}catch{l("error")}};return u==="done"?r("div",{class:"cf-form cf-form--done",children:[r(fn,{}),r("span",{children:d})]}):r("div",{class:"cf-form",ref:o,children:[f.length===0&&x&&r("div",{class:"cf-form__as",children:Ve(i.actionAs,{identity:x})}),f.map(v=>r(Ud,{field:v,value:s[v.key]??"",onInput:m=>c(T=>({...T,[v.key]:m}))},v.key)),u==="error"&&r("div",{class:"cf-form__err",children:i.formError}),r("div",{class:"cf-form__actions",children:[a&&r("button",{type:"button",class:"cf-form__cancel",onClick:a,children:i.cancel}),r("button",{type:"button",class:"cf-form__submit",disabled:!_||u==="submitting",onClick:w,children:u==="submitting"?i.sending:e.submit})]})]})},vo=e=>String(e).padStart(2,"0"),qd=()=>{const e=[];for(let t=9;t<=17;t++)e.push(`${vo(t)}:00`),e.push(`${vo(t)}:30`);return e},Vd=e=>{const t=new Date;return t.setHours(0,0,0,0),Array.from({length:e},(n,a)=>{const i=new Date(t);return i.setDate(t.getDate()+a),i})},Hd=(e,t)=>{const[n,a]=t.split(":").map(Number),i=new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,a??0);try{return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",timeZoneName:"short"}).format(i)}catch{return`${e.toDateString()} ${t}`}},Lt=(e,t)=>{const[n,a]=t.split(":").map(Number);return new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,a??0)},jd=(e,t)=>{const n=Lt(e,t);try{return new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(n)}catch{return t}},wa=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{return""}},xo=(e,t)=>{try{const n=new URL(e);return n.searchParams.set("embed_type","Inline"),globalThis.location?.hostname&&n.searchParams.set("embed_domain",globalThis.location.hostname),t.name?.trim()&&n.searchParams.set("name",t.name.trim()),t.email?.trim()&&n.searchParams.set("email",t.email.trim()),n.toString()}catch{return e}},Wd=(e,t)=>{if(!t?.contentWindow||e.source!==t.contentWindow)return!1;try{const n=new URL(e.origin).hostname;if(n!=="calendly.com"&&!n.endsWith(".calendly.com"))return!1}catch{return!1}return!!(e.data&&typeof e.data=="object"&&typeof e.data.event=="string")},Gd=({actionId:e,fields:t=xa["book-demo"].fields,visitor:n,onSubmit:a,onCancel:i,onDemoSlots:o,onConfirmHostedBooking:s,scheduler:c,title:u,submitLabel:l})=>{const d=e==="public_schedule_callback",p=d?xa["schedule-callback"]:xa["book-demo"],h=u?.trim()||p.title,f=ct(),_=ho(),x=!!(!d&&c?.connected&&c.provider==="calendly"),w=x?f.bookingOpenScheduler:l?.trim()||p.submit,v=!!(c?.connected&&c.mode==="event"&&!x&&(c.availability===void 0||c.availability.calendarIds.length>0)),m=Math.min(60,Math.max(1,c?.availability?.bookingWindowDays??14)),T=qe(()=>Vd(m),[m]),[P,O]=S(null),[re,J]=S(v?"loading":"request_only"),[G,N]=S(c?.availability?.slotDurationMinutes??30),[se,q]=S(wa()||c?.availability?.timezone||""),F=qe(()=>v?re!=="available"||P===null?[]:[...new Set([...P].map(ee=>{const ve=new Date(ee);return`${String(ve.getHours()).padStart(2,"0")}:${String(ve.getMinutes()).padStart(2,"0")}`}))].sort():qd(),[P,re,v]),C=qe(()=>{const ee=Date.now();for(let ve=0;ve<T.length;ve++)if(F.some(Te=>Lt(T[ve],Te).getTime()>ee))return ve;return 0},[T,F]),[I,ce]=S(C),[te,ue]=S(null),[le,z]=S(n.name??""),[ne,He]=S(n.email??""),[y,V]=S(n.phone??""),[we,oe]=S(""),[_e,he]=S("idle"),[Ge,ke]=S(""),[K,Ne]=S(!1),[Ze,$]=S(""),[j,U]=S("scheduler"),[Y,Q]=S(null),[$e,Me]=S("idle"),[et,Je]=S(""),[tt,at]=S(""),[A,ge]=S(""),me=R(null),be=async(ee,ve,Te)=>{Me("loading");try{const pe=await s?.(ee,ve,Te);if(!pe?.confirmed)throw new Error("booking confirmation unavailable");const ye=pe?.meetingUrl||pe?.eventLink||"",wt=pe?.rescheduleUrl||pe?.cancelUrl||"";$(ye||wt),U(ye?"meeting":"manage"),Me("idle"),Ne(!1),ke(Rn(f.bookingScheduled,tt,f))}catch{Me("error"),Ne(!0),ke(f.bookingDetailsUnavailable)}};X(()=>{if(!et)return;const ee=ve=>{if(!Wd(ve,me.current)||ve.data.event!=="calendly.event_scheduled")return;const Te=ve.data.payload,pe=Te?.event?.uri?.trim()||"",ye=Te?.invitee?.uri?.trim()||"";A&&pe&&ye?(Q({eventUri:pe,inviteeUri:ye}),be(A,pe,ye),ke(f.bookingCheckingDetails)):(Me("error"),Ne(!0),ke(f.bookingDetailsUnavailable)),Je(""),he("done")};return window.addEventListener("message",ee),()=>window.removeEventListener("message",ee)},[s,tt,A,et,f]),X(()=>{if(!v||re!=="available"||P===null)return;const ee=T.findIndex(ve=>F.some(Te=>P.has(Lt(ve,Te).getTime())));ee>=0&&ce(ee)},[P,re,T,v,F]);const Ue=!!(!d&&c?.connected&&(c.mode==="link"||c.provider==="calendly")),Ke=async()=>{if(_e==="submitting"||_e==="scheduling"||!n.name?.trim()&&!le.trim()||!n.email?.trim()&&!ne.trim())return;he("submitting");const ee={};ne.trim()&&(ee.email=ne.trim()),le.trim()&&(ee.name=le.trim());try{const ve=await a({...ne.trim()?{visitorEmail:ne.trim()}:{},...le.trim()?{visitorName:le.trim()}:{}},ee),Te=ve.booking?.schedulingLink||c?.bookingLink||"";if(!Te){he("error");return}$(Te),U("scheduler"),at(ve.caseReference||""),ge(ve.inquiryId||""),Je(xo(Te,{name:le.trim()||n.name,email:ne.trim()||n.email})),he("scheduling")}catch{he("error")}},[mt,pt]=S(new Set),[yt,Dt]=S([]),[_t,Hn]=S(0),[an,rt]=S(!1);X(()=>{if(!o)return;let ee=!0;const ve=new Date,Te=new Date;return Te.setDate(Te.getDate()+m+1),o(ve.toISOString(),Te.toISOString()).then(pe=>{if(ee)if(pt(new Set(pe.taken.map(ye=>Date.parse(ye)).filter(ye=>!Number.isNaN(ye)))),Dt(pe.busy.map(ye=>[Date.parse(ye.start),Date.parse(ye.end)]).filter(([ye,wt])=>!Number.isNaN(ye)&&!Number.isNaN(wt))),N(pe.slotDurationMinutes??30),q(wa()||pe.timezone||""),v){if(pe.status!=="available"||!Array.isArray(pe.available)){O(null),J("unavailable");return}O(new Set(pe.available.map(ye=>Date.parse(ye)).filter(ye=>!Number.isNaN(ye)))),J("available")}else J(pe.status??"request_only")}).catch(()=>{!ee||!v||(O(null),J("unavailable"))}),()=>{ee=!1}},[m,v,o,_t]);const Pt=!!n.email?.trim(),bn=!!n.name?.trim(),Ht=!!n.phone?.trim(),gt=y,jt=!!te&&(!v||re==="available")&&(bn||le.trim()!=="")&&(d?Ht||td(gt):Pt||ne.trim()!==""),Ot=(d?n.phone||n.name:n.email||n.name)||"",bt=ee=>t.find(ve=>ve.key===ee),dt=bt("visitorName")?.label||p.fields.find(ee=>ee.key==="visitorName").label,Qe=bt("visitorEmail")?.label||f.handoffEmail,Ft=bt("visitorPhone"),it=bt("topic"),Ut=ee=>mt.has(Lt(T[I],ee).getTime()),Wt=ee=>Lt(T[I],ee).getTime()<=Date.now(),jn=G*60*1e3,Wn=ee=>{const ve=Lt(T[I],ee).getTime(),Te=ve+jn;return yt.some(([pe,ye])=>ve<ye&&Te>pe)},Gn=ee=>!v||P?.has(Lt(T[I],ee).getTime())===!0,Kn=async()=>{if(!jt||_e==="submitting"||!te)return;he("submitting"),rt(!1);const ee=Lt(T[I],te),ve=Hd(T[I],te),Te={};le.trim()&&(Te.name=le.trim()),d?gt&&(Te.phone=gt):ne.trim()&&(Te.email=ne.trim());try{const pe=await a(d?{bestTime:ve,slotAt:ee.toISOString(),visitorTimezone:wa()||"UTC",...gt?{visitorPhone:gt}:{},...le.trim()?{visitorName:le.trim()}:{},...we.trim()?{topic:we.trim()}:{}}:{preferredAt:ve,slotAt:ee.toISOString(),visitorTimezone:wa()||"UTC",...ne.trim()?{visitorEmail:ne.trim()}:{},...le.trim()?{visitorName:le.trim()}:{}},Te);if(!d&&pe.booking?.mode==="link"&&pe.booking.schedulingLink?.trim()){const ye=pe.booking.schedulingLink.trim();$(ye),at(pe.caseReference||""),ge(pe.inquiryId||""),Je(xo(ye,{name:le.trim()||n.name,email:ne.trim()||n.email})),he("scheduling");return}if(pe.booking?.confirmed)ke(Rn(pe.note||Ve(d?f.bookingCallbackConfirmed:f.bookingConfirmed,{when:ve}),pe.caseReference,f)),$(pe.booking.meetingUrl||pe.booking.rescheduleUrl||pe.booking.cancelUrl||pe.booking.eventLink||""),U(pe.booking.meetingUrl||pe.booking.eventLink?"meeting":"manage");else if(pe.booking?.verificationPending){Ne(!0);const ye=pe.booking.eventLink||pe.booking.meetingUrl||"";/^https?:\/\//i.test(ye)&&($(ye),U("unverified")),ke(Rn(pe.note||Ve(f.bookingVerificationPending,{when:ve}),pe.caseReference,f))}else ke(Rn(pe.note||Ve(d?f.bookingCallbackRequested:f.bookingRequested,{when:ve}),pe.caseReference,f));he("done")}catch(pe){pe?.status===409?(pt(ye=>new Set(ye).add(ee.getTime())),ue(null),rt(!0),Hn(ye=>ye+1),he("idle")):he("error")}},Tt=()=>{Je(""),he("idle"),i?.()};return _e==="scheduling"&&et?r("div",{class:"cf-scheduler-overlay",role:"dialog","aria-modal":"true","aria-label":h,children:[r("header",{class:"cf-scheduler-overlay__head",children:[r("button",{type:"button",class:"cf-scheduler-overlay__back",onClick:Tt,children:f.bookingBackToChat}),r("strong",{children:h}),r("div",{class:"cf-scheduler-overlay__tools",children:[r("a",{href:Ze,target:"_blank",rel:"noopener noreferrer",children:[f.bookingOpenNewTab," ",r(Dn,{})]}),r("button",{type:"button","aria-label":f.bookingCloseScheduler,onClick:Tt,children:r(Pn,{})})]})]}),r("div",{class:"cf-scheduler-overlay__body",children:[r("div",{class:"cf-scheduler-overlay__loading",children:f.bookingLoadingScheduler}),r("iframe",{ref:me,class:"cf-scheduler-overlay__frame",src:et,title:h,allow:"camera; microphone; fullscreen; payment"})]})]}):_e==="done"?r("div",{class:`cf-form cf-form--done${K?" cf-form--pending":""}`,role:K?"alert":"status",children:[!K&&r(fn,{}),r("span",{children:Ge}),$e==="loading"&&r("span",{role:"status",children:f.bookingCheckingDetails}),$e==="error"&&r("div",{class:"cf-booking__receipt-error",role:"alert",children:[r("span",{children:f.bookingDetailsUnavailable}),Y&&A&&s&&r("button",{type:"button",class:"cf-booking__back",onClick:()=>{be(A,Y.eventUri,Y.inviteeUri)},children:f.bookingRetryDetails})]}),Ze&&r("a",{class:"cf-booking__link",href:Ze,target:"_blank",rel:"noopener noreferrer",children:[j==="meeting"?f.bookingMeetingLink:j==="manage"?f.bookingManageLink:j==="unverified"?f.bookingUnverifiedLink:f.bookingOpenScheduler," ",r(Dn,{}),r("span",{class:"cf-booking__url",children:Ze})]}),i&&r("button",{type:"button",class:"cf-booking__back",onClick:i,children:f.bookingBackToChat})]}):Ue?r("div",{class:"cf-form cf-booking",ref:_,children:[r("div",{class:"cf-booking__hint",children:Ve(f.bookingViaProvider,{provider:c?.label??f.bookingSchedulerFallback})}),Pt?Ot?r("div",{class:"cf-form__as",children:Ve(f.actionAs,{identity:Ot})}):null:r(de,{children:[!n.name?.trim()&&r("input",{class:"cf-form__input",type:"text",placeholder:`${dt} *`,value:le,"aria-label":dt,onInput:ee=>z(ee.target.value)}),r("input",{class:"cf-form__input",type:"email",placeholder:`${Qe} *`,value:ne,"aria-label":Qe,onInput:ee=>He(ee.target.value)})]}),_e==="error"&&r("div",{class:"cf-form__err",children:f.formError}),r("div",{class:"cf-form__actions",children:[i&&r("button",{type:"button",class:"cf-form__cancel",onClick:i,children:f.cancel}),r("button",{type:"button",class:"cf-form__submit",disabled:_e==="submitting"||!n.name?.trim()&&le.trim()===""||!Pt&&ne.trim()==="",onClick:Ke,children:_e==="submitting"?f.sending:f.bookingOpenScheduler})]})]}):r("div",{class:"cf-form cf-booking",ref:_,children:[r("div",{class:"cf-booking__hint",children:[f.bookingPickTime," ·"," ",r("span",{class:"cf-booking__dur",children:Ve(d?f.bookingCallbackDuration:f.bookingDuration,{count:String(G)})}),se?r("span",{class:"cf-booking__timezone",children:Ve(f.bookingTimezone,{timezone:se})}):null]}),v&&re==="loading"?r("div",{class:"cf-booking__state",role:"status",children:f.bookingCheckingAvailability}):null,v&&re==="unavailable"?r("div",{class:"cf-form__err",role:"alert",children:f.bookingAvailabilityUnavailable}):null,v&&re==="available"&&F.length===0?r("div",{class:"cf-booking__state",role:"status",children:f.bookingNoSlots}):null,F.length>0?r("div",{class:"cf-booking__dates",role:"tablist","aria-label":f.bookingPickDay,children:T.map((ee,ve)=>r("button",{type:"button",role:"tab","aria-selected":ve===I,disabled:v&&re==="available"&&!F.some(Te=>P?.has(Lt(ee,Te).getTime())),class:`cf-booking__date ${ve===I?"is-selected":""}`,onClick:()=>{ce(ve),ue(null)},children:[r("span",{class:"cf-booking__dow",children:ee.toLocaleDateString(void 0,{weekday:"short"})}),r("span",{class:"cf-booking__dom",children:ee.getDate()})]},ve))}):null,F.length>0?r("div",{class:"cf-booking__slots",role:"listbox","aria-label":f.bookingPickTimeLabel,children:F.map(ee=>{const ve=Wt(ee),Te=Wn(ee),pe=Ut(ee),ye=Gn(ee),wt=pe||ve||Te||!ye;return r("button",{type:"button",role:"option","aria-selected":te===ee,disabled:wt,title:ve?f.bookingEarlierToday:Te?f.bookingCalendarBusy:pe?f.bookingAlreadyBooked:ye?void 0:f.bookingNotOffered,class:`cf-booking__slot ${te===ee?"is-selected":""} ${wt?"is-taken":""}`,onClick:()=>ue(ee),children:jd(T[I],ee)},ee)})}):null,an&&r("div",{class:"cf-form__err",children:f.bookingSlotTaken}),Ot?r("div",{class:"cf-form__as",children:Ve(f.actionAs,{identity:Ot})}):null,!bn&&r("input",{class:"cf-form__input",type:"text",placeholder:`${dt} *`,value:le,"aria-label":dt,onInput:ee=>z(ee.target.value)}),d&&!Ht&&r(bo,{label:Ft?.label??"Phone number",required:!0,value:y,onInput:V}),d&&it?r("input",{class:"cf-form__input",type:"text",placeholder:it.placeholder||it.label,value:we,"aria-label":it.label,onInput:ee=>oe(ee.target.value)}):null,!d&&!Pt&&r(de,{children:r("input",{class:"cf-form__input",type:"email",placeholder:`${Qe} *`,value:ne,"aria-label":Qe,onInput:ee=>He(ee.target.value)})}),_e==="error"&&r("div",{class:"cf-form__err",children:f.formError}),r("div",{class:"cf-form__actions",children:[i&&r("button",{type:"button",class:"cf-form__cancel",onClick:i,children:f.cancel}),r("button",{type:"button",class:"cf-form__submit",disabled:!jt||_e==="submitting",onClick:Kn,children:_e==="submitting"?f.sending:w})]})]})},yo=({actions:e,descriptors:t,visitor:n,onSubmitForm:a,onDemoSlots:i,onConfirmHostedBooking:o,scheduler:s,exclude:c=[],openAction:u,showTrigger:l=!0,translations:d={},onClose:p})=>{const h=ct(),[f,_]=S(null),[x,w]=S(!1),v=R(null),m=R(null),T=R(!1),P=R(null),O=R(void 0),re=R(!1),J=qe(()=>`cf-actions-${Math.random().toString(36).slice(2,9)}`,[]),G=qe(()=>Od(t,e,d).filter(I=>!c.includes(I.id)&&!c.includes(I.endpoint)),[t,e,c,d]);X(()=>{if(!u){O.current=void 0;return}O.current!==u&&G.some(I=>I.id===u)&&(O.current=u,re.current=!0,_(u),w(!0))},[u,G]);const N=f?G.find(I=>I.id===f):void 0,se=D(()=>{if(p){p();return}T.current=!0,P.current=v.current||m.current?.closest(".cf-panel")?.querySelector(".cf-footer-actions .cf-action-trigger, .cf-textarea")||null,re.current=!1,_(null),w(!1)},[p]),q=D(()=>{re.current?se():p?p():_(null)},[p,se]);Sn(()=>{x||!T.current||(T.current=!1,P.current?.focus(),P.current=null)},[x]);const F=R({drawerOpen:x,activeId:f});if(F.current={drawerOpen:x,activeId:f},X(()=>{const I=ce=>{if(ce.key!=="Escape")return;const{drawerOpen:te,activeId:ue}=F.current;!te&&!ue||(ce.stopPropagation(),ue?q():se())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[q,se]),X(()=>{if(!x)return;const I=m.current;if(!I)return;I.querySelector("button, input, textarea, select")?.focus({preventScroll:!0});let ce;const te=()=>{cancelAnimationFrame(ce),ce=requestAnimationFrame(()=>I.scrollIntoView?.({block:"nearest"}))};te();const ue=I.closest(".cf-body")&&typeof ResizeObserver=="function"?new ResizeObserver(te):null;return ue?.observe(I),()=>{cancelAnimationFrame(ce),ue?.disconnect()}},[x,f]),G.length===0||!l&&!x)return null;const C=x?N?r("div",{ref:m,id:J,class:"cf-action-drawer is-open",role:"dialog","aria-modal":"false","aria-label":N.formTitle||N.label,children:[r("div",{class:"cf-action-drawer__handle","aria-hidden":"true"}),r("div",{class:"cf-action-drawer__head",children:[r("div",{children:[r("strong",{children:N.formTitle||N.label}),N.legacyFallback?r("small",{class:"cf-action-test-mode",children:h.actionTestMode}):null]}),r("button",{type:"button",class:"cf-action-drawer__close","aria-label":h.actionClose,onClick:q,children:r(Pn,{})})]}),N.readiness==="degraded"&&N.readinessNote?r("p",{class:"cf-action-drawer__note cf-action-drawer__note--warn",role:"status",children:N.readinessNote}):null,N.presentation==="booking"||N.endpoint==="book-demo"||N.endpoint==="schedule-callback"?r(Gd,{actionId:N.id,fields:N.fields,visitor:n,title:N.formTitle,submitLabel:N.submitLabel,onCancel:q,onSubmit:(I,ce)=>a(N.id,I,ce,N.endpoint),onDemoSlots:i,onConfirmHostedBooking:o,scheduler:s}):r(Bd,{spec:{title:N.formTitle||N.label,submit:N.submitLabel,fields:N.endpoint==="request-callback"?N.fields.filter(I=>I.key!=="bestTime"):N.fields},visitor:n,onCancel:q,onSubmit:(I,ce)=>a(N.id,I,ce,N.endpoint)})]}):r("div",{ref:m,id:J,class:"cf-action-drawer cf-action-drawer--menu",role:"dialog","aria-modal":"false","aria-label":h.actionChoose,children:[r("div",{class:"cf-action-drawer__handle","aria-hidden":"true"}),r("div",{class:"cf-action-drawer__head",children:[r("div",{children:[r("span",{class:"cf-action-drawer__eyebrow",children:h.actionNeedHelp}),r("strong",{children:h.actionChoose})]}),r("button",{type:"button",class:"cf-action-drawer__close","aria-label":h.actionClose,onClick:se,children:r(Pn,{})})]}),r("div",{class:"cf-action-drawer__grid",children:G.map(I=>{const ce=Ld(I.icon);return r("button",{type:"button",class:"cf-action-card",onClick:()=>{re.current=!1,_(I.id)},children:[r("span",{class:`cf-action-card__icon cf-action-card__icon--${I.category}`,children:r(ce,{})}),r("span",{class:"cf-action-card__copy",children:[r("strong",{children:I.label}),I.legacyFallback?r("small",{class:"cf-action-test-mode",children:h.actionTestMode}):null,r("small",{children:I.description}),I.readiness==="degraded"&&I.readinessNote?r("small",{class:"cf-action-card__warn",children:I.readinessNote}):null]}),r(pn,{})]},I.id)})}),r("p",{class:"cf-action-drawer__note",children:h.actionFooter})]}):null;return r("div",{class:"cf-action-shell",children:[l&&r("button",{ref:v,type:"button",class:"cf-action-trigger",hidden:x,"aria-expanded":x,"aria-controls":J,onClick:()=>x?se():w(!0),children:[r("span",{class:"cf-action-trigger__icon",children:r(br,{})}),r("span",{class:"cf-action-trigger__copy",children:[r("strong",{children:h.actionContactOptions}),r("small",{children:Fd(G,h)})]}),r(pn,{})]}),C]})},Kd=({hasEmail:e,visitor:t,question:n,onSubmitForm:a})=>{const i=ct(),[o,s]=S(!1),[c,u]=S(!1),[l,d]=S(t.name??""),[p,h]=S(t.email??"");if(e)return r("div",{class:"cf-handoff cf-handoff--done",children:[r(fn,{}),r("span",{children:"We’ve alerted the team. If someone is available, they can continue here."})]});if(o){const _=t.email||p;return r("div",{class:"cf-handoff cf-handoff--done",children:[r(fn,{}),r("span",{children:Ve(i.handoffShared,{email:_})})]})}const f=async()=>{if(!(!p.trim()||c)){u(!0);try{await a("inquiry",{visitorEmail:p.trim(),...l.trim()?{visitorName:l.trim()}:{},message:n||"I had a question the assistant couldn’t answer.",subject:"Help request from chat"},{email:p.trim(),name:l.trim()||void 0}),s(!0)}catch{u(!1)}}};return r("div",{class:"cf-handoff",children:[r("div",{class:"cf-handoff__title",children:i.handoffTitle}),r("input",{class:"cf-form__input",type:"text",placeholder:i.handoffName,value:l,"aria-label":i.handoffName,onInput:_=>d(_.target.value)}),r("input",{class:"cf-form__input",type:"email",placeholder:`${i.handoffEmail} *`,value:p,"aria-label":i.handoffEmail,onInput:_=>h(_.target.value)}),r("button",{type:"button",class:"cf-form__submit",disabled:!p.trim()||c,onClick:f,children:c?i.sending:i.handoffNotify})]})},Yd=({text:e})=>{const t=ct(),[n,a]=S(!1);return r("button",{type:"button",class:"cf-tool",onClick:async()=>{try{await navigator.clipboard.writeText(e),a(!0),setTimeout(()=>a(!1),1500)}catch{}},"aria-label":t.copy,children:[n?r(fn,{}):r(hd,{}),n?t.copied:t.copy]})},Zd=({items:e,onPick:t})=>e.length===0?null:r("div",{class:"cf-starters",children:e.map((n,a)=>r("button",{type:"button",class:"cf-starter",onClick:()=>t(n),children:n},a))}),Jd=({items:e})=>{const t=e.filter(n=>n.label.trim()&&n.url.trim()).slice(0,4);return t.length===0?null:r("div",{class:"cf-featured-links",children:t.map((n,a)=>r("a",{class:"cf-featured-link",href:n.url,target:"_blank",rel:"noopener noreferrer nofollow",title:n.label,children:[r(Dn,{}),r("span",{children:n.label})]},`${n.url}-${a}`))})},Xd=({msg:e,onRate:t})=>{const n=ct(),[a,i]=S(!1),[o,s]=S(""),c=e.feedback,u=()=>{t(e.id,"up"),i(!1)},l=()=>{t(e.id,"down"),i(!0)},d=()=>{t(e.id,"down",o.trim()),i(!1)};return r("div",{class:"cf-feedback",children:[r("div",{class:"cf-feedback__row",children:[r("span",{class:"cf-feedback__label",children:n.feedbackAnswerPrompt}),r("button",{type:"button",class:`cf-feedback__btn ${c==="up"?"is-active":""}`,"aria-label":`${n.feedbackHelpful} answer`,"aria-pressed":c==="up",onClick:u,children:r(lo,{})}),r("button",{type:"button",class:`cf-feedback__btn ${c==="down"?"is-active":""}`,"aria-label":`${n.feedbackNotHelpful} answer`,"aria-pressed":c==="down",onClick:l,children:r(uo,{})}),c&&!a&&r("span",{class:"cf-feedback__thanks",children:n.feedbackThanks})]}),a&&c==="down"&&r("div",{class:"cf-feedback__comment",children:[r("textarea",{class:"cf-feedback__input",rows:2,placeholder:n.feedbackCommentPlaceholder,value:o,onInput:p=>s(p.target.value)}),r("button",{type:"button",class:"cf-feedback__send",onClick:d,children:n.feedbackSend})]})]})},_o=e=>e.attachments??(e.attachmentName?[{id:e.attachmentId,name:e.attachmentName}]:[]),Qd=({msg:e,persona:t,isLast:n,visitor:a,hasEmail:i,lastQuestion:o,showActions:s,onPickReply:c,onSubmitForm:u,onDemoSlots:l,onConfirmHostedBooking:d,onRetry:p,ratable:h,onRate:f,onExpandVisualization:_,onExpandExplanation:x,onReconnect:w,onOpenAttachment:v,onExplanationFeedback:m,explanationTransport:T,onOpenAnalyticsSource:P})=>{const O=ct(),re=gr(),J=e.role==="user",G=e.liveEventType??"",N=e.content.trim().toLowerCase(),se=G==="handoff_queued"||G==="agent_joined"||G==="agent_left"||G==="ai_handback"||G==="conversation_ended"||N.includes("joined the chat")||N.includes("left the chat")||N.includes("support agents will be with you"),q=e.role==="system"||se,F=e.requestedContactFields?.includes("email")===!0,C=n&&!J&&!q&&!e.reconnectOffer&&!!(e.handoffOffered||F),I=C&&!i?["inquiry"]:[],ce=!e.pending&&!e.streaming,te=[...e.artifacts??[],...e.visualization&&!(e.artifacts??[]).some(z=>z.type==="visualization")?[{type:"visualization",visualization:e.visualization}]:[]],ue=e.visualization?fo(e.visualization):void 0,le=!J&&ue?r("div",{class:"cf-analytics-explanation","data-testid":"inline-analytics-explanation","data-explanation-message":e.id,children:r(ao,{classPrefix:"cf",copy:O.analytics?.explanation,locale:re,onExpand:x?()=>x(e.id):void 0,explanation:ue,onFollowUp:c,onFeedback:m,aiTransport:T,canOpenSource:z=>!!P&&(z.kind==="liveboard_tile"||z.kind==="insight"),onOpenSource:P?z=>{(z.kind==="liveboard_tile"||z.kind==="insight")&&P({kind:z.kind,id:z.id,...e.visualization?.appliedFilters?.length?{appliedFilters:e.visualization.appliedFilters}:{}})}:void 0,maxFollowUps:3,showLead:!ue.headline?.trim()||!e.content.toLocaleLowerCase().includes(ue.headline.trim().toLocaleLowerCase())})}):null;return q?r("div",{class:"cf-msg cf-msg--system",children:r("div",{class:"cf-system-event",children:[r("div",{class:"cf-system-event__mark","aria-hidden":"true"}),r("div",{class:"cf-system-event__text",children:e.content}),w&&r("button",{type:"button",class:"cf-system-event__action",onClick:w,children:O.reconnectSupport}),e.createdAt&&r("div",{class:"cf-system-event__time",children:new Date(e.createdAt).toLocaleString(void 0,{day:"2-digit",month:"short",year:"numeric",hour:"numeric",minute:"2-digit"})})]})}):r("div",{class:`cf-msg cf-msg--${J?"user":"agent"}`,children:[!J&&r(mo,{persona:t,small:!0}),r("div",{class:`cf-msg__col${!J&&s?" cf-msg__col--actions":""}`,children:[e.pending&&e.content===""?r(Ad,{}):e.imageUrl?r("div",{class:"cf-msg__bubble cf-msg__bubble--media",children:[r("img",{class:"cf-msg__media",src:e.imageUrl,alt:"GIF"}),e.content&&r("span",{class:"cf-msg__caption",children:e.content})]}):r("div",{class:"cf-msg__bubble",children:[J?e.content:Td(e.content),e.streaming&&r("span",{class:"cf-caret","aria-hidden":"true"})]}),le,J?null:te.map((z,ne)=>z.type==="visualization"&&z.visualization?r(wo,{visualization:z.visualization,onFollowUp:c,onExpand:_?()=>_(e.id):void 0,expandControlId:e.id},`visualization-${ne}`):z.type==="image"&&(z.data||z.uri?.startsWith("https://"))&&["image/png","image/jpeg","image/webp"].includes(z.mimeType??"")?r("figure",{class:"cf-artifact",children:[z.title?r("figcaption",{children:z.title}):null,r("img",{src:z.uri||`data:${z.mimeType};base64,${z.data}`,alt:z.altText||z.caption||z.title||"Tool result"}),z.caption&&z.caption!==z.title?r("p",{children:z.caption}):null]},`image-${ne}`):z.type==="video"&&z.uri?.startsWith("https://")&&(z.mimeType??"").startsWith("video/")?r("figure",{class:"cf-artifact",children:[z.title?r("figcaption",{children:z.title}):null,r("video",{controls:!0,preload:"metadata",playsInline:!0,src:z.uri}),z.caption&&z.caption!==z.title?r("p",{children:z.caption}):null]},`video-${ne}`):z.type==="resource_link"&&z.uri?.startsWith("https://")?r("a",{class:"cf-artifact-link",href:z.uri,target:"_blank",rel:"noopener noreferrer nofollow",children:[r("strong",{children:z.title||z.name||"Open result"}),z.caption?r("span",{children:z.caption}):null]},`link-${ne}`):null),!J&&e.resultExpired&&!e.visualization?r("p",{class:"cf-analytics-expired","data-testid":"analytics-result-expired",children:[e.resultExpired.title?r("strong",{children:[e.resultExpired.title,". "]}):null,O.resultExpired]}):null,J&&_o(e).length>0&&r("div",{class:"cf-attach-row cf-attach-row--sent",children:_o(e).map((z,ne)=>v?r("button",{type:"button",class:"cf-attach-chip cf-attach-chip--open",title:Ve(O.attachOpen,{name:z.name}),"aria-label":Ve(O.attachOpen,{name:z.name}),onClick:()=>v(e,z,ne),children:[r(ya,{}),r("span",{children:z.name})]},`${z.id??z.name}-${ne}`):r("div",{class:"cf-attach-chip",title:z.name,children:[r(ya,{}),r("span",{children:z.name})]},`${z.id??z.name}-${ne}`))}),!J&&r(de,{children:[ce&&(e.error||e.content)&&r("div",{class:"cf-msg__actions",children:[r("div",{class:"cf-msg__tools",children:e.error?r("button",{type:"button",class:"cf-tool",onClick:()=>p(e.id,e.retryText??""),children:[r(md,{}),O.retry]}):r(Yd,{text:e.content})}),h&&!e.error&&e.content?r(Xd,{msg:e,onRate:f}):null]}),r(Ed,{msg:e}),n&&r(zd,{replies:e.suggestedReplies,onPick:c}),C&&r(Kd,{hasEmail:i,visitor:a,question:o,onSubmitForm:u}),s&&r(yo,{showTrigger:!1,actions:e.availableActions,descriptors:e.actions,openAction:e.selectedAction,visitor:a,onSubmitForm:u,onDemoSlots:l,onConfirmHostedBooking:d,scheduler:t?.scheduler,exclude:I})]})]})]})},eu=({visualization:e,onClose:t,onFollowUp:n,onFeedback:a,transport:i,onOpenSource:o})=>{const s=ct(),c=gr(),u=fo(e);return u?r("div",{class:"cf-analytics-explanation is-expanded","data-testid":"expanded-analytics-explanation",children:r(ao,{classPrefix:"cf",explanation:u,copy:s.analytics?.explanation,locale:c,expanded:!0,onCollapse:t,onFollowUp:n,onFeedback:a,aiTransport:i,canOpenSource:l=>!!o&&(l.kind==="liveboard_tile"||l.kind==="insight"),onOpenSource:o?l=>{(l.kind==="liveboard_tile"||l.kind==="insight")&&o({kind:l.kind,id:l.id,...e.appliedFilters?.length?{appliedFilters:e.appliedFilters}:{}})}:void 0})}):null},wo=({visualization:e,expanded:t=!1,onExpand:n,onClose:a,onFollowUp:i,expandControlId:o})=>{const s=ct(),c=gr();return r(xc,{visualization:e,classPrefix:"cf",labels:s.analytics,locale:c,expanded:t,onExpand:n,onClose:a,onFollowUp:i,expandControlId:o})},ko=e=>new Promise((t,n)=>{const a=new FileReader;a.onload=()=>t(String(a.result).split(",")[1]??""),a.onerror=n,a.readAsDataURL(e)}),tu=({onPick:e})=>r("div",{class:"cf-picker cf-emoji",children:Gl.map(t=>r("div",{class:"cf-emoji__group",children:[r("div",{class:"cf-emoji__label",children:t.name}),r("div",{class:"cf-emoji__grid",children:t.emojis.map((n,a)=>r("button",{type:"button",class:"cf-emoji__btn",onClick:()=>e(n),"aria-label":n,children:n},a))})]},t.name))}),nu=({onSearch:e,onPick:t})=>{const n=ct(),[a,i]=S(""),[o,s]=S([]),[c,u]=S(!0);return X(()=>{let l=!0;u(!0);const d=setTimeout(()=>{e(a).then(p=>l&&(s(p),u(!1))).catch(()=>l&&(s([]),u(!1)))},300);return()=>{l=!1,clearTimeout(d)}},[a,e]),r("div",{class:"cf-picker cf-gif",children:[r("input",{class:"cf-gif__search",placeholder:n.searchGifs,value:a,"aria-label":n.searchGifs,onInput:l=>i(l.target.value)}),r("div",{class:"cf-gif__grid",children:c?r("div",{class:"cf-gif__hint",children:n.searchingGifs}):o.length===0?r("div",{class:"cf-gif__hint",children:n.noGifs}):o.map(l=>r("button",{type:"button",class:"cf-gif__item",onClick:()=>t(l.url),"aria-label":l.alt,children:r("img",{src:l.preview,alt:l.alt,loading:"lazy"})},l.id))}),r("div",{class:"cf-gif__powered",children:"via Tenor"})]})},au=5*1024*1024,xr=5,ru="image/png,image/jpeg,image/webp,image/gif,application/pdf",iu=15e3,mn=e=>e==="listening"||e==="hearing",yr=e=>{switch(e){case"connecting":return"Connecting with AI…";case"listening":return"Listening now — go ahead.";case"hearing":return"Hearing you…";case"unavailable":return"I can’t hear you — check your microphone.";case"speaking":return"AI is speaking — talk to interrupt.";case"processing":return"Working on it — keep talking to add more.";case"noise":return"I couldn't hear clear words. Try again closer to the mic.";case"misunderstood":return"I didn't understand that. Please try again.";case"denied":return"Microphone access is blocked. Allow the mic or type your question.";case"muted":return"Muted — tap the mic to unmute.";case"timeout":return"Didn't hear anything for a while — ending the call.";default:return""}},ou=.004,So=({muted:e,listening:t,micLevel:n,onToggleMute:a})=>{const i=t&&n>=ou;return r("button",{type:"button",class:`cf-call-btn ${e?"is-muted":""} ${t?"is-listening":""} ${i?"is-hot":""}`,"aria-label":e?"Unmute microphone":"Mute microphone","aria-pressed":e,onClick:a,style:t?{"--cf-wave":String(Math.max(.2,Math.min(1,n*6)))}:void 0,children:e?r(rd,{}):r(Ln,{})})},su=({audioDevices:e,selectedAudioDeviceId:t,onSelectAudioDevice:n})=>{const[a,i]=S(!1),[o,s]=S(null),c=R(null);X(()=>{if(!a)return;const l=d=>{c.current&&!d.composedPath().includes(c.current)&&i(!1)};return document.addEventListener("pointerdown",l),()=>document.removeEventListener("pointerdown",l)},[a]),Sn(()=>{if(!a){s(null);return}const l=c.current;if(!l)return;let d=new DOMRect(0,0,window.innerWidth,window.innerHeight);for(let w=l.parentElement;w;w=w.parentElement){const v=getComputedStyle(w);if(v.overflow!=="visible"||v.overflowY!=="visible"){d=w.getBoundingClientRect();break}}const p=l.getBoundingClientRect(),h=8,f=d.bottom-p.bottom-h*2,_=p.top-d.top-h*2,x=_>f;s({up:x,maxHeight:Math.max(72,Math.floor(x?_:f))})},[a]);const u=[{deviceId:"",label:"Default microphone"},...e];return r("div",{class:"cf-call-more",ref:c,children:[r("button",{type:"button",class:"cf-call-btn cf-call-btn--microphones","aria-label":"Choose microphone","aria-expanded":a,onClick:()=>i(l=>!l),children:r(pn,{})}),a&&r("div",{class:`cf-call-menu${o?.up?" cf-call-menu--up":""}`,role:"menu",style:o?{maxHeight:`${o.maxHeight}px`}:{visibility:"hidden"},children:[r("div",{class:"cf-call-menu__label",children:"Microphone"}),u.map(l=>r("button",{type:"button",role:"menuitemradio","aria-checked":l.deviceId===t,class:`cf-call-menu__item ${l.deviceId===t?"is-active":""}`,onClick:()=>{n(l.deviceId),i(!1)},children:[l.deviceId===t?r(fn,{}):r("span",{class:"cf-call-menu__spacer"}),r("span",{children:l.label})]},l.deviceId))]})]})},cu=({voiceState:e,muted:t,onToggleMute:n,onEndCall:a,onTalkNow:i,showTalkNow:o,micLevel:s,theaterMode:c,onToggleTheater:u,onMinimize:l,audioDevices:d,selectedAudioDeviceId:p,onSelectAudioDevice:h})=>r("div",{class:"cf-call-controls",children:[r(So,{muted:t,listening:mn(e)&&!t,micLevel:s,onToggleMute:n}),r(su,{audioDevices:d,selectedAudioDeviceId:p,onSelectAudioDevice:h}),o&&r("button",{type:"button",class:"cf-call-btn cf-call-btn--talk","aria-label":"Talk now",onClick:i,children:r(Ln,{})}),r("button",{type:"button",class:"cf-call-btn","aria-label":c?"Exit expanded view":"Expand view","aria-pressed":c,onClick:u,children:c?r(xd,{}):r(vd,{})}),r("button",{type:"button",class:"cf-call-btn","aria-label":"Minimize voice chat",onClick:l,children:r(yd,{})}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--end","aria-label":"End voice chat",onClick:a,children:r(vr,{})})]}),lu=({persona:e,voiceState:t,muted:n,onToggleMute:a,onEndCall:i,micLevel:o,onExpand:s})=>{const c=h=>h.stopPropagation(),u=e?.assistantMediaUrl?.trim()||e?.agentAvatarUrl?.trim()||"",l=e?.assistantMediaKind==="video"&&!!u,d=e?.agentName||"Assistant",p=["cf-floating-call-card",mn(t)&&!n?"is-listening":"",t==="speaking"?"is-speaking":"",t==="processing"||t==="connecting"?"is-thinking":"",n?"is-muted":""].filter(Boolean).join(" ");return r("div",{class:p,style:mn(t)&&!n?{"--cf-listen":String(Math.max(.18,Math.min(1,o*8)))}:void 0,role:"button",tabIndex:0,"aria-label":`Reopen voice chat with ${d}`,onClick:s,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),s())},children:[r("div",{class:"cf-floating-call-card__media","aria-hidden":"true",children:u?l?r("video",{src:u,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):r("img",{src:u,alt:""}):r("div",{class:`cf-floating-call-card__avatar${On(e)}`,children:[r("span",{children:_a(e)}),r("span",{class:"cf-floating-call-card__eye cf-floating-call-card__eye--left"}),r("span",{class:"cf-floating-call-card__eye cf-floating-call-card__eye--right"}),r("span",{class:"cf-floating-call-card__mouth"})]})}),r("div",{class:"cf-floating-call-card__shade","aria-hidden":"true"}),r("span",{class:"cf-floating-call-card__status",role:"status","aria-live":"polite",children:yr(t)}),r("div",{class:"cf-floating-call-card__controls",onClick:c,onKeyDown:c,role:"presentation",children:[r(So,{muted:n,listening:mn(t)&&!n,micLevel:o,onToggleMute:a}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--restore","aria-label":"Restore voice chat",onClick:h=>{c(h),s()},children:r(_d,{})}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--end","aria-label":"End voice chat",onClick:h=>{c(h),i()},children:r(vr,{})})]})]})},du=(e,t)=>{switch(e){case"connecting":return t.voiceConnecting;case"listening":return t.voiceListening;case"hearing":return t.voiceHearing;case"unavailable":return t.voiceUnavailable;case"processing":return t.voiceProcessing;case"speaking":return t.voiceSpeaking;case"noise":return t.voiceNoise;case"misunderstood":return t.voiceMisunderstood;case"denied":return t.voiceDenied;default:return yr(e)}},uu=({draftStore:e,onSend:t,onSendGif:n,onTyping:a,disabled:i,allowVoice:o,onTranscribe:s,gifEnabled:c,onSearchGifs:u,allowAttach:l,analyzeAttachments:d=!0,onUpload:p,voiceStartSignal:h=0,onVoiceStateChange:f,onPreviewAttachment:_})=>{const x=ct(),[w,v]=S(()=>e.value),m=A=>{const ge=typeof A=="function"?A(w):A;e.value=ge,v(ge)},[T,P]=S(!1),[O,re]=S(!1),[J,G]=S("idle"),[N,se]=S("none"),[q,F]=S([]),C=R([]);C.current=q;const I=R(0),[ce,te]=S(!1),[ue,le]=S(!1),[z,ne]=S(""),He=R(null),y=R(null),V=R(null),we=R(0),oe=R(null),_e=R(void 0),he=A=>{G(A),f?.(A)},Ge=()=>{_e.current&&window.clearTimeout(_e.current),_e.current=void 0};X(()=>{const A=He.current;A&&(A.style.height="auto",A.style.height=`${Math.min(A.scrollHeight,110)}px`)},[w]),X(()=>()=>{for(const A of C.current)A.previewUrl&&URL.revokeObjectURL(A.previewUrl)},[]);const ke=A=>{F(ge=>{const me=ge.find(be=>be.key===A);return me?.previewUrl&&URL.revokeObjectURL(me.previewUrl),ge.filter(be=>be.key!==A)})},K=()=>F([]);X(()=>{if(N==="none")return;const A=ge=>{y.current&&!ge.composedPath().includes(y.current)&&se("none")};return document.addEventListener("pointerdown",A),()=>document.removeEventListener("pointerdown",A)},[N]);const Ne=A=>se(ge=>ge===A?"none":A),Ze=A=>{const ge=He.current;if(!ge){m(Ue=>Ue+A);return}const me=ge.selectionStart??w.length,be=ge.selectionEnd??w.length;m(w.slice(0,me)+A+w.slice(be)),requestAnimationFrame(()=>{ge.focus();const Ue=me+A.length;ge.setSelectionRange(Ue,Ue)})},$=A=>{se("none"),n(A)},j=async A=>{if(A.length===0)return;ne("");const ge=we.current,me=xr-C.current.length-I.current;if(me<=0){ne(Ve(x.attachLimit,{count:String(xr)}));return}const be=A.slice(0,me);I.current+=be.length,te(!0);for(const Ue of be){if(ge!==we.current)break;try{await U(Ue,ge)}finally{ge===we.current&&(I.current-=1,te(I.current>0))}}ge===we.current&&A.length>be.length&&ne(Ve(x.attachLimit,{count:String(xr)}))},U=async(A,ge)=>{if(A.size>au){ne(x.attachTooLarge);return}if(!p){ne(x.attachFailed);return}try{const me=await ko(A);if(ge!==we.current)return;const be=await p(me,A.type||"application/octet-stream",A.name,d);if(ge!==we.current)return;const Ue={key:`${be.id||A.name}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,id:be.id,analysisFailed:be.analysisFailed,name:A.name,text:be.text,mimeType:A.type||"application/octet-stream",size:A.size,previewUrl:A.type.startsWith("image/")?URL.createObjectURL(A):void 0,file:A};F(Ke=>[...Ke,Ue])}catch(me){if(ge!==we.current)return;me instanceof un&&me.status===413?ne(x.attachTooLarge):me instanceof un&&[400,415,503].includes(me.status)?ne(me.message):ne(x.attachFailed)}},Y=async A=>{const ge=A.target,me=Array.from(ge.files??[]);ge.value="",await j(me)},Q=()=>{we.current+=1,I.current=0,te(!1),ne("")},$e=(!!w.trim()||q.length>0)&&!i&&!ce&&!O,Me=()=>{$e&&(t(w,q.length>0?{attachments:q.map(A=>({id:A.id,name:A.name,text:A.text,file:A.file}))}:void 0),a?.(!1),m(""),K(),ne(""))},et=A=>{const ge=A.trim();if(!ge||i){he("misunderstood");return}const me=w.trim(),be=me?`${me} ${ge}`:ge;t(be),a?.(!1),m(""),K(),ne(""),he("idle")},Je=A=>{if(A.key==="Enter"&&!A.shiftKey){if(i)return;A.preventDefault(),Me()}else A.key==="Escape"&&N!=="none"&&(A.preventDefault(),A.stopPropagation(),se("none"))},tt=()=>{Ge(),oe.current?.stop("dictation-ended"),oe.current=null,P(!1),re(!1)},at=async()=>{const A=oe.current;if(A){const{mic:be,processing:Ue}=A.snapshot;be==="hearing"||Ue?A.finishTurn():(tt(),he("idle"));return}const ge=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||void 0;he("connecting");const me=new Hi({transcribe:async({audio:be,mimeType:Ue,durationSeconds:Ke})=>s(await ko(be),Ue,ge,Ke),listener:{state:({mic:be,processing:Ue,reason:Ke})=>{if(oe.current===me){if(be==="unavailable"){if(Ke==="permission-denied"||Ke==="unsupported"||Ke==="no-device"||Ke==="error"){tt(),he("denied");return}he("unavailable");return}P(be==="listening"||be==="hearing"),re(Ue),be==="starting"?he("connecting"):Ue&&be!=="hearing"?he("processing"):be==="hearing"?he("hearing"):be==="listening"&&he("listening")}},speechStart:()=>Ge(),turn:be=>{oe.current===me&&(tt(),et(be.text))},noise:be=>{oe.current===me&&(tt(),he(be.reason==="transcribe-failed"?"misunderstood":"noise"))}}});oe.current=me,_e.current=window.setTimeout(()=>{oe.current===me&&(tt(),he("noise"))},iu),await me.start()};return X(()=>{!h||!o||i||T||O||at()},[h]),X(()=>()=>{Ge(),oe.current?.stop("unmounted"),oe.current=null},[]),r("div",{class:`cf-composer ${ue?"is-dragging":""}`,ref:y,onDragEnter:A=>{l&&(A.preventDefault(),le(!0))},onDragOver:A=>{l&&A.preventDefault()},onDragLeave:A=>{A.currentTarget===A.target&&le(!1)},onDrop:A=>{l&&(A.preventDefault(),le(!1),j(Array.from(A.dataTransfer?.files??[])))},children:[N==="emoji"&&r(tu,{onPick:Ze}),N==="gif"&&r(nu,{onSearch:u,onPick:$}),(q.length>0||ce||z)&&r("div",{class:"cf-attach-row",role:"list","aria-label":x.attachedFiles,children:[q.map(A=>r("span",{class:"cf-attach-chip",role:"listitem",title:A.name,children:[r("button",{type:"button",class:"cf-attach-open","aria-label":Ve(x.attachOpen,{name:A.name}),disabled:!_,onClick:()=>_?.(A.file,A.name),children:[A.previewUrl?r("img",{class:"cf-attach-preview",src:A.previewUrl,alt:""}):r(ya,{}),r("span",{class:"cf-attach-copy",children:[r("span",{children:A.name}),r("small",{children:A.analysisFailed?x.attachAnalysisFailed:`${Math.max(1,Math.ceil(A.size/1024))} KB`})]})]}),r("button",{type:"button",class:"cf-attach-x","aria-label":Ve(x.removeAttachmentNamed,{name:A.name}),onClick:()=>ke(A.key),children:r(Pn,{})})]},A.key)),ce&&r("span",{class:"cf-attach-status",children:[r("span",{children:x.attaching}),r("button",{type:"button",onClick:Q,children:x.cancel})]}),z&&!ce&&r("span",{class:"cf-attach-status cf-attach-status--err",children:z})]}),J!=="idle"&&r("div",{class:"cf-voice-state","aria-live":"polite",children:[r("span",{class:`cf-voice-state__dot ${T?"is-live":""}`}),du(J,x)]}),r("div",{class:"cf-composer__field",children:[r("button",{type:"button",class:`cf-iconbtn ${N==="emoji"?"is-active":""}`,"aria-label":x.emoji,"aria-pressed":N==="emoji",onClick:()=>Ne("emoji"),children:N==="emoji"?r(Pn,{}):r(ud,{})}),c&&r("button",{type:"button",class:`cf-iconbtn cf-gifbtn ${N==="gif"?"is-active":""}`,"aria-label":x.gifs,"aria-pressed":N==="gif",onClick:()=>Ne("gif"),children:r("span",{class:"cf-gif-label",children:"GIF"})}),l&&r(de,{children:[r("input",{ref:V,type:"file",class:"cf-file-input",accept:ru,multiple:!0,onChange:Y,tabIndex:-1,"aria-hidden":"true"}),r("button",{type:"button",class:"cf-iconbtn","aria-label":x.attachFile,disabled:ce,onClick:()=>V.current?.click(),children:r(ya,{})})]}),r("textarea",{ref:He,class:"cf-textarea",rows:1,placeholder:x.composerPlaceholder,value:w,"aria-label":x.composerPlaceholder,"aria-busy":i,onInput:A=>{const ge=A.target.value;m(ge),a?.(!!ge.trim())},onPaste:A=>{const ge=Array.from(A.clipboardData?.files??[]);!l||ge.length===0||(A.preventDefault(),j(ge))},onKeyDown:Je}),o&&r("button",{type:"button",class:`cf-iconbtn cf-mic ${T?"is-recording":""}`,"aria-label":T?x.stopRecording:x.recordVoice,"aria-pressed":T,disabled:O||i,onClick:at,children:r(Ln,{})}),r("button",{type:"button",class:"cf-send","aria-label":x.send,disabled:!$e,onClick:Me,children:r(ad,{})})]})]})},pu=e=>e.replace(/\[[^\]]{0,60}\]/g," ").replace(/\(([^)]{0,60})\)/g,(t,n)=>$o.has(n.trim().toLowerCase().replace(/[.!?,…]+$/,"").replace(/\s+/g," "))?" ":t).replace(/\*[^*]{0,60}\*/g," ").replace(/\s+/g," ").trim(),$o=new Set(["background noise","engine noise","noise","inaudible","unintelligible","silence","no speech","static","music","laughter","applause","wind","breathing","click","clicks","clicking","mouse click","mouse clicks","beep","beeps","beeping","tap","taps","tapping","typing","keyboard typing","cough","coughing","sigh","hmm","mm","mmm","uh","um","ah","oh"]),fu=/^\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?(?:\s*(?:-|–|—|to|-->)\s*\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?)?$/,hu=e=>{const t=e.trim().toLowerCase().replace(/[()[\]*]/g," ").replace(/[.!?,…]+$/,"").replace(/\s+/g," ").trim();return!t||/^(?:sh+\s*)+$/.test(t)||fu.test(t)?!0:$o.has(t)},mu=e=>{const t=e.trim().toLowerCase().replace(/\s+/g," ");return t?/^(?:transcribe|transcription|transcribed text)[.!:]*$/.test(t)?!0:t.includes("transcribe this audio recording verbatim")||t.includes("preserve the spoken language and any code-switching")||t.includes("output only the transcribed text, no commentary"):!1};let To=!0,Fn=null;const gu=e=>{To=e},bu=()=>{const e=typeof window<"u"?window.AudioContext??window.webkitAudioContext:void 0;if(!e)return null;if(!Fn)try{Fn=new e}catch{return null}return Fn.state==="suspended"&&Fn.resume(),Fn},Un=(e,t,n,a,i,o)=>{const s=e.createOscillator(),c=e.createGain();s.type=i,s.frequency.setValueAtTime(t,n),s.connect(c),c.connect(e.destination),c.gain.setValueAtTime(1e-4,n),c.gain.exponentialRampToValueAtTime(o,n+.012),c.gain.exponentialRampToValueAtTime(1e-4,n+a),s.start(n),s.stop(n+a+.03)},gn=e=>{if(!To)return;const t=bu();if(!t)return;const n=t.currentTime;try{e==="open"?(Un(t,523,n,.12,"sine",.05),Un(t,784,n+.08,.16,"sine",.05)):e==="send"?Un(t,660,n,.08,"triangle",.04):e==="receive"&&(Un(t,880,n,.1,"sine",.045),Un(t,1175,n+.09,.14,"sine",.045))}catch{}},vu=e=>e.startsWith("image/")?"image":e==="application/pdf"?"pdf":"other",xu=({state:e,onClose:t})=>{const n=ct(),a=R(null);X(()=>{a.current?.focus();const o=s=>{s.key==="Escape"&&(s.stopPropagation(),t())};return document.addEventListener("keydown",o,!0),()=>document.removeEventListener("keydown",o,!0)},[t]);const i=e.status==="ready"?vu(e.mimeType):"other";return r("div",{class:"cf-preview",role:"dialog","aria-modal":"true","aria-label":Ve(n.attachPreviewTitle,{name:e.name}),onClick:o=>{o.target===o.currentTarget&&t()},children:r("div",{class:"cf-preview__frame",children:[r("div",{class:"cf-preview__bar",children:[r("span",{class:"cf-preview__name",title:e.name,children:e.name}),e.status==="ready"&&r("a",{class:"cf-preview__btn",href:e.url,download:e.name,children:n.attachDownload}),r("button",{ref:a,type:"button",class:"cf-preview__btn cf-preview__close","aria-label":n.attachPreviewClose,onClick:t,children:"✕"})]}),r("div",{class:"cf-preview__body",children:[e.status==="loading"&&r("p",{class:"cf-preview__note",children:n.attachPreviewLoading}),e.status==="error"&&r("p",{class:"cf-preview__note",children:n.attachPreviewFailed}),e.status==="ready"&&i==="image"&&r("img",{class:"cf-preview__image",src:e.url,alt:e.name}),e.status==="ready"&&i==="pdf"&&r("iframe",{class:"cf-preview__pdf",src:e.url,title:e.name}),e.status==="ready"&&i==="other"&&r("p",{class:"cf-preview__note",children:n.attachPreviewUnsupported})]})]})})},yu=e=>new Promise((t,n)=>{const a=new FileReader;a.onload=()=>t(String(a.result??"").split(",")[1]??""),a.onerror=()=>n(a.error),a.readAsDataURL(e)}),_u=(e,t)=>e?.status===429?t.errorRateLimit:t.errorGeneric,_r=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),ka=(e,t)=>{const n=_r(),a={stage:e,durationMs:Math.max(0,n-t)};try{performance.measure(`centrinfo-widget:${e}`,{start:t,end:n})}catch{}return typeof window<"u"&&typeof CustomEvent<"u"&&window.dispatchEvent(new CustomEvent("centrinfo:performance",{detail:a})),a},wu=/!?\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,ku=/https?:\/\/[^\s)]+/g,Co=e=>qi(e).replace(wu,"$1").replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/(^|[\s([{])\*([^*\n]{1,120})\*(?=[\s.,;:!?)}\]]|$)/g,"$1$2").replace(/(^|[\s([{])_([^_\n]{1,120})_(?=[\s.,;:!?)}\]]|$)/g,"$1$2").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s{0,3}[-*+]\s+/gm,"").replace(/^\s{0,3}\d+\.\s+/gm,"").replace(/\s+\*/g," ").replace(/\*\s+/g," ").replace(/[*_]{2,}/g,"").replace(ku,t=>t.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/$/,"")).replace(/[ \t]+\n/g,`
168
168
  `).replace(/\n{3,}/g,`
169
169
 
170
- `).replace(/[ \t]{2,}/g," ").trim(),xu=(e,t)=>ko(Bc(e,t)),yu=45e3,_r=e=>e.type==="visualization",_u=e=>{const t=!!e.visualization,n=(e.artifacts??[]).some(_r);if(!t&&!n)return e;const{visualization:a,artifacts:i,...o}=e,s=(i??[]).filter(d=>!_r(d)),c=a?.title??(i??[]).find(_r)?.visualization?.title??e.resultExpired?.title;return{...o,...s.length>0?{artifacts:s}:{},resultExpired:c?{title:c}:{}}},wr=e=>e.map(_u),wu=(e,t=Date.now())=>{const n=e.visualization?.explanation?.aiExplanation;if(!e.visualization?.explanation||!n||n.status!=="pending")return e;const a=e.createdAt?Date.parse(e.createdAt):NaN;return Number.isFinite(a)&&t-a<yu?e:{...e,visualization:{...e.visualization,explanation:{...e.visualization.explanation,aiExplanation:{...n,status:"failed",retryAvailable:!1}}}}},ku=e=>e instanceof DOMException&&(e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED"),Su=(e,t,n,a)=>{let i=a;for(let o=0;o<4&&i.length>0;o+=1)try{return e.setItem(t,n(i)),!0}catch(s){if(!ku(s))return!1;i=i.slice(Math.ceil(i.length/2))}try{e.removeItem(t)}catch{}return!1},$u=(e,t)=>{if(e)try{const n=[];for(let a=0;a<e.length;a+=1){const i=e.key(a);i?.startsWith(t)&&n.push(i)}for(const a of n){const i=e.getItem(a);if(!i)continue;const o=JSON.parse(i);if(!Array.isArray(o.messages))continue;const s=wr(o.messages);s.some((c,d)=>c!==o.messages[d])&&e.setItem(a,JSON.stringify({...o,messages:s}))}}catch{}},Tu=(e,t=()=>Date.now())=>{let n=null,a=null,i=Number.NEGATIVE_INFINITY;const o=()=>{a!==null&&(clearTimeout(a),a=null);const s=n;n=null,s&&(i=t(),s())};return{schedule:s=>{if(n=s,a!==null)return;const c=e-(t()-i);c<=0?o():a=setTimeout(o,c)},flush:o,cancel:()=>{a!==null&&clearTimeout(a),a=null,n=null}}},lt=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.round(Math.random()*1e9)}`,ka=(e,t)=>{typeof console>"u"||console.warn(`[centrinfo-widget] ${e}`,t??{})},So=(e,t,n,a,i=1,o,s=!1,c,d)=>{e.current?.pause(),e.current=null,typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel(),t.current=null;const l=()=>{const h=o?.trim();if(!s||!h||typeof window>"u"||!("speechSynthesis"in window)||typeof SpeechSynthesisUtterance>"u")return!1;const I=new SpeechSynthesisUtterance(h);let x=!1;const g=()=>{x||(x=!0,t.current===I&&(t.current=null,d?.()))};return I.rate=i,I.lang=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en-US",I.onend=g,I.onerror=g,t.current=I,c?.(),window.speechSynthesis.cancel(),window.speechSynthesis.speak(I),!0};if(!n||typeof Audio>"u")return l();const u=new Audio(`data:${a||"audio/mpeg"};base64,${n}`);let p=!1,m=!1;const f=()=>{p||(p=!0,e.current===u&&(e.current=null,d?.()))},_=()=>{if(!p){if(m||e.current!==u){f();return}p=!0,e.current=null,l()||d?.()}};return u.playbackRate=i,u.onended=f,u.onerror=_,e.current=u,u.play().then(()=>{if(!p){if(e.current!==u){f();return}m=!0,c?.(Number.isFinite(u.duration)?u.duration*1e3:void 0)}}).catch(_),!0},Cu=e=>{try{return e==="none"?null:e==="session"?sessionStorage:localStorage}catch{return null}},Au=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)},Mu=e=>{try{const t=e?.split(".")[1];if(!t)return;const n=t.replace(/-/g,"+").replace(/_/g,"/"),a=JSON.parse(atob(n.padEnd(Math.ceil(n.length/4)*4,"=")));for(const i of["sub","external_user_id","user_id"]){const o=a[i];if(typeof o=="string"&&o.trim())return o.trim()}}catch{}},Iu=e=>{const t=e.user?.externalId?.trim()||e.user?.userId?.trim()||e.user?.email?.trim().toLowerCase()||Mu(e.identityToken)||(e.identityToken||e.getIdentityToken?"authenticated":"anonymous");return`${e.token.slice(0,12)}:${e.chatSurface}:${Au(t)}`},Un=e=>`${e.chatSurface}:${lt()}`,Eu=e=>e.slice(0,12),Bn=e=>`centrinfo:session:${e}`,kr=e=>`centrinfo:visitor:${e}`,Sa=(e,t)=>`centrinfo:chat:${e}:${t}`,Sr=e=>`centrinfo:history:${e}`,zu=1e3,$o=20,$r=720*60*60*1e3,Nu=1440*60*1e3,Ru=(e,t)=>{try{return JSON.parse(e?.getItem(kr(t))||"{}")}catch{return{}}},Lu=(e,t,n)=>{if(!e)return Un(n);try{const a=Bn(t),i=e.getItem(a);if(i)return i;const o=Un(n);return e.setItem(a,o),o}catch{return Un(n)}},To=(e,t,n)=>{if(!e)return{};try{const a=e.getItem(Sa(t,n));return a?JSON.parse(a):{}}catch{return{}}},Co=(e,t,n)=>{const{ts:a,expiresAt:i,messages:o}=To(e,t,n);return Array.isArray(o)?typeof i=="number"&&Date.now()>i?[]:typeof a=="number"&&Date.now()-a>$r?[]:wr(o):[]},Du=(e,t,n)=>{const{ts:a,expiresAt:i,messages:o,ended:s}=To(e,t,n);return!Array.isArray(o)||o.length===0||typeof i=="number"&&Date.now()>i||typeof a=="number"&&Date.now()-a>$r?!1:s===!0||typeof a=="number"&&Date.now()-a>Nu},Pu=e=>Number.isFinite(e??NaN)?Math.max(5,Math.min(200,Math.round(e))):50,Ou=e=>Number.isFinite(e??NaN)?Math.max(1,Math.min(365,Math.round(e)))*24*60*60*1e3:$r,Ao=(e,t,n,a,i,o,s,c)=>{if(e)try{if(!o){e.removeItem(Sa(t,n));return}const d=a.filter(u=>!u.pending).slice(-s);if(d.length===0)return;const l=Date.now();Su(e,Sa(t,n),u=>JSON.stringify({ts:l,expiresAt:l+c,messages:wr(u),ended:i}),d)}catch{}},Fu=(e,t)=>{if(!e)return[];try{const n=e.getItem(Sr(t)),a=n?JSON.parse(n):[];return Array.isArray(a)?a:[]}catch{return[]}},$a=(e,t,n)=>{if(e)try{e.setItem(Sr(t),JSON.stringify(n.slice(0,$o)))}catch{}},Mo=(e,t)=>{if(e)try{const n=`centrinfo:chat:${t}:`,a=new Set([Bn(t),kr(t),Sr(t)]),i=[];for(let o=0;o<e.length;o++){const s=e.key(o);s&&(a.has(s)||s.startsWith(n))&&i.push(s)}i.forEach(o=>e.removeItem(o))}catch{}},Uu=e=>{const a=(e.find(i=>i.role==="user"&&i.content.trim())?.content||e.find(i=>i.content.trim())?.content||"").trim().replace(/\s+/g," ");return a.length>60?a.slice(0,60)+"…":a||"Conversation"},Bu=e=>({id:`live:${e.id}`,role:e.type==="chat"||e.type==="ai_resume"?"assistant":"system",content:e.content,authorName:e.authorName,liveEventType:e.type,createdAt:e.createdAt,offerReconnect:e.type==="ai_handback"&&e.reconnectOffered===!0}),Io=e=>(e??[]).find(t=>t.category==="support"&&t.enabled&&t.readiness!=="unavailable"&&(t.liveHandoff??t.id==="public_contact_support")),qu=(e,t)=>{if(t==="ai")for(let n=e.length-1;n>=0;n--){const a=e[n];if(a){if(a.reconnectOffer)return;if(a.liveEventType==="ai_handback")return a.offerReconnect?a.id:void 0}}},Vu=(e,t,n=!0)=>{const a=R(Cu(t.persistence)).current,i=Iu(t),o=R(Lu(a,i,t)),s=R(null),c=R(null),d=R(null),l=R(null),u=R(null),p=R(null),m=R(new Map),f=R(!1),_=R(void 0),h=R(null),I=R({}),x=R({}),[g,T]=$(null),[V,P]=$(()=>Co(a,i,o.current)),ee=R(null);ee.current||(ee.current=Tu(zu));const Z=R(V.length>0),Y=R(V.some(b=>b.role==="user")),[z,te]=$(!1),[U,B]=$(!1),[A,N]=$({status:"idle"}),y=R({}),[D,S]=$(()=>Du(a,i,o.current)),[O,ue]=$(()=>Ru(a,i)),[oe,Fe]=$(()=>Fu(a,i)),[_e,Te]=$(null),[Le,Ie]=$([]),[Ce,ve]=$("ai"),[Xe,ge]=$(void 0),[ie,He]=$(void 0),We=R(new Date().toISOString()),k=R(void 0),K=R(!1),j=R(0),G=R(O);X(()=>{G.current=O},[O]);const ne=g?.memoryEnabled!==!1,ye=Pu(g?.memoryMessageCap),Se=Ou(g?.memoryRetentionDays),et=F(()=>{s.current?.abort(),ee.current?.cancel(),Mo(a,i),Mo(a,Eu(t.token));const b=Un(t);o.current=b;try{a?.setItem(Bn(i),b)}catch{}Te(null),Ie([]),S(!1),Fe([]),ue({}),ve("ai"),ge(void 0),He(void 0),We.current=new Date().toISOString(),P(g?[{id:lt(),role:"assistant",content:g.greeting,availableActions:g.availableActions,actions:g.actions}]:[])},[a,i,t.token,g]),Ye=F(b=>{try{a?.setItem(kr(i),JSON.stringify(b))}catch{}},[a,i]),tt=F(b=>{const w=(b.email??"").trim().toLowerCase(),E=(G.current.email??"").trim().toLowerCase();w&&E&&w!==E&&et();const C={};b.email?.trim()&&(C.email=b.email.trim()),b.phone?.trim()&&(C.phone=b.phone.trim());const J=[b.firstName,b.lastName].filter(me=>!!me?.trim()).join(" ").trim()||b.name?.trim()||"";J&&(C.name=J),Object.keys(C).length>0&&ue(me=>{const ae={...C,...me};return Ye(ae),ae}),e.identify(o.current,b).catch(()=>{})},[e,Ye,et]),at=R(0),M=F(b=>{at.current=Date.now(),T(b),P(w=>{if(w.length===0)return[{id:lt(),role:"assistant",content:b.greeting,availableActions:b.availableActions,actions:b.actions}];const E=w.some(H=>H.role==="user"),C=w[0];return!E&&C?.role==="assistant"?[{...C,content:b.greeting,availableActions:b.availableActions,actions:b.actions},...w.slice(1)]:w})},[]);X(()=>{if(g?.memoryEnabled===!1){ee.current?.cancel();try{a?.removeItem(Sa(i,o.current))}catch{}$a(a,i,[]),Fe([]),Te(null),Ie([]),P(b=>Z.current?(Z.current=!1,g?[{id:lt(),role:"assistant",content:g.greeting,availableActions:g.availableActions,actions:g.actions}]:[]):b)}},[g,a,i]);const pe=F(async()=>{const b=await e.bootstrap();M(b)},[M,e]);X(()=>{let b=!0;const w=E=>E.messages.map(C=>wu({id:C.id,role:C.role,content:C.content,authorName:C.authorName,liveEventType:C.messageType,offerReconnect:C.messageType==="ai_handback"&&C.reconnectOffered===!0,sources:C.sources,visualization:C.visualization,artifacts:C.artifacts,createdAt:C.createdAt}));return e.history().then(E=>{if(!b||E.conversations.length===0)return;const C=E.conversations.map(ae=>({sessionId:ae.sessionId,ts:Date.parse(ae.lastSeenAt)||Date.now(),title:ae.title,ended:ae.ended}));for(const ae of E.conversations)Ao(a,i,ae.sessionId,w(ae),ae.ended,!0,ye,Se);$a(a,i,C),Fe(C);const H=E.conversations.find(ae=>ae.sessionId===E.activeSessionId);if(!H||Y.current)return;const J=w(H);o.current=H.sessionId,Z.current=J.length>0;try{a?.setItem(Bn(i),H.sessionId)}catch{}const me=J[J.length-1]?.createdAt;me&&(We.current=me),S(H.ended),P(J)}).catch(()=>{}),()=>{b=!1}},[ye,Se,i,a,e]),X(()=>{let b=!0;return at.current=Date.now(),e.bootstrap().then(w=>{b&&M(w)}),t.user&&tt(t.user),()=>{b=!1}},[M,e]),X(()=>{const b=t.configRefreshSeconds;if(!n||b<=0||typeof window>"u")return;let w=!0,E=!1;const C=Math.max(10,b)*1e3,H=()=>typeof document>"u"||document.visibilityState!=="hidden",J=async()=>{if(!(!w||E||!H())){E=!0;try{await pe()}catch{}finally{E=!1}}};Date.now()-at.current>=C&&J();const me=window.setInterval(J,C),ae=()=>{J()},xe=()=>{J()};return window.addEventListener("focus",ae),document?.addEventListener?.("visibilitychange",xe),()=>{w=!1,window.clearInterval(me),window.removeEventListener("focus",ae),document?.removeEventListener?.("visibilitychange",xe)}},[n,t.configRefreshSeconds,pe]),X(()=>{const b=o.current;ee.current.schedule(()=>Ao(a,i,b,V,D,ne,ye,Se))},[V,D,a,i,ne,ye,Se]),X(()=>{const b=ee.current,w=()=>{document.visibilityState==="hidden"&&b.flush()};return document.addEventListener("visibilitychange",w),window.addEventListener("pagehide",b.flush),()=>{document.removeEventListener("visibilitychange",w),window.removeEventListener("pagehide",b.flush),b.flush()}},[]),X(()=>{$u(a,"centrinfo:chat:")},[a]),X(()=>{if(!n||D||_e)return;const b=()=>{document.visibilityState==="visible"&&e.presence(o.current)};b();const w=window.setInterval(b,1e4);return document.addEventListener("visibilitychange",b),()=>{window.clearInterval(w),document.removeEventListener("visibilitychange",b)}},[n,D,e,_e]),X(()=>{if(!n||D||_e)return;let b=!0,w=!1,E=0,C;const H=()=>{C!==void 0&&window.clearTimeout(C),!(!b||document.hidden)&&(C=window.setTimeout(()=>{J()},Math.min(3e4,2200*2**E)))},J=async()=>{if(!(w||document.hidden||!b)){w=!0;try{const ae=await e.liveEvents(o.current,We.current);if(!b)return;if(E=0,ve(ae.mode),ge(ae.assignedAgentName||void 0),He(ae.agentTyping?ae.agentTypingName||ae.assignedAgentName||"Agent":void 0),ae.conversationEnded){S(!0),ve("ai"),ge(void 0),He(void 0),P(xe=>xe.some(re=>re.id==="live:conversation-ended")?xe:[...xe,{id:"live:conversation-ended",role:"system",content:t.strings.conversationEnded,liveEventType:"conversation_ended",createdAt:new Date().toISOString()}]);return}if(ae.events.length>0){let xe=We.current,re=Date.parse(xe);const ot=ae.events.map(Ue=>{const Ve=Date.parse(Ue.createdAt);return Number.isFinite(Ve)&&Ve>re&&(re=Ve,xe=Ue.createdAt),Bu(Ue)});We.current=xe,P(Ue=>{const Ve=new Set(Ue.map(nt=>nt.id)),Ze=ot.filter(nt=>!Ve.has(nt.id));return Ze.length>0?[...Ue,...Ze]:Ue}),ot.some(Ue=>Ue.role==="assistant")&&gn("receive")}}catch{E=Math.min(E+1,4)}finally{w=!1,H()}}},me=()=>{document.hidden?C!==void 0&&window.clearTimeout(C):J()};return document.addEventListener("visibilitychange",me),document.hidden||J(),()=>{b=!1,C!==void 0&&window.clearTimeout(C),document.removeEventListener("visibilitychange",me)}},[n,t.strings.conversationEnded,e,D,_e]),X(()=>{if(!ne){$a(a,i,[]),Fe(w=>w.length>0?[]:w);return}V.some(w=>w.role==="user")&&Fe(w=>{const E=o.current,H=[{sessionId:E,ts:Date.now(),title:Uu(V),ended:D},...w.filter(J=>J.sessionId!==E)];return $a(a,i,H),H.slice(0,$o)})},[V,D,a,i,ne]);const de=F((b,w)=>{P(E=>E.map(C=>C.id===b?{...C,...w}:C))},[]),fe=F(()=>{_.current!==void 0&&typeof window<"u"&&window.clearInterval(_.current),_.current=void 0},[]),Oe=F((b,w)=>{fe(),delete I.current[b],h.current===b&&(h.current=null),de(b,{content:w,pending:!1,streaming:!1})},[fe,de]),Ge=F((b,w,E)=>{const C=w.trim();if(!C||typeof window>"u"){Oe(b,C);return}fe(),h.current=b;const H=C.match(/\S+\s*/g)??[C],J=E&&E>0?E:H.length*95,me=Math.max(28,Math.min(150,J/Math.max(H.length,1)));let ae=0;de(b,{content:"",pending:!1,streaming:!0}),_.current=window.setInterval(()=>{ae+=1;const xe=H.slice(0,ae).join("");de(b,{content:xe,pending:!1,streaming:ae<H.length}),ae>=H.length&&(fe(),delete I.current[b],h.current===b&&(h.current=null),de(b,{content:C,pending:!1,streaming:!1}))},me)},[fe,Oe,de]),ht=F(()=>{const b=h.current;fe(),h.current=null;const w=I.current;I.current={};for(const[E,C]of Object.entries(w))de(E,{content:C,pending:!1,streaming:!1});b&&!(b in w)&&de(b,{pending:!1,streaming:!1})},[fe,de]),pt=F(b=>{if(D||_e||Ce==="ai"||typeof window>"u")return;if(k.current!==void 0&&window.clearTimeout(k.current),!b){if(!K.current)return;K.current=!1,j.current=0,e.typing(o.current,!1).catch(()=>{});return}const w=Date.now();(!K.current||w-j.current>2500)&&(K.current=!0,j.current=w,e.typing(o.current,!0).catch(()=>{})),k.current=window.setTimeout(()=>{K.current&&(K.current=!1,j.current=0,e.typing(o.current,!1).catch(()=>{}))},1600)},[e,D,_e,Ce]);X(()=>()=>{k.current!==void 0&&typeof window<"u"&&window.clearTimeout(k.current)},[]),X(()=>()=>fe(),[fe]);const yt=F((b,w,E={})=>{ht(),te(!0);const C=yr();let H=!1;const J=new AbortController;s.current=J;const me=!!(g?.allowVoiceInput&&g?.voiceOutputEnabled&&g.talkbackMode!=="text"),ae=!!E.forceVoicePlayback,xe=W=>{ae&&N(Ae=>Ae.agentId===w?{status:W,agentId:w}:Ae)};ae&&N({status:"answering",agentId:w});const re={pending:new Map,nextSeq:0,highestSeq:-1,playing:!1,ended:!1,started:!1,stopped:!1,utterance:null},ot=()=>{p.current===Mt&&(p.current=null),re.started&&(re.started=!1,B(!1),xe("done"))},Ue=()=>{re.stopped||re.started||(re.started=!0,wa("voice-first-audio",C),B(!0),xe("speaking"))},Ve=()=>typeof window<"u"&&"speechSynthesis"in window&&typeof SpeechSynthesisUtterance<"u",Ze=()=>{l.current&&re.playing&&(l.current.pause(),l.current=null),re.utterance&&(u.current===re.utterance&&(u.current=null),re.utterance=null,Ve()&&window.speechSynthesis.cancel()),re.playing=!1},nt=(W,Ae)=>{const Ee=W?.trim();if(!Ee||!Ve())return!1;const ke=new SpeechSynthesisUtterance(Ee);return ke.rate=g?.voiceSpeed??1,ke.lang=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en-US",ke.onstart=Ue,ke.onend=Ae,ke.onerror=Ae,re.utterance=ke,u.current=ke,window.speechSynthesis.speak(ke),f.current&&window.speechSynthesis.pause(),!0},ft=()=>{for(;!re.stopped&&!re.playing;){let W=re.pending.get(re.nextSeq);if(!W&&re.ended&&re.pending.size>0&&(re.nextSeq=Math.min(...re.pending.keys()),W=re.pending.get(re.nextSeq)),!W){re.ended&&ot();return}if(re.pending.delete(re.nextSeq),re.nextSeq+=1,De(W))return}},De=W=>{let Ae=!1;const Ee=()=>{Ae||(Ae=!0,u.current===re.utterance&&(u.current=null),re.utterance=null,re.playing=!1,ft())};if(!W.audioBase64||typeof Audio>"u")return re.playing=nt(W.text,Ee),re.playing;const ke=new Audio(`data:${W.mimeType||"audio/mpeg"};base64,${W.audioBase64}`);ke.playbackRate=g?.voiceSpeed??1,ke.volume=f.current?.2:1,re.playing=!0,l.current=ke;let Ke=!1,Bt=!1;const It=()=>{Ae||Bt||(Bt=!0,l.current===ke&&(l.current=null),!(!Ke&&!re.stopped&&nt(W.text,Ee))&&Ee())};return ke.onended=()=>{l.current===ke&&(l.current=null),Ee()},ke.onerror=It,ke.play().then(()=>{Ke=!0,Ue()}).catch(It),!0},Mt=()=>{re.stopped=!0,re.pending.clear(),Ze(),ot()};e.stream(b,o.current,{voicePlaybackRequested:!!E.forceVoicePlayback,clientMessageId:E.clientMessageId,attachmentId:E.attachmentId,attachmentIds:E.attachmentIds,signal:J.signal,onChunk:W=>{W&&!H&&(H=!0,wa("data-first-chunk",C)),E.forceVoicePlayback&&W&&(x.current[w]=!0),P(Ae=>Ae.map(Ee=>Ee.id===w?{...Ee,content:Ee.content+W,pending:!1,streaming:!0}:Ee))},onTextReady:()=>{P(W=>W.map(Ae=>Ae.id===w?{...Ae,pending:!1,streaming:!1}:Ae))},onReset:()=>{P(W=>W.map(Ae=>Ae.id===w?{...Ae,content:"",pending:!0,streaming:!1}:Ae)),re.pending.clear(),re.nextSeq=re.highestSeq+1,Ze()},onAudioSegment:W=>{!ae||re.stopped||W.seq<re.nextSeq||re.pending.has(W.seq)||(p.current=Mt,re.highestSeq=Math.max(re.highestSeq,W.seq),re.pending.set(W.seq,W),ft())}}).then(W=>{if(n&&!W.conversationEnded&&typeof document<"u"&&document.visibilityState==="visible"&&e.presence(o.current),W.liveMode&&(ve(W.liveMode),ge(W.assignedAgentName||void 0)),W.liveMode&&W.liveMode!=="ai"&&!W.answer.trim()){P(ke=>ke.filter(Ke=>Ke.id!==w)),xe("done");return}const Ae=!!x.current[w];delete x.current[w];const Ee=!!(E.forceVoicePlayback&&me&&!W.liveAudio&&W.audioBase64&&W.answer.trim()&&!Ae);if(Ee&&(I.current[w]=W.answer),P(ke=>ke.map(Ke=>Ke.id===w?{...Ke,content:Ee?"":W.answer||Ke.content||t.strings.emptyReply,pending:!1,streaming:Ee,error:!1,retryText:void 0,sources:W.sources,suggestedReplies:W.suggestedReplies,availableActions:W.availableActions,actions:W.actions,selectedAction:W.selectedAction,handoffOffered:W.handoffOffered,requestedContactFields:W.requestedContactFields,visualization:W.visualization,artifacts:W.artifacts}:Ke)),gn("receive"),W.liveAudio?(re.ended=!0,ft()):E.forceVoicePlayback&&!W.audioBase64&&ka(me?"Talkback expected backend TTS audio, but the chat response did not include audioBase64.":"Talkback voice was requested, but the loaded widget token config does not enable provider TTS.",{voiceOutputEnabled:g?.voiceOutputEnabled,talkbackMode:g?.talkbackMode,voiceProvider:g?.voiceProvider,hasAudioBase64:!!W.audioBase64}),E.forceVoicePlayback&&!W.liveAudio){const ke=So(l,u,W.audioBase64,W.mimeType,g?.voiceSpeed??1,xu(W.answer,W.visualization),!0,Ke=>{B(!0),xe("speaking"),Ee&&Ge(w,W.answer,Ke)},()=>{B(!1),xe("done"),Ee&&Oe(w,W.answer)});ke||xe("done"),Ee&&!ke&&Oe(w,W.answer)}W.answer&&t.onMessage?.({role:"assistant",content:W.answer}),W.handoffOffered&&t.onHandoff?.(),W.conversationEnded&&S(!0)}).catch(W=>{if(J.signal.aborted){re.stopped||Mt(),delete x.current[w],P(Ee=>Ee.flatMap(ke=>ke.id!==w?[ke]:ke.content.trim()?[{...ke,pending:!1,streaming:!1}]:[])),xe("done");return}xe("failed"),delete x.current[w];const Ae=gu(W,t.strings);de(w,{content:Ae,pending:!1,streaming:!1,error:!0,retryText:b})}).finally(()=>{wa("data-complete",C),delete x.current[w],s.current===J&&(te(!1),s.current=null,c.current?.agentId===w&&(c.current=null))})},[e,n,t,de,g?.allowVoiceInput,g?.talkbackMode,g?.voiceOutputEnabled,g?.voiceSpeed,ht]),Dt=F((b,w={})=>{const E=b.trim(),{imageUrl:C,attachmentName:H,attachmentText:J,attachmentId:me,attachmentFile:ae,forceVoicePlayback:xe,userMessageId:re}=w,ot=w.attachments??(H||me||J?[{id:me,name:H??"",text:J,file:ae}]:[]);if(!E&&!C&&ot.length===0||s.current&&!s.current.signal.aborted||D)return;Y.current=!0;let Ue=E;!Ue&&ot.length>0&&(Ue="Please look at the attached file."),!Ue&&C&&(Ue=C);const Ve=ot.map(De=>({id:De.id,name:De.name})),Ze=ot.flatMap(De=>De.id?[De.id]:[]),nt={id:re||lt(),role:"user",content:E,imageUrl:C,attachments:Ve.length>0?Ve:void 0};ot.forEach((De,Mt)=>{De.file&&(m.current.set(`${nt.id}:${Mt}`,De.file),De.id&&m.current.set(De.id,De.file))});const ft=lt();P(De=>[...!!(re&&De.some(Ae=>Ae.id===re))?De.map(Ae=>Ae.id===re?{...Ae,content:E,pending:!1,streaming:!1,imageUrl:C,attachments:nt.attachments}:Ae):[...De,nt],{id:ft,role:"assistant",content:"",pending:!0}]),gn("send"),t.onMessage?.({role:"user",content:Ue}),y.current[ft]=nt.id,c.current={userId:nt.id,agentId:ft,text:E,backendText:Ue},yt(Ue,ft,{forceVoicePlayback:xe,clientMessageId:nt.id,attachmentId:Ze[0],attachmentIds:Ze})},[D,t,yt]),_t=F((b,w,E,C,H)=>{const J=lt();P(me=>[...me.filter(ae=>ae.id!==b.agentId&&(!C.userMessageId||ae.id!==C.userMessageId)).map(ae=>ae.id===b.userId?{...ae,content:w,pending:!1,streaming:!1}:ae),{id:J,role:"assistant",content:"",pending:!0}]),H&&t.onMessage?.({role:"user",content:H}),y.current[J]=b.userId,c.current={userId:b.userId,agentId:J,text:w,backendText:E},yt(E,J,{forceVoicePlayback:C.forceVoicePlayback,clientMessageId:lt()})},[t,yt]),Vn=F((b,w={})=>{const E=b.trim();if(!E||D)return;const C=s.current&&!s.current.signal.aborted?c.current:null,H=C??d.current;if(d.current=null,!H){Dt(E,w);return}C&&s.current?.abort(),_t(H,`${H.text} ${E}`.replace(/\s+/g," ").trim(),`${H.backendText}
171
- ${E}`.trim(),w,E)},[D,_t,Dt]),an=F(()=>{const b=s.current&&!s.current.signal.aborted?c.current:null;return b?(d.current=b,s.current?.abort(),!0):!1},[]),rt=F(()=>{const b=d.current;d.current=null,!(!b||D)&&_t(b,b.text,b.backendText,{forceVoicePlayback:!0})},[D,_t]),Pt=F(()=>s.current?.abort(),[]),bn=F(b=>{f.current=b;const w=l.current;w&&(w.volume=b?.2:1),u.current&&typeof window<"u"&&"speechSynthesis"in window&&(b?window.speechSynthesis.pause():window.speechSynthesis.resume())},[]),jt=F(()=>{p.current?.(),p.current=null,f.current=!1,ht(),N(b=>b.status==="speaking"||b.status==="answering"?{...b,status:"done"}:b),l.current?.pause(),l.current=null,typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel(),u.current=null,B(!1)},[ht]),mt=F(b=>{const w=ko(b);if(!w)return Promise.resolve(!1);ht();const E=!!(g?.allowVoiceInput&&g?.voiceOutputEnabled&&g.talkbackMode!=="text"),C=(H,J)=>new Promise(me=>{let ae=!1;So(l,u,H,J,g?.voiceSpeed??1,w,!0,()=>{ae=!0,B(!0)},()=>{B(!1),me(ae)})||(B(!1),me(!1))});return E?e.speak(w).then(H=>H.audioBase64?C(H.audioBase64,H.mimeType):(ka("Talkback prompt TTS did not return provider audio.",{providerReady:H.providerReady,message:H.message,voiceProvider:g?.voiceProvider,voiceOutputEnabled:g?.voiceOutputEnabled,talkbackMode:g?.talkbackMode}),C())).catch(H=>(ka("Talkback prompt TTS request failed before audio playback.",{error:H instanceof Error?H.message:String(H),voiceProvider:g?.voiceProvider,voiceOutputEnabled:g?.voiceOutputEnabled,talkbackMode:g?.talkbackMode}),C())):(ka("Talkback prompt wanted voice, but the loaded widget token config has provider TTS disabled.",{voiceOutputEnabled:g?.voiceOutputEnabled,talkbackMode:g?.talkbackMode,voiceProvider:g?.voiceProvider}),C())},[g?.allowVoiceInput,g?.talkbackMode,g?.voiceOutputEnabled,g?.voiceSpeed,ht,e]),Ht=F((b,w,E={})=>{if(z||D||!w)return;de(b,{content:"",pending:!0,streaming:!1,error:!1}),gn("send");const C=V.findIndex(J=>J.id===b),H=C>0?V[C-1]:void 0;yt(w,b,{...E,clientMessageId:y.current[b]??(H?.role==="user"?H.id:void 0)})},[z,D,V,de,yt]),Ot=F((b,w,E)=>{de(b,{feedback:w});const C=V.findIndex(me=>me.id===b),H=C>=0?V[C]?.content:void 0;let J;for(let me=C-1;me>=0;me--)if(V[me]?.role==="user"){J=V[me]?.content;break}e.sendFeedback({sessionId:o.current,messageId:b,rating:w,comment:E,question:J,answer:H}).catch(()=>{})},[e,de,V]),gt=F(b=>{const w=b.content.trim();if(!w)return;const E=b.id.trim()||lt();P(C=>C.some(H=>H.id===E)?C:[...C,{id:E,role:"assistant",content:w,createdAt:new Date().toISOString()}])},[]),dt=F(async(b,w,E={},C)=>{t.onAction?.(b);const H=b==="public_contact_support"||b==="public_submit_inquiry"?{actionId:b}:{},J=await e.action(b,{sessionId:o.current,...w,...H},C),me={};return E.name?.trim()&&(me.name=E.name.trim()),E.email?.trim()&&(me.email=E.email.trim()),E.phone?.trim()&&(me.phone=E.phone.trim()),Object.keys(me).length>0&&(ue(ae=>{const xe={...ae,...me};return Ye(xe),xe}),me.email&&b!=="contact"&&e.action("contact",{sessionId:o.current,...me}).catch(()=>{})),gt({id:J.receipt?.id||lt(),content:J.receipt?.content||J.note||(J.caseReference?`Action completed.
172
- Reference: ${J.caseReference}`:"Action completed.")}),gn("receive"),J},[e,t,Ye,gt]),Qe=F(async(b,w,E)=>{const C=await e.confirmHostedBooking?.({sessionId:o.current,inquiryId:b,eventUri:w,inviteeUri:E});return C?.receipt&&gt(C.receipt),C},[e,gt]),Ft=F(b=>{const w=b.trim();w&&P(E=>E.some(C=>C.role==="assistant"&&C.content===w)?E:[...E,{id:lt(),role:"assistant",content:w}])},[]),it=F(()=>{const b=Io(g?.actions);return b?(P(w=>[...w,{id:lt(),role:"assistant",content:t.strings.reconnectPrompt,actions:[b],selectedAction:b.id,handoffOffered:!0,reconnectOffer:!0,createdAt:new Date().toISOString()}]),!0):!1},[t.strings.reconnectPrompt,g?.actions]),Ut=F(b=>{Y.current=!0;const w=lt();return P(E=>[...E,{id:w,role:"user",content:b.trim(),pending:!0}]),w},[]),Wt=F((b,w)=>{P(E=>E.map(C=>C.id===b?{...C,...w}:C))},[]),jn=F(b=>{P(w=>w.filter(E=>E.id!==b))},[]),Hn=F(async(b,w="widget")=>{if(!e.sendExplanationFeedback)throw new Error("Explanation feedback is unavailable.");await e.sendExplanationFeedback({...b,sessionId:o.current,surface:w})},[e]),Wn=F((b="widget")=>{const w=e.fetchExplanation?.bind(e);if(!w)return;const E=e.retryExplanation?.bind(e),C=H=>H;return{poll:async(H,J)=>C(await w(H,o.current,b,J)),settled:(H,J)=>{J!=="not_requested"&&P(me=>me.map(ae=>{const xe=ae.visualization?.explanation?.aiExplanation;return!xe||(xe.explanationId??ae.visualization?.explanation?.explanationId)!==H||xe.status===J?ae:{...ae,visualization:{...ae.visualization,explanation:{...ae.visualization.explanation,aiExplanation:{...xe,status:J}}}}}))},...E?{retry:async H=>C(await E(H,o.current,b))}:{}}},[e]),Gn=F((b,w)=>{e.sendFeedback({sessionId:o.current,messageId:"__csat__",rating:b,comment:w}).catch(()=>{})},[e]),Tt=F(async(b,w,E,C)=>{const H=yr();try{if(typeof b!="string"&&e.transcribeAudio)return await e.transcribeAudio(b,w,E,C);const J=typeof b=="string"?b:await mu(b);return await e.transcribe(J,w,E,C)}finally{wa("voice-transcription",H)}},[e]),Q=F(async(b,w,E=0)=>{const C=m.current.get(`${b.id}:${E}`)??(w.id?m.current.get(w.id):void 0);if(C)return C;if(!w.id||!e.fetchAttachment)throw new Error("This file is no longer available.");return e.fetchAttachment(w.id,o.current)},[e]),he=F((b,w,E,C)=>e.uploadAttachment?e.uploadAttachment(b,w,E,o.current,C):Promise.reject(new Error("File upload is unavailable")),[e]),we=F(b=>e.searchGifs(b),[e]),ce=F((b,w)=>e.demoSlots(b,w),[e]),be=F(b=>Dt("",{imageUrl:b}),[Dt]),wt=t.demo||!!t.gifApiKey,rn=F(()=>{s.current?.abort(),S(!0),e.endConversation(o.current).catch(()=>{})},[e]),Kn=F(()=>{s.current?.abort();const b=Un(t);o.current=b;try{a?.setItem(Bn(i),b)}catch{}Te(null),Ie([]),S(!1),ve("ai"),ge(void 0),He(void 0),We.current=new Date().toISOString(),P(g?[{id:lt(),role:"assistant",content:g.greeting,availableActions:g.availableActions,actions:g.actions}]:[])},[a,i,g]),Gt=F(b=>{if(ne){if(b===o.current){Te(null);return}Ie(Co(a,i,b)),Te(b)}},[a,i,ne]),Ct=F(()=>{Te(null),Ie([])},[]),At=t.starters.length>0?t.starters:g?.starterQuestions??[],kt=g?.featuredLinks??[];return{persona:g,messages:V,sending:z,assistantSpeaking:U,voiceReply:A,visitor:O,starters:At,featuredLinks:kt,hasEmail:!!O.email,liveMode:Ce,assignedAgentName:Xe,agentTypingName:ie,send:Dt,amend:Vn,hold:an,resumeHeld:rt,duckSpeaking:bn,sendGif:be,notifyTyping:pt,stop:Pt,retry:Ht,rateMessage:Ot,rateExplanation:Hn,explanationTransport:Wn,injectAssistant:Ft,reconnectSupport:it,appendUserDraft:Ut,patchMessage:Wt,removeMessage:jn,submitCsat:Gn,submitForm:dt,confirmHostedBooking:Qe,transcribe:Tt,uploadAttachment:he,loadAttachment:Q,searchGifs:we,demoSlots:ce,gifEnabled:wt,identify:tt,ended:D,endConversation:rn,startNew:Kn,history:ne?oe:[],viewingSessionId:_e,viewMessages:Le,openConversation:Gt,closeHistoryView:Ct,shutdown:et,stopSpeaking:jt,speakAssistantText:mt}},ju=({name:e,greeting:t})=>{const n=ct();return r("section",{class:"cf-empty-welcome","aria-label":qe(n.welcomeLabel,{name:e}),children:[r("span",{class:"cf-empty-welcome__eyebrow",children:n.welcomeEyebrow}),r("h2",{children:e}),r("p",{children:t||n.welcomePrompt})]})},Tr=(e,t,n)=>{if(e.key==="Escape"){e.preventDefault(),e.stopPropagation(),n();return}if(e.key!=="Tab")return;const a=Array.from(t.querySelectorAll('button, [href], textarea, input, select, [tabindex]:not([tabindex="-1"])')).filter(l=>!l.hasAttribute("disabled")&&l.getAttribute("aria-hidden")!=="true"&&l.tabIndex>=0);if(a.length===0)return;const i=t.getRootNode(),o=e.composedPath()[0],s=o instanceof HTMLElement?o:"activeElement"in i?i.activeElement:document.activeElement,c=a[0],d=a[a.length-1];e.shiftKey&&(s===c||!t.contains(s))?(e.preventDefault(),e.stopPropagation(),d.focus()):!e.shiftKey&&(s===d||!t.contains(s))&&(e.preventDefault(),e.stopPropagation(),c.focus())},Ta=new Map,Eo=e=>{if(!e||typeof document>"u"||typeof CanvasRenderingContext2D>"u")return;const t=document.createElement("canvas").getContext("2d");if(!t)return;t.fillStyle="#010203",t.fillStyle=e;const n=t.fillStyle;if(n==="#010203"&&e.trim().toLowerCase()!=="#010203")return;const a=n.match(/^#([\da-f]{6})$/i)?.[1];if(a)return[Number.parseInt(a.slice(0,2),16),Number.parseInt(a.slice(2,4),16),Number.parseInt(a.slice(4,6),16),1];const i=n.match(/^rgba?\(([\d.]+)[, ]+([\d.]+)[, ]+([\d.]+)(?:[, /]+([\d.]+))?\)$/i);if(!i)return;const o=i.slice(1,5).map(Number);if(!o.some(s=>!Number.isFinite(s)))return[o[0],o[1],o[2],o[3]??1]},Hu=(e,t="#ffffff")=>{const n=`${e??""}|${t}`;if(Ta.has(n))return Ta.get(n);const a=Eo(e),i=Eo(t)??[255,255,255,1];if(!a){Ta.set(n,void 0);return}const o=a[3],c=a.slice(0,3).map((m,f)=>m*o+i[f]*(1-o)).map(m=>{const f=m/255;return f<=.04045?f/12.92:((f+.055)/1.055)**2.4}),d=c[0]*.2126+c[1]*.7152+c[2]*.0722,l=1.05/(d+.05),u=(d+.05)/.059,p=l>=u?"#ffffff":"#0f1e2a";return Ta.set(n,p),p},Wu=e=>{const[t,n]=$("light");return X(()=>{if(e!=="auto"||typeof matchMedia>"u")return;const a=matchMedia("(prefers-color-scheme: dark)"),i=()=>n(a.matches?"dark":"light");return i(),a.addEventListener("change",i),()=>a.removeEventListener("change",i)},[e]),e==="auto"?t:e},Gu=6e4,Ku=90,zo={end:"end the call",mute:"mute your microphone",minimize:"minimize the chat",expand:"expand the view",shrink:"exit the expanded view"},No=e=>e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s']/gu," ").replace(/\s+/g," ").trim(),Yu=[{action:"shrink",re:/\b(?:exit|leave|quit|close)\b[\s\w]*\b(?:full ?screen|expanded|theat(?:er|re))\b|\bshrink\b|\bsmaller view\b/},{action:"end",re:/\b(?:end|close|stop|finish|hang ?up|quit|exit)\b[\s\w]*\b(?:call|chat|conversation|convo|session|talking)\b|\bhang ?up\b|\bgood ?bye\b|^bye(?: bye)?$/},{action:"mute",re:/\bmute\b|\bstop listening\b/},{action:"minimize",re:/\bminimi[sz]e\b|\bhide\b[\s\w]*\b(?:chat|call|window|widget)\b/},{action:"expand",re:/\bexpand\b|\bmaximi[sz]e\b|\bfull ?screen\b|\btheat(?:er|re) mode\b|\bbigger view\b/}],Zu=/^(?:yes|yeah|yep|yup|sure|correct|confirm|affirmative|go ahead|do it|please do|ok(?:ay)?)\b/,Ju=/^(?:no|nope|nah|cancel|never ?mind|don'?t|stop)\b/,Xu=/^(?:end|close|stop|finish|hang ?up|quit|exit|bye|good ?bye)\b/,Qu=e=>{const t=No(e);if(!t)return null;for(const{action:n,re:a}of Yu)if(a.test(t)){const i=t.split(" ").length;return{action:n,confident:n==="end"?i<=10:i<=6}}return null},ep=e=>`I didn't catch yes or no. Say yes to ${zo[e]}, or no to keep talking.`,tp=({transport:e,config:t,bindControls:n,composerDraftStore:a})=>{const i=t.strings,[o,s]=$(t.openByDefault),{persona:c,messages:d,sending:l,assistantSpeaking:u,visitor:p,hasEmail:m,liveMode:f,assignedAgentName:_,agentTypingName:h,starters:I,featuredLinks:x,send:g,sendGif:T,notifyTyping:V,stop:P,amend:ee,hold:Z,resumeHeld:Y,duckSpeaking:z,retry:te,rateMessage:U,rateExplanation:B,explanationTransport:A,injectAssistant:N,reconnectSupport:y,appendUserDraft:D,patchMessage:S,removeMessage:O,submitCsat:ue,submitForm:oe,confirmHostedBooking:Fe,transcribe:_e,uploadAttachment:Te,loadAttachment:Le,searchGifs:Ie,demoSlots:Ce,gifEnabled:ve,identify:Xe,ended:ge,endConversation:ie,startNew:He,history:We,viewingSessionId:k,viewMessages:K,openConversation:j,closeHistoryView:G,shutdown:ne,stopSpeaking:ye,speakAssistantText:Se}=Vu(e,t,o),et=qu(d,f),[Ye,tt]=$(null),at=R(0),M=F((v,L,le)=>{le===at.current&&tt({status:"ready",name:L,url:URL.createObjectURL(v),mimeType:v.type||"application/octet-stream"})},[]),pe=F((v,L,le)=>{const Me=L.name,Ne=++at.current;tt({status:"loading",name:Me}),Le(v,L,le).then(bt=>M(bt,Me,Ne),()=>{Ne===at.current&&tt({status:"error",name:Me})})},[Le,M]),de=F((v,L)=>M(v,L,++at.current),[M]),fe=F(()=>{at.current+=1,tt(null)},[]);X(()=>()=>{Ye?.status==="ready"&&URL.revokeObjectURL(Ye.url)},[Ye]);const Oe=!!Io(c?.actions),[Ge,ht]=$(0),[pt,yt]=$({mic:"off",processing:!1}),[Dt,_t]=$(null),[Vn,an]=$(!1),[rt,Pt]=$(!1),[bn,jt]=$(!1),[mt,Ht]=$(!1),[Ot,gt]=$(0),[dt,Qe]=$(!1),[Ft,it]=$(null),[Ut,Wt]=$(null),[jn,Hn]=$([]),[Wn,Gn]=$(""),[Tt,Q]=$(()=>{try{return localStorage.getItem("centrinfo:muted")==="1"}catch{return!1}}),he=Wu(t.theme),we=c?.soundEnabled??!0;X(()=>{uu(t.sound&&we&&!Tt)},[t.sound,we,Tt]);const ce=F(()=>{Q(v=>{const L=!v;try{localStorage.setItem("centrinfo:muted",L?"1":"0")}catch{}return L})},[]),be=R(null),wt=R(null),rn=R(null),Kn=R(0),Gt=R(!1),Ct=R(!1),At=R(null),kt=R(0),b=R(void 0),w=R(0),E=R(null),C=R(!1),H=R(null),J=R(""),me=R(()=>{}),ae=R(""),xe=R(l),re=R(g);re.current=g;const ot=R(ee);ot.current=ee;const Ue=R(_e);Ue.current=_e;const Ve=R(!1),Ze=R(!1),nt=R("");nt.current=[...d].reverse().find(v=>v.role==="assistant")?.content??"";const ft=R(u);xe.current=l,ft.current=u;const De=rt?Vn?"timeout":mt||pt.mic==="muted"?"muted":pt.mic==="unavailable"?pt.reason==="permission-denied"||pt.reason==="unsupported"?"denied":"unavailable":pt.mic==="off"||pt.mic==="starting"?"connecting":pt.mic==="hearing"?"hearing":u?"speaking":Dt??(pt.processing||l?"processing":"listening"):"idle",[Mt,W]=$(!0),[Ae,Ee]=$(!1),ke=R(0),[Ke,Bt]=$(!1),[It,on]=$(!1),Uo=R(null),[Kt,sn]=$(!1),hp=R({value:""}),mp=a??hp.current,Bo=R({confirmEnd:Ke,confirmClear:It,showHistory:Kt});Bo.current={confirmEnd:Ke,confirmClear:It,showHistory:Kt};const[gp,qo]=$(!1),ze=!!k,Ca=ze?K:d,Yn=Ca.find(v=>v.id===Ft&&v.visualization)?.visualization,Zn=Ca.find(v=>v.id===Ut&&v.visualization);X(()=>{!Ut||Zn||(Wt(null),Qe(!1))},[Ut,Zn]),X(()=>{!Ft||Yn||(it(null),Qe(!1))},[Yn,Ft]);const vn=F(()=>{s(!0),ht(0),gn("open"),t.onOpen?.(),t.onShow?.()},[t]),Et=F(()=>{s(!1),Qe(!1),it(null),t.onClose?.(),t.onHide?.(),wt.current?.focus()},[t]),Jn=F(()=>o?Et():vn(),[o,vn,Et]),bp=F(()=>Bt(!0),[]),vp=F(()=>{ie(),Bt(!1)},[ie]),xp=F(()=>{He(),Ee(!1),W(!0)},[He]);X(()=>{Ke&&Uo.current?.focus()},[Ke]),X(()=>{n({open:vn,close:Et,toggle:Jn,identify:Xe,startNew:He,endConversation:ie,shutdown:ne})},[n,vn,Et,Jn,Xe,He,ie,ne]),X(()=>{const v=d.filter(L=>L.role==="assistant"&&!L.pending).length;if(o){Kn.current=v;return}v>Kn.current&&ht(v-Kn.current)},[d,o]),X(()=>{t.onUnreadChange?.(Ge)},[Ge,t]),X(()=>{const v=t.sessionDurationMinutes;if(!v||v<=0)return;const L=setTimeout(()=>ne(),v*60*1e3);return()=>clearTimeout(L)},[t.sessionDurationMinutes,d,o,ne]),X(()=>{const v=t.customLauncherSelector;if(!v||typeof document>"u")return;let L=[];try{L=Array.from(document.querySelectorAll(v))}catch{return}const le=Me=>{Me.preventDefault(),Jn()};return L.forEach(Me=>Me.addEventListener("click",le)),()=>L.forEach(Me=>Me.removeEventListener("click",le))},[t.customLauncherSelector,Jn]);const Vo=R(!1);X(()=>{const v=t.proactiveMessage?.trim();if(!v||Vo.current)return;const L=t.proactiveOnPaths??[],le=typeof location<"u"?location.pathname:"";if(L.length>0&&!L.some(bt=>le.includes(bt)))return;const Me=`centrinfo:proactive:${t.token.slice(0,12)}`;try{if(sessionStorage.getItem(Me)==="1")return}catch{}const Ne=setTimeout(()=>{if(!(o||ge||d.some(bt=>bt.role==="user"))){Vo.current=!0;try{sessionStorage.setItem(Me,"1")}catch{}N(v),vn()}},Math.max(0,t.proactiveDelaySeconds)*1e3);return()=>clearTimeout(Ne)},[t.proactiveMessage]),X(()=>{const v=rn.current;if(!o||!v)return;const L=d[d.length-1],le=Date.now()<ke.current;L?.role==="user"||Mt||le?(requestAnimationFrame(()=>{v.scrollTop=v.scrollHeight}),Ee(!1),le&&W(!0)):Ee(!0)},[d,o,l,Mt]);const jo=R(!0);jo.current=Mt,X(()=>{const v=rn.current;if(!(!o||!v))return yc(v,{isAtBottom:()=>jo.current,onUnseen:()=>Ee(!0)})},[o,ze]);const yp=F(()=>{const v=rn.current;if(!v)return;if(Gt.current&&!ze){W(!0),Ee(!1);return}const L=v.scrollHeight-v.scrollTop-v.clientHeight<80;W(L),L&&Ee(!1)},[ze]),Yt=F(()=>{const v=rn.current;v&&(v.scrollTop=v.scrollHeight),Ee(!1),W(!0)},[]),Aa=F(()=>{ke.current=Date.now()+3e3,requestAnimationFrame(Yt)},[Yt]);X(()=>{if(!o||ze||!rt||De==="connecting")return;ke.current=Date.now()+6e4,Yt();const v=requestAnimationFrame(()=>{Yt(),requestAnimationFrame(Yt)}),L=[80,180,360].map(le=>window.setTimeout(Yt,le));return()=>{cancelAnimationFrame(v),L.forEach(le=>window.clearTimeout(le))}},[u,d,o,Yt,l,rt,ze,De]);const Ho=F(()=>{be.current?.querySelector(".cf-textarea")?.focus()},[]),Xn=F((v,L)=>{_t(v),b.current&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>_t(null),3e3),L&&!Ct.current&&Se(L)},[Se]),Ma=F(v=>{const L=H.current;if(L)return L;Aa();const le=D(v);return H.current=le,S(le,{content:J.current||v,pending:!0,streaming:!1}),le},[D,Aa,S]),qt=F(()=>{const v=H.current;if(v){if(J.current){S(v,{content:J.current,pending:!0});return}H.current=null,O(v)}},[S,O]),Zt=F(()=>{Ze.current&&(Ze.current=!1,z(!1)),Ve.current&&(Ve.current=!1,Y())},[z,Y]),ut=F(()=>{Gt.current=!1,At.current?.stop("call-ended"),At.current=null,Ve.current=!1,Ze.current=!1,Ct.current=!1,E.current=null,C.current=!1;const v=H.current;H.current=null,J.current="",v&&O(v),b.current&&window.clearTimeout(b.current),_t(null),an(!1),yt({mic:"off",processing:!1}),gt(0),Pt(!1),jt(!1),Ht(!1),Qe(!1),it(null),ye()},[O,ye]),_p=F(()=>{dt&&it(null),Qe(!dt)},[dt]),wp=F(v=>{it(v),Qe(!0)},[]),kp=F(v=>{Wt(v),Qe(!0)},[]),Ia=F(()=>{const v=Ft,L=Ut;it(null),Wt(null),Qe(!1),window.requestAnimationFrame(()=>{(L?be.current?.querySelector(`[data-explanation-message="${L}"]`)?.querySelector('[data-testid="analytics-explanation-expand"]'):Array.from(be.current?.querySelectorAll("[data-visualization-message]")??[]).find(Me=>Me.dataset.visualizationMessage===v))?.focus()})},[Ft,Ut]),Sp=F(()=>{it(null),Wt(null),Qe(!1)},[]),Wo=F((v,L,le=!1)=>{if(Aa(),L&&(S(L,{content:v,pending:!1,streaming:!1}),H.current===L&&(H.current=null)),J.current="",le){ye(),ot.current(v,{forceVoicePlayback:!0,userMessageId:L});return}Gt.current&&(Z()?ot.current(v,{forceVoicePlayback:!0,userMessageId:L}):re.current(v,{forceVoicePlayback:!0,userMessageId:L}))},[Aa,Z,S,ye]),zt=F(v=>{N(v),Se(v)},[N,Se]),Go=F(()=>{if(kt.current=Date.now(),_t(null),ft.current){Ze.current=!0,z(!0);return}Ve.current||(Ve.current=Z()),Ma("Listening...")},[z,Ma,Z]),Ko=F(v=>{const L=H.current;if(!L||Ze.current)return;const le=[J.current,v].filter(Boolean).join(" ");S(L,{content:`${le} ...`,pending:!0})},[S]),Yo=F(v=>{kt.current=Date.now();const L=[J.current,v.text].map(Nt=>Nt.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if((Ze.current||v.overlappedOutput)&&Uc(v.text,nt.current)){qt(),Zt();return}if(!L||lu(L)||du(L)){const Nt=Ze.current||Ve.current;qt(),Zt(),Nt||Xn("misunderstood");return}Ze.current&&(Ze.current=!1,P(),ye());const Me=E.current;if(Me){J.current="",qt();const Nt=No(L);if(Zu.test(Nt)||Me==="end"&&Xu.test(Nt)){E.current=null,me.current(Me);return}if(Ju.test(Nt)){E.current=null,zt("Okay, never mind — what would you like to know?");return}zt(ep(Me));return}const Ne=Qu(L);if(Ne){if(J.current="",qt(),Zt(),Ne.confident){me.current(Ne.action);return}E.current=Ne.action,zt(`Just to confirm — you want me to ${zo[Ne.action]}? Please say yes or no.`);return}const bt=Ma(L);S(bt,{content:L,pending:!0});const xn=Ve.current;Ve.current=!1,Wo(L,bt,xn)},[Ma,S,Zt,Wo,qt,Xn,zt,P,ye]),Zo=F(v=>{kt.current=Date.now();const L=Ze.current||Ve.current;if(qt(),Zt(),!(L||v.overlappedOutput||v.reason==="too-short")){if(v.reason==="transcribe-failed"){Xn("misunderstood","I couldn't transcribe that. Please try again, or type your question.");return}Xn("noise")}},[Zt,qt,Xn]),Qn=R({speechStart:Go,partial:Ko,turn:Yo,noise:Zo});Qn.current={speechStart:Go,partial:Ko,turn:Yo,noise:Zo};const Jo=F(()=>{navigator.mediaDevices?.enumerateDevices().then(v=>{Hn(v.filter(L=>L.kind==="audioinput").map((L,le)=>({deviceId:L.deviceId,label:L.label||`Microphone ${le+1}`})))}).catch(()=>{})},[]),$p=F(()=>{if(Gt.current){ut();return}if(Ho(),!c?.allowVoiceInput||!c.talkbackMode||c.talkbackMode==="text"||xe.current||ge||ze)return;kt.current=Date.now(),Ct.current=!1,Gt.current=!0,Ht(!1),Pt(!0),jt(!1),an(!1);let v=!1;const L=new qi({deviceId:ae.current||void 0,transcribe:async({audio:le,mimeType:Me,durationSeconds:Ne})=>{const bt=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||void 0;return su(await Ue.current(le,Me,bt,Ne))},listener:{state:le=>{yt(le),le.mic!=="starting"&&le.mic!=="off"&&jt(!0),!v&&le.mic==="listening"&&(v=!0,Jo())},speechStart:()=>Qn.current.speechStart(),partial:({text:le})=>Qn.current.partial(le),turn:le=>Qn.current.turn(le),noise:le=>Qn.current.noise(le),level:le=>{const Me=performance.now();Me-w.current<Ku||(w.current=Me,gt(le))}}});At.current=L,L.setOutputActive(ft.current),L.start()},[ut,ge,Ho,c,Jo,ze]),Ea=F(()=>{const v=!Ct.current;Ct.current=v,Ht(v),At.current?.setMuted(v),v?(J.current="",qt(),Zt()):kt.current=Date.now()},[Zt,qt]),Xo=F(v=>{switch(kt.current=Date.now(),v){case"end":C.current=!0,zt("Okay — ending our call now. Goodbye!"),window.setTimeout(()=>{C.current&&(C.current=!1,ut())},2e3);break;case"mute":{Ct.current||Ea(),zt("Muted. Tap the mic button when you want me to listen again.");break}case"minimize":Et(),zt("Minimized — I'm still listening. Tap the call pill to bring the chat back.");break;case"expand":Qe(!0),zt("Sure — expanding the view.");break;case"shrink":it(null),Qe(!1),zt("Okay — back to the smaller view.");break}},[Et,ut,zt,Ea]);X(()=>{me.current=Xo},[Xo]);const Qo=R(!1);X(()=>{Qo.current&&!u&&C.current&&(C.current=!1,ut()),Qo.current=u},[u,ut]);const Tp=F(v=>{ae.current=v,Gn(v),At.current?.selectDevice(v||void 0)},[]),Cp=F(()=>{!Gt.current||Ct.current||(Ze.current=!1,Ve.current=!1,P(),ye(),kt.current=Date.now())},[P,ye]);X(()=>{At.current?.setOutputActive(u),kt.current=Date.now()},[u]),X(()=>{if(De!=="denied")return;const v=window.setTimeout(()=>ut(),3500);return()=>window.clearTimeout(v)},[ut,De]),X(()=>{if(!rt)return;const v=window.setInterval(()=>{const L=At.current;!L||Ct.current||xe.current||ft.current||L.snapshot.mic==="hearing"||L.snapshot.processing||Date.now()-kt.current<Gu||(At.current?.log.add("call-timeout"),an(!0),window.setTimeout(()=>ut(),2400))},5e3);return()=>window.clearInterval(v)},[ut,rt]);const Ap=rt&&!mt&&(l||u);X(()=>()=>ut(),[ut]);const[Mp,Ip]=$(""),es=R(!1);X(()=>{if(es.current&&!l){const v=[...d].reverse().find(L=>L.role==="assistant"&&!L.streaming&&!L.pending&&L.content);v&&Ip(v.content)}es.current=l},[l,d]),Sn(()=>{if(!o)return;const v=be.current,L=Ke||It?v?.querySelector(".cf-confirm__card"):Kt?v?.querySelector(".cf-history"):null;if(!L)return;const le=L.getRootNode(),Me="activeElement"in le?le.activeElement:document.activeElement;(!Me||!L.contains(Me))&&L.querySelector('button, [href], textarea, input, [tabindex]:not([tabindex="-1"])')?.focus()},[It,Ke,o,Kt]),X(()=>{if(!o)return;const v=be.current,L=Ke||It?v?.querySelector(".cf-confirm__card"):Kt?v?.querySelector(".cf-history"):null,le=v?.querySelectorAll(":scope > .cf-header, :scope > .cf-panel__video, :scope > .cf-panel__chat");le?.forEach(Ne=>{L?(Ne.setAttribute("inert",""),Ne.setAttribute("aria-hidden","true")):(Ne.removeAttribute("inert"),Ne.removeAttribute("aria-hidden"))}),L||requestAnimationFrame(()=>v?.querySelector(".cf-textarea")?.focus());const Me=Ne=>{if(Ne.key==="Escape"){Ne.preventDefault();const ta=Bo.current;if(ta.confirmEnd){Bt(!1);return}if(ta.confirmClear){on(!1);return}if(ta.showHistory){sn(!1);return}if(v?.querySelector(".cf-action-drawer"))return;Et();return}if(Ne.key!=="Tab"||!L)return;const bt=L.querySelectorAll('button, [href], textarea, input, [tabindex]:not([tabindex="-1"])'),xn=Array.from(bt).filter(ta=>!ta.hasAttribute("disabled"));if(xn.length===0)return;const Nt=xn[0],rs=xn[xn.length-1],is=L.getRootNode()instanceof ShadowRoot?L.getRootNode().activeElement:document.activeElement;Ne.shiftKey&&is===Nt?(Ne.preventDefault(),rs.focus()):!Ne.shiftKey&&is===rs&&(Ne.preventDefault(),Nt.focus())};return v?.addEventListener("keydown",Me),()=>{v?.removeEventListener("keydown",Me),le?.forEach(Ne=>{Ne.removeAttribute("inert"),Ne.removeAttribute("aria-hidden")})}},[o,Et,Ke,It,Kt]),X(()=>{const v=be.current;v&&(o?v.removeAttribute("inert"):v.setAttribute("inert",""))},[o]);const za=t.accentColor??t.themeTokens?.accent??c?.accentColor,ts=t.themeTokens?.accentText??Hu(za,t.themeTokens?.background??(he==="dark"?"#0f1c27":"#ffffff")),Ep={zIndex:t.zIndex,"--cf-h-pad":`${t.horizontalPadding}px`,"--cf-v-pad":`${t.verticalPadding}px`,...ts?{"--cf-accent-ink":ts}:{},...t.themeTokens?.accentStrong?{"--cf-accent-2":t.themeTokens.accentStrong}:{},...t.themeTokens?.background?{"--cf-bg":t.themeTokens.background}:{},...t.themeTokens?.surface?{"--cf-surface":t.themeTokens.surface}:{},...t.themeTokens?.surfaceMuted?{"--cf-surface-2":t.themeTokens.surfaceMuted}:{},...t.themeTokens?.text?{"--cf-text":t.themeTokens.text}:{},...t.themeTokens?.mutedText?{"--cf-muted":t.themeTokens.mutedText}:{},...t.themeTokens?.border?{"--cf-border":t.themeTokens.border}:{},...t.themeTokens?.shadow?{"--cf-shadow":t.themeTokens.shadow}:{},...t.themeTokens?.radius?{"--cf-radius":t.themeTokens.radius}:{},...t.themeTokens?.fontFamily?{"--cf-font":t.themeTokens.fontFamily}:{},...t.themeTokens?.success?{"--cf-success":t.themeTokens.success}:{},...t.themeTokens?.warning?{"--cf-warning":t.themeTokens.warning}:{},...t.themeTokens?.danger?{"--cf-danger":t.themeTokens.danger}:{},...za?{"--cf-accent":za,"--cf-accent-2":t.themeTokens?.accentStrong??`color-mix(in oklab, ${za} 76%, #14141f)`}:{}},zp=v=>g(v),Np=[...d].reverse().find(v=>v.role==="user"&&v.content.trim())?.content??"",Na=d.some(v=>v.role==="user"),ns=!!(c?.allowVoiceInput&&c?.talkbackMode&&c.talkbackMode!=="text"),as=ns,ea=!ze&&as&&!Na?Ca.filter((v,L)=>!(L===0&&v.role==="assistant")):Ca,Rp=f==="human"&&_?_:c?.agentName??i.chatName,Lp=f==="human"?i.liveSupport:f==="queued"?i.waitingForTeam:c?.offline?i.statusOffline:i.statusOnline,Ar=!ge&&!ze?c?.availableActions:void 0,Dp=!ge&&!ze?c?.actions:void 0,Mr=rt&&!bn&&De==="connecting"&&!ze;return r(jl,{value:i,children:r(Hl,{value:t.locale,children:r("div",{class:"cf-root",dir:t.dir,"data-theme":he,"data-align":t.alignment,"data-display":"floating",style:Ep,children:[dt&&o&&r("div",{class:"cf-theater-backdrop",onClick:Sp}),r("div",{ref:be,class:`cf-panel ${o?"is-open":""} ${rt?"cf-panel--call":""} ${Mr?"cf-panel--voice-connecting":""} ${dt&&o?"cf-panel--theater":""} ${Yn||Zn?"cf-panel--analytics-focus":""}`,role:"dialog","aria-modal":"false","aria-label":`${i.chatName}: ${c?.agentName??i.assistantName}`,"aria-hidden":!o,children:[Ye&&o&&r(hu,{state:Ye,onClose:fe}),r("div",{class:"cf-header",children:[r(uo,{persona:c,hideWhenMissing:!0}),r("div",{class:"cf-header__meta",children:[r("div",{class:"cf-header__name",children:Rp}),r("div",{class:`cf-header__status ${f==="ai"&&c?.offline?"cf-header__status--offline":""}`,children:r("span",{class:"cf-header__status-text",children:Lp})})]}),r("div",{class:"cf-header__actions",children:[We.length>0&&r("button",{type:"button",class:"cf-header__btn","aria-label":i.pastConversations,title:i.pastConversations,"aria-pressed":Kt,onClick:()=>sn(v=>!v),children:r(pd,{})}),Na&&!ge&&!ze&&r("button",{type:"button",class:"cf-header__btn","aria-label":i.endChat,title:i.endChat,onClick:bp,children:r(br,{})}),t.sound&&we&&r("button",{type:"button",class:"cf-header__btn","aria-label":Tt?i.unmuteSounds:i.muteSounds,"aria-pressed":Tt,onClick:ce,children:Tt?r(cd,{}):r(sd,{})}),r("button",{type:"button",class:"cf-header__btn cf-header__close","aria-label":i.closeChat,onClick:Et,children:r(pn,{})})]})]}),r("div",{class:"cf-panel__video",children:Yn?r("div",{class:"cf-analytics-focus",role:"region","aria-label":i.expandedAnalyticsResult,children:r(vo,{visualization:Yn,expanded:!0,onFollowUp:v=>{Ia(),g(v)},onClose:Ia})}):Zn?.visualization?r("div",{class:"cf-analytics-focus",role:"region","aria-label":i.expandedAnalyticsResult,children:r(Yd,{visualization:Zn.visualization,onClose:Ia,onFollowUp:v=>{Ia(),g(v)},onFeedback:ze?void 0:B,transport:ze?void 0:A("widget"),onOpenSource:t.onOpenAnalyticsSource})}):!ze&&as?r(Ad,{persona:c,starters:[],onPick:g,onFocusComposer:$p,speaking:u,voiceState:De,replyPending:rt&&l&&!u,pinned:!0,muted:mt,onToggleMute:Ea,onEndCall:ut,onTalkNow:Cp,showTalkNow:Ap,micLevel:Ot,theaterMode:dt,onToggleTheater:_p,onMinimize:Et,audioDevices:jn,selectedAudioDeviceId:Wn,onSelectAudioDevice:Tp,connectingOnly:Mr}):null}),!Mr&&r("div",{class:"cf-panel__chat",children:[t.preview&&r("div",{class:"cf-preview-banner",children:i.previewBanner}),ze&&r("div",{class:"cf-viewing-banner",children:i.viewingPast}),r("div",{class:"cf-body",ref:rn,role:"log",onScroll:yp,children:[ea.map((v,L)=>r(Kd,{msg:v,persona:c,isLast:!ze&&L===ea.length-1,visitor:p,hasEmail:m,lastQuestion:Np,showActions:!ze&&L===ea.length-1&&!!(v.handoffOffered||v.selectedAction),onPickReply:zp,onSubmitForm:oe,onDemoSlots:Ce,onConfirmHostedBooking:Fe,onRetry:te,ratable:!ze&&ea.slice(0,L).some(le=>le.role==="user"),onRate:U,onExplanationFeedback:ze?void 0:B,explanationTransport:ze?void 0:A("widget"),onOpenAnalyticsSource:t.onOpenAnalyticsSource,onExpandVisualization:ze?void 0:wp,onExpandExplanation:ze?void 0:kp,onOpenAttachment:pe,onReconnect:!ze&&!ge&&Oe&&v.id===et?y:void 0},v.id)),!Na&&!ze&&r(se,{children:[ea.length===0&&r(ju,{name:c?.agentName??i.assistantName,greeting:c?.greeting}),r(Hd,{items:I,onPick:g}),r(Wd,{items:x})]}),Ae&&r("button",{type:"button",class:"cf-newmsg",onClick:Yt,children:[r(bd,{}),i.newMessages]})]}),r("div",{class:"cf-sr-live","aria-live":"polite","aria-atomic":"true",children:Mp}),l&&!ge&&!ze&&r("div",{class:"cf-stopbar",children:r("button",{type:"button",class:"cf-stop",onClick:P,children:[r(ud,{}),i.stop]})}),ze?r("div",{class:"cf-ended",children:r("button",{type:"button",class:"cf-ended__btn",onClick:G,children:i.backToChat})}):ge?r("div",{class:"cf-ended",children:[r("p",{class:"cf-ended__text",children:i.conversationEnded}),t.csat&&Na?gp?r("p",{class:"cf-ended__text",children:i.feedbackThanks}):r("div",{class:"cf-csat",children:[r("span",{class:"cf-csat__q",children:i.csatPrompt}),r("button",{type:"button",class:"cf-csat__btn","aria-label":i.feedbackHelpful,onClick:()=>{ue("up"),qo(!0)},children:r(oo,{})}),r("button",{type:"button",class:"cf-csat__btn","aria-label":i.feedbackNotHelpful,onClick:()=>{ue("down"),qo(!0)},children:r(so,{})})]}):null,r("button",{type:"button",class:"cf-ended__btn",onClick:xp,children:i.startNewChat})]}):r(se,{children:[h?r("div",{class:"cf-live-typing","aria-live":"polite",children:qe(i.agentTyping,{name:h})}):null,Ar&&Ar.length>0&&r("div",{class:"cf-footer-actions",children:r(go,{actions:Ar,descriptors:Dp,visitor:p,onSubmitForm:oe,onDemoSlots:Ce,onConfirmHostedBooking:Fe,scheduler:c?.scheduler,translations:t.actionTranslations})},"footer-actions"),r(ou,{draftStore:mp,onSend:g,onSendGif:T,onTyping:V,disabled:l,allowVoice:ns,onTranscribe:_e,gifEnabled:ve,onSearchGifs:Ie,allowAttach:t.attachments,analyzeAttachments:!0,onUpload:Te,onPreviewAttachment:de},"composer")]}),!ge&&c?.disclaimerText&&r("div",{class:"cf-disclaimer",children:c.disclaimerText}),r("div",{class:"cf-footer",children:[r("button",{type:"button",class:"cf-footer__privacy","aria-label":i.clearDeviceData,onClick:()=>on(!0),children:i.privacyAndData}),r("span",{"aria-hidden":"true",children:"·"}),i.poweredBy," ",r("a",{href:"https://accurix.tech/centrinfo",target:"_blank",rel:"noopener noreferrer",children:"Centrinfo"})]})]}),Ke&&r("div",{class:"cf-confirm",onClick:()=>Bt(!1),children:r("div",{class:"cf-confirm__card",role:"alertdialog","aria-modal":"true","aria-label":i.endChatConfirm,onClick:v=>v.stopPropagation(),onKeyDownCapture:v=>Tr(v,v.currentTarget,()=>Bt(!1)),children:[r("div",{class:"cf-confirm__title",children:i.endChatConfirm}),r("div",{class:"cf-confirm__body",children:i.endChatConfirmBody}),r("div",{class:"cf-confirm__actions",children:[r("button",{ref:Uo,type:"button",class:"cf-confirm__btn cf-confirm__btn--cancel",onClick:()=>Bt(!1),children:i.cancel}),r("button",{type:"button",class:"cf-confirm__btn cf-confirm__btn--danger",onClick:vp,children:i.endConfirmCta})]})]})},"confirm-end"),Kt&&r("div",{class:"cf-confirm",onClick:()=>sn(!1),children:r("div",{class:"cf-history",role:"dialog","aria-modal":"true","aria-label":i.pastConversations,onClick:v=>v.stopPropagation(),onKeyDownCapture:v=>Tr(v,v.currentTarget,()=>sn(!1)),children:[r("div",{class:"cf-history__head",children:[r("span",{children:i.pastConversations}),r("button",{type:"button",class:"cf-header__btn","aria-label":i.closeHistory,onClick:()=>sn(!1),children:r(pn,{})})]}),r("div",{class:"cf-history__list",children:We.map(v=>r("button",{type:"button",class:`cf-history__item ${v.sessionId===k?"is-active":""}`,onClick:()=>{j(v.sessionId),sn(!1)},children:[r("span",{class:"cf-history__title",children:v.title}),r("span",{class:"cf-history__meta",children:[new Date(v.ts).toLocaleDateString(void 0,{month:"short",day:"numeric"}),v.ended?` · ${i.historyEnded}`:""]})]},v.sessionId))}),r("div",{class:"cf-history__footer",children:r("button",{type:"button",class:"cf-history__clear",onClick:()=>{sn(!1),on(!0)},children:i.clearDeviceData})})]})},"history"),It&&r("div",{class:"cf-confirm",onClick:()=>on(!1),children:r("div",{class:"cf-confirm__card",role:"alertdialog","aria-modal":"true","aria-label":i.clearDeviceData,onClick:v=>v.stopPropagation(),onKeyDownCapture:v=>Tr(v,v.currentTarget,()=>on(!1)),children:[r("div",{class:"cf-confirm__title",children:i.clearDeviceData}),r("div",{class:"cf-confirm__body",children:i.clearDeviceDataBody}),r("div",{class:"cf-confirm__actions",children:[r("button",{type:"button",class:"cf-confirm__btn cf-confirm__btn--cancel",onClick:()=>on(!1),children:i.cancel}),r("button",{type:"button",class:"cf-confirm__btn cf-confirm__btn--danger",onClick:()=>{on(!1),ne()},children:i.clearDeviceDataCta})]})]})},"confirm-clear")]}),rt&&!o?r(ru,{persona:c,voiceState:De,muted:mt,onToggleMute:Ea,onEndCall:ut,micLevel:Ot,onExpand:vn}):dt&&o?null:!t.hideDefaultLauncher&&r("button",{ref:wt,type:"button",class:"cf-launcher","aria-label":o?i.closeChat:Ge>0?`${i.openChat}. ${Ge===1?i.unreadMessage:qe(i.unreadMessages,{count:String(Ge)})}`:i.openChat,"aria-expanded":o,onClick:Jn,children:[t.launcherIcon?r("img",{class:"cf-launcher__img",src:t.launcherIcon,alt:""}):r(Jl,{}),!o&&Ge>0&&r("span",{class:"cf-launcher__badge","aria-hidden":"true",children:Ge>99?"99+":Ge})]})]})})})},np="https://api.accurixtech.com",ap=()=>typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en",rp=(e,t)=>{if(!e)return;const n=t.trim().toLowerCase(),a=n.split("-")[0]??n,i=Object.entries(e);return i.find(([o])=>o.toLowerCase()===n)?.[1]??i.find(([o])=>o.toLowerCase()===a)?.[1]},ip=e=>{if(!e||typeof e.token!="string"||e.token.length===0)throw new Error("[centrinfo-widget] `token` is required — pass your pub_* token to Centrinfo.init({ token }).");const t=e.locale?.trim()||ap(),n=rp(e.translations,t);return{token:e.token,chatSurface:e.chatSurface??"floating",analyticsContextToken:e.analyticsContextToken,identityToken:e.identityToken,getIdentityToken:e.getIdentityToken,apiBaseUrl:(e.apiBaseUrl??np).replace(/\/$/,""),accentColor:e.accentColor,themeTokens:e.themeTokens,agentName:e.agentName?.trim()||void 0,agentAvatarUrl:e.agentAvatarUrl?.trim()||void 0,launcherIcon:e.launcherIcon,gifApiKey:e.gifApiKey,theme:e.theme??"auto",openByDefault:e.openByDefault??!1,sound:e.sound??!0,starters:e.starters??[],strings:Vl({...n?.labels,...e.labels,...n?.labels?.analytics||e.labels?.analytics?{analytics:{...n?.labels?.analytics,...e.labels?.analytics,explanation:{...n?.labels?.analytics?.explanation,...e.labels?.analytics?.explanation}}}:{}}),locale:t,dir:Gl(t,e.dir),actionTranslations:n?.actions??{},persistence:e.persistence??"local",attachments:e.attachments??!0,zIndex:e.zIndex??2147483e3,styleNonce:e.styleNonce?.trim()??"",demo:e.demo??!1,preview:e.preview??!1,alignment:e.alignment==="left"?"left":"right",horizontalPadding:typeof e.horizontalPadding=="number"?e.horizontalPadding:20,verticalPadding:typeof e.verticalPadding=="number"?e.verticalPadding:20,hideDefaultLauncher:e.hideDefaultLauncher??!1,customLauncherSelector:e.customLauncherSelector,sessionDurationMinutes:typeof e.sessionDurationMinutes=="number"?e.sessionDurationMinutes:0,configRefreshSeconds:typeof e.configRefreshSeconds=="number"?e.configRefreshSeconds:30,proactiveMessage:e.proactiveMessage,proactiveDelaySeconds:typeof e.proactiveDelaySeconds=="number"?e.proactiveDelaySeconds:5,proactiveOnPaths:e.proactiveOnPaths,csat:e.csat??!0,user:e.user,onOpen:e.onOpen,onClose:e.onClose,onShow:e.onShow,onHide:e.onHide,onUnreadChange:e.onUnreadChange,onMessage:e.onMessage,onOpenAnalyticsSource:e.onOpenAnalyticsSource,onAction:e.onAction,onHandoff:e.onHandoff}},Ro=`
170
+ `).replace(/[ \t]{2,}/g," ").trim(),Su=(e,t)=>Co(Hc(e,t)),$u=45e3,wr=e=>e.type==="visualization",Tu=e=>{const t=!!e.visualization,n=(e.artifacts??[]).some(wr);if(!t&&!n)return e;const{visualization:a,artifacts:i,...o}=e,s=(i??[]).filter(u=>!wr(u)),c=a?.title??(i??[]).find(wr)?.visualization?.title??e.resultExpired?.title;return{...o,...s.length>0?{artifacts:s}:{},resultExpired:c?{title:c}:{}}},kr=e=>e.map(Tu),Cu=(e,t=Date.now())=>{const n=e.visualization?.explanation?.aiExplanation;if(!e.visualization?.explanation||!n||n.status!=="pending")return e;const a=e.createdAt?Date.parse(e.createdAt):NaN;return Number.isFinite(a)&&t-a<$u?e:{...e,visualization:{...e.visualization,explanation:{...e.visualization.explanation,aiExplanation:{...n,status:"failed",retryAvailable:!1}}}}},Mu=e=>e instanceof DOMException&&(e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED"),Au=(e,t,n,a)=>{let i=a;for(let o=0;o<4&&i.length>0;o+=1)try{return e.setItem(t,n(i)),!0}catch(s){if(!Mu(s))return!1;i=i.slice(Math.ceil(i.length/2))}try{e.removeItem(t)}catch{}return!1},Iu=(e,t)=>{if(e)try{const n=[];for(let a=0;a<e.length;a+=1){const i=e.key(a);i?.startsWith(t)&&n.push(i)}for(const a of n){const i=e.getItem(a);if(!i)continue;const o=JSON.parse(i);if(!Array.isArray(o.messages))continue;const s=kr(o.messages);s.some((c,u)=>c!==o.messages[u])&&e.setItem(a,JSON.stringify({...o,messages:s}))}}catch{}},Eu=(e,t=()=>Date.now())=>{let n=null,a=null,i=Number.NEGATIVE_INFINITY;const o=()=>{a!==null&&(clearTimeout(a),a=null);const s=n;n=null,s&&(i=t(),s())};return{schedule:s=>{if(n=s,a!==null)return;const c=e-(t()-i);c<=0?o():a=setTimeout(o,c)},flush:o,cancel:()=>{a!==null&&clearTimeout(a),a=null,n=null}}},lt=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.round(Math.random()*1e9)}`,Sa=(e,t)=>{typeof console>"u"||console.warn(`[centrinfo-widget] ${e}`,t??{})},Mo=(e,t,n,a,i=1,o,s=!1,c,u)=>{e.current?.pause(),e.current=null,typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel(),t.current=null;const l=()=>{const x=o?.trim();if(!s||!x||typeof window>"u"||!("speechSynthesis"in window)||typeof SpeechSynthesisUtterance>"u")return!1;const w=new SpeechSynthesisUtterance(x);let v=!1;const m=()=>{v||(v=!0,t.current===w&&(t.current=null,u?.()))};return w.rate=i,w.lang=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en-US",w.onend=m,w.onerror=m,t.current=w,c?.(),window.speechSynthesis.cancel(),window.speechSynthesis.speak(w),!0};if(!n||typeof Audio>"u")return l();const d=new Audio(`data:${a||"audio/mpeg"};base64,${n}`);let p=!1,h=!1;const f=()=>{p||(p=!0,e.current===d&&(e.current=null,u?.()))},_=()=>{if(!p){if(h||e.current!==d){f();return}p=!0,e.current=null,l()||u?.()}};return d.playbackRate=i,d.onended=f,d.onerror=_,e.current=d,d.play().then(()=>{if(!p){if(e.current!==d){f();return}h=!0,c?.(Number.isFinite(d.duration)?d.duration*1e3:void 0)}}).catch(_),!0},zu=e=>{try{return e==="none"?null:e==="session"?sessionStorage:localStorage}catch{return null}},Nu=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)},Ru=e=>{try{const t=e?.split(".")[1];if(!t)return;const n=t.replace(/-/g,"+").replace(/_/g,"/"),a=JSON.parse(atob(n.padEnd(Math.ceil(n.length/4)*4,"=")));for(const i of["sub","external_user_id","user_id"]){const o=a[i];if(typeof o=="string"&&o.trim())return o.trim()}}catch{}},Lu=e=>{const t=e.user?.externalId?.trim()||e.user?.userId?.trim()||e.user?.email?.trim().toLowerCase()||Ru(e.identityToken)||(e.identityToken||e.getIdentityToken?"authenticated":"anonymous");return`${e.token.slice(0,12)}:${e.chatSurface}:${Nu(t)}`},Bn=e=>`${e.chatSurface}:${lt()}`,Du=e=>e.slice(0,12),qn=e=>`centrinfo:session:${e}`,Sr=e=>`centrinfo:visitor:${e}`,$a=(e,t)=>`centrinfo:chat:${e}:${t}`,$r=e=>`centrinfo:history:${e}`,Pu=1e3,Ao=20,Tr=720*60*60*1e3,Ou=1440*60*1e3,Fu=(e,t)=>{try{return JSON.parse(e?.getItem(Sr(t))||"{}")}catch{return{}}},Uu=(e,t,n)=>{if(!e)return Bn(n);try{const a=qn(t),i=e.getItem(a);if(i)return i;const o=Bn(n);return e.setItem(a,o),o}catch{return Bn(n)}},Io=(e,t,n)=>{if(!e)return{};try{const a=e.getItem($a(t,n));return a?JSON.parse(a):{}}catch{return{}}},Eo=(e,t,n)=>{const{ts:a,expiresAt:i,messages:o}=Io(e,t,n);return Array.isArray(o)?typeof i=="number"&&Date.now()>i?[]:typeof a=="number"&&Date.now()-a>Tr?[]:kr(o):[]},Bu=(e,t,n)=>{const{ts:a,expiresAt:i,messages:o,ended:s}=Io(e,t,n);return!Array.isArray(o)||o.length===0||typeof i=="number"&&Date.now()>i||typeof a=="number"&&Date.now()-a>Tr?!1:s===!0||typeof a=="number"&&Date.now()-a>Ou},qu=e=>Number.isFinite(e??NaN)?Math.max(5,Math.min(200,Math.round(e))):50,Vu=e=>Number.isFinite(e??NaN)?Math.max(1,Math.min(365,Math.round(e)))*24*60*60*1e3:Tr,zo=(e,t,n,a,i,o,s,c)=>{if(e)try{if(!o){e.removeItem($a(t,n));return}const u=a.filter(d=>!d.pending).slice(-s);if(u.length===0)return;const l=Date.now();Au(e,$a(t,n),d=>JSON.stringify({ts:l,expiresAt:l+c,messages:kr(d),ended:i}),u)}catch{}},Hu=(e,t)=>{if(!e)return[];try{const n=e.getItem($r(t)),a=n?JSON.parse(n):[];return Array.isArray(a)?a:[]}catch{return[]}},Ta=(e,t,n)=>{if(e)try{e.setItem($r(t),JSON.stringify(n.slice(0,Ao)))}catch{}},No=(e,t)=>{if(e)try{const n=`centrinfo:chat:${t}:`,a=new Set([qn(t),Sr(t),$r(t)]),i=[];for(let o=0;o<e.length;o++){const s=e.key(o);s&&(a.has(s)||s.startsWith(n))&&i.push(s)}i.forEach(o=>e.removeItem(o))}catch{}},ju=e=>{const a=(e.find(i=>i.role==="user"&&i.content.trim())?.content||e.find(i=>i.content.trim())?.content||"").trim().replace(/\s+/g," ");return a.length>60?a.slice(0,60)+"…":a||"Conversation"},Wu=e=>({id:`live:${e.id}`,role:e.type==="chat"||e.type==="ai_resume"?"assistant":"system",content:e.content,authorName:e.authorName,liveEventType:e.type,createdAt:e.createdAt,offerReconnect:e.type==="ai_handback"&&e.reconnectOffered===!0}),Ro=e=>(e??[]).find(t=>t.category==="support"&&t.enabled&&t.readiness!=="unavailable"&&(t.liveHandoff??t.id==="public_contact_support")),Gu=(e,t)=>{if(t==="ai")for(let n=e.length-1;n>=0;n--){const a=e[n];if(a){if(a.reconnectOffer)return;if(a.liveEventType==="ai_handback")return a.offerReconnect?a.id:void 0}}},Ku=(e,t,n=!0)=>{const a=R(zu(t.persistence)).current,i=Lu(t),o=R(Uu(a,i,t)),s=R(null),c=R(null),u=R(null),l=R(null),d=R(null),p=R(null),h=R(new Map),f=R(!1),_=R(void 0),x=R(null),w=R({}),v=R({}),[m,T]=S(null),[P,O]=S(()=>Eo(a,i,o.current)),re=R(null);re.current||(re.current=Eu(Pu));const J=R(P.length>0),G=R(P.some(g=>g.role==="user")),[N,se]=S(!1),[q,F]=S(!1),[C,I]=S({status:"idle"}),ce=R({}),[te,ue]=S(()=>Bu(a,i,o.current)),[le,z]=S(()=>Fu(a,i)),[ne,He]=S(()=>Hu(a,i)),[y,V]=S(null),[we,oe]=S([]),[_e,he]=S("ai"),[Ge,ke]=S(void 0),[K,Ne]=S(void 0),Ze=R(new Date().toISOString()),$=R(void 0),j=R(!1),U=R(0),Y=R(le);X(()=>{Y.current=le},[le]);const Q=m?.memoryEnabled!==!1,$e=qu(m?.memoryMessageCap),Me=Vu(m?.memoryRetentionDays),et=D(()=>{s.current?.abort(),re.current?.cancel(),No(a,i),No(a,Du(t.token));const g=Bn(t);o.current=g;try{a?.setItem(qn(i),g)}catch{}V(null),oe([]),ue(!1),He([]),z({}),he("ai"),ke(void 0),Ne(void 0),Ze.current=new Date().toISOString(),O(m?[{id:lt(),role:"assistant",content:m.greeting,availableActions:m.availableActions,actions:m.actions}]:[])},[a,i,t.token,m]),Je=D(g=>{try{a?.setItem(Sr(i),JSON.stringify(g))}catch{}},[a,i]),tt=D(g=>{const k=(g.email??"").trim().toLowerCase(),E=(Y.current.email??"").trim().toLowerCase();k&&E&&k!==E&&et();const M={};g.email?.trim()&&(M.email=g.email.trim()),g.phone?.trim()&&(M.phone=g.phone.trim());const Z=[g.firstName,g.lastName].filter(xe=>!!xe?.trim()).join(" ").trim()||g.name?.trim()||"";Z&&(M.name=Z),Object.keys(M).length>0&&z(xe=>{const ae={...M,...xe};return Je(ae),ae}),e.identify(o.current,g).catch(()=>{})},[e,Je,et]),at=R(0),A=D(g=>{at.current=Date.now(),T(g),O(k=>{if(k.length===0)return[{id:lt(),role:"assistant",content:g.greeting,availableActions:g.availableActions,actions:g.actions}];const E=k.some(H=>H.role==="user"),M=k[0];return!E&&M?.role==="assistant"?[{...M,content:g.greeting,availableActions:g.availableActions,actions:g.actions},...k.slice(1)]:k})},[]);X(()=>{if(m?.memoryEnabled===!1){re.current?.cancel();try{a?.removeItem($a(i,o.current))}catch{}Ta(a,i,[]),He([]),V(null),oe([]),O(g=>J.current?(J.current=!1,m?[{id:lt(),role:"assistant",content:m.greeting,availableActions:m.availableActions,actions:m.actions}]:[]):g)}},[m,a,i]);const ge=D(async()=>{const g=await e.bootstrap();A(g)},[A,e]);X(()=>{let g=!0;const k=E=>E.messages.map(M=>Cu({id:M.id,role:M.role,content:M.content,authorName:M.authorName,liveEventType:M.messageType,offerReconnect:M.messageType==="ai_handback"&&M.reconnectOffered===!0,sources:M.sources,visualization:M.visualization,artifacts:M.artifacts,createdAt:M.createdAt}));return e.history().then(E=>{if(!g||E.conversations.length===0)return;const M=E.conversations.map(ae=>({sessionId:ae.sessionId,ts:Date.parse(ae.lastSeenAt)||Date.now(),title:ae.title,ended:ae.ended}));for(const ae of E.conversations)zo(a,i,ae.sessionId,k(ae),ae.ended,!0,$e,Me);Ta(a,i,M),He(M);const H=E.conversations.find(ae=>ae.sessionId===E.activeSessionId);if(!H||G.current)return;const Z=k(H);o.current=H.sessionId,J.current=Z.length>0;try{a?.setItem(qn(i),H.sessionId)}catch{}const xe=Z[Z.length-1]?.createdAt;xe&&(Ze.current=xe),ue(H.ended),O(Z)}).catch(()=>{}),()=>{g=!1}},[$e,Me,i,a,e]),X(()=>{let g=!0;return at.current=Date.now(),e.bootstrap().then(k=>{g&&A(k)}),t.user&&tt(t.user),()=>{g=!1}},[A,e]),X(()=>{const g=t.configRefreshSeconds;if(!n||g<=0||typeof window>"u")return;let k=!0,E=!1;const M=Math.max(10,g)*1e3,H=()=>typeof document>"u"||document.visibilityState!=="hidden",Z=async()=>{if(!(!k||E||!H())){E=!0;try{await ge()}catch{}finally{E=!1}}};Date.now()-at.current>=M&&Z();const xe=window.setInterval(Z,M),ae=()=>{Z()},Se=()=>{Z()};return window.addEventListener("focus",ae),document?.addEventListener?.("visibilitychange",Se),()=>{k=!1,window.clearInterval(xe),window.removeEventListener("focus",ae),document?.removeEventListener?.("visibilitychange",Se)}},[n,t.configRefreshSeconds,ge]),X(()=>{const g=o.current;re.current.schedule(()=>zo(a,i,g,P,te,Q,$e,Me))},[P,te,a,i,Q,$e,Me]),X(()=>{const g=re.current,k=()=>{document.visibilityState==="hidden"&&g.flush()};return document.addEventListener("visibilitychange",k),window.addEventListener("pagehide",g.flush),()=>{document.removeEventListener("visibilitychange",k),window.removeEventListener("pagehide",g.flush),g.flush()}},[]),X(()=>{Iu(a,"centrinfo:chat:")},[a]),X(()=>{if(!n||te||y)return;const g=()=>{document.visibilityState==="visible"&&e.presence(o.current)};g();const k=window.setInterval(g,1e4);return document.addEventListener("visibilitychange",g),()=>{window.clearInterval(k),document.removeEventListener("visibilitychange",g)}},[n,te,e,y]),X(()=>{if(!n||te||y)return;let g=!0,k=!1,E=0,M;const H=()=>{M!==void 0&&window.clearTimeout(M),!(!g||document.hidden)&&(M=window.setTimeout(()=>{Z()},Math.min(3e4,2200*2**E)))},Z=async()=>{if(!(k||document.hidden||!g)){k=!0;try{const ae=await e.liveEvents(o.current,Ze.current);if(!g)return;if(E=0,he(ae.mode),ke(ae.assignedAgentName||void 0),Ne(ae.agentTyping?ae.agentTypingName||ae.assignedAgentName||"Agent":void 0),ae.conversationEnded){ue(!0),he("ai"),ke(void 0),Ne(void 0),O(Se=>Se.some(ie=>ie.id==="live:conversation-ended")?Se:[...Se,{id:"live:conversation-ended",role:"system",content:t.strings.conversationEnded,liveEventType:"conversation_ended",createdAt:new Date().toISOString()}]);return}if(ae.events.length>0){let Se=Ze.current,ie=Date.parse(Se);const ot=ae.events.map(Be=>{const je=Date.parse(Be.createdAt);return Number.isFinite(je)&&je>ie&&(ie=je,Se=Be.createdAt),Wu(Be)});Ze.current=Se,O(Be=>{const je=new Set(Be.map(nt=>nt.id)),Xe=ot.filter(nt=>!je.has(nt.id));return Xe.length>0?[...Be,...Xe]:Be}),ot.some(Be=>Be.role==="assistant")&&gn("receive")}}catch{E=Math.min(E+1,4)}finally{k=!1,H()}}},xe=()=>{document.hidden?M!==void 0&&window.clearTimeout(M):Z()};return document.addEventListener("visibilitychange",xe),document.hidden||Z(),()=>{g=!1,M!==void 0&&window.clearTimeout(M),document.removeEventListener("visibilitychange",xe)}},[n,t.strings.conversationEnded,e,te,y]),X(()=>{if(!Q){Ta(a,i,[]),He(k=>k.length>0?[]:k);return}P.some(k=>k.role==="user")&&He(k=>{const E=o.current,H=[{sessionId:E,ts:Date.now(),title:ju(P),ended:te},...k.filter(Z=>Z.sessionId!==E)];return Ta(a,i,H),H.slice(0,Ao)})},[P,te,a,i,Q]);const me=D((g,k)=>{O(E=>E.map(M=>M.id===g?{...M,...k}:M))},[]),be=D(()=>{_.current!==void 0&&typeof window<"u"&&window.clearInterval(_.current),_.current=void 0},[]),Ue=D((g,k)=>{be(),delete w.current[g],x.current===g&&(x.current=null),me(g,{content:k,pending:!1,streaming:!1})},[be,me]),Ke=D((g,k,E)=>{const M=k.trim();if(!M||typeof window>"u"){Ue(g,M);return}be(),x.current=g;const H=M.match(/\S+\s*/g)??[M],Z=E&&E>0?E:H.length*95,xe=Math.max(28,Math.min(150,Z/Math.max(H.length,1)));let ae=0;me(g,{content:"",pending:!1,streaming:!0}),_.current=window.setInterval(()=>{ae+=1;const Se=H.slice(0,ae).join("");me(g,{content:Se,pending:!1,streaming:ae<H.length}),ae>=H.length&&(be(),delete w.current[g],x.current===g&&(x.current=null),me(g,{content:M,pending:!1,streaming:!1}))},xe)},[be,Ue,me]),mt=D(()=>{const g=x.current;be(),x.current=null;const k=w.current;w.current={};for(const[E,M]of Object.entries(k))me(E,{content:M,pending:!1,streaming:!1});g&&!(g in k)&&me(g,{pending:!1,streaming:!1})},[be,me]),pt=D(g=>{if(te||y||_e==="ai"||typeof window>"u")return;if($.current!==void 0&&window.clearTimeout($.current),!g){if(!j.current)return;j.current=!1,U.current=0,e.typing(o.current,!1).catch(()=>{});return}const k=Date.now();(!j.current||k-U.current>2500)&&(j.current=!0,U.current=k,e.typing(o.current,!0).catch(()=>{})),$.current=window.setTimeout(()=>{j.current&&(j.current=!1,U.current=0,e.typing(o.current,!1).catch(()=>{}))},1600)},[e,te,y,_e]);X(()=>()=>{$.current!==void 0&&typeof window<"u"&&window.clearTimeout($.current)},[]),X(()=>()=>be(),[be]);const yt=D((g,k,E={})=>{mt(),se(!0);const M=_r();let H=!1;const Z=new AbortController;s.current=Z;const xe=!!(m?.allowVoiceInput&&m?.voiceOutputEnabled&&m.talkbackMode!=="text"),ae=!!E.forceVoicePlayback,Se=W=>{ae&&I(Ie=>Ie.agentId===k?{status:W,agentId:k}:Ie)};ae&&I({status:"answering",agentId:k});const ie={pending:new Map,nextSeq:0,highestSeq:-1,playing:!1,ended:!1,started:!1,stopped:!1,utterance:null},ot=()=>{p.current===At&&(p.current=null),ie.started&&(ie.started=!1,F(!1),Se("done"))},Be=()=>{ie.stopped||ie.started||(ie.started=!0,ka("voice-first-audio",M),F(!0),Se("speaking"))},je=()=>typeof window<"u"&&"speechSynthesis"in window&&typeof SpeechSynthesisUtterance<"u",Xe=()=>{l.current&&ie.playing&&(l.current.pause(),l.current=null),ie.utterance&&(d.current===ie.utterance&&(d.current=null),ie.utterance=null,je()&&window.speechSynthesis.cancel()),ie.playing=!1},nt=(W,Ie)=>{const ze=W?.trim();if(!ze||!je())return!1;const Ce=new SpeechSynthesisUtterance(ze);return Ce.rate=m?.voiceSpeed??1,Ce.lang=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en-US",Ce.onstart=Be,Ce.onend=Ie,Ce.onerror=Ie,ie.utterance=Ce,d.current=Ce,window.speechSynthesis.speak(Ce),f.current&&window.speechSynthesis.pause(),!0},ft=()=>{for(;!ie.stopped&&!ie.playing;){let W=ie.pending.get(ie.nextSeq);if(!W&&ie.ended&&ie.pending.size>0&&(ie.nextSeq=Math.min(...ie.pending.keys()),W=ie.pending.get(ie.nextSeq)),!W){ie.ended&&ot();return}if(ie.pending.delete(ie.nextSeq),ie.nextSeq+=1,Oe(W))return}},Oe=W=>{let Ie=!1;const ze=()=>{Ie||(Ie=!0,d.current===ie.utterance&&(d.current=null),ie.utterance=null,ie.playing=!1,ft())};if(!W.audioBase64||typeof Audio>"u")return ie.playing=nt(W.text,ze),ie.playing;const Ce=new Audio(`data:${W.mimeType||"audio/mpeg"};base64,${W.audioBase64}`);Ce.playbackRate=m?.voiceSpeed??1,Ce.volume=f.current?.2:1,ie.playing=!0,l.current=Ce;let Ye=!1,Bt=!1;const It=()=>{Ie||Bt||(Bt=!0,l.current===Ce&&(l.current=null),!(!Ye&&!ie.stopped&&nt(W.text,ze))&&ze())};return Ce.onended=()=>{l.current===Ce&&(l.current=null),ze()},Ce.onerror=It,Ce.play().then(()=>{Ye=!0,Be()}).catch(It),!0},At=()=>{ie.stopped=!0,ie.pending.clear(),Xe(),ot()};e.stream(g,o.current,{voicePlaybackRequested:!!E.forceVoicePlayback,clientMessageId:E.clientMessageId,attachmentId:E.attachmentId,attachmentIds:E.attachmentIds,signal:Z.signal,onChunk:W=>{W&&!H&&(H=!0,ka("data-first-chunk",M)),E.forceVoicePlayback&&W&&(v.current[k]=!0),O(Ie=>Ie.map(ze=>ze.id===k?{...ze,content:ze.content+W,pending:!1,streaming:!0}:ze))},onTextReady:()=>{O(W=>W.map(Ie=>Ie.id===k?{...Ie,pending:!1,streaming:!1}:Ie))},onReset:()=>{O(W=>W.map(Ie=>Ie.id===k?{...Ie,content:"",pending:!0,streaming:!1}:Ie)),ie.pending.clear(),ie.nextSeq=ie.highestSeq+1,Xe()},onAudioSegment:W=>{!ae||ie.stopped||W.seq<ie.nextSeq||ie.pending.has(W.seq)||(p.current=At,ie.highestSeq=Math.max(ie.highestSeq,W.seq),ie.pending.set(W.seq,W),ft())}}).then(W=>{if(n&&!W.conversationEnded&&typeof document<"u"&&document.visibilityState==="visible"&&e.presence(o.current),W.liveMode&&(he(W.liveMode),ke(W.assignedAgentName||void 0)),W.liveMode&&W.liveMode!=="ai"&&!W.answer.trim()){O(Ce=>Ce.filter(Ye=>Ye.id!==k)),Se("done");return}const Ie=!!v.current[k];delete v.current[k];const ze=!!(E.forceVoicePlayback&&xe&&!W.liveAudio&&W.audioBase64&&W.answer.trim()&&!Ie);if(ze&&(w.current[k]=W.answer),O(Ce=>Ce.map(Ye=>Ye.id===k?{...Ye,content:ze?"":W.answer||Ye.content||t.strings.emptyReply,pending:!1,streaming:ze,error:!1,retryText:void 0,sources:W.sources,suggestedReplies:W.suggestedReplies,availableActions:W.availableActions,actions:W.actions,selectedAction:W.selectedAction,handoffOffered:W.handoffOffered,requestedContactFields:W.requestedContactFields,visualization:W.visualization,artifacts:W.artifacts}:Ye)),gn("receive"),W.liveAudio?(ie.ended=!0,ft()):E.forceVoicePlayback&&!W.audioBase64&&Sa(xe?"Talkback expected backend TTS audio, but the chat response did not include audioBase64.":"Talkback voice was requested, but the loaded widget token config does not enable provider TTS.",{voiceOutputEnabled:m?.voiceOutputEnabled,talkbackMode:m?.talkbackMode,voiceProvider:m?.voiceProvider,hasAudioBase64:!!W.audioBase64}),E.forceVoicePlayback&&!W.liveAudio){const Ce=Mo(l,d,W.audioBase64,W.mimeType,m?.voiceSpeed??1,Su(W.answer,W.visualization),!0,Ye=>{F(!0),Se("speaking"),ze&&Ke(k,W.answer,Ye)},()=>{F(!1),Se("done"),ze&&Ue(k,W.answer)});Ce||Se("done"),ze&&!Ce&&Ue(k,W.answer)}W.answer&&t.onMessage?.({role:"assistant",content:W.answer}),W.handoffOffered&&t.onHandoff?.(),W.conversationEnded&&ue(!0)}).catch(W=>{if(Z.signal.aborted){ie.stopped||At(),delete v.current[k],O(ze=>ze.flatMap(Ce=>Ce.id!==k?[Ce]:Ce.content.trim()?[{...Ce,pending:!1,streaming:!1}]:[])),Se("done");return}Se("failed"),delete v.current[k];const Ie=_u(W,t.strings);me(k,{content:Ie,pending:!1,streaming:!1,error:!0,retryText:g})}).finally(()=>{ka("data-complete",M),delete v.current[k],s.current===Z&&(se(!1),s.current=null,c.current?.agentId===k&&(c.current=null))})},[e,n,t,me,m?.allowVoiceInput,m?.talkbackMode,m?.voiceOutputEnabled,m?.voiceSpeed,mt]),Dt=D((g,k={})=>{const E=g.trim(),{imageUrl:M,attachmentName:H,attachmentText:Z,attachmentId:xe,attachmentFile:ae,forceVoicePlayback:Se,userMessageId:ie}=k,ot=k.attachments??(H||xe||Z?[{id:xe,name:H??"",text:Z,file:ae}]:[]);if(!E&&!M&&ot.length===0||s.current&&!s.current.signal.aborted||te)return;G.current=!0;let Be=E;!Be&&ot.length>0&&(Be="Please look at the attached file."),!Be&&M&&(Be=M);const je=ot.map(Oe=>({id:Oe.id,name:Oe.name})),Xe=ot.flatMap(Oe=>Oe.id?[Oe.id]:[]),nt={id:ie||lt(),role:"user",content:E,imageUrl:M,attachments:je.length>0?je:void 0};ot.forEach((Oe,At)=>{Oe.file&&(h.current.set(`${nt.id}:${At}`,Oe.file),Oe.id&&h.current.set(Oe.id,Oe.file))});const ft=lt();O(Oe=>[...!!(ie&&Oe.some(Ie=>Ie.id===ie))?Oe.map(Ie=>Ie.id===ie?{...Ie,content:E,pending:!1,streaming:!1,imageUrl:M,attachments:nt.attachments}:Ie):[...Oe,nt],{id:ft,role:"assistant",content:"",pending:!0}]),gn("send"),t.onMessage?.({role:"user",content:Be}),ce.current[ft]=nt.id,c.current={userId:nt.id,agentId:ft,text:E,backendText:Be},yt(Be,ft,{forceVoicePlayback:Se,clientMessageId:nt.id,attachmentId:Xe[0],attachmentIds:Xe})},[te,t,yt]),_t=D((g,k,E,M,H)=>{const Z=lt();O(xe=>[...xe.filter(ae=>ae.id!==g.agentId&&(!M.userMessageId||ae.id!==M.userMessageId)).map(ae=>ae.id===g.userId?{...ae,content:k,pending:!1,streaming:!1}:ae),{id:Z,role:"assistant",content:"",pending:!0}]),H&&t.onMessage?.({role:"user",content:H}),ce.current[Z]=g.userId,c.current={userId:g.userId,agentId:Z,text:k,backendText:E},yt(E,Z,{forceVoicePlayback:M.forceVoicePlayback,clientMessageId:lt()})},[t,yt]),Hn=D((g,k={})=>{const E=g.trim();if(!E||te)return;const M=s.current&&!s.current.signal.aborted?c.current:null,H=M??u.current;if(u.current=null,!H){Dt(E,k);return}M&&s.current?.abort(),_t(H,`${H.text} ${E}`.replace(/\s+/g," ").trim(),`${H.backendText}
171
+ ${E}`.trim(),k,E)},[te,_t,Dt]),an=D(()=>{const g=s.current&&!s.current.signal.aborted?c.current:null;return g?(u.current=g,s.current?.abort(),!0):!1},[]),rt=D(()=>{const g=u.current;u.current=null,!(!g||te)&&_t(g,g.text,g.backendText,{forceVoicePlayback:!0})},[te,_t]),Pt=D(()=>s.current?.abort(),[]),bn=D(g=>{f.current=g;const k=l.current;k&&(k.volume=g?.2:1),d.current&&typeof window<"u"&&"speechSynthesis"in window&&(g?window.speechSynthesis.pause():window.speechSynthesis.resume())},[]),Ht=D(()=>{p.current?.(),p.current=null,f.current=!1,mt(),I(g=>g.status==="speaking"||g.status==="answering"?{...g,status:"done"}:g),l.current?.pause(),l.current=null,typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel(),d.current=null,F(!1)},[mt]),gt=D(g=>{const k=Co(g);if(!k)return Promise.resolve(!1);mt();const E=!!(m?.allowVoiceInput&&m?.voiceOutputEnabled&&m.talkbackMode!=="text"),M=(H,Z)=>new Promise(xe=>{let ae=!1;Mo(l,d,H,Z,m?.voiceSpeed??1,k,!0,()=>{ae=!0,F(!0)},()=>{F(!1),xe(ae)})||(F(!1),xe(!1))});return E?e.speak(k).then(H=>H.audioBase64?M(H.audioBase64,H.mimeType):(Sa("Talkback prompt TTS did not return provider audio.",{providerReady:H.providerReady,message:H.message,voiceProvider:m?.voiceProvider,voiceOutputEnabled:m?.voiceOutputEnabled,talkbackMode:m?.talkbackMode}),M())).catch(H=>(Sa("Talkback prompt TTS request failed before audio playback.",{error:H instanceof Error?H.message:String(H),voiceProvider:m?.voiceProvider,voiceOutputEnabled:m?.voiceOutputEnabled,talkbackMode:m?.talkbackMode}),M())):(Sa("Talkback prompt wanted voice, but the loaded widget token config has provider TTS disabled.",{voiceOutputEnabled:m?.voiceOutputEnabled,talkbackMode:m?.talkbackMode,voiceProvider:m?.voiceProvider}),M())},[m?.allowVoiceInput,m?.talkbackMode,m?.voiceOutputEnabled,m?.voiceSpeed,mt,e]),jt=D((g,k,E={})=>{if(N||te||!k)return;me(g,{content:"",pending:!0,streaming:!1,error:!1}),gn("send");const M=P.findIndex(Z=>Z.id===g),H=M>0?P[M-1]:void 0;yt(k,g,{...E,clientMessageId:ce.current[g]??(H?.role==="user"?H.id:void 0)})},[N,te,P,me,yt]),Ot=D((g,k,E)=>{me(g,{feedback:k});const M=P.findIndex(xe=>xe.id===g),H=M>=0?P[M]?.content:void 0;let Z;for(let xe=M-1;xe>=0;xe--)if(P[xe]?.role==="user"){Z=P[xe]?.content;break}e.sendFeedback({sessionId:o.current,messageId:g,rating:k,comment:E,question:Z,answer:H}).catch(()=>{})},[e,me,P]),bt=D(g=>{const k=g.content.trim();if(!k)return;const E=g.id.trim()||lt();O(M=>M.some(H=>H.id===E)?M:[...M,{id:E,role:"assistant",content:k,createdAt:new Date().toISOString()}])},[]),dt=D(async(g,k,E={},M)=>{t.onAction?.(g);const H=g==="public_contact_support"||g==="public_submit_inquiry"?{actionId:g}:{},Z=await e.action(g,{sessionId:o.current,...k,...H},M),xe={};return E.name?.trim()&&(xe.name=E.name.trim()),E.email?.trim()&&(xe.email=E.email.trim()),E.phone?.trim()&&(xe.phone=E.phone.trim()),Object.keys(xe).length>0&&(z(ae=>{const Se={...ae,...xe};return Je(Se),Se}),xe.email&&g!=="contact"&&e.action("contact",{sessionId:o.current,...xe}).catch(()=>{})),bt({id:Z.receipt?.id||lt(),content:Z.receipt?.content||Z.note||(Z.caseReference?`Action completed.
172
+ Reference: ${Z.caseReference}`:"Action completed.")}),gn("receive"),Z},[e,t,Je,bt]),Qe=D(async(g,k,E)=>{const M=await e.confirmHostedBooking?.({sessionId:o.current,inquiryId:g,eventUri:k,inviteeUri:E});return M?.receipt&&bt(M.receipt),M},[e,bt]),Ft=D(g=>{const k=g.trim();k&&O(E=>E.some(M=>M.role==="assistant"&&M.content===k)?E:[...E,{id:lt(),role:"assistant",content:k}])},[]),it=D(()=>{const g=Ro(m?.actions);return g?(O(k=>[...k,{id:lt(),role:"assistant",content:t.strings.reconnectPrompt,actions:[g],selectedAction:g.id,handoffOffered:!0,reconnectOffer:!0,createdAt:new Date().toISOString()}]),!0):!1},[t.strings.reconnectPrompt,m?.actions]),Ut=D(g=>{G.current=!0;const k=lt();return O(E=>[...E,{id:k,role:"user",content:g.trim(),pending:!0}]),k},[]),Wt=D((g,k)=>{O(E=>E.map(M=>M.id===g?{...M,...k}:M))},[]),jn=D(g=>{O(k=>k.filter(E=>E.id!==g))},[]),Wn=D(async(g,k="widget")=>{if(!e.sendExplanationFeedback)throw new Error("Explanation feedback is unavailable.");await e.sendExplanationFeedback({...g,sessionId:o.current,surface:k})},[e]),Gn=D((g="widget")=>{const k=e.fetchExplanation?.bind(e);if(!k)return;const E=e.retryExplanation?.bind(e),M=H=>H;return{poll:async(H,Z)=>M(await k(H,o.current,g,Z)),settled:(H,Z)=>{Z!=="not_requested"&&O(xe=>xe.map(ae=>{const Se=ae.visualization?.explanation?.aiExplanation;return!Se||(Se.explanationId??ae.visualization?.explanation?.explanationId)!==H||Se.status===Z?ae:{...ae,visualization:{...ae.visualization,explanation:{...ae.visualization.explanation,aiExplanation:{...Se,status:Z}}}}}))},...E?{retry:async H=>M(await E(H,o.current,g))}:{}}},[e]),Kn=D((g,k)=>{e.sendFeedback({sessionId:o.current,messageId:"__csat__",rating:g,comment:k}).catch(()=>{})},[e]),Tt=D(async(g,k,E,M)=>{const H=_r();try{if(typeof g!="string"&&e.transcribeAudio)return await e.transcribeAudio(g,k,E,M);const Z=typeof g=="string"?g:await yu(g);return await e.transcribe(Z,k,E,M)}finally{ka("voice-transcription",H)}},[e]),ee=D(async(g,k,E=0)=>{const M=h.current.get(`${g.id}:${E}`)??(k.id?h.current.get(k.id):void 0);if(M)return M;if(!k.id||!e.fetchAttachment)throw new Error("This file is no longer available.");return e.fetchAttachment(k.id,o.current)},[e]),ve=D((g,k,E,M)=>e.uploadAttachment?e.uploadAttachment(g,k,E,o.current,M):Promise.reject(new Error("File upload is unavailable")),[e]),Te=D(g=>e.searchGifs(g),[e]),pe=D((g,k)=>e.demoSlots(g,k),[e]),ye=D(g=>Dt("",{imageUrl:g}),[Dt]),wt=t.demo||!!t.gifApiKey,rn=D(()=>{s.current?.abort(),ue(!0),e.endConversation(o.current).catch(()=>{})},[e]),Yn=D(()=>{s.current?.abort();const g=Bn(t);o.current=g;try{a?.setItem(qn(i),g)}catch{}V(null),oe([]),ue(!1),he("ai"),ke(void 0),Ne(void 0),Ze.current=new Date().toISOString(),O(m?[{id:lt(),role:"assistant",content:m.greeting,availableActions:m.availableActions,actions:m.actions}]:[])},[a,i,m]),Gt=D(g=>{if(Q){if(g===o.current){V(null);return}oe(Eo(a,i,g)),V(g)}},[a,i,Q]),Ct=D(()=>{V(null),oe([])},[]),Mt=t.starters.length>0?t.starters:m?.starterQuestions??[],kt=m?.featuredLinks??[];return{persona:m,messages:P,sending:N,assistantSpeaking:q,voiceReply:C,visitor:le,starters:Mt,featuredLinks:kt,hasEmail:!!le.email,liveMode:_e,assignedAgentName:Ge,agentTypingName:K,send:Dt,amend:Hn,hold:an,resumeHeld:rt,duckSpeaking:bn,sendGif:ye,notifyTyping:pt,stop:Pt,retry:jt,rateMessage:Ot,rateExplanation:Wn,explanationTransport:Gn,injectAssistant:Ft,reconnectSupport:it,appendUserDraft:Ut,patchMessage:Wt,removeMessage:jn,submitCsat:Kn,submitForm:dt,confirmHostedBooking:Qe,transcribe:Tt,uploadAttachment:ve,loadAttachment:ee,searchGifs:Te,demoSlots:pe,gifEnabled:wt,identify:tt,ended:te,endConversation:rn,startNew:Yn,history:Q?ne:[],viewingSessionId:y,viewMessages:we,openConversation:Gt,closeHistoryView:Ct,shutdown:et,stopSpeaking:Ht,speakAssistantText:gt}},Yu=({name:e,greeting:t})=>{const n=ct();return r("section",{class:"cf-empty-welcome","aria-label":Ve(n.welcomeLabel,{name:e}),children:[r("span",{class:"cf-empty-welcome__eyebrow",children:n.welcomeEyebrow}),r("h2",{children:e}),r("p",{children:t||n.welcomePrompt})]})},Cr=(e,t,n)=>{if(e.key==="Escape"){e.preventDefault(),e.stopPropagation(),n();return}if(e.key!=="Tab")return;const a=Array.from(t.querySelectorAll('button, [href], textarea, input, select, [tabindex]:not([tabindex="-1"])')).filter(l=>!l.hasAttribute("disabled")&&l.getAttribute("aria-hidden")!=="true"&&l.tabIndex>=0);if(a.length===0)return;const i=t.getRootNode(),o=e.composedPath()[0],s=o instanceof HTMLElement?o:"activeElement"in i?i.activeElement:document.activeElement,c=a[0],u=a[a.length-1];e.shiftKey&&(s===c||!t.contains(s))?(e.preventDefault(),e.stopPropagation(),u.focus()):!e.shiftKey&&(s===u||!t.contains(s))&&(e.preventDefault(),e.stopPropagation(),c.focus())},Ca=new Map,Lo=e=>{if(!e||typeof document>"u"||typeof CanvasRenderingContext2D>"u")return;const t=document.createElement("canvas").getContext("2d");if(!t)return;t.fillStyle="#010203",t.fillStyle=e;const n=t.fillStyle;if(n==="#010203"&&e.trim().toLowerCase()!=="#010203")return;const a=n.match(/^#([\da-f]{6})$/i)?.[1];if(a)return[Number.parseInt(a.slice(0,2),16),Number.parseInt(a.slice(2,4),16),Number.parseInt(a.slice(4,6),16),1];const i=n.match(/^rgba?\(([\d.]+)[, ]+([\d.]+)[, ]+([\d.]+)(?:[, /]+([\d.]+))?\)$/i);if(!i)return;const o=i.slice(1,5).map(Number);if(!o.some(s=>!Number.isFinite(s)))return[o[0],o[1],o[2],o[3]??1]},Zu=(e,t="#ffffff")=>{const n=`${e??""}|${t}`;if(Ca.has(n))return Ca.get(n);const a=Lo(e),i=Lo(t)??[255,255,255,1];if(!a){Ca.set(n,void 0);return}const o=a[3],c=a.slice(0,3).map((h,f)=>h*o+i[f]*(1-o)).map(h=>{const f=h/255;return f<=.04045?f/12.92:((f+.055)/1.055)**2.4}),u=c[0]*.2126+c[1]*.7152+c[2]*.0722,l=1.05/(u+.05),d=(u+.05)/.059,p=l>=d?"#ffffff":"#0f1e2a";return Ca.set(n,p),p},Ju=e=>{const[t,n]=S("light");return X(()=>{if(e!=="auto"||typeof matchMedia>"u")return;const a=matchMedia("(prefers-color-scheme: dark)"),i=()=>n(a.matches?"dark":"light");return i(),a.addEventListener("change",i),()=>a.removeEventListener("change",i)},[e]),e==="auto"?t:e},Xu=6e4,Qu=90,Do={end:"end the call",mute:"mute your microphone",minimize:"minimize the chat",expand:"expand the view",shrink:"exit the expanded view"},Po=e=>e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s']/gu," ").replace(/\s+/g," ").trim(),ep=[{action:"shrink",re:/\b(?:exit|leave|quit|close)\b[\s\w]*\b(?:full ?screen|expanded|theat(?:er|re))\b|\bshrink\b|\bsmaller view\b/},{action:"end",re:/\b(?:end|close|stop|finish|hang ?up|quit|exit)\b[\s\w]*\b(?:call|chat|conversation|convo|session|talking)\b|\bhang ?up\b|\bgood ?bye\b|^bye(?: bye)?$/},{action:"mute",re:/\bmute\b|\bstop listening\b/},{action:"minimize",re:/\bminimi[sz]e\b|\bhide\b[\s\w]*\b(?:chat|call|window|widget)\b/},{action:"expand",re:/\bexpand\b|\bmaximi[sz]e\b|\bfull ?screen\b|\btheat(?:er|re) mode\b|\bbigger view\b/}],tp=/^(?:yes|yeah|yep|yup|sure|correct|confirm|affirmative|go ahead|do it|please do|ok(?:ay)?)\b/,np=/^(?:no|nope|nah|cancel|never ?mind|don'?t|stop)\b/,ap=/^(?:end|close|stop|finish|hang ?up|quit|exit|bye|good ?bye)\b/,rp=e=>{const t=Po(e);if(!t)return null;for(const{action:n,re:a}of ep)if(a.test(t)){const i=t.split(" ").length;return{action:n,confident:n==="end"?i<=10:i<=6}}return null},ip=e=>`I didn't catch yes or no. Say yes to ${Do[e]}, or no to keep talking.`,op=({transport:e,config:t,bindControls:n,composerDraftStore:a})=>{const i=t.strings,[o,s]=S(t.openByDefault),{persona:c,messages:u,sending:l,assistantSpeaking:d,visitor:p,hasEmail:h,liveMode:f,assignedAgentName:_,agentTypingName:x,starters:w,featuredLinks:v,send:m,sendGif:T,notifyTyping:P,stop:O,amend:re,hold:J,resumeHeld:G,duckSpeaking:N,retry:se,rateMessage:q,rateExplanation:F,explanationTransport:C,injectAssistant:I,reconnectSupport:ce,appendUserDraft:te,patchMessage:ue,removeMessage:le,submitCsat:z,submitForm:ne,confirmHostedBooking:He,transcribe:y,uploadAttachment:V,loadAttachment:we,searchGifs:oe,demoSlots:_e,gifEnabled:he,identify:Ge,ended:ke,endConversation:K,startNew:Ne,history:Ze,viewingSessionId:$,viewMessages:j,openConversation:U,closeHistoryView:Y,shutdown:Q,stopSpeaking:$e,speakAssistantText:Me}=Ku(e,t,o),et=Gu(u,f),[Je,tt]=S(null),at=R(0),A=D((b,L,fe)=>{fe===at.current&&tt({status:"ready",name:L,url:URL.createObjectURL(b),mimeType:b.type||"application/octet-stream"})},[]),ge=D((b,L,fe)=>{const Ee=L.name,Le=++at.current;tt({status:"loading",name:Ee}),we(b,L,fe).then(vt=>A(vt,Ee,Le),()=>{Le===at.current&&tt({status:"error",name:Ee})})},[we,A]),me=D((b,L)=>A(b,L,++at.current),[A]),be=D(()=>{at.current+=1,tt(null)},[]);X(()=>()=>{Je?.status==="ready"&&URL.revokeObjectURL(Je.url)},[Je]);const Ue=!!Ro(c?.actions),[Ke,mt]=S(0),[pt,yt]=S({mic:"off",processing:!1}),[Dt,_t]=S(null),[Hn,an]=S(!1),[rt,Pt]=S(!1),[bn,Ht]=S(!1),[gt,jt]=S(!1),[Ot,bt]=S(0),[dt,Qe]=S(!1),[Ft,it]=S(null),[Ut,Wt]=S(null),[jn,Wn]=S([]),[Gn,Kn]=S(""),[Tt,ee]=S(()=>{try{return localStorage.getItem("centrinfo:muted")==="1"}catch{return!1}}),ve=Ju(t.theme),Te=c?.soundEnabled??!0;X(()=>{gu(t.sound&&Te&&!Tt)},[t.sound,Te,Tt]);const pe=D(()=>{ee(b=>{const L=!b;try{localStorage.setItem("centrinfo:muted",L?"1":"0")}catch{}return L})},[]),ye=R(null),wt=R(null),rn=R(null),Yn=R(0),Gt=R(!1),Ct=R(!1),Mt=R(null),kt=R(0),g=R(void 0),k=R(0),E=R(null),M=R(!1),H=R(null),Z=R(""),xe=R(()=>{}),ae=R(""),Se=R(l),ie=R(m);ie.current=m;const ot=R(re);ot.current=re;const Be=R(y);Be.current=y;const je=R(!1),Xe=R(!1),nt=R("");nt.current=[...u].reverse().find(b=>b.role==="assistant")?.content??"";const ft=R(d);Se.current=l,ft.current=d;const Oe=rt?Hn?"timeout":gt||pt.mic==="muted"?"muted":pt.mic==="unavailable"?pt.reason==="permission-denied"||pt.reason==="unsupported"?"denied":"unavailable":pt.mic==="off"||pt.mic==="starting"?"connecting":pt.mic==="hearing"?"hearing":d?"speaking":Dt??(pt.processing||l?"processing":"listening"):"idle",[At,W]=S(!0),[Ie,ze]=S(!1),Ce=R(0),[Ye,Bt]=S(!1),[It,on]=S(!1),Ho=R(null),[Kt,sn]=S(!1),xp=R({value:""}),yp=a??xp.current,jo=R({confirmEnd:Ye,confirmClear:It,showHistory:Kt});jo.current={confirmEnd:Ye,confirmClear:It,showHistory:Kt};const[_p,Wo]=S(!1),Re=!!$,Ma=Re?j:u,Zn=Ma.find(b=>b.id===Ft&&b.visualization)?.visualization,Jn=Ma.find(b=>b.id===Ut&&b.visualization);X(()=>{!Ut||Jn||(Wt(null),Qe(!1))},[Ut,Jn]),X(()=>{!Ft||Zn||(it(null),Qe(!1))},[Zn,Ft]);const vn=D(()=>{s(!0),mt(0),gn("open"),t.onOpen?.(),t.onShow?.()},[t]),Et=D(()=>{s(!1),Qe(!1),it(null),t.onClose?.(),t.onHide?.(),wt.current?.focus()},[t]),Xn=D(()=>o?Et():vn(),[o,vn,Et]),wp=D(()=>Bt(!0),[]),kp=D(()=>{K(),Bt(!1)},[K]),Sp=D(()=>{Ne(),ze(!1),W(!0)},[Ne]);X(()=>{Ye&&Ho.current?.focus()},[Ye]),X(()=>{n({open:vn,close:Et,toggle:Xn,identify:Ge,startNew:Ne,endConversation:K,shutdown:Q})},[n,vn,Et,Xn,Ge,Ne,K,Q]),X(()=>{const b=u.filter(L=>L.role==="assistant"&&!L.pending).length;if(o){Yn.current=b;return}b>Yn.current&&mt(b-Yn.current)},[u,o]),X(()=>{t.onUnreadChange?.(Ke)},[Ke,t]),X(()=>{const b=t.sessionDurationMinutes;if(!b||b<=0)return;const L=setTimeout(()=>Q(),b*60*1e3);return()=>clearTimeout(L)},[t.sessionDurationMinutes,u,o,Q]),X(()=>{const b=t.customLauncherSelector;if(!b||typeof document>"u")return;let L=[];try{L=Array.from(document.querySelectorAll(b))}catch{return}const fe=Ee=>{Ee.preventDefault(),Xn()};return L.forEach(Ee=>Ee.addEventListener("click",fe)),()=>L.forEach(Ee=>Ee.removeEventListener("click",fe))},[t.customLauncherSelector,Xn]);const Go=R(!1);X(()=>{const b=t.proactiveMessage?.trim();if(!b||Go.current)return;const L=t.proactiveOnPaths??[],fe=typeof location<"u"?location.pathname:"";if(L.length>0&&!L.some(vt=>fe.includes(vt)))return;const Ee=`centrinfo:proactive:${t.token.slice(0,12)}`;try{if(sessionStorage.getItem(Ee)==="1")return}catch{}const Le=setTimeout(()=>{if(!(o||ke||u.some(vt=>vt.role==="user"))){Go.current=!0;try{sessionStorage.setItem(Ee,"1")}catch{}I(b),vn()}},Math.max(0,t.proactiveDelaySeconds)*1e3);return()=>clearTimeout(Le)},[t.proactiveMessage]),X(()=>{const b=rn.current;if(!o||!b)return;const L=u[u.length-1],fe=Date.now()<Ce.current;L?.role==="user"||At||fe?(requestAnimationFrame(()=>{b.scrollTop=b.scrollHeight}),ze(!1),fe&&W(!0)):ze(!0)},[u,o,l,At]);const Ko=R(!0);Ko.current=At,X(()=>{const b=rn.current;if(!(!o||!b))return kc(b,{isAtBottom:()=>Ko.current,onUnseen:()=>ze(!0)})},[o,Re]);const $p=D(()=>{const b=rn.current;if(!b)return;if(Gt.current&&!Re){W(!0),ze(!1);return}const L=b.scrollHeight-b.scrollTop-b.clientHeight<80;W(L),L&&ze(!1)},[Re]),Yt=D(()=>{const b=rn.current;b&&(b.scrollTop=b.scrollHeight),ze(!1),W(!0)},[]),Aa=D(()=>{Ce.current=Date.now()+3e3,requestAnimationFrame(Yt)},[Yt]);X(()=>{if(!o||Re||!rt||Oe==="connecting")return;Ce.current=Date.now()+6e4,Yt();const b=requestAnimationFrame(()=>{Yt(),requestAnimationFrame(Yt)}),L=[80,180,360].map(fe=>window.setTimeout(Yt,fe));return()=>{cancelAnimationFrame(b),L.forEach(fe=>window.clearTimeout(fe))}},[d,u,o,Yt,l,rt,Re,Oe]);const Yo=D(()=>{ye.current?.querySelector(".cf-textarea")?.focus()},[]),Qn=D((b,L)=>{_t(b),g.current&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>_t(null),3e3),L&&!Ct.current&&Me(L)},[Me]),Ia=D(b=>{const L=H.current;if(L)return L;Aa();const fe=te(b);return H.current=fe,ue(fe,{content:Z.current||b,pending:!0,streaming:!1}),fe},[te,Aa,ue]),qt=D(()=>{const b=H.current;if(b){if(Z.current){ue(b,{content:Z.current,pending:!0});return}H.current=null,le(b)}},[ue,le]),Zt=D(()=>{Xe.current&&(Xe.current=!1,N(!1)),je.current&&(je.current=!1,G())},[N,G]),ut=D(()=>{Gt.current=!1,Mt.current?.stop("call-ended"),Mt.current=null,je.current=!1,Xe.current=!1,Ct.current=!1,E.current=null,M.current=!1;const b=H.current;H.current=null,Z.current="",b&&le(b),g.current&&window.clearTimeout(g.current),_t(null),an(!1),yt({mic:"off",processing:!1}),bt(0),Pt(!1),Ht(!1),jt(!1),Qe(!1),it(null),$e()},[le,$e]),Tp=D(()=>{dt&&it(null),Qe(!dt)},[dt]),Cp=D(b=>{it(b),Qe(!0)},[]),Mp=D(b=>{Wt(b),Qe(!0)},[]),Ea=D(()=>{const b=Ft,L=Ut;it(null),Wt(null),Qe(!1),window.requestAnimationFrame(()=>{(L?ye.current?.querySelector(`[data-explanation-message="${L}"]`)?.querySelector('[data-testid="analytics-explanation-expand"]'):Array.from(ye.current?.querySelectorAll("[data-visualization-message]")??[]).find(Ee=>Ee.dataset.visualizationMessage===b))?.focus()})},[Ft,Ut]),Ap=D(()=>{it(null),Wt(null),Qe(!1)},[]),Zo=D((b,L,fe=!1)=>{if(Aa(),L&&(ue(L,{content:b,pending:!1,streaming:!1}),H.current===L&&(H.current=null)),Z.current="",fe){$e(),ot.current(b,{forceVoicePlayback:!0,userMessageId:L});return}Gt.current&&(J()?ot.current(b,{forceVoicePlayback:!0,userMessageId:L}):ie.current(b,{forceVoicePlayback:!0,userMessageId:L}))},[Aa,J,ue,$e]),zt=D(b=>{I(b),Me(b)},[I,Me]),Jo=D(()=>{if(kt.current=Date.now(),_t(null),ft.current){Xe.current=!0,N(!0);return}je.current||(je.current=J()),Ia("Listening...")},[N,Ia,J]),Xo=D(b=>{const L=H.current;if(!L||Xe.current)return;const fe=[Z.current,b].filter(Boolean).join(" ");ue(L,{content:`${fe} ...`,pending:!0})},[ue]),Qo=D(b=>{kt.current=Date.now();const L=[Z.current,b.text].map(Nt=>Nt.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if((Xe.current||b.overlappedOutput)&&Vc(b.text,nt.current)){qt(),Zt();return}if(!L||hu(L)||mu(L)){const Nt=Xe.current||je.current;qt(),Zt(),Nt||Qn("misunderstood");return}Xe.current&&(Xe.current=!1,O(),$e());const Ee=E.current;if(Ee){Z.current="",qt();const Nt=Po(L);if(tp.test(Nt)||Ee==="end"&&ap.test(Nt)){E.current=null,xe.current(Ee);return}if(np.test(Nt)){E.current=null,zt("Okay, never mind — what would you like to know?");return}zt(ip(Ee));return}const Le=rp(L);if(Le){if(Z.current="",qt(),Zt(),Le.confident){xe.current(Le.action);return}E.current=Le.action,zt(`Just to confirm — you want me to ${Do[Le.action]}? Please say yes or no.`);return}const vt=Ia(L);ue(vt,{content:L,pending:!0});const xn=je.current;je.current=!1,Zo(L,vt,xn)},[Ia,ue,Zt,Zo,qt,Qn,zt,O,$e]),es=D(b=>{kt.current=Date.now();const L=Xe.current||je.current;if(qt(),Zt(),!(L||b.overlappedOutput||b.reason==="too-short")){if(b.reason==="transcribe-failed"){Qn("misunderstood","I couldn't transcribe that. Please try again, or type your question.");return}Qn("noise")}},[Zt,qt,Qn]),ea=R({speechStart:Jo,partial:Xo,turn:Qo,noise:es});ea.current={speechStart:Jo,partial:Xo,turn:Qo,noise:es};const ts=D(()=>{navigator.mediaDevices?.enumerateDevices().then(b=>{Wn(b.filter(L=>L.kind==="audioinput").map((L,fe)=>({deviceId:L.deviceId,label:L.label||`Microphone ${fe+1}`})))}).catch(()=>{})},[]),Ip=D(()=>{if(Gt.current){ut();return}if(Yo(),!c?.allowVoiceInput||!c.talkbackMode||c.talkbackMode==="text"||Se.current||ke||Re)return;kt.current=Date.now(),Ct.current=!1,Gt.current=!0,jt(!1),Pt(!0),Ht(!1),an(!1);let b=!1;const L=new Hi({deviceId:ae.current||void 0,transcribe:async({audio:fe,mimeType:Ee,durationSeconds:Le})=>{const vt=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||void 0;return pu(await Be.current(fe,Ee,vt,Le))},listener:{state:fe=>{yt(fe),fe.mic!=="starting"&&fe.mic!=="off"&&Ht(!0),!b&&fe.mic==="listening"&&(b=!0,ts())},speechStart:()=>ea.current.speechStart(),partial:({text:fe})=>ea.current.partial(fe),turn:fe=>ea.current.turn(fe),noise:fe=>ea.current.noise(fe),level:fe=>{const Ee=performance.now();Ee-k.current<Qu||(k.current=Ee,bt(fe))}}});Mt.current=L,L.setOutputActive(ft.current),L.start()},[ut,ke,Yo,c,ts,Re]),za=D(()=>{const b=!Ct.current;Ct.current=b,jt(b),Mt.current?.setMuted(b),b?(Z.current="",qt(),Zt()):kt.current=Date.now()},[Zt,qt]),ns=D(b=>{switch(kt.current=Date.now(),b){case"end":M.current=!0,zt("Okay — ending our call now. Goodbye!"),window.setTimeout(()=>{M.current&&(M.current=!1,ut())},2e3);break;case"mute":{Ct.current||za(),zt("Muted. Tap the mic button when you want me to listen again.");break}case"minimize":Et(),zt("Minimized — I'm still listening. Tap the call pill to bring the chat back.");break;case"expand":Qe(!0),zt("Sure — expanding the view.");break;case"shrink":it(null),Qe(!1),zt("Okay — back to the smaller view.");break}},[Et,ut,zt,za]);X(()=>{xe.current=ns},[ns]);const as=R(!1);X(()=>{as.current&&!d&&M.current&&(M.current=!1,ut()),as.current=d},[d,ut]);const Ep=D(b=>{ae.current=b,Kn(b),Mt.current?.selectDevice(b||void 0)},[]),zp=D(()=>{!Gt.current||Ct.current||(Xe.current=!1,je.current=!1,O(),$e(),kt.current=Date.now())},[O,$e]);X(()=>{Mt.current?.setOutputActive(d),kt.current=Date.now()},[d]),X(()=>{if(Oe!=="denied")return;const b=window.setTimeout(()=>ut(),3500);return()=>window.clearTimeout(b)},[ut,Oe]),X(()=>{if(!rt)return;const b=window.setInterval(()=>{const L=Mt.current;!L||Ct.current||Se.current||ft.current||L.snapshot.mic==="hearing"||L.snapshot.processing||Date.now()-kt.current<Xu||(Mt.current?.log.add("call-timeout"),an(!0),window.setTimeout(()=>ut(),2400))},5e3);return()=>window.clearInterval(b)},[ut,rt]);const Np=rt&&!gt&&(l||d);X(()=>()=>ut(),[ut]);const[Rp,Lp]=S(""),rs=R(!1);X(()=>{if(rs.current&&!l){const b=[...u].reverse().find(L=>L.role==="assistant"&&!L.streaming&&!L.pending&&L.content);b&&Lp(b.content)}rs.current=l},[l,u]),Sn(()=>{if(!o)return;const b=ye.current,L=Ye||It?b?.querySelector(".cf-confirm__card"):Kt?b?.querySelector(".cf-history"):null;if(!L)return;const fe=L.getRootNode(),Ee="activeElement"in fe?fe.activeElement:document.activeElement;(!Ee||!L.contains(Ee))&&L.querySelector('button, [href], textarea, input, [tabindex]:not([tabindex="-1"])')?.focus()},[It,Ye,o,Kt]),X(()=>{if(!o)return;const b=ye.current,L=Ye||It?b?.querySelector(".cf-confirm__card"):Kt?b?.querySelector(".cf-history"):null,fe=b?.querySelectorAll(":scope > .cf-header, :scope > .cf-panel__video, :scope > .cf-panel__chat");fe?.forEach(Le=>{L?(Le.setAttribute("inert",""),Le.setAttribute("aria-hidden","true")):(Le.removeAttribute("inert"),Le.removeAttribute("aria-hidden"))}),L||requestAnimationFrame(()=>b?.querySelector(".cf-textarea")?.focus());const Ee=Le=>{if(Le.key==="Escape"){Le.preventDefault();const na=jo.current;if(na.confirmEnd){Bt(!1);return}if(na.confirmClear){on(!1);return}if(na.showHistory){sn(!1);return}if(b?.querySelector(".cf-action-drawer"))return;Et();return}if(Le.key!=="Tab"||!L)return;const vt=L.querySelectorAll('button, [href], textarea, input, [tabindex]:not([tabindex="-1"])'),xn=Array.from(vt).filter(na=>!na.hasAttribute("disabled"));if(xn.length===0)return;const Nt=xn[0],cs=xn[xn.length-1],ls=L.getRootNode()instanceof ShadowRoot?L.getRootNode().activeElement:document.activeElement;Le.shiftKey&&ls===Nt?(Le.preventDefault(),cs.focus()):!Le.shiftKey&&ls===cs&&(Le.preventDefault(),Nt.focus())};return b?.addEventListener("keydown",Ee),()=>{b?.removeEventListener("keydown",Ee),fe?.forEach(Le=>{Le.removeAttribute("inert"),Le.removeAttribute("aria-hidden")})}},[o,Et,Ye,It,Kt]),X(()=>{const b=ye.current;b&&(o?b.removeAttribute("inert"):b.setAttribute("inert",""))},[o]);const Na=t.accentColor??t.themeTokens?.accent??c?.accentColor,is=t.themeTokens?.accentText??Zu(Na,t.themeTokens?.background??(ve==="dark"?"#0f1c27":"#ffffff")),Dp={zIndex:t.zIndex,"--cf-h-pad":`${t.horizontalPadding}px`,"--cf-v-pad":`${t.verticalPadding}px`,...is?{"--cf-accent-ink":is}:{},...t.themeTokens?.accentStrong?{"--cf-accent-2":t.themeTokens.accentStrong}:{},...t.themeTokens?.background?{"--cf-bg":t.themeTokens.background}:{},...t.themeTokens?.surface?{"--cf-surface":t.themeTokens.surface}:{},...t.themeTokens?.surfaceMuted?{"--cf-surface-2":t.themeTokens.surfaceMuted}:{},...t.themeTokens?.text?{"--cf-text":t.themeTokens.text}:{},...t.themeTokens?.mutedText?{"--cf-muted":t.themeTokens.mutedText}:{},...t.themeTokens?.border?{"--cf-border":t.themeTokens.border}:{},...t.themeTokens?.shadow?{"--cf-shadow":t.themeTokens.shadow}:{},...t.themeTokens?.radius?{"--cf-radius":t.themeTokens.radius}:{},...t.themeTokens?.fontFamily?{"--cf-font":t.themeTokens.fontFamily}:{},...t.themeTokens?.success?{"--cf-success":t.themeTokens.success}:{},...t.themeTokens?.warning?{"--cf-warning":t.themeTokens.warning}:{},...t.themeTokens?.danger?{"--cf-danger":t.themeTokens.danger}:{},...Na?{"--cf-accent":Na,"--cf-accent-2":t.themeTokens?.accentStrong??`color-mix(in oklab, ${Na} 76%, #14141f)`}:{}},Pp=b=>m(b),Op=[...u].reverse().find(b=>b.role==="user"&&b.content.trim())?.content??"",Ra=u.some(b=>b.role==="user"),os=!!(c?.allowVoiceInput&&c?.talkbackMode&&c.talkbackMode!=="text"),ss=os,ta=!Re&&ss&&!Ra?Ma.filter((b,L)=>!(L===0&&b.role==="assistant")):Ma,Fp=f==="human"&&_?_:c?.agentName??i.chatName,Up=f==="human"?i.liveSupport:f==="queued"?i.waitingForTeam:c?.offline?i.statusOffline:i.statusOnline,Ar=!ke&&!Re?c?.availableActions:void 0,Bp=!ke&&!Re?c?.actions:void 0,Ir=rt&&!bn&&Oe==="connecting"&&!Re;return r(Yl,{value:i,children:r(Zl,{value:t.locale,children:r("div",{class:"cf-root",dir:t.dir,"data-theme":ve,"data-align":t.alignment,"data-display":"floating",style:Dp,children:[dt&&o&&r("div",{class:"cf-theater-backdrop",onClick:Ap}),r("div",{ref:ye,class:`cf-panel ${o?"is-open":""} ${rt?"cf-panel--call":""} ${Ir?"cf-panel--voice-connecting":""} ${dt&&o?"cf-panel--theater":""} ${Zn||Jn?"cf-panel--analytics-focus":""}`,role:"dialog","aria-modal":"false","aria-label":`${i.chatName}: ${c?.agentName??i.assistantName}`,"aria-hidden":!o,children:[Je&&o&&r(xu,{state:Je,onClose:be}),r("div",{class:"cf-header",children:[r(mo,{persona:c,hideWhenMissing:!0}),r("div",{class:"cf-header__meta",children:[r("div",{class:"cf-header__name",children:Fp}),r("div",{class:`cf-header__status ${f==="ai"&&c?.offline?"cf-header__status--offline":""}`,children:r("span",{class:"cf-header__status-text",children:Up})})]}),r("div",{class:"cf-header__actions",children:[Ze.length>0&&r("button",{type:"button",class:"cf-header__btn","aria-label":i.pastConversations,title:i.pastConversations,"aria-pressed":Kt,onClick:()=>sn(b=>!b),children:r(bd,{})}),Ra&&!ke&&!Re&&r("button",{type:"button",class:"cf-header__btn","aria-label":i.endChat,title:i.endChat,onClick:wp,children:r(vr,{})}),t.sound&&Te&&r("button",{type:"button",class:"cf-header__btn","aria-label":Tt?i.unmuteSounds:i.muteSounds,"aria-pressed":Tt,onClick:pe,children:Tt?r(fd,{}):r(pd,{})}),r("button",{type:"button",class:"cf-header__btn cf-header__close","aria-label":i.closeChat,onClick:Et,children:r(pn,{})})]})]}),r("div",{class:"cf-panel__video",children:Zn?r("div",{class:"cf-analytics-focus",role:"region","aria-label":i.expandedAnalyticsResult,children:r(wo,{visualization:Zn,expanded:!0,onFollowUp:b=>{Ea(),m(b)},onClose:Ea})}):Jn?.visualization?r("div",{class:"cf-analytics-focus",role:"region","aria-label":i.expandedAnalyticsResult,children:r(eu,{visualization:Jn.visualization,onClose:Ea,onFollowUp:b=>{Ea(),m(b)},onFeedback:Re?void 0:F,transport:Re?void 0:C("widget"),onOpenSource:t.onOpenAnalyticsSource})}):!Re&&ss?r(Nd,{persona:c,starters:[],onPick:m,onFocusComposer:Ip,speaking:d,voiceState:Oe,replyPending:rt&&l&&!d,pinned:!0,muted:gt,onToggleMute:za,onEndCall:ut,onTalkNow:zp,showTalkNow:Np,micLevel:Ot,theaterMode:dt,onToggleTheater:Tp,onMinimize:Et,audioDevices:jn,selectedAudioDeviceId:Gn,onSelectAudioDevice:Ep,connectingOnly:Ir}):null}),!Ir&&r("div",{class:"cf-panel__chat",children:[t.preview&&r("div",{class:"cf-preview-banner",children:i.previewBanner}),Re&&r("div",{class:"cf-viewing-banner",children:i.viewingPast}),r("div",{class:"cf-body",ref:rn,role:"log",onScroll:$p,children:[ta.map((b,L)=>r(Qd,{msg:b,persona:c,isLast:!Re&&L===ta.length-1,visitor:p,hasEmail:h,lastQuestion:Op,showActions:!Re&&L===ta.length-1&&!!(b.handoffOffered||b.selectedAction),onPickReply:Pp,onSubmitForm:ne,onDemoSlots:_e,onConfirmHostedBooking:He,onRetry:se,ratable:!Re&&ta.slice(0,L).some(fe=>fe.role==="user"),onRate:q,onExplanationFeedback:Re?void 0:F,explanationTransport:Re?void 0:C("widget"),onOpenAnalyticsSource:t.onOpenAnalyticsSource,onExpandVisualization:Re?void 0:Cp,onExpandExplanation:Re?void 0:Mp,onOpenAttachment:ge,onReconnect:!Re&&!ke&&Ue&&b.id===et?ce:void 0},b.id)),!Ra&&!Re&&r(de,{children:[ta.length===0&&r(Yu,{name:c?.agentName??i.assistantName,greeting:c?.greeting}),r(Zd,{items:w,onPick:m}),r(Jd,{items:v})]}),Ie&&r("button",{type:"button",class:"cf-newmsg",onClick:Yt,children:[r(wd,{}),i.newMessages]})]}),r("div",{class:"cf-sr-live","aria-live":"polite","aria-atomic":"true",children:Rp}),l&&!ke&&!Re&&r("div",{class:"cf-stopbar",children:r("button",{type:"button",class:"cf-stop",onClick:O,children:[r(gd,{}),i.stop]})}),Re?r("div",{class:"cf-ended",children:r("button",{type:"button",class:"cf-ended__btn",onClick:Y,children:i.backToChat})}):ke?r("div",{class:"cf-ended",children:[r("p",{class:"cf-ended__text",children:i.conversationEnded}),t.csat&&Ra?_p?r("p",{class:"cf-ended__text",children:i.feedbackThanks}):r("div",{class:"cf-csat",children:[r("span",{class:"cf-csat__q",children:i.csatPrompt}),r("button",{type:"button",class:"cf-csat__btn","aria-label":i.feedbackHelpful,onClick:()=>{z("up"),Wo(!0)},children:r(lo,{})}),r("button",{type:"button",class:"cf-csat__btn","aria-label":i.feedbackNotHelpful,onClick:()=>{z("down"),Wo(!0)},children:r(uo,{})})]}):null,r("button",{type:"button",class:"cf-ended__btn",onClick:Sp,children:i.startNewChat})]}):r(de,{children:[x?r("div",{class:"cf-live-typing","aria-live":"polite",children:Ve(i.agentTyping,{name:x})}):null,Ar&&Ar.length>0&&r("div",{class:"cf-footer-actions",children:r(yo,{actions:Ar,descriptors:Bp,visitor:p,onSubmitForm:ne,onDemoSlots:_e,onConfirmHostedBooking:He,scheduler:c?.scheduler,translations:t.actionTranslations})},"footer-actions"),r(uu,{draftStore:yp,onSend:m,onSendGif:T,onTyping:P,disabled:l,allowVoice:os,onTranscribe:y,gifEnabled:he,onSearchGifs:oe,allowAttach:t.attachments,analyzeAttachments:!0,onUpload:V,onPreviewAttachment:me},"composer")]}),!ke&&c?.disclaimerText&&r("div",{class:"cf-disclaimer",children:c.disclaimerText}),r("div",{class:"cf-footer",children:[r("button",{type:"button",class:"cf-footer__privacy","aria-label":i.clearDeviceData,onClick:()=>on(!0),children:i.privacyAndData}),r("span",{"aria-hidden":"true",children:"·"}),i.poweredBy," ",r("a",{href:"https://accurix.tech/centrinfo",target:"_blank",rel:"noopener noreferrer",children:"Centrinfo"})]})]}),Ye&&r("div",{class:"cf-confirm",onClick:()=>Bt(!1),children:r("div",{class:"cf-confirm__card",role:"alertdialog","aria-modal":"true","aria-label":i.endChatConfirm,onClick:b=>b.stopPropagation(),onKeyDownCapture:b=>Cr(b,b.currentTarget,()=>Bt(!1)),children:[r("div",{class:"cf-confirm__title",children:i.endChatConfirm}),r("div",{class:"cf-confirm__body",children:i.endChatConfirmBody}),r("div",{class:"cf-confirm__actions",children:[r("button",{ref:Ho,type:"button",class:"cf-confirm__btn cf-confirm__btn--cancel",onClick:()=>Bt(!1),children:i.cancel}),r("button",{type:"button",class:"cf-confirm__btn cf-confirm__btn--danger",onClick:kp,children:i.endConfirmCta})]})]})},"confirm-end"),Kt&&r("div",{class:"cf-confirm",onClick:()=>sn(!1),children:r("div",{class:"cf-history",role:"dialog","aria-modal":"true","aria-label":i.pastConversations,onClick:b=>b.stopPropagation(),onKeyDownCapture:b=>Cr(b,b.currentTarget,()=>sn(!1)),children:[r("div",{class:"cf-history__head",children:[r("span",{children:i.pastConversations}),r("button",{type:"button",class:"cf-header__btn","aria-label":i.closeHistory,onClick:()=>sn(!1),children:r(pn,{})})]}),r("div",{class:"cf-history__list",children:Ze.map(b=>r("button",{type:"button",class:`cf-history__item ${b.sessionId===$?"is-active":""}`,onClick:()=>{U(b.sessionId),sn(!1)},children:[r("span",{class:"cf-history__title",children:b.title}),r("span",{class:"cf-history__meta",children:[new Date(b.ts).toLocaleDateString(void 0,{month:"short",day:"numeric"}),b.ended?` · ${i.historyEnded}`:""]})]},b.sessionId))}),r("div",{class:"cf-history__footer",children:r("button",{type:"button",class:"cf-history__clear",onClick:()=>{sn(!1),on(!0)},children:i.clearDeviceData})})]})},"history"),It&&r("div",{class:"cf-confirm",onClick:()=>on(!1),children:r("div",{class:"cf-confirm__card",role:"alertdialog","aria-modal":"true","aria-label":i.clearDeviceData,onClick:b=>b.stopPropagation(),onKeyDownCapture:b=>Cr(b,b.currentTarget,()=>on(!1)),children:[r("div",{class:"cf-confirm__title",children:i.clearDeviceData}),r("div",{class:"cf-confirm__body",children:i.clearDeviceDataBody}),r("div",{class:"cf-confirm__actions",children:[r("button",{type:"button",class:"cf-confirm__btn cf-confirm__btn--cancel",onClick:()=>on(!1),children:i.cancel}),r("button",{type:"button",class:"cf-confirm__btn cf-confirm__btn--danger",onClick:()=>{on(!1),Q()},children:i.clearDeviceDataCta})]})]})},"confirm-clear")]}),rt&&!o?r(lu,{persona:c,voiceState:Oe,muted:gt,onToggleMute:za,onEndCall:ut,micLevel:Ot,onExpand:vn}):dt&&o?null:!t.hideDefaultLauncher&&r("button",{ref:wt,type:"button",class:"cf-launcher","aria-label":o?i.closeChat:Ke>0?`${i.openChat}. ${Ke===1?i.unreadMessage:Ve(i.unreadMessages,{count:String(Ke)})}`:i.openChat,"aria-expanded":o,onClick:Xn,children:[t.launcherIcon?r("img",{class:"cf-launcher__img",src:t.launcherIcon,alt:""}):r(nd,{}),!o&&Ke>0&&r("span",{class:"cf-launcher__badge","aria-hidden":"true",children:Ke>99?"99+":Ke})]})]})})})},sp="https://api.accurixtech.com",cp=()=>typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en",lp=(e,t)=>{if(!e)return;const n=t.trim().toLowerCase(),a=n.split("-")[0]??n,i=Object.entries(e);return i.find(([o])=>o.toLowerCase()===n)?.[1]??i.find(([o])=>o.toLowerCase()===a)?.[1]},dp=e=>{if(!e||typeof e.token!="string"||e.token.length===0)throw new Error("[centrinfo-widget] `token` is required — pass your pub_* token to Centrinfo.init({ token }).");const t=e.locale?.trim()||cp(),n=lp(e.translations,t);return{token:e.token,chatSurface:e.chatSurface??"floating",analyticsContextToken:e.analyticsContextToken,identityToken:e.identityToken,getIdentityToken:e.getIdentityToken,apiBaseUrl:(e.apiBaseUrl??sp).replace(/\/$/,""),accentColor:e.accentColor,themeTokens:e.themeTokens,agentName:e.agentName?.trim()||void 0,agentAvatarUrl:e.agentAvatarUrl?.trim()||void 0,launcherIcon:e.launcherIcon,gifApiKey:e.gifApiKey,theme:e.theme??"auto",openByDefault:e.openByDefault??!1,sound:e.sound??!0,starters:e.starters??[],strings:Kl({...n?.labels,...e.labels,...n?.labels?.analytics||e.labels?.analytics?{analytics:{...n?.labels?.analytics,...e.labels?.analytics,explanation:{...n?.labels?.analytics?.explanation,...e.labels?.analytics?.explanation}}}:{}}),locale:t,dir:Xl(t,e.dir),actionTranslations:n?.actions??{},persistence:e.persistence??"local",attachments:e.attachments??!0,zIndex:e.zIndex??2147483e3,styleNonce:e.styleNonce?.trim()??"",demo:e.demo??!1,preview:e.preview??!1,alignment:e.alignment==="left"?"left":"right",horizontalPadding:typeof e.horizontalPadding=="number"?e.horizontalPadding:20,verticalPadding:typeof e.verticalPadding=="number"?e.verticalPadding:20,hideDefaultLauncher:e.hideDefaultLauncher??!1,customLauncherSelector:e.customLauncherSelector,sessionDurationMinutes:typeof e.sessionDurationMinutes=="number"?e.sessionDurationMinutes:0,configRefreshSeconds:typeof e.configRefreshSeconds=="number"?e.configRefreshSeconds:30,proactiveMessage:e.proactiveMessage,proactiveDelaySeconds:typeof e.proactiveDelaySeconds=="number"?e.proactiveDelaySeconds:5,proactiveOnPaths:e.proactiveOnPaths,csat:e.csat??!0,user:e.user,onOpen:e.onOpen,onClose:e.onClose,onShow:e.onShow,onHide:e.onHide,onUnreadChange:e.onUnreadChange,onMessage:e.onMessage,onOpenAnalyticsSource:e.onOpenAnalyticsSource,onAction:e.onAction,onHandoff:e.onHandoff}},Oo=`
173
173
  :host {
174
174
  all: initial;
175
175
  }
@@ -3393,8 +3393,8 @@ Reference: ${J.caseReference}`:"Action completed.")}),gn("receive"),J},[e,t,Ye,g
3393
3393
  .cf-analytics-explanation .cf-xp { font-size: 12px; }
3394
3394
  .cf-analytics-explanation.is-expanded .cf-xp { font-size: 14px; }
3395
3395
  .cf-analytics-explanation .cf-xp__headline { font-size: 15px; }
3396
- ${Ml("cf",{surface:"var(--cf-surface)",subtle:"var(--cf-bg)",text:"var(--cf-text)",muted:"var(--cf-muted)",border:"var(--cf-border)",accent:"var(--cf-accent)",warning:"var(--cf-warning)",danger:"var(--cf-danger)",success:"var(--cf-success)",onAccent:"var(--cf-accent-ink)"})}
3397
- ${xc("cf",{bg:"var(--cf-bg)",surface:"var(--cf-surface)",surface2:"var(--cf-surface-2)",text:"var(--cf-text)",muted:"var(--cf-muted)",border:"var(--cf-border)",accent:"var(--cf-accent)",onAccent:"var(--cf-accent-ink)",chart:bc,chartDark:vc,darkSelector:".cf-root[data-theme='dark']"})}
3396
+ ${Nl("cf",{surface:"var(--cf-surface)",subtle:"var(--cf-bg)",text:"var(--cf-text)",muted:"var(--cf-muted)",border:"var(--cf-border)",accent:"var(--cf-accent)",warning:"var(--cf-warning)",danger:"var(--cf-danger)",success:"var(--cf-success)",onAccent:"var(--cf-accent-ink)"})}
3397
+ ${wc("cf",{bg:"var(--cf-bg)",surface:"var(--cf-surface)",surface2:"var(--cf-surface-2)",text:"var(--cf-text)",muted:"var(--cf-muted)",border:"var(--cf-border)",accent:"var(--cf-accent)",onAccent:"var(--cf-accent-ink)",chart:yc,chartDark:_c,darkSelector:".cf-root[data-theme='dark']"})}
3398
3398
 
3399
3399
  @media (max-width: 639px) {
3400
3400
  .cf-panel.cf-panel--analytics-focus {
@@ -3515,4 +3515,4 @@ ${xc("cf",{bg:"var(--cf-bg)",surface:"var(--cf-surface)",surface2:"var(--cf-surf
3515
3515
  max-height: calc(100dvh - 24px);
3516
3516
  }
3517
3517
  }
3518
- `,Cr="centrinfo-widget";class op extends HTMLElement{constructor(){super(...arguments);q(this,"controls",null);q(this,"composerDraftStore",{value:""})}mountWith(n){const a=ip(n),i=this.shadowRoot??this.attachShadow({mode:"open"});if(this.style.zIndex=String(a.zIndex),"adoptedStyleSheets"in Document.prototype&&typeof CSSStyleSheet<"u"&&typeof CSSStyleSheet.prototype.replaceSync=="function"){const s=new CSSStyleSheet;s.replaceSync(Ro),i.adoptedStyleSheets=[s]}else{const s=document.createElement("style");a.styleNonce&&(s.nonce=a.styleNonce),s.textContent=Ro,i.appendChild(s)}const o=Pc(a);Jr(r(tp,{transport:o,config:a,bindControls:s=>this.controls=s,composerDraftStore:this.composerDraftStore}),i)}open(){this.controls?.open()}close(){this.controls?.close()}toggle(){this.controls?.toggle()}identify(n){this.controls?.identify(n)}clear(){this.controls?.startNew()}shutdown(){this.controls?.shutdown()}unmount(){this.shadowRoot&&Jr(null,this.shadowRoot)}}typeof customElements<"u"&&!customElements.get(Cr)&&customElements.define(Cr,op);const sp=(e,t=document.body)=>{if(typeof document>"u")throw new Error("[centrinfo-widget] createWidget must run in a browser.");const n=document.createElement(Cr);return n.style.pointerEvents="none",n.style.position="fixed",n.style.inset="0",n.style.width="0",n.style.height="0",t.appendChild(n),n.mountWith(e),{open:()=>n.open(),close:()=>n.close(),toggle:()=>n.toggle(),show:()=>n.open(),hide:()=>n.close(),identify:a=>n.identify(a),update:a=>n.identify(a),clear:()=>n.clear(),shutdown:()=>n.shutdown(),logout:()=>n.shutdown(),destroy:()=>{n.unmount(),n.remove()}}},Lo=e=>sp(e);let Do=null;const Po=e=>{Do?.destroy();const t=Lo(e);return Do=t,t},cp=e=>e==="light"||e==="dark"||e==="auto"?e:void 0,qn=e=>{if(e==null||e.trim()==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0},lp=e=>{if(e)try{const t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch{return}},dp=e=>{const t=a=>e.getAttribute(a),n=t("data-token");return n?{token:n,apiBaseUrl:t("data-api-base")??void 0,accentColor:t("data-accent")??void 0,agentName:t("data-agent-name")??void 0,agentAvatarUrl:t("data-agent-avatar-url")??void 0,launcherIcon:t("data-launcher-icon")??void 0,gifApiKey:t("data-gif-api-key")??void 0,theme:cp(t("data-theme")),sound:t("data-sound")!=="false",openByDefault:t("data-open")==="true",demo:t("data-demo")==="true",preview:t("data-preview")==="true",alignment:t("data-alignment")==="left"?"left":void 0,horizontalPadding:qn(t("data-horizontal-padding")),verticalPadding:qn(t("data-vertical-padding")),hideDefaultLauncher:t("data-hide-launcher")==="true",styleNonce:(t("data-style-nonce")??e.nonce)||void 0,customLauncherSelector:t("data-custom-launcher-selector")??void 0,sessionDurationMinutes:qn(t("data-session-duration")),configRefreshSeconds:qn(t("data-config-refresh")),proactiveMessage:t("data-proactive-message")??void 0,proactiveDelaySeconds:qn(t("data-proactive-delay")),csat:t("data-csat")==="false"?!1:void 0,user:lp(t("data-user"))}:null},up=document.currentScript?.src||document.querySelector('script[src*="centrinfo-widget"]')?.src||"",Oo=e=>new URL(e,up||location.href).href;Fs(()=>import(Oo("centrinfo-widget-charts.js"))),Dc(()=>import(Oo("centrinfo-widget-dev.js")));const pp=e=>{typeof document>"u"||(document.readyState!=="loading"?e():document.addEventListener("DOMContentLoaded",e,{once:!0}))},fp=()=>{const e=document.currentScript??document.querySelector("script[data-token]");if(!e)return;const t=dp(e);t&&Po(t)};pp(()=>{try{fp()}catch(e){console.error("[centrinfo-widget]",e)}});const Fo=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));return St.createWidget=Lo,St.init=Po,Object.defineProperty(St,Symbol.toStringTag,{value:"Module"}),St})({});
3518
+ `,Mr="centrinfo-widget";class up extends HTMLElement{constructor(){super(...arguments);B(this,"controls",null);B(this,"composerDraftStore",{value:""})}mountWith(n){const a=dp(n),i=this.shadowRoot??this.attachShadow({mode:"open"});if(this.style.zIndex=String(a.zIndex),"adoptedStyleSheets"in Document.prototype&&typeof CSSStyleSheet<"u"&&typeof CSSStyleSheet.prototype.replaceSync=="function"){const s=new CSSStyleSheet;s.replaceSync(Oo),i.adoptedStyleSheets=[s]}else{const s=document.createElement("style");a.styleNonce&&(s.nonce=a.styleNonce),s.textContent=Oo,i.appendChild(s)}const o=Uc(a);Xr(r(op,{transport:o,config:a,bindControls:s=>this.controls=s,composerDraftStore:this.composerDraftStore}),i)}open(){this.controls?.open()}close(){this.controls?.close()}toggle(){this.controls?.toggle()}identify(n){this.controls?.identify(n)}clear(){this.controls?.startNew()}shutdown(){this.controls?.shutdown()}unmount(){this.shadowRoot&&Xr(null,this.shadowRoot)}}typeof customElements<"u"&&!customElements.get(Mr)&&customElements.define(Mr,up);const pp=(e,t=document.body)=>{if(typeof document>"u")throw new Error("[centrinfo-widget] createWidget must run in a browser.");const n=document.createElement(Mr);return n.style.pointerEvents="none",n.style.position="fixed",n.style.inset="0",n.style.width="0",n.style.height="0",t.appendChild(n),n.mountWith(e),{open:()=>n.open(),close:()=>n.close(),toggle:()=>n.toggle(),show:()=>n.open(),hide:()=>n.close(),identify:a=>n.identify(a),update:a=>n.identify(a),clear:()=>n.clear(),shutdown:()=>n.shutdown(),logout:()=>n.shutdown(),destroy:()=>{n.unmount(),n.remove()}}},Fo=e=>pp(e);let Uo=null;const Bo=e=>{Uo?.destroy();const t=Fo(e);return Uo=t,t},fp=e=>e==="light"||e==="dark"||e==="auto"?e:void 0,Vn=e=>{if(e==null||e.trim()==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0},hp=e=>{if(e)try{const t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch{return}},mp=e=>{const t=a=>e.getAttribute(a),n=t("data-token");return n?{token:n,apiBaseUrl:t("data-api-base")??void 0,accentColor:t("data-accent")??void 0,agentName:t("data-agent-name")??void 0,agentAvatarUrl:t("data-agent-avatar-url")??void 0,launcherIcon:t("data-launcher-icon")??void 0,gifApiKey:t("data-gif-api-key")??void 0,theme:fp(t("data-theme")),sound:t("data-sound")!=="false",openByDefault:t("data-open")==="true",demo:t("data-demo")==="true",preview:t("data-preview")==="true",alignment:t("data-alignment")==="left"?"left":void 0,horizontalPadding:Vn(t("data-horizontal-padding")),verticalPadding:Vn(t("data-vertical-padding")),hideDefaultLauncher:t("data-hide-launcher")==="true",styleNonce:(t("data-style-nonce")??e.nonce)||void 0,customLauncherSelector:t("data-custom-launcher-selector")??void 0,sessionDurationMinutes:Vn(t("data-session-duration")),configRefreshSeconds:Vn(t("data-config-refresh")),proactiveMessage:t("data-proactive-message")??void 0,proactiveDelaySeconds:Vn(t("data-proactive-delay")),csat:t("data-csat")==="false"?!1:void 0,user:hp(t("data-user"))}:null},gp=document.currentScript?.src||document.querySelector('script[src*="centrinfo-widget"]')?.src||"",qo=e=>new URL(e,gp||location.href).href;qs(()=>import(qo("centrinfo-widget-charts.js"))),Fc(()=>import(qo("centrinfo-widget-dev.js")));const bp=e=>{typeof document>"u"||(document.readyState!=="loading"?e():document.addEventListener("DOMContentLoaded",e,{once:!0}))},vp=()=>{const e=document.currentScript??document.querySelector("script[data-token]");if(!e)return;const t=mp(e);t&&Bo(t)};bp(()=>{try{vp()}catch(e){console.error("[centrinfo-widget]",e)}});const Vo=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));return St.createWidget=Fo,St.init=Bo,Object.defineProperty(St,Symbol.toStringTag,{value:"Module"}),St})({});