@accurix/centrinfo-widget 5.1.0 → 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 Lp=Object.defineProperty;var Dp=(St,$t,Yt)=>$t in St?Lp(St,$t,{enumerable:!0,configurable:!0,writable:!0,value:Yt}):St[$t]=Yt;var B=(St,$t,Yt)=>Dp(St,typeof $t!="symbol"?$t+"":$t,Yt);const $t={notComparable:"Not comparable yet"},Yt=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}:Yt(e.status)?Yt(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`}},_n=e=>e&&["day","week","month","quarter","year"].includes(e)?e:"period",Er=e=>e==="day"?"vs yesterday at this time":`vs same point last ${_n(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 ${_n(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",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 ${_n(e.grain)}`,g=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 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:g,compactSecondary:f,title:I}}return{basis:i,kind:"neutral",tone:"neutral",label:h.label,copy:Er(e.grain),secondary:g,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 y=[typeof l=="number"?`${c} so far: ${s(l)}`:`${c}: in progress`];return d!==void 0&&y.push(`${u}: ${s(d)} (${p})`),{basis:"current_in_progress_no_time",kind:"neutral",tone:"neutral",label:y.join(" · "),copy:"",title:e.reason,reason:e.reason}},Nr=e=>e?.grain==="day"?"Yesterday at this time":`Same point last ${_n(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(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: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":_n(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]:[]:[]},ta="__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(ta))return e;let o=i.find(p=>Dr(t.seriesField,p));if(!o)return e;let s=p=>a.find(g=>(g.key??g.name)===p),c=i.find(p=>{let g=s(p);return g?.semanticRole==="date"||g?.role==="date"||g?.dataType==="date"||g?.dataType==="datetime"}),u=(t.measureField?i.find(p=>Dr(t.measureField,p)):void 0)??i.find(p=>s(p)?.semanticRole==="measure"),l=n.map(p=>{let g=c?Rr(t,p[c]):"current",f=t.series?.find(h=>h.key===String(p[o]??"")),y=g&&typeof f?.previousToDateValue=="number"?f.previousToDateValue:null;return{...p,[ta]:y}}),d={...(u?s(u):void 0)??{dataType:"number",semanticRole:"measure"},key:ta,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,ta]:e.columns,columnMetadata:a.length?[...a,d]:e.columnMetadata}},us=e=>!!(e?.lastPeriodInProgress||e?.caveats?.some(t=>t.code==="incomplete_final_period")||e?.periodComparison?.currentPeriod?.inProgress),ps="In progress";var na,Re,Pr,Bt,Or,Fr,Ur,Da,aa,wn,Br,Pa,Oa,Fa,qr,ra={},ia=[],fs=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,oa=Array.isArray;function Et(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?na.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 sa(e,s,a,i,null)}function sa(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 ce(e){return e.children}function ca(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=Et({},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)&&Bt.push(e)&&!la.__r++||Or!=Re.debounceRendering)&&((Or=Re.debounceRendering)||Fr)(la)}function la(){try{for(var e,t=1;Bt.length;)Bt.length>t&&Bt.sort(Ur),e=Bt.shift(),t=Bt.length,ms(e)}finally{Bt.length=la.__r=0}}function jr(e,t,n,a,i,o,s,c,u,l,d){var p,g,f,y,h,I,x,m=a&&a.__k||ia,T=t.length;for(u=gs(n,t,m,u,T),p=0;p<T;p++)(f=n.__k[p])!=null&&(g=f.__i!=-1&&m[f.__i]||ra,f.__i=p,I=qa(e,f,g,i,o,s,c,u,l,d),y=f.__e,f.ref&&g.ref!=f.ref&&(g.ref&&ja(g.ref,null,f),d.push(f.ref,f.__c||y,f)),h==null&&y!=null&&(h=y),(x=!!(4&f.__u))||g.__k===f.__k?(u=Hr(f,u,e,x),x&&g.__e&&(g.__e=null)):typeof f.type=="function"&&I!==void 0?u=I:y&&(u=y.nextSibling),f.__u&=-7);return n.__e=h,u}function gs(e,t,n,a,i){var o,s,c,u,l,d=n.length,p=d,g=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]=sa(null,s,null,null,null):oa(s)?s=e.__k[o]=sa(ce,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=sa(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[o]=s,u=o+g,s.__=e,s.__b=e.__b+1,c=null,(l=s.__i=bs(s,n,u,p))!=-1&&(p--,(c=n[l])&&(c.__u|=2)),c==null||c.__v==null?(l==-1&&(i>d?g--:i<d&&g++),typeof s.type!="function"&&(s.__u|=4)):l!=u&&(l==u-1?g--:l==u+1?g++:(l>u?g--:g++,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)),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,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 Wr(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||fs.test(t)?n:n+"px"}function da(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[wn]=a[wn]:(n[wn]=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[aa]==null)t[aa]=Pa++;else if(t[aa]<n[wn])return;return n(Re.event?Re.event(t):t)}}}function qa(e,t,n,a,i,o,s,c,u,l){var d,p,g,f,y,h,I,x,m,T,F,M,Q,Y,X,j=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(u=!!(32&n.__u),o=[c=t.__e=n.__e]),(d=Re.__b)&&d(t);e:if(typeof j=="function")try{if(x=t.props,m=j.prototype&&j.prototype.render,T=(d=j.contextType)&&a[d.__c],F=d?T?T.props.value:d.__:a,n.__c?I=(p=t.__c=n.__c).__=p.__E:(m?t.__c=p=new j(x,F):(t.__c=p=new ca(x,F),p.constructor=j,p.render=xs),T&&T.sub(p),p.state||(p.state={}),p.__n=a,g=p.__d=!0,p.__h=[],p._sb=[]),m&&p.__s==null&&(p.__s=p.state),m&&j.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Et({},p.__s)),Et(p.__s,j.getDerivedStateFromProps(x,p.__s))),f=p.props,y=p.state,p.__v=t,g)m&&j.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),m&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(m&&j.getDerivedStateFromProps==null&&x!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(x,F),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(x,p.__s,F)===!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(U){U&&(U.__=t)}),ia.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(x,p.__s,F),m&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,y,h)})}if(p.context=F,p.props=x,p.__P=e,p.__e=!1,M=Re.__r,Q=0,m)p.state=p.__s,p.__d=!1,M&&M(t),d=p.render(p.props,p.state,p.context),ia.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,M&&M(t),d=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++Q<25);p.state=p.__s,p.getChildContext!=null&&(a=Et(Et({},a),p.getChildContext())),m&&!g&&p.getSnapshotBeforeUpdate!=null&&(h=p.getSnapshotBeforeUpdate(f,y)),Y=d!=null&&d.type===ce&&d.key==null?Yr(d.props.children):d,c=jr(e,oa(Y)?Y:[Y],t,n,a,i,o,s,c,u,l),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),I&&(p.__E=p.__=null)}catch(U){if(t.__v=null,u||o!=null)if(U.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(X=o.length;X--;)Ua(o[X]);Va(t)}else t.__e=n.__e,t.__k=n.__k,U.then||Va(t);Re.__e(U,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,u,l);return(d=Re.diffed)&&d(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:oa(e)?e.map(Yr):e.constructor!==void 0?null:Et({},e)}function vs(e,t,n,a,i,o,s,c,u){var l,d,p,g,f,y,h,I=n.props||ra,x=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(x);e=document.createElementNS(i,m,x.is&&x),c&&(Re.__m&&Re.__m(t,o),c=!1),o=null}if(m==null)I===x||c&&e.data==x||(e.data=x);else{if(o=m=="textarea"&&x.defaultValue!=null?null:o&&na.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||da(e,l,null,f,i);for(l in x)f=x[l],l=="children"?g=f:l=="dangerouslySetInnerHTML"?d=f:l=="value"?y=f:l=="checked"?h=f:c&&typeof f!="function"||I[l]===f||da(e,l,f,I[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,oa(g)?g:[g],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--;)Ua(o[l]);c&&m!="textarea"||(l="value",m=="progress"&&y==null?e.removeAttribute("value"):y!=null&&(y!==e[l]||m=="progress"&&!y||m=="option"&&y!=I[l])&&da(e,l,y,I[l],i),l="checked",h!=null&&h!=e[l]&&da(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(ce,null,[e]),i||ra,ra,t.namespaceURI,i?null:t.firstChild?na.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}na=ia.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,ca.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Et({},this.state),typeof e=="function"&&(e=e(Et({},n),this.props)),e&&Et(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Ba(this))},ca.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Ba(this))},ca.prototype.render=ce,Bt=[],Fr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ur=function(e,t){return e.__v.__b-t.__v.__b},la.__r=0,Da=Math.random().toString(8),aa="__d"+Da,wn="__a"+Da,Br=/(PointerCapture)$|Capture$/i,Pa=0,Oa=Gr(!1),Fa=Gr(!0),qr=0;var Zt,Oe,Wa,Xr,kn=0,Qr=[],je=Re,ei=je.__b,ti=je.__r,ni=je.diffed,ai=je.__c,ri=je.unmount,ii=je.__;function Sn(e,t){je.__h&&je.__h(Oe,e,kn||t),kn=0;var n=Oe.__H||(Oe.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function S(e){return kn=1,ys(si,e)}function ys(e,t,n){var a=Sn(Zt++,2);if(a.t=e,!a.__c&&(a.__=[si(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=Oe,!Oe.__f)){var i=function(c,u,l){if(!a.__c.__H)return!0;var d=a.__c.__H.__.filter(function(g){return g.__c});if(d.every(function(g){return!g.__N}))return!o||o.call(this,c,u,l);var p=a.__c.props!==c;return d.some(function(g){if(g.__N){var f=g.__[0];g.__=g.__N,g.__N=void 0,f!==g.__[0]&&(p=!0)}}),o&&o.call(this,c,u,l)||p};Oe.__f=!0;var o=Oe.shouldComponentUpdate,s=Oe.componentWillUpdate;Oe.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)},Oe.shouldComponentUpdate=i}return a.__N||a.__}function J(e,t){var n=Sn(Zt++,3);!je.__s&&Ya(n.__H,t)&&(n.__=e,n.u=t,Oe.__H.__h.push(n))}function $n(e,t){var n=Sn(Zt++,4);!je.__s&&Ya(n.__H,t)&&(n.__=e,n.u=t,Oe.__h.push(n))}function R(e){return kn=5,qe(function(){return{current:e}},[])}function qe(e,t){var n=Sn(Zt++,7);return Ya(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function O(e,t){return kn=8,qe(function(){return e},t)}function Ga(e){var t=Oe.context[e.__c],n=Sn(Zt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(Oe)),t.props.value):e.__}function _s(){for(var e;e=Qr.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(ua),t.__h.some(Ka),t.__h=[]}catch(n){t.__h=[],je.__e(n,e.__v)}}}je.__b=function(e){Oe=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),Zt=0;var t=(Oe=e.__c).__H;t&&(Wa===Oe?(t.__h=[],Oe.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(ua),t.__h.some(Ka),t.__h=[],Zt=0)),Wa=Oe},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=Oe=null},je.__c=function(e,t){t.some(function(n){try{n.__h.some(ua),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{ua(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 ua(e){var t=Oe,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Oe=t}function Ka(e){var t=Oe;e.__c=e.__(),Oe=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,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:--ks,__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 Re.vnode&&Re.vnode(l),l}const pa=(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=>pa(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(u=>{let l=String(u);try{typeof a=="function"&&(l=String(a(u)))}catch{}return pa(l)})):pa("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,u=Za(e.series),l={...e.grid??{}},d=(o.data??[]).map(h=>String(h&&typeof h=="object"?h.value??"":h)),p={...e,grid:l},g={...o},f={...s},y=0;if(i)c&&(y=Math.min(t*.35,90),g={...g,axisLabel:{...o.axisLabel,width:Math.floor(y),overflow:"truncate",ellipsis:"…"}},l.left=8);else{let h=As(s,u);if(y=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)},y+=18}}if(!i){let h=typeof l.left=="number"?l.left:0,I=typeof l.right=="number"?l.right:0,x=Ts(d,Math.max(40,t-h-I-y)/Math.max(1,d.length)),m=o.axisLabel?.fontSize??11,T=m+2;if(x.kind==="truncate"||x.kind==="rotate"){let F=x.kind==="rotate"?x.rotate:0;if(g.axisLabel={...o.axisLabel,interval:0,hideOverlap:!1,rotate:F,width:x.width,overflow:"truncate",ellipsis:"…"},F){let M=Math.max(0,...d.map(Y=>pa(Y,m))),Q=Math.min(x.width,M);T=Math.ceil(Q*Math.sin(F*Math.PI/180))+m}}o.name&&c?g.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)?[g,...a.slice(1)]:g,p.xAxis=Array.isArray(e.xAxis)?[f,...n.slice(1)]:f):(p.xAxis=Array.isArray(e.xAxis)?[g,...n.slice(1)]:g,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"},Jt=(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 Jt(n.locale,{year:"numeric",timeZone:o}).format(s);case"quarter":{let c=Number(Jt("en-US",{month:"numeric",timeZone:o}).format(s)),u=Jt(n.locale,{year:"numeric",timeZone:o}).format(s);return`Q${Math.floor((c-1)/3)+1} ${u}`}case"month":return Jt(n.locale,{month:"short",year:"numeric",timeZone:o}).format(s);case"week":case"day":return Jt(n.locale,{day:"numeric",month:"short",year:"numeric",timeZone:o}).format(s);case"hour":return Jt(n.locale,{day:"numeric",month:"short",hour:"numeric",minute:"2-digit",timeZone:o}).format(s);default:return Jt(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}},Tn=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=Tn(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)},fa={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"},bt=(e,t)=>e.replace(/\{(\w+)\}/g,(n,a)=>String(t[a]??"")),Os=e=>Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!=null)),Qa=e=>({...fa,...Os(e),explanation:{...e?.explanation}});let hi=()=>Promise.resolve().then(()=>Fo),Cn=null,mi=!1;const Fs=e=>{hi=e,Cn=null,mi=!0},Us=()=>(Cn||(Cn=hi().catch(e=>{throw Cn=null,e})),Cn),Xt={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)}),An=(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=An(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,u=Math.max(0,Math.min(c,Math.round(s-(o-1)/2)));return{startIndex:u,endIndex:u+o-1}},Bs=(e,t,n=fa)=>{let a=e.length;if(a===0)return n.zoomNone;let i=An(t,a);return i.startIndex===0&&i.endIndex===a-1?bt(a===1?n.zoomAllOne:n.zoomAllMany,{count:a}):bt(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=Tn,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)}`},In=(e,t)=>t?e.columnMetadata?.find(n=>n.key===t):void 0,tr=(e,t)=>{let n=In(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},En=(e,t)=>In(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=In(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=In(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)},Qt=(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?` ${bt(o.seriesLimited,{shown:a.length,total:a.length+i})}`:"",u=(d,p)=>Qt(d,p,e,!1,s);if(t==="line"){let d=n.length-1,p=a.map(g=>{let f=g.values[d];return f==null?null:`${g.name}: ${u(f,g.valueColumn)}`}).filter(g=>!!g);return p.length?`${bt(o.summaryLatest,{category:n[d]??"",values:p.join("; ")})}${c}`:`${o.summaryNoTrend}${c}`}let l;return a.forEach(d=>{d.values.forEach((p,g)=>{p===null||l&&p<=l.value||(l={category:n[g]??o.notSet,series:d,value:p})})}),l?`${bt(o.summaryHighest,{category:l.category,series:l.series.name,value:u(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 u=ki(e),l=Si(e,s,u);if(l.length===0)return null;let d=l.length===1?u:void 0,p=yi(e,s,c),g=l[0],f=d&&La(e.periodComparison)&&(!e.periodComparison.measureField||!g||g===e.periodComparison.measureField||g.endsWith(`.${e.periodComparison.measureField}`)||e.periodComparison.measureField.endsWith(`.${g}`))?e.periodComparison:void 0,y=(()=>{if(!f?.seriesField||!d)return;let D=(q,C)=>q===C||q.endsWith(`.${C}`)||C.endsWith(`.${q}`);if(D(f.seriesField,s))return{group:s,time:d,timeIsSeries:!0};if(D(f.seriesField,d))return{group:d,time:s,timeIsSeries:!1}})(),h=D=>Qt(D,tr(e,g??""),e,!1,i),I=D=>f&&y?Lr(f,D[y.time],D[y.group],{format:h,locale:i}):void 0,x=(D,q)=>f?.comparisonBasis==="like_for_like"&&Lr(f,D,f.series?.[0]?.key)?.side==="previous"?Nr(f):q,m=[],T=new Set;c.forEach(D=>{let q=Mn(D[s]);if(T.has(q))return;T.add(q);let C=_i(e,s,D[s],a,i,p);m.push({key:q,label:y&&!y.timeIsSeries?x(D[s],C):C})});let F=m.map(D=>D.label),M=0,Q;if(d){let D=[],q=new Set;c.forEach(_=>{let L=Mn(_[d]);if(q.has(L))return;q.add(L);let $=_i(e,d,_[d],a,i,yi(e,d,c));D.push({key:L,label:y?.timeIsSeries?x(_[d],$):$})});let C=D.slice(0,4);M=Math.max(0,D.length-C.length);let Z=l[0];Q=C.map(_=>{let L=new Map,$=new Map;return c.forEach(P=>{if(Mn(P[d])!==_.key)return;let fe=Mn(P[s]);if(!L.has(fe)){let oe=I(P);$.set(fe,oe),L.set(fe,oe?.side==="previous"&&oe.plotValue!==void 0?oe.plotValue:er(P[Z]))}}),{field:Z,name:_.label,values:m.map(P=>L.get(P.key)??null),valueColumn:tr(e,Z),...y?{points:m.map(P=>$.get(P.key))}:{}}})}else M=Math.max(0,l.length-4),Q=l.slice(0,4).map(D=>({field:D,name:En(e,D),values:c.map(q=>er(q[D])),valueColumn:tr(e,D)}));if(Q.length===0)return null;let Y=En(e,s),X=a.chartValues;d?X=En(e,l[0]):Q.length===1&&(X=Q[0].name);let j=e.title?.trim()||bt(a.chartTitle,{measure:X,dimension:Y}),U;if(In(e,s)?.semanticRole==="date"&&m.length>1&&us(e)){let D="";c.forEach(C=>{let Z=String(C[s]??"");Z>D&&(D=Z)});let q=m.findIndex(C=>C.key===Mn(D));q>=0&&(U=q)}return{type:o,title:j,xAxisTitle:Y,yAxisTitle:X,categories:F,series:Q,omittedSeriesCount:M,inProgressIndex:U,...y&&f?{comparison:f,comparisonNote:ss(f)}:{},locale:i,labels:a,summary:Ws(e,o,F,Q,M,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=fa)=>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 ${En(e,t)} for each ${En(e,a)}. Return a chart and show a table if this app permits it.`},Zs=(e,t=fa)=>{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:"),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(Qt(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],u=c?.points?.[Number(s.dataIndex)],l=d=>Qt(d,c?.valueColumn,void 0,!1,e.locale);return[`${String(s.marker??"")}${a(String(s.seriesName??""))}: ${a(l(s.value))}`,...cs(e.comparison,u,l).map(d=>`<span style="opacity:.75">${a(d)}</span>`)]});return[i?`<strong>${a(i)}</strong>`:"",...o].filter(Boolean).join("<br/>")},Qs=(e,{expanded:t=!1,reducedMotion:n=!1,theme:a=Xt,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=An(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: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=>Qt(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,g={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:y=>Qt(y,l.valueColumn,void 0,!1,e.locale)}};if(p<0)return[g];let f=a.colors[d%a.colors.length];return e.type==="line"?p===0?[g]:[{...g,lineStyle:{...g.lineStyle,color:f},itemStyle:{...g.itemStyle,color:f},data:l.values.map((y,h)=>h===p?null:y)},{...g,id:`in-progress:${d}`,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((y,h)=>h===p||h===p-1?y:null)}]:[{...g,data:l.values.map((y,h)=>h===p?{value:y,itemStyle:{opacity:.45,borderType:"dashed",borderWidth:1.5,borderColor:f}}:y)}]})}},ec=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]=Xt.colors;return{background:n(["--rv-bg","--cf-bg"],Xt.background),border:n(["--rv-border","--cf-border"],Xt.border),muted:n(["--rv-muted","--cf-muted"],Xt.muted),surface:n(["--rv-surface","--cf-surface"],Xt.surface),text:n(["--rv-text","--cf-text"],Xt.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]=S(()=>({model:e,window:ln(e.categories.length)})),[c,u]=S(!1),l=o.model===e?An(o.window,e.categories.length):ln(e.categories.length),d=R(l);d.current=l;let p=X=>{let j=An(X,e.categories.length);d.current=j,s({model:e,window:j}),i.current?.dispatchAction({type:"dataZoom",dataZoomId:gi,startValue:j.startIndex,endValue:j.endIndex})},[g,f]=S(!1),[y,h]=S(0),[I,x]=S(0);J(()=>{let X=a.current;if(X)return nc(X,()=>x(j=>j+1))},[]),J(()=>{let X=a.current;if(!X)return;let j=!1,U=null;return Us().then(({init:D})=>{if(j||!X.isConnected||!mi&&typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("jsdom"))return;let q=D(X,null,{renderer:"canvas",devicePixelRatio:Math.min(window.devicePixelRatio||1,2)});i.current=q;let C=()=>{q.resize(),h(Math.round(X.clientWidth/40))},Z=typeof ResizeObserver>"u"?null:new ResizeObserver(C);Z?.observe(X),Z||window.addEventListener("resize",C,{passive:!0}),U=()=>{Z?.disconnect(),Z||window.removeEventListener("resize",C),q.dispose(),i.current=null},f(!0)}).catch(()=>{j||u(!0)}),()=>{j=!0,U?.()}},[]),J(()=>{let X=a.current,j=i.current;if(!X||!j)return;let U=typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;j.setOption(Ms(Qs(e,{expanded:t,reducedMotion:U,theme:ec(X),zoomWindow:d.current}),X.clientWidth),{lazyUpdate:!0,notMerge:!0}),j.resize()},[t,e,g,I,y]);let m=e.labels,T=!c&&e.categories.length>2,F=l.endIndex-l.startIndex+1,M=l.startIndex===0&&l.endIndex===e.categories.length-1,Q=T&&F>2,Y=T&&!M;return r(ce,{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,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:!Y,onClick:()=>p(vi(d.current,"out",e.categories.length)),children:"−"}),r("button",{type:"button",class:`${n}-analytics-zoom__reset`,"aria-label":m.zoomReset,title:m.zoomReset,disabled:M,onClick:()=>p(ln(e.categories.length)),children:m.zoomResetShort}),r("button",{type:"button","aria-label":m.zoomIn,title:m.zoomIn,disabled:!Q,onClick:()=>p(vi(d.current,"in",e.categories.length)),children:"+"})]})]}):null]})},zn=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:zn(n)}:{...n,label:n.label?.trim()||zn(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,u]=S(n),[l,d]=S(!1);J(()=>u(n),[n]);let p=f=>`${i}-${f}`,g=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 y=f.currentTarget.open;d(y);let h=s.current;if(h){if(h.setAttribute("popover","manual"),!y){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)),m=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+m+6<=innerHeight-12?I.bottom+6:Math.max(12,I.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,y])=>r("button",{type:"button",role:"option","aria-selected":f===c,onClick:()=>g(f),children:y},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 u=qe(()=>Ti(e,t),[t,e]),l=u.map(k=>k.key).join("\0"),[d,p]=S(()=>u.map(k=>k.key)),[g,f]=S(""),[y,h]=S(),[I,x]=S("asc"),[m,T]=S({}),[F,M]=S(),[Q,Y]=S([]),[X,j]=S({}),[U,D]=S(()=>u.map(k=>k.key)),[q,C]=S(!1),[Z,_]=S([]),[L,$]=S("table"),[P,fe]=S(1),[oe,Ue]=S(c),ke=R(null);J(()=>{let k=V=>{let H=V.composedPath();ke.current?.querySelectorAll("details[data-result-popover][open]").forEach(ae=>{H.includes(ae)||(ae.open=!1)})},K=V=>{let H=[...ke.current?.querySelectorAll("details[data-result-popover][open]")??[]].at(-1);V.key!=="Escape"||!H||(H.open=!1,H.querySelector("summary")?.focus(),V.preventDefault())};return document.addEventListener("pointerdown",k),document.addEventListener("keydown",K),()=>{document.removeEventListener("pointerdown",k),document.removeEventListener("keydown",K)}},[]),J(()=>{p(u.map(k=>k.key)),h(void 0),T({}),M(void 0),Y([]),j({}),D(u.map(k=>k.key)),_([]),fe(1)},[l]);let Ce=U.map(k=>u.find(K=>K.key===k)).filter(k=>!!(k&&d.includes(k.key))),Le=qe(()=>{let k=g.toLocaleLowerCase(a),K=e.map((V,H)=>({row:V,index:H})).filter(({row:V})=>Ce.some(H=>rr(V[H.key],a,H,i).toLocaleLowerCase(a).includes(k))&&Object.entries(m).every(([H,ae])=>{let ye=u.find(Se=>Se.key===H);return ic(V[H],rr(V[H],a,ye,i),ae)}));return y?K.sort((V,H)=>{let ae=V.row[y],ye=H.row[y],Se=typeof ae=="number"?ae:NaN,Qe=typeof ye=="number"?ye:NaN,Ge=!Number.isNaN(Se)&&!Number.isNaN(Qe)?Se-Qe:String(ae??"").localeCompare(String(ye??""),a,{numeric:!0,sensitivity:"base"});return I==="asc"?Ge:-Ge}):K},[Ce,m,i,a,g,u,e,I,y]),Ie=Le.slice(0,Math.max(1,n)),Ae=Math.max(1,Math.ceil(Ie.length/oe)),ge=Math.min(P,Ae),Ze=o?Ie:Ie.slice((ge-1)*oe,ge*oe),be=Ze.length>0&&Ze.every(({index:k})=>Z.includes(k)),ie=k=>`${s}-${k}`,Je=()=>{p(u.map(k=>k.key)),D(u.map(k=>k.key)),j({}),h(void 0),x("asc"),T({}),M(void 0),Y([]),C(!1),f(""),_([]),$("table"),fe(1)};if(e.length===0||u.length===0)return r("div",{class:ie("table-note"),children:"No rows returned."});let He=k=>{let K=new Set(Ze.map(({index:V})=>V));_(V=>k?[...new Set([...V,...K])]:V.filter(H=>!K.has(H)))};return r("section",{ref:ke,class:ie("data-table"),children:[r("div",{class:ie("table-fields"),children:[r("strong",{children:"Fields"}),r("div",{class:ie("field-list"),children:u.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:g,placeholder:"Search this result...","aria-label":"Search this result",onInput:k=>{f(k.currentTarget.value.trim()),fe(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")}${L===k?" is-active":""}`,"aria-pressed":L===k,onClick:()=>$(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:U.map((k,K)=>{let V=u.find(H=>H.key===k);return V?r("div",{class:ie("column-picker-row"),children:[r("label",{children:[r("input",{type:"checkbox",checked:d.includes(V.key),onChange:H=>{let ae=H.currentTarget.checked;p(ye=>ae?[...new Set([...ye,V.key])]:ye.length>1?ye.filter(Se=>Se!==V.key):ye)}}),r("span",{children:X[V.key]||V.label})]}),r("button",{type:"button","aria-label":`Move ${V.label} left`,disabled:K===0,onClick:()=>D(H=>{let ae=[...H];return[ae[K-1],ae[K]]=[ae[K],ae[K-1]],ae}),children:"↑"}),r("button",{type:"button","aria-label":`Move ${V.label} right`,disabled:K===U.length-1,onClick:()=>D(H=>{let ae=[...H];return[ae[K+1],ae[K]]=[ae[K],ae[K+1]],ae}),children:"↓"})]},V.key):null})})]}),r("button",{type:"button",class:ie("table-view-button"),"aria-pressed":q,onClick:()=>C(k=>!k),children:q?"Comfortable rows":"Compact rows"}),r("button",{type:"button",class:ie("table-view-button"),onClick:Je,children:"Reset view"})]}),Object.keys(m).length?r("div",{class:ie("table-filter-bar"),children:Object.entries(m).map(([k,K])=>{let V=u.find(H=>H.key===k);return r("button",{type:"button",class:ie("table-filter-chip"),"aria-label":`Clear ${V?.label??k} filter`,onClick:()=>T(H=>{let ae={...H};return delete ae[k],ae}),children:[X[k]||V?.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")}${L==="matrix"?" is-matrix":""}${q?" 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:be,onChange:k=>He(k.currentTarget.checked)})}),Ce.map(k=>r("th",{scope:"col",class:F===k.key?"is-pinned":void 0,style:F===k.key?{left:"34px"}:void 0,"aria-sort":y===k.key?I==="asc"?"ascending":"descending":"none",children:[r("button",{type:"button",class:ie("table-sort"),"aria-label":`Sort by ${k.label}`,onClick:()=>{y===k.key?x(K=>K==="asc"?"desc":"asc"):(h(k.key),x("asc")),fe(1)},children:[r("span",{children:X[k.key]||k.label}),r("span",{class:ie("sort-direction"),"aria-hidden":"true",children:y===k.key?I==="asc"?"↑":"↓":"↕"})]}),r("details",{"data-result-popover":!0,class:ie("table-column-menu"),onToggle:K=>{let V=K.currentTarget,H=V.querySelector(`.${ie("table-column-panel")}`);if(H?.setAttribute("popover","manual"),!V.open){H&&typeof H.hidePopover=="function"&&H.matches(":popover-open")&&H.hidePopover(),V.querySelectorAll("details[data-result-select][open]").forEach(ae=>{ae.open=!1});return}ke.current?.querySelectorAll("details[data-result-popover][open]").forEach(ae=>{ae!==V&&!V.contains(ae)&&(ae.open=!1)}),H&&typeof H.showPopover=="function"&&!H.matches(":popover-open")&&H.showPopover(),requestAnimationFrame(()=>{if(!V.open||!V.isConnected)return;let ae=V.querySelector("summary")?.getBoundingClientRect();if(!ae||!H)return;let{width:ye,height:Se}=H.getBoundingClientRect(),Qe=ae.bottom+Se+5<=innerHeight-12?ae.bottom+5:ae.top-Se-5;H.style.left=`${Math.max(12,Math.min(ae.right-ye,innerWidth-ye-12))}px`,H.style.top=`${Math.max(12,Math.min(Qe,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:X[k.key]||k.label}),r("button",{type:"button",onClick:()=>{h(k.key),x("asc"),fe(1)},children:"Sort ascending"}),r("button",{type:"button",onClick:()=>{h(k.key),x("desc"),fe(1)},children:"Sort descending"}),r("span",{children:"Filter values"}),r(Ai,{classPrefix:s,label:`Filter operator for ${k.label}`,value:m[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:m[k.key]?.value??"",placeholder:"Enter a value"}),r("button",{type:"button",onClick:K=>{let V=K.currentTarget.parentElement,H=V.querySelector('input[aria-label^="Filter value"]').value.trim(),ae=V.querySelector("[data-result-select]").dataset.value;T(ye=>{let Se={...ye};return H?Se[k.key]={operator:ae,value:H}:delete Se[k.key],Se}),fe(1),K.currentTarget.closest("details").open=!1},children:"Apply filter"}),r("button",{type:"button",onClick:K=>{M(V=>V===k.key?void 0:k.key),D(V=>[k.key,...V.filter(H=>H!==k.key)]),K.currentTarget.closest("details").open=!1},children:F===k.key?"Unpin column":"Pin column"}),r("button",{type:"button",onClick:K=>{Y(V=>V.includes(k.key)?V.filter(H=>H!==k.key):[...V,k.key]),K.currentTarget.closest("details").open=!1},children:Q.includes(k.key)?"Do not wrap text":"Wrap text"}),r("input",{type:"text","aria-label":`Display name for ${k.label}`,defaultValue:X[k.key]||k.label,maxLength:80}),r("button",{type:"button",onClick:K=>{let V=K.currentTarget.parentElement.querySelector('input[aria-label^="Display name"]').value.trim();j(H=>({...H,[k.key]:V||k.label||k.key})),K.currentTarget.closest("details").open=!1},children:"Apply display name"})]})]})]},k.key))]})}),r("tbody",{children:Ze.map(({row:k,index:K})=>r("tr",{class:Z.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:Z.includes(K),onChange:V=>_(H=>V.currentTarget.checked?[...new Set([...H,K])]:H.filter(ae=>ae!==K))})}),Ce.map(V=>r("td",{class:`${Q.includes(V.key)?"is-wrapped":""} ${F===V.key?"is-pinned":""}`.trim(),style:F===V.key?{left:"34px"}:void 0,children:rr(k[V.key],a,V,i)},V.key))]},K))})]})}),r("div",{class:ie("table-summary"),children:[r("span",{children:Ie.length?`${((ge-1)*oe+1).toLocaleString(a)}-${Math.min(ge*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=>{Ue(Number(k)),fe(1)}})]}),r("button",{type:"button","aria-label":"Previous page",disabled:ge<=1,onClick:()=>fe(k=>Math.max(1,k-1)),children:"‹"}),r("span",{children:[ge," / ",Ae]}),r("button",{type:"button","aria-label":"Next page",disabled:ge>=Ae,onClick:()=>fe(k=>Math.min(Ae,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:bt(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:bt(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:zn(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=>Tn(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))}),ha=({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(ha,{children:r("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})}),fc=()=>r(ha,{children:r("path",{d:"M18 6 6 18M6 6l12 12"})}),zi=()=>r(ha,{size:13,children:r("path",{d:"m6 9 6 6 6-6"})}),hc=()=>r(ha,{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(ce,{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(ce,{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]=S(!1),a=R(null),i=R(null),o=R(t);return o.current=t,J(()=>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()}}),[]),$n(()=>{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,g=document.documentElement.clientHeight||window.innerHeight,f=getComputedStyle(c).direction==="rtl",y=e==="end"===f?d.left:d.right-l.width;y=Math.max(8,Math.min(y,p-l.width-8));let h=d.bottom+7;h+l.height>g-8&&d.top-7-l.height>8&&(h=d.top-7-l.height),u.style.left=`${y-l.left}px`,u.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),u=t?s[0]?.[t]:void 0,l=Tn(u),d=x=>Qt(x,c,e,!1,i),p=l===null?String(u??a.noValue):d(l),g=e.periodComparison,f=!g?.measureField||g.measureField===t,y=t?Tn(s[1]?.[t]):null,h=l!==null&&g&&f?zr(g,{value:l,status:"observed",label:g.currentPeriod?.label},{value:y??g.previousFullValue??g.previousToDateValue,status:"observed",label:g.previousPeriod?.label},{format:d,locale:i}):void 0,I=c?.label??(t?zn(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(ce,{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:u,onDownload:l,headerActions:d,children:p,dataToggle:g,cardRef:f,maxTableRows:y=100})=>{let h=qe(()=>Qa(n),[n]),I=qe(()=>nr(e,void 0,{labels:h,locale:a}),[e,h,a]),[x,m]=S(I?.type);J(()=>m(I?.type),[I]);let[T,F]=S(!1),M=qe(()=>Zs(e,h),[e,h]),Q=qe(()=>nr(e,x,{labels:h,locale:a}),[e,x,h,a]),Y=x??Q?.type??I?.type,X=M.find(be=>be.type===Y),j=[...new Set(Q?.series.map(be=>be.field)??[])],U=Ri("end"),D=Ri("start"),q=e.rows??[],C=Mi(e),Z=qe(()=>ds(e),[e]),_=qe(()=>cc(Z),[Z]),L=qe(()=>({locale:a,timezone:e.timezone||e.periodComparison?.timezone,yes:h.yes,no:h.no}),[a,e.timezone,e.periodComparison?.timezone,h]),$=sc(e,h,a),P=l===!1||!e.downloadAvailable?null:()=>(l??dc)(C,q),fe=$.length?r("details",{class:`${t}-analytics-inspect`,children:[r("summary",{children:h.aboutResult}),r("dl",{children:$.map(be=>r("div",{children:[r("dt",{children:be.label}),r("dd",{children:be.value})]},be.label))})]}):null,oe=(()=>{let be=e.freshness?.answeredAt,ie=be?new Date(be):null;return!ie||Number.isNaN(ie.getTime())?h.liveData:bt(h.updatedAt,{time:new Intl.DateTimeFormat(a,{hour:"numeric",minute:"2-digit"}).format(ie)})})(),Ue=e.rowCount??q.length,ke=e.appliedFilters?.length??0,Ce=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:bt(Ue===1?h.rowOne:h.rowMany,{count:Ue})}),ke>0?r("span",{children:bt(ke===1?h.filtersOne:h.filtersMany,{count:ke})}):null]}),Le=(be,ie,Je,He=h.expandChart)=>r("div",{class:`${t}-analytics-result`,children:[r("section",{ref:f,class:`${t}-analytics-visualization${i?" is-expanded":""}`,"aria-label":be,children:[r("div",{class:`${t}-analytics-visualization__header`,children:[r("div",{children:[r("div",{class:`${t}-analytics-visualization__title`,children:be}),Ce]}),r("div",{class:`${t}-analytics-visualization__actions`,children:[Je,d,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":He,title:He,"data-visualization-message":c,onClick:o,children:r(pc,{})}):null]})]}),ie,fe,p]}),r("div",{class:`${t}-analytics-layer`,children:[u?r("div",{ref:D.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:"fixed"},role:"menu","aria-label":h.aggregate,hidden:!D.open,children:j.flatMap(k=>$i(e,k).map(K=>{let V=e.columnMetadata?.find(H=>H.key===k)?.label??zn(k);return r("button",{type:"button",role:"menuitem",onClick:()=>{let H=Ys(e,k,K.value);H&&u(H),D.setOpen(!1)},children:r("span",{class:`${t}-analytics-chart-picker__copy`,children:[r("strong",{children:[Ks(K.value,h)," · ",V]}),r("small",{children:h.aggregateCharge})]})},`${k}:${K.value}`)}))}):null,r("div",{ref:U.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:"fixed"},role:"listbox","aria-label":h.chartType,hidden:!U.open,children:M.map(k=>{let K=k.type===Y;return r("button",{type:"button",role:"option","aria-selected":K,class:K?"is-selected":"",onClick:()=>{m(k.type),U.setOpen(!1),U.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:Z.rows??q,columns:_,maxRows:y,expanded:i,classPrefix:t,locale:a,format:L}),Ae=()=>e.tableAvailable===!1||C.length===0?null:Le(e.title?.trim()||h.resultDetails,r(ce,{children:Ie}),P?r("button",{type:"button",class:`${t}-analytics-visualization__download`,onClick:P,children:h.download}):null,h.expandTable);if(q.length===0)return r(ce,{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})]}),fe,p]});if(e.presentation==="table"||!e.presentation&&e.type==="table")return Ae()??r(ce,{children:p});let ge=g&&e.tableAvailable!==!1?r("button",{type:"button",class:`${t}-analytics-visualization__download`,"aria-expanded":T,onClick:()=>F(be=>{let ie=!be;return g.onToggle?.(ie),ie}),children:T?h.hideData:h.viewData}):null,Ze=T?r("div",{class:`${t}-analytics-data`,children:Ie}):null;return e.presentation==="kpi"||!e.presentation&&e.type==="kpi"?Le(h.liveMetric,r(ce,{children:[r(mc,{visualization:e,field:lc(e,C),prefix:t,labels:h,locale:a}),ge,Ze]})):Q?Le(Q.title,r(ce,{children:[r(ac,{model:Q,expanded:i,classPrefix:t}),P?r("button",{type:"button",class:`${t}-analytics-visualization__download`,onClick:P,children:h.downloadData}):null,ge,Ze]}),r(ce,{children:[u?r("div",{class:`${t}-analytics-chart-picker ${t}-analytics-chart-picker--aggregation`,children:r("button",{type:"button",ref:D.triggerRef,"aria-haspopup":"menu","aria-expanded":D.open,"aria-label":h.aggregate,title:h.aggregateTitle,onClick:()=>{U.setOpen(!1),D.setOpen(!D.open)},children:[r("span",{class:`${t}-analytics-chart-picker__current`,children:r("span",{children:h.aggregate})}),r(zi,{})]})}):null,M.length>1?r("div",{class:`${t}-analytics-chart-picker`,children:r("button",{type:"button",ref:U.triggerRef,"aria-haspopup":"listbox","aria-expanded":U.open,"aria-label":h.chooseChartType,title:h.chooseChartType,onClick:()=>{D.setOpen(!1),U.setOpen(!U.open)},children:[r("span",{class:`${t}-analytics-chart-picker__current`,children:[r(Ni,{type:Y??Q.type,className:`${t}-chart-type-icon`}),r("span",{children:X?.label??h.chartFallback})]}),r(zi,{})]})}):null]})):Ae()??r(ce,{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,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 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=["/transcribe","/speak","/attachments","/stream"],Tc=e=>{const t=e.split("?")[0]??e;return $c.some(n=>t.includes(`/public-chat${n}`))||t.endsWith("/public-chat")?Sc:kc},Cc=e=>{const t=e.headers?.get?.("Retry-After"),n=t?Number(t):NaN;return Number.isFinite(n)&&n>=0?n:void 0},Ac=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 Mc{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?Ac(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()},Tc(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=Ec(n)??`request failed (${t.status})`;throw new un(t.status,a,Cc(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)):zc(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,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}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(Ic(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 Ic=(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},Ec=e=>{const t=e?.message;if(Array.isArray(t))return t.join(", ");if(typeof t=="string")return t},zc=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(`
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,u);o=o.slice(u+2);const d=Nc(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=Di(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},Nc=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 Rc=e=>{sr=e},Pi=e=>new Mc(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")}},Lc=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 Dc{constructor(t){B(this,"ratio");B(this,"position",0);B(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 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 Pc=(e,t=cr)=>{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"})},Fi=e=>e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(t=>t.length>1),Oc=(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()},Fc=(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,Uc=()=>{const e=globalThis;if(e.__voiceDebug)return!0;try{return e.localStorage?.getItem("accurix.voiceDebug")==="1"}catch{return!1}};class Bc{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>Bi&&this.entries.splice(0,this.entries.length-Bi),Uc()&&console.debug(`VOICEDBG ${t} ${n?JSON.stringify(n):""}`)}list(){return this.entries.slice()}}const lr=cr/50,it=20,qc=500,Vc=120,jc=300,Hc=280,Wc=600,Gc=300,Kc=12e3,Yc=25e3,Zc=300,Jc=2e4,Xc=60,Qc=400,el=250,dr=8e-4,tl=.1,nl=2.8,al=1.8,rl=.006,il=.004,ol=1.8,sl=1.4,cl=2e3,ll=2e3;class dl{constructor(t){B(this,"options");B(this,"endSilenceMs");B(this,"pending",new Float32Array(0));B(this,"levels",[]);B(this,"framesSinceFloor",0);B(this,"floor",dr*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??ll}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 g=t[p]??0;n+=g*g,a=Math.max(a,Math.abs(g))}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(rl,this.floor*nl)*(s?ol:1),u=Math.max(il,this.floor*al)*(s?sl:1),l=i>=c,d=i>=u;if(!o?.capturing){for(this.preroll.push(t);this.preroll.length*it>qc;)this.preroll.shift();this.recentSpeech.push(l);const p=(s?Wc:jc)/it;for(;this.recentSpeech.length>p;)this.recentSpeech.shift();const g=this.recentSpeech.filter(Boolean).length*it;g>=(s?Hc:Vc)&&this.beginCapture(g);return}o.chunk.push(t),o.chunkMs+=it,o.durationMs+=it,l&&(o.voicedMs+=it,o.chunkVoicedMs+=it),o.quietMs=d?0:o.quietMs+it,s&&(o.overlappedOutput=!0),o.quietMs>=this.endSilenceMs?this.endTurn(o,"silence"):(o.chunkMs>=Yc||o.chunkMs>=Kc&&o.quietMs>=Zc||o.chunkMs>=Jc&&o.quietMs>=Xc)&&this.cutChunk(o)}trackFloor(t){if(this.levels.push(t),this.levels.length>el&&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*tl)]??dr)}trackInputSilence(t){this.silentMs=t===0?this.silentMs+it:0;const n=this.silentMs>=cl;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*it,a.durationMs+=this.preroll.length*it,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-Qc)/it));if(a>0&&(t.chunk.splice(t.chunk.length-Math.min(a,t.chunk.length)),t.chunkMs=t.chunk.length*it),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<Gc){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*it,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:Pc(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 ul=2048,pl=[300,1e3,2500],fl=()=>typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof globalThis.AudioContext=="function",hl=e=>{const t=e?.name;return t==="NotAllowedError"||t==="SecurityError"?"permission-denied":t==="NotFoundError"||t==="OverconstrainedError"?"no-device":"error"};class qi{constructor(t){B(this,"options");B(this,"log",new Bc);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 dl({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??(fl()?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=hl(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 Dc(n.sampleRate),this.source=n.createMediaStreamSource(t),this.processor=n.createScriptProcessor(ul,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=pl[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()),ml=(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?.()},vt={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,gl=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"}},bl=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}$/,ma=(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)=>ma(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 ma(a,t.locale,o?i:{...i,month:"short",day:"numeric"},t.timezone)},vl=(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:ma(o,t,{day:"numeric",month:"short",year:"numeric"},"UTC")}const i=new Date(a);return Number.isNaN(i.getTime())?a:ma(i,t,{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1},n)},xl=(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}`:""},yl=(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"}},Ke=(e,t)=>t(String(e??"").replace(/\s+/g," ").trim()).trim(),Zi=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e.toLocaleString(t):"",_l=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},wl=(e,t={})=>{const{locale:n}=t,a={...vt,...t.copy},i=t.cleanText??(_=>_),o=e.timezone?.trim()||void 0,s=new Map;for(const _ of e.evidenceItems??[])_?.id?.trim()&&!s.has(_.id.trim())&&s.set(_.id.trim(),_);const c=[],u={},l=_=>{const L=_?.trim();if(!L)return;const $=u[L];if($)return{id:L,index:$.index};const P=s.get(L);if(!P)return;const fe=P.valueStatus,oe=ji(fe)||(fe==="observed"?"observed":""),Ue=P.source?.kind,ke={id:L,index:c.length+1,text:Ke(P.text,i),...P.metric?.trim()?{metric:P.metric.trim()}:{},...P.period?.label?.trim()?{periodLabel:P.period.label.trim()}:{},...(()=>{const Ce=xl(P.period,{locale:n,timezone:o});return Ce?{periodRange:Ce}:{}})(),...P.period?.timezone?.trim()||o?{timezone:P.period?.timezone?.trim()||o}:{},...P.filters?.length?{filters:P.filters.map(Ce=>Ce.trim()).filter(Boolean)}:{},...(()=>{const Ce=Zi(P.value,n);return Ce?{valueText:Ce}:{}})(),...oe?{statusLabel:oe}:{},statusTone:Hi(fe),...P.statusReason?.trim()?{statusReason:Ke(P.statusReason,i)}:{},...Ue==="card"?{sourceLabel:vt.sourceCard}:Ue==="supporting_query"?{sourceLabel:vt.sourceSupportingQuery}:{},sourceTargets:_l(P.source),...(()=>{const Ce=Ki(P.checkedAt??e.checkedAt,{locale:n,timezone:o,now:t.now});return Ce?{checkedText:Ce}:{}})()};return ke.filters&&ke.filters.length===0&&delete ke.filters,c.push(ke),u[L]=ke,{id:L,index:ke.index}},d=_=>{const L=new Set,$=[];for(const P of _??[]){const fe=l(P);fe&&!L.has(fe.id)&&(L.add(fe.id),$.push(fe))}return $},p=gl(e.source)||e.level==="detailed",g=Ke(e.headline,i)||Ke(e.summary,i),f={text:g,citations:d(e.headlineEvidenceIds)},y=Ke(e.summary,i),h=y&&y!==g?{text:y,citations:d(e.summaryEvidenceIds)}:void 0;if(!h&&y&&e.summaryEvidenceIds?.length)for(const _ of d(e.summaryEvidenceIds))f.citations.some(L=>L.id===_.id)||f.citations.push(_);const I=(e.periods??[]).filter(_=>_?.label?.trim()).map(_=>{const L=_.valueStatus,$=ji(L),P=_.valueText?.trim()||Zi(_.value,n)||(L==="missing"?"—":""),fe=$?_.statusReason?.trim()||s.get(_.evidenceId?.trim()??"")?.statusReason?.trim():"",oe=l(_.evidenceId);return{key:_.evidenceId||`${_.label}-${_.start??""}-${_.end??""}`,label:_.label.trim(),valueText:P,...L?{status:L}:{},statusLabel:$,statusTone:Hi(L),inProgress:!!_.inProgress,current:!!_.current,...fe?{reason:Ke(fe,i)}:{},...oe?{citation:oe}:{}}}),x=t.maxConclusions??4,m=(e.evidenceStatements??[]).map(_=>({text:Ke(_.text,i),citations:d(_.evidenceIds)})).filter(_=>_.text),T=(m.length>0?m:(e.evidence??[]).map(_=>Ke(_,i)).filter(Boolean).map(_=>({text:_,citations:[]}))).filter((_,L,$)=>$.findIndex(P=>P.text===_.text)===L).filter(_=>_.text!==f.text&&_.text!==h?.text).slice(0,x),F=Ke(e.businessMeaning,i),M=F?{text:F,citations:d(e.businessMeaningEvidenceIds)}:void 0,Q=[],Y=_=>{_.text&&!Q.some(L=>L.text===_.text)&&Q.push(_)},X=(e.limitations??[]).map(_=>_.toLowerCase());for(const _ of I){const L=X.some($=>$.includes(_.label.toLowerCase())&&$.includes("in progress"));_.inProgress&&!L&&Y({kind:"in_progress",text:`${_.label} is still in progress, so its total can still change.`,..._.citation?{citation:_.citation}:{}}),(_.status==="empty_bucket"||_.status==="unconfirmed_zero")&&Y({kind:"no_records",text:`${_.label} has no records yet. This is not a confirmed 0${_.reason?`: ${_.reason.replace(/\.$/,"")}`:""}.`,..._.citation?{citation:_.citation}:{}}),_.status==="missing"&&Y({kind:"missing",text:`${_.label} is missing${_.reason?`: ${_.reason.replace(/\.$/,"")}`:""}.`,..._.citation?{citation:_.citation}:{}})}e.currentPeriodInProgress&&!I.some(_=>_.inProgress)&&Y({kind:"in_progress",text:"The current period is still in progress, so its total can still change."});for(const _ of e.missing??[]){if(!_?.label?.trim()||!_.reason?.trim())continue;const L=l(_.evidenceId);Y({kind:"missing",text:kl(_),...L?{citation:L}:{}})}(e.dataFreshness?.status==="delayed"||e.dataFreshness?.status==="no_data")&&Y({kind:"freshness",text:yl(e.dataFreshness,e.checkedAt,n).description});for(const _ of e.limitations??[]){const L=Ke(_,i);L&&Y({kind:"limitation",text:L})}const j=(e.possibleDrivers??[]).map(_=>({title:Ke(_.hypothesis,i),howToCheck:Ke(_.howToCheck,i),citations:d(_.evidenceIds)})).filter(_=>_.title).slice(0,t.maxCauses??3),U=(e.recommendations??[]).map(_=>({title:Ke(_.action,i),why:Ke(_.why,i),..._.successMetric?.trim()?{watch:Ke(_.successMetric,i)}:{},citations:d(_.evidenceIds)})).filter(_=>_.title).slice(0,t.maxRecommendations??3),D=Ke(e.forecast?.text,i),q=D?{badge:bl(e.forecast?.qualityStatus),text:D,...e.forecast?.limitations?.trim()?{note:Ke(e.forecast.limitations,i)}:{}}:void 0,C=(e.followUps??[]).map(_=>Ke(_,i)).filter(Boolean).filter((_,L,$)=>$.indexOf(_)===L).slice(0,t.maxFollowUps??4);for(const _ of s.keys())l(_);const Z=Ke(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,...Z?{preface:Z}:{},headline:f,...h?{summary:h}:{}},comparison:I,conclusions:T,...M?{businessMeaning:M}:{},limits:Q,checkedLine:vl(e,{locale:n,now:t.now}),investigate:{causes:j,recommendations:U,...q?{outlook:q}:{},followUps:C},hasInvestigate:j.length>0||U.length>0||!!q||C.length>0||c.length>0,evidence:c,evidenceById:u,sourceNote:p?a.sourceNoteAI:a.sourceNoteGoverned}},kl=e=>`${e.label.trim()} could not be established: ${e.reason.trim()}`,Sl=e=>`[${e.index}]`,$l=(e,t)=>{const n={...vt,...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},Tl=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}:{}}},Cl=(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,20 +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 Al{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(Tl({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:vt.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",Ml=e=>fr(e?.aiExplanation?.status);class Il{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,"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:Ji.delaysMs,this.capMs=i.capMs??Ji.capMs,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=Ml(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:vt.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:vt.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:vt.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:vt.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(vt),Nn=()=>Ga(Xi),El=(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:(g,f)=>n.current.poll(g,f),...d.retry?{retry:(g,f)=>n.current.retry(g,f)}:{}}:void 0;return new Il(e,p,g=>a.current(g),{onSettled:g=>n.current?.settled?.(i,g)})},[i,o,!!t]),[c,u]=S(s.state);return J(()=>(a.current=u,u(s.state),s.start(),()=>s.dispose()),[s]),[c.status==="ready"?c:{...c,explanation:e},s]},zl=({prefix:e,state:t,onRetry:n})=>{const a=Nn();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})]})},Nl=({citations:e,step:t,prefix:n,active:a,onToggle:i,evidenceById:o})=>{const s=Nn();return e.length===0?null:r(ce,{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:Sl(c).slice(1,-1)},c.id)})})},Rl=(e,t)=>e.sourceTargets.find(n=>t?t(n):!0),Ll=({evidence:e,prefix:t,onClose:n,onOpenSource:a,canOpenSource:i})=>{const o=Nn(),s=R(null);J(()=>{s.current?.focus()},[e.id]);const c=a?Rl(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:$l(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]})},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"})}),Dl=(e,t,n)=>t==="wrong_numbers"?e.reasonWrongNumbers:t==="missing_comparison"?e.reasonMissingComparison:t==="unclear"?e.reasonUnclear:t==="too_long"?e.reasonTooLong:n,Pl=({prefix:e,explanationId:t,submit:n,context:a})=>{const i=Nn(),[o,s]=S({phase:"idle",reasons:[],comment:""}),c=qe(()=>new Al(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(Qi,{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(Qi,{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}),Vi.map(l=>r("button",{type:"button",class:`${e}-xp__reason`,"aria-pressed":o.reasons.includes(l.id),onClick:()=>c.toggleReason(l.id),children:Dl(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:u,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]=El(t.explanation,e),i=Ol(t.explanation),o=qe(()=>({...vt,...t.copy}),[t.copy]);return r(Xi.Provider,{value:o,children:r(Fl,{...t,explanation:n.explanation,aiStatus:i?r(zl,{prefix:t.classPrefix,state:n,onRetry:()=>{a.retry()}}):null})})},Ol=e=>!!(e.aiExplanation&&e.aiExplanation.status!=="not_requested"),Fl=({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:g=!1,...f})=>{const y=Nn(),h=R(null),I=R(null),x=R(!1),m=()=>{const C=h.current,Z=C?.getRootNode(),_=Z&&"activeElement"in Z?Z.activeElement:null;return!!(C&&_&&C.contains(_))},T=qe(()=>(x.current=m(),wl(e,{...f,copy:y})),[e,f.locale,f.cleanText,y]),[F,M]=S(),Q=R(null);$n(()=>{!F||T.evidenceById[F.id]&&h.current?.querySelector('[data-testid="analytics-explanation-evidence"]')||(M(void 0),x.current&&!m()&&(I.current??h.current)?.focus())},[T]);const Y=(C,Z,_)=>{Q.current=_,M(L=>L?.id===C&&L.step===Z?void 0:{id:C,step:Z})},X=()=>{M(void 0);const C=Q.current;C?.isConnected?C.focus():(I.current??h.current)?.focus()},j=(C,Z)=>r(Nl,{citations:C,step:Z,prefix:n,active:F,onToggle:Y,evidenceById:T.evidenceById}),U=C=>{if(!F||F.step!==C)return null;const Z=T.evidenceById[F.id];return Z?r(Ll,{evidence:Z,prefix:n,onClose:X,onOpenSource:s,canOpenSource:c}):null},D=(C,Z)=>r(ce,{children:[C.text,j(C.citations,Z)]}),{investigate:q}=T;return r("section",{ref:h,class:`${n}-xp${g?" is-expanded":""}${d||p?" has-expand":""}`,"data-testid":"analytics-explanation","aria-label":y.region,tabIndex:-1,children:[g&&p?r("button",{type:"button",class:`${n}-xp__expand`,"aria-label":y.collapse,title:y.collapse,onClick:p,children:"×"}):d?r("button",{type:"button",class:`${n}-xp__expand`,"aria-label":y.expand,title:y.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:I,tabIndex:-1,children:D(T.lead.headline,"lead")}),T.lead.summary?r("p",{class:`${n}-xp__summary`,children:D(T.lead.summary,"lead")}):null,U("lead")]}):null,t,T.comparison.length>0?r("section",{class:`${n}-xp__step`,"data-step":"comparison",children:[r("h4",{class:`${n}-xp__title`,children:y.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:y.inProgress}):null,C.citation?j([C.citation],"comparison"):null,C.reason?r("small",{class:`${n}-xp__period-reason`,children:C.reason}):null]},C.key))}),U("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:y.conclusions}),T.conclusions.length>0?r("ul",{class:`${n}-xp__list`,children:T.conclusions.map(C=>r("li",{children:D(C,"conclusions")},C.text))}):null,T.businessMeaning?r("p",{class:`${n}-xp__meaning`,children:[r("strong",{children:[y.whyItMatters,": "]}),D(T.businessMeaning,"conclusions")]}):null,U("conclusions")]}):null,T.limits.length>0?r("section",{class:`${n}-xp__step`,"data-step":"limits",children:[r("h4",{class:`${n}-xp__title`,children:y.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?j([C.citation],"limits"):null]},C.text))}),U("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:y.investigate}),r("div",{class:`${n}-xp__investigate-body`,children:[q.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:y.causes}),r("span",{class:`${n}-xp__hint`,children:y.causesHint})]}),q.causes.map(C=>r("article",{class:`${n}-xp__card`,children:[r("p",{class:`${n}-xp__card-title`,children:[C.title,j(C.citations,"investigate")]}),C.howToCheck?r("p",{class:`${n}-xp__card-body`,children:[y.howToCheck," ",C.howToCheck]}):null]},C.title))]}):null,q.recommendations.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:y.recommendations}),q.recommendations.map(C=>r("article",{class:`${n}-xp__card`,children:[r("p",{class:`${n}-xp__card-title`,children:[C.title,j(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:[y.watch," ",C.watch]}):null]},C.title))]}):null,q.outlook?r("div",{class:`${n}-xp__group`,children:[r("div",{class:`${n}-xp__group-head`,children:[r("h4",{class:`${n}-xp__title`,children:y.outlook}),r("span",{class:`${n}-xp__hint`,children:q.outlook.badge})]}),r("p",{class:`${n}-xp__card-body`,children:q.outlook.text}),q.outlook.note?r("p",{class:`${n}-xp__card-body`,children:q.outlook.note}):null]}):null,o&&q.followUps.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:y.followUps}),r("div",{class:`${n}-xp__questions`,children:q.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:y.evidenceList}),r("ul",{class:`${n}-xp__list`,children:T.evidence.map(C=>r("li",{children:[C.text,j([{id:C.id,index:C.index}],"investigate")]},C.id))})]}):null,U("investigate")]})]}):null,r("p",{class:`${n}-xp__source`,children:T.sourceNote}),u&&T.explanationId?r(Pl,{prefix:n,explanationId:T.explanationId,submit:u,context:l}):null]})},Ul=[{name:"Smileys",emojis:["😀","😃","😄","😁","😅","😂","🤣","😊","😇","🙂","🙃","😉","😌","😍","🥰","😘","😋","😛","😜","🤪","🤗","🤭","🤔","🤐","😐","😶","😏","🙄","😴","🥳","😎","🤓","🥺","😢","😭","😤","😠","🤯","😬","😱","🤩","🥱"]},{name:"Gestures",emojis:["👍","👎","👌","🤌","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","👇","✋","🖐️","👋","🤝","🙏","💪","👏","🙌","👐","🤲","🫶"]},{name:"Hearts & symbols",emojis:["❤️","🧡","💛","💚","💙","💜","🖤","🤍","💔","❣️","💕","💖","💘","💝","✨","⭐","🌟","💫","🔥","🎉","🎊","✅","❌","⚡","💯","🚀"]},{name:"Animals & nature",emojis:["🐶","🐱","🦊","🐻","🐼","🐨","🦁","🐮","🐸","🐵","🐧","🦄","🐝","🦋","🐢","🐬","🌷","🌸","🌹","🌻","🌳","🍀"]},{name:"Food & drink",emojis:["🍎","🍌","🍉","🍓","🍒","🥑","🍔","🍟","🍕","🌮","🍿","🍩","🍪","🎂","☕","🍵","🍺","🥂","🍷"]},{name:"Objects & travel",emojis:["🚀","✈️","🚗","🏠","📦","📱","💻","⌚","📷","💡","🔑","🎁","📌","✏️","📝","📞","📧","💰","📈","⏰","🔔","🎯","🏆","🎮","🎵","💬","👀"]}],ga={"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:"Requested for {when} — we’ll confirm by email.",bookingVerificationPending:"We received your request for {when}, but could not verify the calendar booking. Check your email; the team will follow up. Please do not book this time again.",bookingCallbackRequested:"Callback requested for {when}.",bookingCallbackConfirmed:"Your callback is scheduled for {when}.",bookingConfirmed:"You’re booked for {when}! A calendar invite is on its way. 📅",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. A calendar invitation has been sent to your email.",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:"Your booking is in Calendly, but we could not load the meeting link. Check your calendar invitation or try again.",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})}`,Bl=e=>e?{...hr,...e}:hr,to=Ha(hr),ql=to.Provider,no=Ha(void 0),Vl=no.Provider,mr=()=>Ga(no),jl=new Set(["ar","he","iw","fa","ur","ps","sd","ug","yi","dv","ckb"]),Hl=(e,t)=>{if(t==="ltr"||t==="rtl")return t;const n=(e??"").trim().toLowerCase().split(/[-_]/)[0]??"";return jl.has(n)?"rtl":"ltr"},ot=()=>Ga(to),en=[["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(""),Wl=()=>{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 en.find(t=>t.iso===e)??en.find(t=>t.iso==="US")},Gl=e=>{const t=Wl(),n=e?.trim()??"";if(!n.startsWith("+"))return{country:t,national:n.replace(/\D/g,"")};const a=n.replace(/\D/g,""),i=[...en].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}`:""},Kl=e=>{const t=e.replace(/\D/g,"");return e.startsWith("+")&&t.length>=8&&t.length<=15},Te=(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}),Yl=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=>Te(r("path",{d:"m6 9 6 6 6-6"}),e),Zl=e=>Te(r(ce,{children:[r("path",{d:"m22 2-7 20-4-9-9-4Z"}),r("path",{d:"M22 2 11 13"})]}),e),Ln=e=>Te(r(ce,{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),Jl=e=>Te(r(ce,{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=>Te(r(ce,{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),Xl=e=>Te(r(ce,{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=>Te(r(ce,{children:[r("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),r("path",{d:"m22 7-10 5L2 7"})]}),e),Ql=e=>Te(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=>Te(r(ce,{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),ed=e=>Te(r(ce,{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),td=e=>Te(r(ce,{children:[r("path",{d:"M3 4h18M4 4v12h16V4M12 16v5M8 21h8"}),r("path",{d:"m8 12 2.5-2.5 2 2L16 8"})]}),e),nd=e=>Te(r(ce,{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),ad=e=>Te(r(ce,{children:[r("path",{d:"M4 4h16v16H5a3 3 0 0 1-3-3V6"}),r("path",{d:"M8 8h8M8 12h8M8 16h5"})]}),e),rd=e=>Te(r(ce,{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=>Te(r(ce,{children:[r("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),e),id=e=>Te(r(ce,{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),od=e=>Te(r(ce,{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=>Te(r("path",{d:"M20 6 9 17l-5-5"}),e),sd=e=>Te(r(ce,{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),cd=e=>Te(r(ce,{children:[r("path",{d:"M1 4v6h6"}),r("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"})]}),e),ld=e=>Te(r("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"}),e),ba=e=>Te(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=>Te(r(ce,{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),dd=e=>Te(r(ce,{children:[r("circle",{cx:"12",cy:"12",r:"9"}),r("path",{d:"M12 7v5l3 2"})]}),e),oo=e=>Te(r(ce,{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=>Te(r(ce,{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),ud=e=>Te(r(ce,{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),pd=e=>Te(r(ce,{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),fd=e=>Te(r(ce,{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),hd=e=>Te(r(ce,{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),md=e=>Te(r(ce,{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,gd=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,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},bd=/^(```|#{1,6}\s|\s*[-*•]\s|\s*\d+\.\s)/,vd=(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)},xd=e=>{const t=gd(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
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(vd(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()!==""&&!bd.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},va=e=>ml(e),lo=()=>{const e=R(null);return J(()=>{const t=requestAnimationFrame(()=>e.current?.scrollIntoView?.({block:"end"}));return()=>cancelAnimationFrame(t)},[]),e},yd=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}`:""},_d={"support-guide":"SG","sales-host":"SH","calm-advisor":"CA","technical-guide":"TG","school-desk":"SD","front-office":"FO"},xa=e=>{const t=e?.avatarId?.trim().toLowerCase();return t&&_d[t]||(e?yd(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}${On(e)}`,children:xa(e)})},wd=()=>{const e=ot(),[t,n]=S(0),a=["Understanding your question","Checking approved information","Preparing your answer"];return J(()=>{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"})]})},kd=3,Sd=({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,kd),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"]})]})},$d=({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,Td=({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:g=!1,micLevel:f=0,theaterMode:y=!1,onToggleTheater:h,onMinimize:I,audioDevices:x=[],selectedAudioDeviceId:m="",onSelectAudioDevice:T,connectingOnly:F=!1})=>{if(!e)return null;const M=!!(e.allowVoiceInput&&e.talkbackMode&&e.talkbackMode!=="text");if(!(M||e.widgetModule==="assistant"))return null;const Y=e.agentAvatarUrl?.trim()||"",X=e.assistantMediaUrl?.trim()||Y,j=e.assistantMediaKind==="video"&&!!X,U=t.slice(0,3),D=o!=="idle",q=o!=="idle"?"End voice chat":`Speak with ${e.agentName}`,C=c&&M&&!D&&!i,Z=o==="connecting"||o==="processing"||D&&s,_=["cf-assistant-card__stage","cf-assistant-card__stage--local",D?"is-live":"",Z?"is-thinking":"",mn(o)&&!u?"is-listening":"",i||o==="speaking"?"is-speaking":"",u?"is-muted":""].filter(Boolean).join(" "),L=mn(o)&&!u?{"--cf-listen":String(Math.max(.18,Math.min(1,f*8)))}:void 0,$=Z&&r("span",{class:"cf-call-ripple","aria-hidden":"true",children:[r("span",{}),r("span",{}),r("span",{})]});if(F)return r("div",{class:"cf-assistant-card cf-assistant-card--connecting","aria-live":"polite",children:[r("div",{class:"cf-assistant-card__connecting-avatar",children:[Y?r("img",{src:Y,alt:""}):r("span",{class:`cf-assistant-card__connecting-face${On(e)}`,children:xa(e)}),$]}),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 P=D&&d&&r(tu,{voiceState:o,muted:u,onToggleMute:l??(()=>{}),onEndCall:d,onTalkNow:p??(()=>{}),showTalkNow:g,micLevel:f,theaterMode:y,onToggleTheater:h??(()=>{}),onMinimize:I??(()=>{}),audioDevices:x,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:[Y?r("span",{class:"cf-assistant-card__compact-avatar",children:r("img",{src:Y,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:q})]})}):r("div",{class:`cf-assistant-card ${c?"cf-assistant-card--pinned":""} ${i?"is-speaking":""}`,children:[(X||M)&&r("div",{class:_,style:L,children:[r("div",{class:`cf-assistant-card__media ${X?"cf-assistant-card__media--uploaded":"cf-assistant-card__media--generated"}${On(e)}`,children:[j?r("video",{src:X,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):X?r("img",{src:X,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:xa(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"})]})}),X&&!j&&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",{})]})]}),$,D&&r("span",{class:"cf-call-status",role:"status","aria-live":"polite",children:xr(o)}),M&&(P||r("button",{type:"button",class:"cf-assistant-card__speak",onClick:a,children:[r(Ln,{}),q]}))]}),!c&&r(ce,{children:[e.agentDescription?r("p",{class:"cf-assistant-card__copy",children:e.agentDescription}):r("p",{class:"cf-assistant-card__copy",children:e.greeting}),U.length>0&&r("div",{class:"cf-assistant-card__chips",children:U.map(fe=>r("button",{type:"button",class:"cf-assistant-card__chip",onClick:()=>n(fe),children:fe},fe))}),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(ce,{children:[" ",r("a",{href:e.assistantPrivacyUrl,target:"_blank",rel:"noopener noreferrer nofollow",children:"Privacy Policy"})]}):null]}):null]})]})},Cd={calendar:Xl,"calendar-clock":nd,headset:io,mail:gr,message:ed,newsletter:ad,phone:Ql,presentation:td,lifebuoy:io},Ad=e=>Cd[e]??gr,Md=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"}},Id={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"}},Ed=(e,t,n={})=>Array.isArray(e)?e.filter(a=>a.readiness!=="unavailable").map(a=>po(a,n[a.id])):(t??[]).flatMap(a=>{const i=Id[a];if(!i)return[];const o=Md({...i,id:a}),s=ga[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]}))}},zd=(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)})}`},fo=({label:e,required:t,value:n,onInput:a})=>{const i=qe(()=>Gl(n),[]),[o,s]=S(i.country.iso),[c,u]=S(i.national),[l,d]=S(!1),[p,g]=S(""),f=R(null),y=en.find(x=>x.iso===o)??i.country,h=qe(()=>{const x=p.trim().toLowerCase().replace(/^\+/,"");return x?en.filter(m=>m.name.toLowerCase().includes(x)||m.iso.toLowerCase().includes(x)||m.dial.includes(x)):en},[p]);J(()=>{if(!l)return;const x=T=>{f.current&&!T.composedPath().includes(f.current)&&d(!1)},m=T=>{T.key==="Escape"&&d(!1)};return document.addEventListener("pointerdown",x),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",x),document.removeEventListener("keydown",m)}},[l]);const I=x=>{const m=en.find(T=>T.iso===x)??y;s(m.iso),d(!1),g(""),a(ro(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":`${y.name}, +${y.dial}. Choose country and calling code`,"aria-haspopup":"listbox","aria-expanded":l,onClick:()=>d(x=>!x),children:[r("span",{"aria-hidden":"true",children:ao(y.iso)}),r("span",{class:"cf-phone__country-code",children:["+",y.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 m=x.target,T=m.value.replace(/\D/g,"");m.value=T,u(T),a(ro(y,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=>g(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===y.iso?"is-selected":""}`,role:"option","aria-selected":x.iso===y.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]})},Nd=({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})},Rd=({spec:e,visitor:t,onSubmit:n,onCancel:a})=>{const i=ot(),o=lo(),[s,c]=S(()=>{const x={};for(const m of e.fields)m.identity&&t[m.identity]&&(x[m.key]=t[m.identity]);return x}),[u,l]=S("idle"),[d,p]=S(""),g=x=>!!(x.identity&&t[x.identity]?.trim()),f=e.fields.filter(x=>!g(x)),y=f.every(x=>!x.required||(s[x.key]?.trim()??"")!==""),h=t.email||t.name||"",I=async()=>{if(!y||u==="submitting")return;l("submitting");const x={},m={};for(const T of e.fields){const F=s[T.key]?.trim();F&&(x[T.key]=F,T.identity&&(m[T.identity]=F))}try{const T=await n(x,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&&h&&r("div",{class:"cf-form__as",children:Ve(i.actionAs,{identity:h})}),f.map(x=>r(Nd,{field:x,value:s[x.key]??"",onInput:m=>c(T=>({...T,[x.key]:m}))},x.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:!y||u==="submitting",onClick:I,children:u==="submitting"?i.sending:e.submit})]})]})},ho=e=>String(e).padStart(2,"0"),Ld=()=>{const e=[];for(let t=9;t<=17;t++)e.push(`${ho(t)}:00`),e.push(`${ho(t)}:30`);return e},Dd=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})},Pd=(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}`}},zt=(e,t)=>{const[n,a]=t.split(":").map(Number);return new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,a??0)},Od=(e,t)=>{const n=zt(e,t);try{return new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(n)}catch{return t}},ya=()=>{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}},Fd=(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")},Ud=({actionId:e,fields:t=ga["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?ga["schedule-callback"]:ga["book-demo"],g=u?.trim()||p.title,f=ot(),y=lo(),h=!!(!d&&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)),m=Math.min(60,Math.max(1,c?.availability?.bookingWindowDays??14)),T=qe(()=>Dd(m),[m]),[F,M]=S(null),[Q,Y]=S(x?"loading":"request_only"),[X,j]=S(c?.availability?.slotDurationMinutes??30),[U,D]=S(ya()||c?.availability?.timezone||""),q=qe(()=>x?Q!=="available"||F===null?[]:[...new Set([...F].map(ee=>{const pe=new Date(ee);return`${String(pe.getHours()).padStart(2,"0")}:${String(pe.getMinutes()).padStart(2,"0")}`}))].sort():Ld(),[F,Q,x]),C=qe(()=>{const ee=Date.now();for(let pe=0;pe<T.length;pe++)if(q.some($e=>zt(T[pe],$e).getTime()>ee))return pe;return 0},[T,q]),[Z,_]=S(C),[L,$]=S(null),[P,fe]=S(n.name??""),[oe,Ue]=S(n.email??""),[ke,Ce]=S(n.phone??""),[Le,Ie]=S(""),[Ae,ge]=S("idle"),[Ze,be]=S(""),[ie,Je]=S(!1),[He,k]=S(""),[K,V]=S("scheduler"),[H,ae]=S(null),[ye,Se]=S("idle"),[Qe,Ge]=S(""),[tt,nt]=S(""),[A,he]=S(""),de=R(null),me=async(ee,pe,$e)=>{Se("loading");try{const ue=await s?.(ee,pe,$e),ve=ue?.meetingUrl||ue?.eventLink||"",wt=ue?.rescheduleUrl||ue?.cancelUrl||"";k(ve||wt),V(ve?"meeting":"manage"),Se(ve||wt?"idle":"error")}catch{Se("error")}};J(()=>{if(!Qe)return;const ee=pe=>{if(!Fd(pe,de.current)||pe.data.event!=="calendly.event_scheduled")return;const $e=pe.data.payload,ue=$e?.event?.uri?.trim()||"",ve=$e?.invitee?.uri?.trim()||"";A&&ue&&ve?(ae({eventUri:ue,inviteeUri:ve}),me(A,ue,ve)):Se("error"),Ge(""),be(Rn(f.bookingScheduled,tt,f)),ge("done")};return window.addEventListener("message",ee),()=>window.removeEventListener("message",ee)},[s,tt,A,Qe,f]),J(()=>{if(!x||Q!=="available"||F===null)return;const ee=T.findIndex(pe=>q.some($e=>F.has(zt(pe,$e).getTime())));ee>=0&&_(ee)},[F,Q,T,x,q]);const Fe=!!(!d&&c?.connected&&(c.mode==="link"||c.provider==="calendly")),We=async()=>{if(Ae==="submitting"||Ae==="scheduling"||!n.name?.trim()&&!P.trim()||!n.email?.trim()&&!oe.trim())return;ge("submitting");const ee={};oe.trim()&&(ee.email=oe.trim()),P.trim()&&(ee.name=P.trim());try{const pe=await a({...oe.trim()?{visitorEmail:oe.trim()}:{},...P.trim()?{visitorName:P.trim()}:{}},ee),$e=pe.booking?.schedulingLink||c?.bookingLink||"";if(!$e){ge("error");return}k($e),V("scheduler"),nt(pe.caseReference||""),he(pe.inquiryId||""),Ge(mo($e,{name:P.trim()||n.name,email:oe.trim()||n.email})),ge("scheduling")}catch{ge("error")}},[pt,dt]=S(new Set),[xt,Nt]=S([]),[yt,jn]=S(0),[tn,at]=S(!1);J(()=>{if(!o)return;let ee=!0;const pe=new Date,$e=new Date;return $e.setDate($e.getDate()+m+1),o(pe.toISOString(),$e.toISOString()).then(ue=>{if(ee)if(dt(new Set(ue.taken.map(ve=>Date.parse(ve)).filter(ve=>!Number.isNaN(ve)))),Nt(ue.busy.map(ve=>[Date.parse(ve.start),Date.parse(ve.end)]).filter(([ve,wt])=>!Number.isNaN(ve)&&!Number.isNaN(wt))),j(ue.slotDurationMinutes??30),D(ya()||ue.timezone||""),x){if(ue.status!=="available"||!Array.isArray(ue.available)){M(null),Y("unavailable");return}M(new Set(ue.available.map(ve=>Date.parse(ve)).filter(ve=>!Number.isNaN(ve)))),Y("available")}else Y(ue.status??"request_only")}).catch(()=>{!ee||!x||(M(null),Y("unavailable"))}),()=>{ee=!1}},[m,x,o,yt]);const Rt=!!n.email?.trim(),bn=!!n.name?.trim(),qt=!!n.phone?.trim(),ft=ke,Vt=!!L&&(!x||Q==="available")&&(bn||P.trim()!=="")&&(d?qt||Kl(ft):Rt||oe.trim()!==""),Lt=(d?n.phone||n.name:n.email||n.name)||"",nn=ee=>t.find(pe=>pe.key===ee),_t=nn("visitorPhone"),Xe=nn("topic"),Dt=ee=>pt.has(zt(T[Z],ee).getTime()),ht=ee=>zt(T[Z],ee).getTime()<=Date.now(),Pt=X*60*1e3,jt=ee=>{const pe=zt(T[Z],ee).getTime(),$e=pe+Pt;return xt.some(([ue,ve])=>pe<ve&&$e>ue)},Hn=ee=>!x||F?.has(zt(T[Z],ee).getTime())===!0,Wn=async()=>{if(!Vt||Ae==="submitting"||!L)return;ge("submitting"),at(!1);const ee=zt(T[Z],L),pe=Pd(T[Z],L),$e={};P.trim()&&($e.name=P.trim()),d?ft&&($e.phone=ft):oe.trim()&&($e.email=oe.trim());try{const ue=await a(d?{bestTime:pe,slotAt:ee.toISOString(),visitorTimezone:ya()||"UTC",...ft?{visitorPhone:ft}:{},...P.trim()?{visitorName:P.trim()}:{},...Le.trim()?{topic:Le.trim()}:{}}:{preferredAt:pe,slotAt:ee.toISOString(),visitorTimezone:ya()||"UTC",...oe.trim()?{visitorEmail:oe.trim()}:{},...P.trim()?{visitorName:P.trim()}:{}},$e);if(!d&&ue.booking?.mode==="link"&&ue.booking.schedulingLink?.trim()){const ve=ue.booking.schedulingLink.trim();k(ve),nt(ue.caseReference||""),he(ue.inquiryId||""),Ge(mo(ve,{name:P.trim()||n.name,email:oe.trim()||n.email})),ge("scheduling");return}ue.booking?.confirmed?(be(Rn(ue.note||Ve(d?f.bookingCallbackConfirmed:f.bookingConfirmed,{when:pe}),ue.caseReference,f)),k(ue.booking.meetingUrl||ue.booking.rescheduleUrl||ue.booking.cancelUrl||ue.booking.eventLink||""),V(ue.booking.meetingUrl||ue.booking.eventLink?"meeting":"manage")):ue.booking?.verificationPending?(Je(!0),be(Rn(ue.note||Ve(f.bookingVerificationPending,{when:pe}),ue.caseReference,f))):be(Rn(ue.note||Ve(d?f.bookingCallbackRequested:f.bookingRequested,{when:pe}),ue.caseReference,f)),ge("done")}catch(ue){ue?.status===409?(dt(ve=>new Set(ve).add(ee.getTime())),$(null),at(!0),jn(ve=>ve+1),ge("idle")):ge("error")}},vn=()=>{Ge(""),ge("idle"),i?.()};return Ae==="scheduling"&&Qe?r("div",{class:"cf-scheduler-overlay",role:"dialog","aria-modal":"true","aria-label":g,children:[r("header",{class:"cf-scheduler-overlay__head",children:[r("button",{type:"button",class:"cf-scheduler-overlay__back",onClick:vn,children:f.bookingBackToChat}),r("strong",{children:g}),r("div",{class:"cf-scheduler-overlay__tools",children:[r("a",{href:He,target:"_blank",rel:"noopener noreferrer",children:[f.bookingOpenNewTab," ",r(Dn,{})]}),r("button",{type:"button","aria-label":f.bookingCloseScheduler,onClick:vn,children:r(Pn,{})})]})]}),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:Qe,title:g,allow:"camera; microphone; fullscreen; payment"})]})]}):Ae==="done"?r("div",{class:`cf-form cf-form--done${ie?" cf-form--pending":""}`,role:ie?"alert":"status",children:[!ie&&r(fn,{}),r("span",{children:Ze}),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}),H&&A&&s&&r("button",{type:"button",class:"cf-booking__back",onClick:()=>{me(A,H.eventUri,H.inviteeUri)},children:f.bookingRetryDetails})]}),He&&r("a",{class:"cf-booking__link",href:He,target:"_blank",rel:"noopener noreferrer",children:[K==="meeting"?f.bookingMeetingLink:K==="manage"?f.bookingManageLink:f.bookingOpenScheduler," ",r(Dn,{}),r("span",{class:"cf-booking__url",children:He})]}),i&&r("button",{type:"button",class:"cf-booking__back",onClick:i,children:f.bookingBackToChat})]}):Fe?r("div",{class:"cf-form cf-booking",ref:y,children:[r("div",{class:"cf-booking__hint",children:Ve(f.bookingViaProvider,{provider:c?.label??f.bookingSchedulerFallback})}),Rt?Lt?r("div",{class:"cf-form__as",children:Ve(f.actionAs,{identity:Lt})}):null:r(ce,{children:[!n.name?.trim()&&r("input",{class:"cf-form__input",type:"text",placeholder:`${f.handoffName} *`,value:P,"aria-label":f.handoffName,onInput:ee=>fe(ee.target.value)}),r("input",{class:"cf-form__input",type:"email",placeholder:`${f.handoffEmail} *`,value:oe,"aria-label":f.handoffEmail,onInput:ee=>Ue(ee.target.value)})]}),Ae==="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:Ae==="submitting"||!n.name?.trim()&&P.trim()===""||!Rt&&oe.trim()==="",onClick:We,children:Ae==="submitting"?f.sending:f.bookingOpenScheduler})]})]}):r("div",{class:"cf-form cf-booking",ref:y,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(X)})}),U?` · ${Ve(f.bookingTimezone,{timezone:U})}`:""]}),x&&Q==="loading"?r("div",{class:"cf-booking__state",role:"status",children:f.bookingCheckingAvailability}):null,x&&Q==="unavailable"?r("div",{class:"cf-form__err",role:"alert",children:f.bookingAvailabilityUnavailable}):null,x&&Q==="available"&&q.length===0?r("div",{class:"cf-booking__state",role:"status",children:f.bookingNoSlots}):null,q.length>0?r("div",{class:"cf-booking__dates",role:"tablist","aria-label":f.bookingPickDay,children:T.map((ee,pe)=>r("button",{type:"button",role:"tab","aria-selected":pe===Z,disabled:x&&Q==="available"&&!q.some($e=>F?.has(zt(ee,$e).getTime())),class:`cf-booking__date ${pe===Z?"is-selected":""}`,onClick:()=>{_(pe),$(null)},children:[r("span",{class:"cf-booking__dow",children:ee.toLocaleDateString(void 0,{weekday:"short"})}),r("span",{class:"cf-booking__dom",children:ee.getDate()})]},pe))}):null,q.length>0?r("div",{class:"cf-booking__slots",role:"listbox","aria-label":f.bookingPickTimeLabel,children:q.map(ee=>{const pe=ht(ee),$e=jt(ee),ue=Dt(ee),ve=Hn(ee),wt=ue||pe||$e||!ve;return r("button",{type:"button",role:"option","aria-selected":L===ee,disabled:wt,title:pe?f.bookingEarlierToday:$e?f.bookingCalendarBusy:ue?f.bookingAlreadyBooked:ve?void 0:f.bookingNotOffered,class:`cf-booking__slot ${L===ee?"is-selected":""} ${wt?"is-taken":""}`,onClick:()=>$(ee),children:Od(T[Z],ee)},ee)})}):null,tn&&r("div",{class:"cf-form__err",children:f.bookingSlotTaken}),Lt?r("div",{class:"cf-form__as",children:Ve(f.actionAs,{identity:Lt})}):null,!bn&&r("input",{class:"cf-form__input",type:"text",placeholder:`${f.handoffName} *`,value:P,"aria-label":f.handoffName,onInput:ee=>fe(ee.target.value)}),d&&!qt&&r(fo,{label:_t?.label??"Phone number",required:!0,value:ke,onInput:Ce}),d&&Xe?r("input",{class:"cf-form__input",type:"text",placeholder:Xe.placeholder||Xe.label,value:Le,"aria-label":Xe.label,onInput:ee=>Ie(ee.target.value)}):null,!d&&!Rt&&r(ce,{children:r("input",{class:"cf-form__input",type:"email",placeholder:`${f.handoffEmail} *`,value:oe,"aria-label":f.handoffEmail,onInput:ee=>Ue(ee.target.value)})}),Ae==="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:!Vt||Ae==="submitting",onClick:Wn,children:Ae==="submitting"?f.sending:I})]})]})},go=({actions:e,descriptors:t,visitor:n,onSubmitForm:a,onDemoSlots:i,onConfirmHostedBooking:o,scheduler:s,exclude:c=[],openAction:u,translations:l={},onClose:d})=>{const p=ot(),[g,f]=S(null),[y,h]=S(!1),I=R(null),x=R(null),m=R(!1),T=qe(()=>`cf-actions-${Math.random().toString(36).slice(2,9)}`,[]),F=qe(()=>Ed(t,e,l).filter(U=>!c.includes(U.id)&&!c.includes(U.endpoint)),[t,e,c,l]);J(()=>{u&&F.some(U=>U.id===u)&&(f(u),h(!0))},[u,F]);const M=g?F.find(U=>U.id===g):void 0,Q=O(()=>{if(d){d();return}m.current=!0,f(null),h(!1)},[d]),Y=O(()=>{d?d():f(null)},[d]);$n(()=>{y||!m.current||(m.current=!1,I.current?.focus())},[y]);const X=R({drawerOpen:y,activeId:g});if(X.current={drawerOpen:y,activeId:g},J(()=>{const U=D=>{if(D.key!=="Escape")return;const{drawerOpen:q,activeId:C}=X.current;!q&&!C||(D.stopPropagation(),C?Y():Q())};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[Y,Q]),J(()=>{y&&x.current?.querySelector("button, input, textarea, select")?.focus()},[y,g]),F.length===0)return null;const j=y?M?r("div",{ref:x,id:T,class:"cf-action-drawer is-open",role:"dialog","aria-modal":"false","aria-label":M.formTitle||M.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:M.formTitle||M.label}),M.legacyFallback?r("small",{class:"cf-action-test-mode",children:p.actionTestMode}):null]}),r("button",{type:"button",class:"cf-action-drawer__close","aria-label":p.actionClose,onClick:Y,children:r(Pn,{})})]}),M.readiness==="degraded"&&M.readinessNote?r("p",{class:"cf-action-drawer__note cf-action-drawer__note--warn",role:"status",children:M.readinessNote}):null,M.presentation==="booking"||M.endpoint==="book-demo"||M.endpoint==="schedule-callback"?r(Ud,{actionId:M.id,fields:M.fields,visitor:n,title:M.formTitle,submitLabel:M.submitLabel,onCancel:Y,onSubmit:(U,D)=>a(M.id,U,D,M.endpoint),onDemoSlots:i,onConfirmHostedBooking:o,scheduler:s}):r(Rd,{spec:{title:M.formTitle||M.label,submit:M.submitLabel,fields:M.endpoint==="request-callback"?M.fields.filter(U=>U.key!=="bestTime"):M.fields},visitor:n,onCancel:Y,onSubmit:(U,D)=>a(M.id,U,D,M.endpoint)})]}):r("div",{ref:x,id:T,class:"cf-action-drawer cf-action-drawer--menu",role:"dialog","aria-modal":"false","aria-label":p.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:p.actionNeedHelp}),r("strong",{children:p.actionChoose})]}),r("button",{type:"button",class:"cf-action-drawer__close","aria-label":p.actionClose,onClick:Q,children:r(Pn,{})})]}),r("div",{class:"cf-action-drawer__grid",children:F.map(U=>{const D=Ad(U.icon);return r("button",{type:"button",class:"cf-action-card",onClick:()=>f(U.id),children:[r("span",{class:`cf-action-card__icon cf-action-card__icon--${U.category}`,children:r(D,{})}),r("span",{class:"cf-action-card__copy",children:[r("strong",{children:U.label}),U.legacyFallback?r("small",{class:"cf-action-test-mode",children:p.actionTestMode}):null,r("small",{children:U.description}),U.readiness==="degraded"&&U.readinessNote?r("small",{class:"cf-action-card__warn",children:U.readinessNote}):null]}),r(pn,{})]},U.id)})}),r("p",{class:"cf-action-drawer__note",children:p.actionFooter})]}):null;return r("div",{class:"cf-action-shell",children:[r("button",{ref:I,type:"button",class:"cf-action-trigger",hidden:y,"aria-expanded":y,"aria-controls":T,onClick:()=>y?Q():h(!0),children:[r("span",{class:"cf-action-trigger__icon",children:r(gr,{})}),r("span",{class:"cf-action-trigger__copy",children:[r("strong",{children:p.actionContactOptions}),r("small",{children:zd(F,p)})]}),r(pn,{})]}),j]})},Bd=({hasEmail:e,visitor:t,question:n,onSubmitForm:a})=>{const i=ot(),[o,s]=S(!1),[c,u]=S(!1),[l,d]=S(t.name??""),[p,g]=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 y=t.email||p;return r("div",{class:"cf-handoff cf-handoff--done",children:[r(fn,{}),r("span",{children:Ve(i.handoffShared,{email:y})})]})}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:y=>d(y.target.value)}),r("input",{class:"cf-form__input",type:"email",placeholder:`${i.handoffEmail} *`,value:p,"aria-label":i.handoffEmail,onInput:y=>g(y.target.value)}),r("button",{type:"button",class:"cf-form__submit",disabled:!p.trim()||c,onClick:f,children:c?i.sending:i.handoffNotify})]})},qd=({text:e})=>{const t=ot(),[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(sd,{}),n?t.copied:t.copy]})},Vd=({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}`))})},Hd=({msg:e,onRate:t})=>{const n=ot(),[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(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:d,children:n.feedbackSend})]})]})},bo=e=>e.attachments??(e.attachmentName?[{id:e.attachmentId,name:e.attachmentName}]:[]),Wd=({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:g,onRate:f,onExpandVisualization:y,onExpandExplanation:h,onReconnect:I,onOpenAttachment:x,onExplanationFeedback:m,explanationTransport:T,onOpenAnalyticsSource:F})=>{const M=ot(),Q=mr(),Y=e.role==="user",X=e.liveEventType??"",j=e.content.trim().toLowerCase(),U=X==="handoff_queued"||X==="agent_joined"||X==="agent_left"||X==="ai_handback"||X==="conversation_ended"||j.includes("joined the chat")||j.includes("left the chat")||j.includes("support agents will be with you"),D=e.role==="system"||U,q=e.requestedContactFields?.includes("email")===!0,C=n&&!Y&&!D&&!e.reconnectOffer&&!!(e.handoffOffered||q),Z=C&&!i?["inquiry"]:[],_=!e.pending&&!e.streaming,L=[...e.artifacts??[],...e.visualization&&!(e.artifacts??[]).some($=>$.type==="visualization")?[{type:"visualization",visualization:e.visualization}]:[]];return D?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:M.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--${Y?"user":"agent"}`,children:[!Y&&r(uo,{persona:t,small:!0}),r("div",{class:"cf-msg__col",children:[e.pending&&e.content===""?r(wd,{}):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:[Y?e.content:xd(e.content),e.streaming&&r("span",{class:"cf-caret","aria-hidden":"true"})]}),Y?null:L.map(($,P)=>$.type==="visualization"&&$.visualization?r(vo,{visualization:$.visualization,onFollowUp:c,onExpand:y?()=>y(e.id):void 0,expandControlId:e.id},`visualization-${P}`):$.type==="image"&&($.data||$.uri?.startsWith("https://"))&&["image/png","image/jpeg","image/webp"].includes($.mimeType??"")?r("figure",{class:"cf-artifact",children:[$.title?r("figcaption",{children:$.title}):null,r("img",{src:$.uri||`data:${$.mimeType};base64,${$.data}`,alt:$.altText||$.caption||$.title||"Tool result"}),$.caption&&$.caption!==$.title?r("p",{children:$.caption}):null]},`image-${P}`):$.type==="video"&&$.uri?.startsWith("https://")&&($.mimeType??"").startsWith("video/")?r("figure",{class:"cf-artifact",children:[$.title?r("figcaption",{children:$.title}):null,r("video",{controls:!0,preload:"metadata",playsInline:!0,src:$.uri}),$.caption&&$.caption!==$.title?r("p",{children:$.caption}):null]},`video-${P}`):$.type==="resource_link"&&$.uri?.startsWith("https://")?r("a",{class:"cf-artifact-link",href:$.uri,target:"_blank",rel:"noopener noreferrer nofollow",children:[r("strong",{children:$.title||$.name||"Open result"}),$.caption?r("span",{children:$.caption}):null]},`link-${P}`):null),!Y&&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,M.resultExpired]}):null,!Y&&e.visualization&&va(e.visualization)?r("div",{class:"cf-analytics-explanation","data-testid":"inline-analytics-explanation","data-explanation-message":e.id,children:r(eo,{classPrefix:"cf",copy:M.analytics?.explanation,locale:Q,onExpand:h?()=>h(e.id):void 0,explanation:va(e.visualization),onFollowUp:c,onFeedback:m,aiTransport:T,canOpenSource:$=>!!F&&($.kind==="liveboard_tile"||$.kind==="insight"),onOpenSource:F?$=>{($.kind==="liveboard_tile"||$.kind==="insight")&&F({kind:$.kind,id:$.id,...e.visualization?.appliedFilters?.length?{appliedFilters:e.visualization.appliedFilters}:{}})}:void 0,maxFollowUps:3,showLead:(()=>{const $=va(e.visualization).headline?.trim().toLocaleLowerCase();return!$||!e.content.toLocaleLowerCase().includes($)})()})}):null,Y&&bo(e).length>0&&r("div",{class:"cf-attach-row cf-attach-row--sent",children:bo(e).map(($,P)=>x?r("button",{type:"button",class:"cf-attach-chip cf-attach-chip--open",title:Ve(M.attachOpen,{name:$.name}),"aria-label":Ve(M.attachOpen,{name:$.name}),onClick:()=>x(e,$,P),children:[r(ba,{}),r("span",{children:$.name})]},`${$.id??$.name}-${P}`):r("div",{class:"cf-attach-chip",title:$.name,children:[r(ba,{}),r("span",{children:$.name})]},`${$.id??$.name}-${P}`))}),!Y&&r(ce,{children:[_&&(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(cd,{}),M.retry]}):r(qd,{text:e.content})}),g&&!e.error&&e.content?r(Hd,{msg:e,onRate:f}):null]}),r(Sd,{msg:e}),n&&r($d,{replies:e.suggestedReplies,onPick:c}),C&&r(Bd,{hasEmail:i,visitor:a,question:o,onSubmitForm:u}),s&&r(go,{actions:e.availableActions,descriptors:e.actions,openAction:e.selectedAction,visitor:a,onSubmitForm:u,onDemoSlots:l,onConfirmHostedBooking:d,scheduler:t?.scheduler,exclude:Z})]})]})]})},Gd=({visualization:e,onClose:t,onFollowUp:n,onFeedback:a,transport:i,onOpenSource:o})=>{const s=ot(),c=mr(),u=va(e);return u?r("div",{class:"cf-analytics-explanation is-expanded","data-testid":"expanded-analytics-explanation",children:r(eo,{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},vo=({visualization:e,expanded:t=!1,onExpand:n,onClose:a,onFollowUp:i,expandControlId:o})=>{const s=ot(),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)}),Kd=({onPick:e})=>r("div",{class:"cf-picker cf-emoji",children:Ul.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))}),Yd=({onSearch:e,onPick:t})=>{const n=ot(),[a,i]=S(""),[o,s]=S([]),[c,u]=S(!0);return J(()=>{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"})]})},Zd=5*1024*1024,vr=5,Jd="image/png,image/jpeg,image/webp,image/gif,application/pdf",Xd=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""}},Qd=.004,yo=({muted:e,listening:t,micLevel:n,onToggleMute:a})=>{const i=t&&n>=Qd;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(Jl,{}):r(Ln,{})})},eu=({audioDevices:e,selectedAudioDeviceId:t,onSelectAudioDevice:n})=>{const[a,i]=S(!1),[o,s]=S(null),c=R(null);J(()=>{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]),$n(()=>{if(!a){s(null);return}const l=c.current;if(!l)return;let d=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"){d=I.getBoundingClientRect();break}}const p=l.getBoundingClientRect(),g=8,f=d.bottom-p.bottom-g*2,y=p.top-d.top-g*2,h=y>f;s({up:h,maxHeight:Math.max(72,Math.floor(h?y: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))]})]})},tu=({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:g})=>r("div",{class:"cf-call-controls",children:[r(yo,{muted:t,listening:mn(e)&&!t,micLevel:s,onToggleMute:n}),r(eu,{audioDevices:d,selectedAudioDeviceId:p,onSelectAudioDevice:g}),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(pd,{}):r(ud,{})}),r("button",{type:"button",class:"cf-call-btn","aria-label":"Minimize voice chat",onClick:l,children:r(fd,{})}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--end","aria-label":"End voice chat",onClick:a,children:r(br,{})})]}),nu=({persona:e,voiceState:t,muted:n,onToggleMute:a,onEndCall:i,micLevel:o,onExpand:s})=>{const c=g=>g.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:g=>{(g.key==="Enter"||g.key===" ")&&(g.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:xa(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:g=>{c(g),s()},children:r(hd,{})}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--end","aria-label":"End voice chat",onClick:g=>{c(g),i()},children:r(br,{})})]})]})},au=(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)}},ru=({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:g=0,onVoiceStateChange:f,onPreviewAttachment:y})=>{const h=ot(),[I,x]=S(()=>e.value),m=A=>{const he=typeof A=="function"?A(I):A;e.value=he,x(he)},[T,F]=S(!1),[M,Q]=S(!1),[Y,X]=S("idle"),[j,U]=S("none"),[D,q]=S([]),C=R([]);C.current=D;const Z=R(0),[_,L]=S(!1),[$,P]=S(!1),[fe,oe]=S(""),Ue=R(null),ke=R(null),Ce=R(null),Le=R(0),Ie=R(null),Ae=R(void 0),ge=A=>{X(A),f?.(A)},Ze=()=>{Ae.current&&window.clearTimeout(Ae.current),Ae.current=void 0};J(()=>{const A=Ue.current;A&&(A.style.height="auto",A.style.height=`${Math.min(A.scrollHeight,110)}px`)},[I]),J(()=>()=>{for(const A of C.current)A.previewUrl&&URL.revokeObjectURL(A.previewUrl)},[]);const be=A=>{q(he=>{const de=he.find(me=>me.key===A);return de?.previewUrl&&URL.revokeObjectURL(de.previewUrl),he.filter(me=>me.key!==A)})},ie=()=>q([]);J(()=>{if(j==="none")return;const A=he=>{ke.current&&!he.composedPath().includes(ke.current)&&U("none")};return document.addEventListener("pointerdown",A),()=>document.removeEventListener("pointerdown",A)},[j]);const Je=A=>U(he=>he===A?"none":A),He=A=>{const he=Ue.current;if(!he){m(Fe=>Fe+A);return}const de=he.selectionStart??I.length,me=he.selectionEnd??I.length;m(I.slice(0,de)+A+I.slice(me)),requestAnimationFrame(()=>{he.focus();const Fe=de+A.length;he.setSelectionRange(Fe,Fe)})},k=A=>{U("none"),n(A)},K=async A=>{if(A.length===0)return;oe("");const he=Le.current,de=vr-C.current.length-Z.current;if(de<=0){oe(Ve(h.attachLimit,{count:String(vr)}));return}const me=A.slice(0,de);Z.current+=me.length,L(!0);for(const Fe of me){if(he!==Le.current)break;try{await V(Fe,he)}finally{he===Le.current&&(Z.current-=1,L(Z.current>0))}}he===Le.current&&A.length>me.length&&oe(Ve(h.attachLimit,{count:String(vr)}))},V=async(A,he)=>{if(A.size>Zd){oe(h.attachTooLarge);return}if(!p){oe(h.attachFailed);return}try{const de=await xo(A);if(he!==Le.current)return;const me=await p(de,A.type||"application/octet-stream",A.name,d);if(he!==Le.current)return;const Fe={key:`${me.id||A.name}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,id:me.id,analysisFailed:me.analysisFailed,name:A.name,text:me.text,mimeType:A.type||"application/octet-stream",size:A.size,previewUrl:A.type.startsWith("image/")?URL.createObjectURL(A):void 0,file:A};q(We=>[...We,Fe])}catch(de){if(he!==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)}},H=async A=>{const he=A.target,de=Array.from(he.files??[]);he.value="",await K(de)},ae=()=>{Le.current+=1,Z.current=0,L(!1),oe("")},ye=(!!I.trim()||D.length>0)&&!i&&!_&&!M,Se=()=>{ye&&(t(I,D.length>0?{attachments:D.map(A=>({id:A.id,name:A.name,text:A.text,file:A.file}))}:void 0),a?.(!1),m(""),ie(),oe(""))},Qe=A=>{const he=A.trim();if(!he||i){ge("misunderstood");return}const de=I.trim(),me=de?`${de} ${he}`:he;t(me),a?.(!1),m(""),ie(),oe(""),ge("idle")},Ge=A=>{if(A.key==="Enter"&&!A.shiftKey){if(i)return;A.preventDefault(),Se()}else A.key==="Escape"&&j!=="none"&&(A.preventDefault(),A.stopPropagation(),U("none"))},tt=()=>{Ze(),Ie.current?.stop("dictation-ended"),Ie.current=null,F(!1),Q(!1)},nt=async()=>{const A=Ie.current;if(A){const{mic:me,processing:Fe}=A.snapshot;me==="hearing"||Fe?A.finishTurn():(tt(),ge("idle"));return}const he=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||void 0;ge("connecting");const de=new qi({transcribe:async({audio:me,mimeType:Fe,durationSeconds:We})=>s(await xo(me),Fe,he,We),listener:{state:({mic:me,processing:Fe,reason:We})=>{if(Ie.current===de){if(me==="unavailable"){if(We==="permission-denied"||We==="unsupported"||We==="no-device"||We==="error"){tt(),ge("denied");return}ge("unavailable");return}F(me==="listening"||me==="hearing"),Q(Fe),me==="starting"?ge("connecting"):Fe&&me!=="hearing"?ge("processing"):me==="hearing"?ge("hearing"):me==="listening"&&ge("listening")}},speechStart:()=>Ze(),turn:me=>{Ie.current===de&&(tt(),Qe(me.text))},noise:me=>{Ie.current===de&&(tt(),ge(me.reason==="transcribe-failed"?"misunderstood":"noise"))}}});Ie.current=de,Ae.current=window.setTimeout(()=>{Ie.current===de&&(tt(),ge("noise"))},Xd),await de.start()};return J(()=>{!g||!o||i||T||M||nt()},[g]),J(()=>()=>{Ze(),Ie.current?.stop("unmounted"),Ie.current=null},[]),r("div",{class:`cf-composer ${$?"is-dragging":""}`,ref:ke,onDragEnter:A=>{l&&(A.preventDefault(),P(!0))},onDragOver:A=>{l&&A.preventDefault()},onDragLeave:A=>{A.currentTarget===A.target&&P(!1)},onDrop:A=>{l&&(A.preventDefault(),P(!1),K(Array.from(A.dataTransfer?.files??[])))},children:[j==="emoji"&&r(Kd,{onPick:He}),j==="gif"&&r(Yd,{onSearch:u,onPick:k}),(D.length>0||_||fe)&&r("div",{class:"cf-attach-row",role:"list","aria-label":h.attachedFiles,children:[D.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(h.attachOpen,{name:A.name}),disabled:!y,onClick:()=>y?.(A.file,A.name),children:[A.previewUrl?r("img",{class:"cf-attach-preview",src:A.previewUrl,alt:""}):r(ba,{}),r("span",{class:"cf-attach-copy",children:[r("span",{children:A.name}),r("small",{children:A.analysisFailed?h.attachAnalysisFailed:`${Math.max(1,Math.ceil(A.size/1024))} KB`})]})]}),r("button",{type:"button",class:"cf-attach-x","aria-label":Ve(h.removeAttachmentNamed,{name:A.name}),onClick:()=>be(A.key),children:r(Pn,{})})]},A.key)),_&&r("span",{class:"cf-attach-status",children:[r("span",{children:h.attaching}),r("button",{type:"button",onClick:ae,children:h.cancel})]}),fe&&!_&&r("span",{class:"cf-attach-status cf-attach-status--err",children:fe})]}),Y!=="idle"&&r("div",{class:"cf-voice-state","aria-live":"polite",children:[r("span",{class:`cf-voice-state__dot ${T?"is-live":""}`}),au(Y,h)]}),r("div",{class:"cf-composer__field",children:[r("button",{type:"button",class:`cf-iconbtn ${j==="emoji"?"is-active":""}`,"aria-label":h.emoji,"aria-pressed":j==="emoji",onClick:()=>Je("emoji"),children:j==="emoji"?r(Pn,{}):r(rd,{})}),c&&r("button",{type:"button",class:`cf-iconbtn cf-gifbtn ${j==="gif"?"is-active":""}`,"aria-label":h.gifs,"aria-pressed":j==="gif",onClick:()=>Je("gif"),children:r("span",{class:"cf-gif-label",children:"GIF"})}),l&&r(ce,{children:[r("input",{ref:Ce,type:"file",class:"cf-file-input",accept:Jd,multiple:!0,onChange:H,tabIndex:-1,"aria-hidden":"true"}),r("button",{type:"button",class:"cf-iconbtn","aria-label":h.attachFile,disabled:_,onClick:()=>Ce.current?.click(),children:r(ba,{})})]}),r("textarea",{ref:Ue,class:"cf-textarea",rows:1,placeholder:h.composerPlaceholder,value:I,"aria-label":h.composerPlaceholder,"aria-busy":i,onInput:A=>{const he=A.target.value;m(he),a?.(!!he.trim())},onPaste:A=>{const he=Array.from(A.clipboardData?.files??[]);!l||he.length===0||(A.preventDefault(),K(he))},onKeyDown:Ge}),o&&r("button",{type:"button",class:`cf-iconbtn cf-mic ${T?"is-recording":""}`,"aria-label":T?h.stopRecording:h.recordVoice,"aria-pressed":T,disabled:M||i,onClick:nt,children:r(Ln,{})}),r("button",{type:"button",class:"cf-send","aria-label":h.send,disabled:!ye,onClick:Se,children:r(Zl,{})})]})]})},iu=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"]),ou=/^\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?(?:\s*(?:-|–|—|to|-->)\s*\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?)?$/,su=e=>{const t=e.trim().toLowerCase().replace(/[()[\]*]/g," ").replace(/[.!?,…]+$/,"").replace(/\s+/g," ").trim();return!t||/^(?:sh+\s*)+$/.test(t)||ou.test(t)?!0:_o.has(t)},cu=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,Fn=null;const lu=e=>{wo=e},du=()=>{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(!wo)return;const t=du();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{}},uu=e=>e.startsWith("image/")?"image":e==="application/pdf"?"pdf":"other",pu=({state:e,onClose:t})=>{const n=ot(),a=R(null);J(()=>{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"?uu(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})]})]})})},fu=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)}),hu=(e,t)=>e?.status===429?t.errorRateLimit:t.errorGeneric,yr=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),_a=(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},mu=/!?\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,gu=/https?:\/\/[^\s)]+/g,ko=e=>Ui(e).replace(mu,"$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(gu,t=>t.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/$/,"")).replace(/[ \t]+\n/g,`
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(),bu=(e,t)=>ko(Fc(e,t)),vu=45e3,_r=e=>e.type==="visualization",xu=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(u=>!_r(u)),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(xu),yu=(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<vu?e:{...e,visualization:{...e.visualization,explanation:{...e.visualization.explanation,aiExplanation:{...n,status:"failed",retryAvailable:!1}}}}},_u=e=>e instanceof DOMException&&(e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED"),wu=(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(!_u(s))return!1;i=i.slice(Math.ceil(i.length/2))}try{e.removeItem(t)}catch{}return!1},ku=(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,u)=>c!==o.messages[u])&&e.setItem(a,JSON.stringify({...o,messages:s}))}}catch{}},Su=(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}}},ut=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.round(Math.random()*1e9)}`,wa=(e,t)=>{typeof console>"u"||console.warn(`[centrinfo-widget] ${e}`,t??{})},So=(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 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 m=()=>{x||(x=!0,t.current===I&&(t.current=null,u?.()))};return I.rate=i,I.lang=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en-US",I.onend=m,I.onerror=m,t.current=I,c?.(),window.speechSynthesis.cancel(),window.speechSynthesis.speak(I),!0};if(!n||typeof Audio>"u")return l();const d=new Audio(`data:${a||"audio/mpeg"};base64,${n}`);let p=!1,g=!1;const f=()=>{p||(p=!0,e.current===d&&(e.current=null,u?.()))},y=()=>{if(!p){if(g||e.current!==d){f();return}p=!0,e.current=null,l()||u?.()}};return d.playbackRate=i,d.onended=f,d.onerror=y,e.current=d,d.play().then(()=>{if(!p){if(e.current!==d){f();return}g=!0,c?.(Number.isFinite(d.duration)?d.duration*1e3:void 0)}}).catch(y),!0},$u=e=>{try{return e==="none"?null:e==="session"?sessionStorage:localStorage}catch{return null}},Tu=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)},Cu=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{}},Au=e=>{const t=e.user?.externalId?.trim()||e.user?.userId?.trim()||e.user?.email?.trim().toLowerCase()||Cu(e.identityToken)||(e.identityToken||e.getIdentityToken?"authenticated":"anonymous");return`${e.token.slice(0,12)}:${e.chatSurface}:${Tu(t)}`},Bn=e=>`${e.chatSurface}:${ut()}`,Mu=e=>e.slice(0,12),qn=e=>`centrinfo:session:${e}`,kr=e=>`centrinfo:visitor:${e}`,ka=(e,t)=>`centrinfo:chat:${e}:${t}`,Sr=e=>`centrinfo:history:${e}`,Iu=1e3,$o=20,$r=720*60*60*1e3,Eu=1440*60*1e3,zu=(e,t)=>{try{return JSON.parse(e?.getItem(kr(t))||"{}")}catch{return{}}},Nu=(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)}},To=(e,t,n)=>{if(!e)return{};try{const a=e.getItem(ka(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):[]},Ru=(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>Eu},Lu=e=>Number.isFinite(e??NaN)?Math.max(5,Math.min(200,Math.round(e))):50,Du=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(ka(t,n));return}const u=a.filter(d=>!d.pending).slice(-s);if(u.length===0)return;const l=Date.now();wu(e,ka(t,n),d=>JSON.stringify({ts:l,expiresAt:l+c,messages:wr(d),ended:i}),u)}catch{}},Pu=(e,t)=>{if(!e)return[];try{const n=e.getItem(Sr(t)),a=n?JSON.parse(n):[];return Array.isArray(a)?a:[]}catch{return[]}},Sa=(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([qn(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{}},Ou=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"},Fu=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")),Uu=(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}}},Bu=(e,t,n=!0)=>{const a=R($u(t.persistence)).current,i=Au(t),o=R(Nu(a,i,t)),s=R(null),c=R(null),u=R(null),l=R(null),d=R(null),p=R(null),g=R(new Map),f=R(!1),y=R(void 0),h=R(null),I=R({}),x=R({}),[m,T]=S(null),[F,M]=S(()=>Co(a,i,o.current)),Q=R(null);Q.current||(Q.current=Su(Iu));const Y=R(F.length>0),X=R(F.some(b=>b.role==="user")),[j,U]=S(!1),[D,q]=S(!1),[C,Z]=S({status:"idle"}),_=R({}),[L,$]=S(()=>Ru(a,i,o.current)),[P,fe]=S(()=>zu(a,i)),[oe,Ue]=S(()=>Pu(a,i)),[ke,Ce]=S(null),[Le,Ie]=S([]),[Ae,ge]=S("ai"),[Ze,be]=S(void 0),[ie,Je]=S(void 0),He=R(new Date().toISOString()),k=R(void 0),K=R(!1),V=R(0),H=R(P);J(()=>{H.current=P},[P]);const ae=m?.memoryEnabled!==!1,ye=Lu(m?.memoryMessageCap),Se=Du(m?.memoryRetentionDays),Qe=O(()=>{s.current?.abort(),Q.current?.cancel(),Mo(a,i),Mo(a,Mu(t.token));const b=Bn(t);o.current=b;try{a?.setItem(qn(i),b)}catch{}Ce(null),Ie([]),$(!1),Ue([]),fe({}),ge("ai"),be(void 0),Je(void 0),He.current=new Date().toISOString(),M(m?[{id:ut(),role:"assistant",content:m.greeting,availableActions:m.availableActions,actions:m.actions}]:[])},[a,i,t.token,m]),Ge=O(b=>{try{a?.setItem(kr(i),JSON.stringify(b))}catch{}},[a,i]),tt=O(b=>{const w=(b.email??"").trim().toLowerCase(),z=(H.current.email??"").trim().toLowerCase();w&&z&&w!==z&&Qe();const E={};b.email?.trim()&&(E.email=b.email.trim()),b.phone?.trim()&&(E.phone=b.phone.trim());const te=[b.firstName,b.lastName].filter(se=>!!se?.trim()).join(" ").trim()||b.name?.trim()||"";te&&(E.name=te),Object.keys(E).length>0&&fe(se=>{const ne={...E,...se};return Ge(ne),ne}),e.identify(o.current,b).catch(()=>{})},[e,Ge,Qe]),nt=R(0),A=O(b=>{nt.current=Date.now(),T(b),M(w=>{if(w.length===0)return[{id:ut(),role:"assistant",content:b.greeting,availableActions:b.availableActions,actions:b.actions}];const z=w.some(G=>G.role==="user"),E=w[0];return!z&&E?.role==="assistant"?[{...E,content:b.greeting,availableActions:b.availableActions,actions:b.actions},...w.slice(1)]:w})},[]);J(()=>{if(m?.memoryEnabled===!1){Q.current?.cancel();try{a?.removeItem(ka(i,o.current))}catch{}Sa(a,i,[]),Ue([]),Ce(null),Ie([]),M(b=>Y.current?(Y.current=!1,m?[{id:ut(),role:"assistant",content:m.greeting,availableActions:m.availableActions,actions:m.actions}]:[]):b)}},[m,a,i]);const he=O(async()=>{const b=await e.bootstrap();A(b)},[A,e]);J(()=>{let b=!0;const w=z=>z.messages.map(E=>yu({id:E.id,role:E.role,content:E.content,authorName:E.authorName,liveEventType:E.messageType,offerReconnect:E.messageType==="ai_handback"&&E.reconnectOffered===!0,sources:E.sources,visualization:E.visualization,artifacts:E.artifacts,createdAt:E.createdAt}));return e.history().then(z=>{if(!b||z.conversations.length===0)return;const E=z.conversations.map(ne=>({sessionId:ne.sessionId,ts:Date.parse(ne.lastSeenAt)||Date.now(),title:ne.title,ended:ne.ended}));for(const ne of z.conversations)Ao(a,i,ne.sessionId,w(ne),ne.ended,!0,ye,Se);Sa(a,i,E),Ue(E);const G=z.conversations.find(ne=>ne.sessionId===z.activeSessionId);if(!G||X.current)return;const te=w(G);o.current=G.sessionId,Y.current=te.length>0;try{a?.setItem(qn(i),G.sessionId)}catch{}const se=te[te.length-1]?.createdAt;se&&(He.current=se),$(G.ended),M(te)}).catch(()=>{}),()=>{b=!1}},[ye,Se,i,a,e]),J(()=>{let b=!0;return nt.current=Date.now(),e.bootstrap().then(w=>{b&&A(w)}),t.user&&tt(t.user),()=>{b=!1}},[A,e]),J(()=>{const b=t.configRefreshSeconds;if(!n||b<=0||typeof window>"u")return;let w=!0,z=!1;const E=Math.max(10,b)*1e3,G=()=>typeof document>"u"||document.visibilityState!=="hidden",te=async()=>{if(!(!w||z||!G())){z=!0;try{await he()}catch{}finally{z=!1}}};Date.now()-nt.current>=E&&te();const se=window.setInterval(te,E),ne=()=>{te()},_e=()=>{te()};return window.addEventListener("focus",ne),document?.addEventListener?.("visibilitychange",_e),()=>{w=!1,window.clearInterval(se),window.removeEventListener("focus",ne),document?.removeEventListener?.("visibilitychange",_e)}},[n,t.configRefreshSeconds,he]),J(()=>{const b=o.current;Q.current.schedule(()=>Ao(a,i,b,F,L,ae,ye,Se))},[F,L,a,i,ae,ye,Se]),J(()=>{const b=Q.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()}},[]),J(()=>{ku(a,"centrinfo:chat:")},[a]),J(()=>{if(!n||L||ke)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,L,e,ke]),J(()=>{if(!n||L||ke)return;let b=!0,w=!1,z=0,E;const G=()=>{E!==void 0&&window.clearTimeout(E),!(!b||document.hidden)&&(E=window.setTimeout(()=>{te()},Math.min(3e4,2200*2**z)))},te=async()=>{if(!(w||document.hidden||!b)){w=!0;try{const ne=await e.liveEvents(o.current,He.current);if(!b)return;if(z=0,ge(ne.mode),be(ne.assignedAgentName||void 0),Je(ne.agentTyping?ne.agentTypingName||ne.assignedAgentName||"Agent":void 0),ne.conversationEnded){$(!0),ge("ai"),be(void 0),Je(void 0),M(_e=>_e.some(re=>re.id==="live:conversation-ended")?_e:[..._e,{id:"live:conversation-ended",role:"system",content:t.strings.conversationEnded,liveEventType:"conversation_ended",createdAt:new Date().toISOString()}]);return}if(ne.events.length>0){let _e=He.current,re=Date.parse(_e);const st=ne.events.map(De=>{const ct=Date.parse(De.createdAt);return Number.isFinite(ct)&&ct>re&&(re=ct,_e=De.createdAt),Fu(De)});He.current=_e,M(De=>{const ct=new Set(De.map(Pe=>Pe.id)),Ye=st.filter(Pe=>!ct.has(Pe.id));return Ye.length>0?[...De,...Ye]:De}),st.some(De=>De.role==="assistant")&&gn("receive")}}catch{z=Math.min(z+1,4)}finally{w=!1,G()}}},se=()=>{document.hidden?E!==void 0&&window.clearTimeout(E):te()};return document.addEventListener("visibilitychange",se),document.hidden||te(),()=>{b=!1,E!==void 0&&window.clearTimeout(E),document.removeEventListener("visibilitychange",se)}},[n,t.strings.conversationEnded,e,L,ke]),J(()=>{if(!ae){Sa(a,i,[]),Ue(w=>w.length>0?[]:w);return}F.some(w=>w.role==="user")&&Ue(w=>{const z=o.current,G=[{sessionId:z,ts:Date.now(),title:Ou(F),ended:L},...w.filter(te=>te.sessionId!==z)];return Sa(a,i,G),G.slice(0,$o)})},[F,L,a,i,ae]);const de=O((b,w)=>{M(z=>z.map(E=>E.id===b?{...E,...w}:E))},[]),me=O(()=>{y.current!==void 0&&typeof window<"u"&&window.clearInterval(y.current),y.current=void 0},[]),Fe=O((b,w)=>{me(),delete I.current[b],h.current===b&&(h.current=null),de(b,{content:w,pending:!1,streaming:!1})},[me,de]),We=O((b,w,z)=>{const E=w.trim();if(!E||typeof window>"u"){Fe(b,E);return}me(),h.current=b;const G=E.match(/\S+\s*/g)??[E],te=z&&z>0?z:G.length*95,se=Math.max(28,Math.min(150,te/Math.max(G.length,1)));let ne=0;de(b,{content:"",pending:!1,streaming:!0}),y.current=window.setInterval(()=>{ne+=1;const _e=G.slice(0,ne).join("");de(b,{content:_e,pending:!1,streaming:ne<G.length}),ne>=G.length&&(me(),delete I.current[b],h.current===b&&(h.current=null),de(b,{content:E,pending:!1,streaming:!1}))},se)},[me,Fe,de]),pt=O(()=>{const b=h.current;me(),h.current=null;const w=I.current;I.current={};for(const[z,E]of Object.entries(w))de(z,{content:E,pending:!1,streaming:!1});b&&!(b in w)&&de(b,{pending:!1,streaming:!1})},[me,de]),dt=O(b=>{if(L||ke||Ae==="ai"||typeof window>"u")return;if(k.current!==void 0&&window.clearTimeout(k.current),!b){if(!K.current)return;K.current=!1,V.current=0,e.typing(o.current,!1).catch(()=>{});return}const w=Date.now();(!K.current||w-V.current>2500)&&(K.current=!0,V.current=w,e.typing(o.current,!0).catch(()=>{})),k.current=window.setTimeout(()=>{K.current&&(K.current=!1,V.current=0,e.typing(o.current,!1).catch(()=>{}))},1600)},[e,L,ke,Ae]);J(()=>()=>{k.current!==void 0&&typeof window<"u"&&window.clearTimeout(k.current)},[]),J(()=>()=>me(),[me]);const xt=O((b,w,z={})=>{pt(),U(!0);const E=yr();let G=!1;const te=new AbortController;s.current=te;const se=!!(m?.allowVoiceInput&&m?.voiceOutputEnabled&&m.talkbackMode!=="text"),ne=!!z.forceVoicePlayback,_e=W=>{ne&&Z(we=>we.agentId===w?{status:W,agentId:w}:we)};ne&&Z({status:"answering",agentId:w});const re={pending:new Map,nextSeq:0,highestSeq:-1,playing:!1,ended:!1,started:!1,stopped:!1,utterance:null},st=()=>{p.current===et&&(p.current=null),re.started&&(re.started=!1,q(!1),_e("done"))},De=()=>{re.stopped||re.started||(re.started=!0,_a("voice-first-audio",E),q(!0),_e("speaking"))},ct=()=>typeof window<"u"&&"speechSynthesis"in window&&typeof SpeechSynthesisUtterance<"u",Ye=()=>{l.current&&re.playing&&(l.current.pause(),l.current=null),re.utterance&&(d.current===re.utterance&&(d.current=null),re.utterance=null,ct()&&window.speechSynthesis.cancel()),re.playing=!1},Pe=(W,we)=>{const Be=W?.trim();if(!Be||!ct())return!1;const xe=new SpeechSynthesisUtterance(Be);return xe.rate=m?.voiceSpeed??1,xe.lang=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en-US",xe.onstart=De,xe.onend=we,xe.onerror=we,re.utterance=xe,d.current=xe,window.speechSynthesis.speak(xe),f.current&&window.speechSynthesis.pause(),!0},kt=()=>{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&&st();return}if(re.pending.delete(re.nextSeq),re.nextSeq+=1,Ee(W))return}},Ee=W=>{let we=!1;const Be=()=>{we||(we=!0,d.current===re.utterance&&(d.current=null),re.utterance=null,re.playing=!1,kt())};if(!W.audioBase64||typeof Audio>"u")return re.playing=Pe(W.text,Be),re.playing;const xe=new Audio(`data:${W.mimeType||"audio/mpeg"};base64,${W.audioBase64}`);xe.playbackRate=m?.voiceSpeed??1,xe.volume=f.current?.2:1,re.playing=!0,l.current=xe;let rt=!1,mt=!1;const Ft=()=>{we||mt||(mt=!0,l.current===xe&&(l.current=null),!(!rt&&!re.stopped&&Pe(W.text,Be))&&Be())};return xe.onended=()=>{l.current===xe&&(l.current=null),Be()},xe.onerror=Ft,xe.play().then(()=>{rt=!0,De()}).catch(Ft),!0},et=()=>{re.stopped=!0,re.pending.clear(),Ye(),st()};e.stream(b,o.current,{voicePlaybackRequested:!!z.forceVoicePlayback,clientMessageId:z.clientMessageId,attachmentId:z.attachmentId,attachmentIds:z.attachmentIds,signal:te.signal,onChunk:W=>{W&&!G&&(G=!0,_a("data-first-chunk",E)),z.forceVoicePlayback&&W&&(x.current[w]=!0),M(we=>we.map(Be=>Be.id===w?{...Be,content:Be.content+W,pending:!1,streaming:!0}:Be))},onTextReady:()=>{M(W=>W.map(we=>we.id===w?{...we,pending:!1,streaming:!1}:we))},onReset:()=>{M(W=>W.map(we=>we.id===w?{...we,content:"",pending:!0,streaming:!1}:we)),re.pending.clear(),re.nextSeq=re.highestSeq+1,Ye()},onAudioSegment:W=>{!ne||re.stopped||W.seq<re.nextSeq||re.pending.has(W.seq)||(p.current=et,re.highestSeq=Math.max(re.highestSeq,W.seq),re.pending.set(W.seq,W),kt())}}).then(W=>{if(n&&!W.conversationEnded&&typeof document<"u"&&document.visibilityState==="visible"&&e.presence(o.current),W.liveMode&&(ge(W.liveMode),be(W.assignedAgentName||void 0)),W.liveMode&&W.liveMode!=="ai"&&!W.answer.trim()){M(xe=>xe.filter(rt=>rt.id!==w)),_e("done");return}const we=!!x.current[w];delete x.current[w];const Be=!!(z.forceVoicePlayback&&se&&!W.liveAudio&&W.audioBase64&&W.answer.trim()&&!we);if(Be&&(I.current[w]=W.answer),M(xe=>xe.map(rt=>rt.id===w?{...rt,content:Be?"":W.answer||rt.content||t.strings.emptyReply,pending:!1,streaming:Be,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}:rt)),gn("receive"),W.liveAudio?(re.ended=!0,kt()):z.forceVoicePlayback&&!W.audioBase64&&wa(se?"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}),z.forceVoicePlayback&&!W.liveAudio){const xe=So(l,d,W.audioBase64,W.mimeType,m?.voiceSpeed??1,bu(W.answer,W.visualization),!0,rt=>{q(!0),_e("speaking"),Be&&We(w,W.answer,rt)},()=>{q(!1),_e("done"),Be&&Fe(w,W.answer)});xe||_e("done"),Be&&!xe&&Fe(w,W.answer)}W.answer&&t.onMessage?.({role:"assistant",content:W.answer}),W.handoffOffered&&t.onHandoff?.(),W.conversationEnded&&$(!0)}).catch(W=>{if(te.signal.aborted){re.stopped||et(),delete x.current[w],M(Be=>Be.flatMap(xe=>xe.id!==w?[xe]:xe.content.trim()?[{...xe,pending:!1,streaming:!1}]:[])),_e("done");return}_e("failed"),delete x.current[w];const we=hu(W,t.strings);de(w,{content:we,pending:!1,streaming:!1,error:!0,retryText:b})}).finally(()=>{_a("data-complete",E),delete x.current[w],s.current===te&&(U(!1),s.current=null,c.current?.agentId===w&&(c.current=null))})},[e,n,t,de,m?.allowVoiceInput,m?.talkbackMode,m?.voiceOutputEnabled,m?.voiceSpeed,pt]),Nt=O((b,w={})=>{const z=b.trim(),{imageUrl:E,attachmentName:G,attachmentText:te,attachmentId:se,attachmentFile:ne,forceVoicePlayback:_e,userMessageId:re}=w,st=w.attachments??(G||se||te?[{id:se,name:G??"",text:te,file:ne}]:[]);if(!z&&!E&&st.length===0||s.current&&!s.current.signal.aborted||L)return;X.current=!0;let De=z;for(const Ee of st){const et=Ee.name?` "${Ee.name}"`:"";Ee.text?De=`${De}
171
-
172
- [Attached file${et}]:
173
- ${Ee.text}`.trim():Ee.id&&(De=`${De}
174
-
175
- [The visitor attached a file${et}. It is saved for staff, but its contents were not available to the AI. Do not claim to have inspected it.]`.trim())}!De&&E&&(De=E);const ct=st.map(Ee=>({id:Ee.id,name:Ee.name})),Ye=st.flatMap(Ee=>Ee.id?[Ee.id]:[]),Pe={id:re||ut(),role:"user",content:z,imageUrl:E,attachments:ct.length>0?ct:void 0};st.forEach((Ee,et)=>{Ee.file&&(g.current.set(`${Pe.id}:${et}`,Ee.file),Ee.id&&g.current.set(Ee.id,Ee.file))});const kt=ut();M(Ee=>[...!!(re&&Ee.some(we=>we.id===re))?Ee.map(we=>we.id===re?{...we,content:z,pending:!1,streaming:!1,imageUrl:E,attachments:Pe.attachments}:we):[...Ee,Pe],{id:kt,role:"assistant",content:"",pending:!0}]),gn("send"),t.onMessage?.({role:"user",content:De}),_.current[kt]=Pe.id,c.current={userId:Pe.id,agentId:kt,text:z,backendText:De},xt(De,kt,{forceVoicePlayback:_e,clientMessageId:Pe.id,attachmentId:Ye[0],attachmentIds:Ye})},[L,t,xt]),yt=O((b,w,z,E,G)=>{const te=ut();M(se=>[...se.filter(ne=>ne.id!==b.agentId&&(!E.userMessageId||ne.id!==E.userMessageId)).map(ne=>ne.id===b.userId?{...ne,content:w,pending:!1,streaming:!1}:ne),{id:te,role:"assistant",content:"",pending:!0}]),G&&t.onMessage?.({role:"user",content:G}),_.current[te]=b.userId,c.current={userId:b.userId,agentId:te,text:w,backendText:z},xt(z,te,{forceVoicePlayback:E.forceVoicePlayback,clientMessageId:ut()})},[t,xt]),jn=O((b,w={})=>{const z=b.trim();if(!z||L)return;const E=s.current&&!s.current.signal.aborted?c.current:null,G=E??u.current;if(u.current=null,!G){Nt(z,w);return}E&&s.current?.abort(),yt(G,`${G.text} ${z}`.replace(/\s+/g," ").trim(),`${G.backendText}
176
- ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.aborted?c.current:null;return b?(u.current=b,s.current?.abort(),!0):!1},[]),at=O(()=>{const b=u.current;u.current=null,!(!b||L)&&yt(b,b.text,b.backendText,{forceVoicePlayback:!0})},[L,yt]),Rt=O(()=>s.current?.abort(),[]),bn=O(b=>{f.current=b;const w=l.current;w&&(w.volume=b?.2:1),d.current&&typeof window<"u"&&"speechSynthesis"in window&&(b?window.speechSynthesis.pause():window.speechSynthesis.resume())},[]),qt=O(()=>{p.current?.(),p.current=null,f.current=!1,pt(),Z(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(),d.current=null,q(!1)},[pt]),ft=O(b=>{const w=ko(b);if(!w)return Promise.resolve(!1);pt();const z=!!(m?.allowVoiceInput&&m?.voiceOutputEnabled&&m.talkbackMode!=="text"),E=(G,te)=>new Promise(se=>{let ne=!1;So(l,d,G,te,m?.voiceSpeed??1,w,!0,()=>{ne=!0,q(!0)},()=>{q(!1),se(ne)})||(q(!1),se(!1))});return z?e.speak(w).then(G=>G.audioBase64?E(G.audioBase64,G.mimeType):(wa("Talkback prompt TTS did not return provider audio.",{providerReady:G.providerReady,message:G.message,voiceProvider:m?.voiceProvider,voiceOutputEnabled:m?.voiceOutputEnabled,talkbackMode:m?.talkbackMode}),E())).catch(G=>(wa("Talkback prompt TTS request failed before audio playback.",{error:G instanceof Error?G.message:String(G),voiceProvider:m?.voiceProvider,voiceOutputEnabled:m?.voiceOutputEnabled,talkbackMode:m?.talkbackMode}),E())):(wa("Talkback prompt wanted voice, but the loaded widget token config has provider TTS disabled.",{voiceOutputEnabled:m?.voiceOutputEnabled,talkbackMode:m?.talkbackMode,voiceProvider:m?.voiceProvider}),E())},[m?.allowVoiceInput,m?.talkbackMode,m?.voiceOutputEnabled,m?.voiceSpeed,pt,e]),Vt=O((b,w,z={})=>{if(j||L||!w)return;de(b,{content:"",pending:!0,streaming:!1,error:!1}),gn("send");const E=F.findIndex(te=>te.id===b),G=E>0?F[E-1]:void 0;xt(w,b,{...z,clientMessageId:_.current[b]??(G?.role==="user"?G.id:void 0)})},[j,L,F,de,xt]),Lt=O((b,w,z)=>{de(b,{feedback:w});const E=F.findIndex(se=>se.id===b),G=E>=0?F[E]?.content:void 0;let te;for(let se=E-1;se>=0;se--)if(F[se]?.role==="user"){te=F[se]?.content;break}e.sendFeedback({sessionId:o.current,messageId:b,rating:w,comment:z,question:te,answer:G}).catch(()=>{})},[e,de,F]),nn=O(async(b,w,z={},E)=>{t.onAction?.(b);const G=b==="public_contact_support"||b==="public_submit_inquiry"?{actionId:b}:{},te=await e.action(b,{sessionId:o.current,...w,...G},E),se={};return z.name?.trim()&&(se.name=z.name.trim()),z.email?.trim()&&(se.email=z.email.trim()),z.phone?.trim()&&(se.phone=z.phone.trim()),Object.keys(se).length>0&&(fe(ne=>{const _e={...ne,...se};return Ge(_e),_e}),se.email&&b!=="contact"&&e.action("contact",{sessionId:o.current,...se}).catch(()=>{})),gn("receive"),te},[e,t,Ge]),_t=O((b,w,z)=>e.confirmHostedBooking?.({sessionId:o.current,inquiryId:b,eventUri:w,inviteeUri:z})??Promise.resolve(void 0),[e]),Xe=O(b=>{const w=b.trim();w&&M(z=>z.some(E=>E.role==="assistant"&&E.content===w)?z:[...z,{id:ut(),role:"assistant",content:w}])},[]),Dt=O(()=>{const b=Io(m?.actions);return b?(M(w=>[...w,{id:ut(),role:"assistant",content:t.strings.reconnectPrompt,actions:[b],selectedAction:b.id,handoffOffered:!0,reconnectOffer:!0,createdAt:new Date().toISOString()}]),!0):!1},[t.strings.reconnectPrompt,m?.actions]),ht=O(b=>{X.current=!0;const w=ut();return M(z=>[...z,{id:w,role:"user",content:b.trim(),pending:!0}]),w},[]),Pt=O((b,w)=>{M(z=>z.map(E=>E.id===b?{...E,...w}:E))},[]),jt=O(b=>{M(w=>w.filter(z=>z.id!==b))},[]),Hn=O(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=O((b="widget")=>{const w=e.fetchExplanation?.bind(e);if(!w)return;const z=e.retryExplanation?.bind(e),E=G=>G;return{poll:async(G,te)=>E(await w(G,o.current,b,te)),settled:(G,te)=>{te!=="not_requested"&&M(se=>se.map(ne=>{const _e=ne.visualization?.explanation?.aiExplanation;return!_e||(_e.explanationId??ne.visualization?.explanation?.explanationId)!==G||_e.status===te?ne:{...ne,visualization:{...ne.visualization,explanation:{...ne.visualization.explanation,aiExplanation:{..._e,status:te}}}}}))},...z?{retry:async G=>E(await z(G,o.current,b))}:{}}},[e]),vn=O((b,w)=>{e.sendFeedback({sessionId:o.current,messageId:"__csat__",rating:b,comment:w}).catch(()=>{})},[e]),ee=O(async(b,w,z,E)=>{const G=yr();try{if(typeof b!="string"&&e.transcribeAudio)return await e.transcribeAudio(b,w,z,E);const te=typeof b=="string"?b:await fu(b);return await e.transcribe(te,w,z,E)}finally{_a("voice-transcription",G)}},[e]),pe=O(async(b,w,z=0)=>{const E=g.current.get(`${b.id}:${z}`)??(w.id?g.current.get(w.id):void 0);if(E)return E;if(!w.id||!e.fetchAttachment)throw new Error("This file is no longer available.");return e.fetchAttachment(w.id,o.current)},[e]),$e=O((b,w,z,E)=>e.uploadAttachment?e.uploadAttachment(b,w,z,o.current,E):Promise.reject(new Error("File upload is unavailable")),[e]),ue=O(b=>e.searchGifs(b),[e]),ve=O((b,w)=>e.demoSlots(b,w),[e]),wt=O(b=>Nt("",{imageUrl:b}),[Nt]),Ot=t.demo||!!t.gifApiKey,Ta=O(()=>{s.current?.abort(),$(!0),e.endConversation(o.current).catch(()=>{})},[e]),an=O(()=>{s.current?.abort();const b=Bn(t);o.current=b;try{a?.setItem(qn(i),b)}catch{}Ce(null),Ie([]),$(!1),ge("ai"),be(void 0),Je(void 0),He.current=new Date().toISOString(),M(m?[{id:ut(),role:"assistant",content:m.greeting,availableActions:m.availableActions,actions:m.actions}]:[])},[a,i,m]),Gn=O(b=>{if(ae){if(b===o.current){Ce(null);return}Ie(Co(a,i,b)),Ce(b)}},[a,i,ae]),Ht=O(()=>{Ce(null),Ie([])},[]),Tt=t.starters.length>0?t.starters:m?.starterQuestions??[],Ct=m?.featuredLinks??[];return{persona:m,messages:F,sending:j,assistantSpeaking:D,voiceReply:C,visitor:P,starters:Tt,featuredLinks:Ct,hasEmail:!!P.email,liveMode:Ae,assignedAgentName:Ze,agentTypingName:ie,send:Nt,amend:jn,hold:tn,resumeHeld:at,duckSpeaking:bn,sendGif:wt,notifyTyping:dt,stop:Rt,retry:Vt,rateMessage:Lt,rateExplanation:Hn,explanationTransport:Wn,injectAssistant:Xe,reconnectSupport:Dt,appendUserDraft:ht,patchMessage:Pt,removeMessage:jt,submitCsat:vn,submitForm:nn,confirmHostedBooking:_t,transcribe:ee,uploadAttachment:$e,loadAttachment:pe,searchGifs:ue,demoSlots:ve,gifEnabled:Ot,identify:tt,ended:L,endConversation:Ta,startNew:an,history:ae?oe:[],viewingSessionId:ke,viewMessages:Le,openConversation:Gn,closeHistoryView:Ht,shutdown:Qe,stopSpeaking:qt,speakAssistantText:ft}},qu=({name:e,greeting:t})=>{const n=ot();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})]})},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],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())},$a=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]},Vu=(e,t="#ffffff")=>{const n=`${e??""}|${t}`;if($a.has(n))return $a.get(n);const a=Eo(e),i=Eo(t)??[255,255,255,1];if(!a){$a.set(n,void 0);return}const o=a[3],c=a.slice(0,3).map((g,f)=>g*o+i[f]*(1-o)).map(g=>{const f=g/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 $a.set(n,p),p},ju=e=>{const[t,n]=S("light");return J(()=>{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},Hu=6e4,Wu=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(),Gu=[{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/}],Ku=/^(?:yes|yeah|yep|yup|sure|correct|confirm|affirmative|go ahead|do it|please do|ok(?:ay)?)\b/,Yu=/^(?:no|nope|nah|cancel|never ?mind|don'?t|stop)\b/,Zu=/^(?:end|close|stop|finish|hang ?up|quit|exit|bye|good ?bye)\b/,Ju=e=>{const t=No(e);if(!t)return null;for(const{action:n,re:a}of Gu)if(a.test(t)){const i=t.split(" ").length;return{action:n,confident:n==="end"?i<=10:i<=6}}return null},Xu=e=>`I didn't catch yes or no. Say yes to ${zo[e]}, or no to keep talking.`,Qu=({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:g,liveMode:f,assignedAgentName:y,agentTypingName:h,starters:I,featuredLinks:x,send:m,sendGif:T,notifyTyping:F,stop:M,amend:Q,hold:Y,resumeHeld:X,duckSpeaking:j,retry:U,rateMessage:D,rateExplanation:q,explanationTransport:C,injectAssistant:Z,reconnectSupport:_,appendUserDraft:L,patchMessage:$,removeMessage:P,submitCsat:fe,submitForm:oe,confirmHostedBooking:Ue,transcribe:ke,uploadAttachment:Ce,loadAttachment:Le,searchGifs:Ie,demoSlots:Ae,gifEnabled:ge,identify:Ze,ended:be,endConversation:ie,startNew:Je,history:He,viewingSessionId:k,viewMessages:K,openConversation:V,closeHistoryView:H,shutdown:ae,stopSpeaking:ye,speakAssistantText:Se}=Bu(e,t,o),Qe=Uu(u,f),[Ge,tt]=S(null),nt=R(0),A=O((v,N,le)=>{le===nt.current&&tt({status:"ready",name:N,url:URL.createObjectURL(v),mimeType:v.type||"application/octet-stream"})},[]),he=O((v,N,le)=>{const Me=N.name,Ne=++nt.current;tt({status:"loading",name:Me}),Le(v,N,le).then(gt=>A(gt,Me,Ne),()=>{Ne===nt.current&&tt({status:"error",name:Me})})},[Le,A]),de=O((v,N)=>A(v,N,++nt.current),[A]),me=O(()=>{nt.current+=1,tt(null)},[]);J(()=>()=>{Ge?.status==="ready"&&URL.revokeObjectURL(Ge.url)},[Ge]);const Fe=!!Io(c?.actions),[We,pt]=S(0),[dt,xt]=S({mic:"off",processing:!1}),[Nt,yt]=S(null),[jn,tn]=S(!1),[at,Rt]=S(!1),[bn,qt]=S(!1),[ft,Vt]=S(!1),[Lt,nn]=S(0),[_t,Xe]=S(!1),[Dt,ht]=S(null),[Pt,jt]=S(null),[Hn,Wn]=S([]),[vn,ee]=S(""),[pe,$e]=S(()=>{try{return localStorage.getItem("centrinfo:muted")==="1"}catch{return!1}}),ue=ju(t.theme),ve=c?.soundEnabled??!0;J(()=>{lu(t.sound&&ve&&!pe)},[t.sound,ve,pe]);const wt=O(()=>{$e(v=>{const N=!v;try{localStorage.setItem("centrinfo:muted",N?"1":"0")}catch{}return N})},[]),Ot=R(null),Ta=R(null),an=R(null),Gn=R(0),Ht=R(!1),Tt=R(!1),Ct=R(null),b=R(0),w=R(void 0),z=R(0),E=R(null),G=R(!1),te=R(null),se=R(""),ne=R(()=>{}),_e=R(""),re=R(l),st=R(m);st.current=m;const De=R(Q);De.current=Q;const ct=R(ke);ct.current=ke;const Ye=R(!1),Pe=R(!1),kt=R("");kt.current=[...u].reverse().find(v=>v.role==="assistant")?.content??"";const Ee=R(d);re.current=l,Ee.current=d;const et=at?jn?"timeout":ft||dt.mic==="muted"?"muted":dt.mic==="unavailable"?dt.reason==="permission-denied"||dt.reason==="unsupported"?"denied":"unavailable":dt.mic==="off"||dt.mic==="starting"?"connecting":dt.mic==="hearing"?"hearing":d?"speaking":Nt??(dt.processing||l?"processing":"listening"):"idle",[W,we]=S(!0),[Be,xe]=S(!1),rt=R(0),[mt,Ft]=S(!1),[rn,on]=S(!1),Uo=R(null),[Wt,sn]=S(!1),pp=R({value:""}),fp=a??pp.current,Bo=R({confirmEnd:mt,confirmClear:rn,showHistory:Wt});Bo.current={confirmEnd:mt,confirmClear:rn,showHistory:Wt};const[hp,qo]=S(!1),ze=!!k,Ca=ze?K:u,Kn=Ca.find(v=>v.id===Dt&&v.visualization)?.visualization,Yn=Ca.find(v=>v.id===Pt&&v.visualization);J(()=>{!Pt||Yn||(jt(null),Xe(!1))},[Pt,Yn]),J(()=>{!Dt||Kn||(ht(null),Xe(!1))},[Kn,Dt]);const xn=O(()=>{s(!0),pt(0),gn("open"),t.onOpen?.(),t.onShow?.()},[t]),At=O(()=>{s(!1),Xe(!1),ht(null),t.onClose?.(),t.onHide?.(),Ta.current?.focus()},[t]),Zn=O(()=>o?At():xn(),[o,xn,At]),mp=O(()=>Ft(!0),[]),gp=O(()=>{ie(),Ft(!1)},[ie]),bp=O(()=>{Je(),xe(!1),we(!0)},[Je]);J(()=>{mt&&Uo.current?.focus()},[mt]),J(()=>{n({open:xn,close:At,toggle:Zn,identify:Ze,startNew:Je,endConversation:ie,shutdown:ae})},[n,xn,At,Zn,Ze,Je,ie,ae]),J(()=>{const v=u.filter(N=>N.role==="assistant"&&!N.pending).length;if(o){Gn.current=v;return}v>Gn.current&&pt(v-Gn.current)},[u,o]),J(()=>{t.onUnreadChange?.(We)},[We,t]),J(()=>{const v=t.sessionDurationMinutes;if(!v||v<=0)return;const N=setTimeout(()=>ae(),v*60*1e3);return()=>clearTimeout(N)},[t.sessionDurationMinutes,u,o,ae]),J(()=>{const v=t.customLauncherSelector;if(!v||typeof document>"u")return;let N=[];try{N=Array.from(document.querySelectorAll(v))}catch{return}const le=Me=>{Me.preventDefault(),Zn()};return N.forEach(Me=>Me.addEventListener("click",le)),()=>N.forEach(Me=>Me.removeEventListener("click",le))},[t.customLauncherSelector,Zn]);const Vo=R(!1);J(()=>{const v=t.proactiveMessage?.trim();if(!v||Vo.current)return;const N=t.proactiveOnPaths??[],le=typeof location<"u"?location.pathname:"";if(N.length>0&&!N.some(gt=>le.includes(gt)))return;const Me=`centrinfo:proactive:${t.token.slice(0,12)}`;try{if(sessionStorage.getItem(Me)==="1")return}catch{}const Ne=setTimeout(()=>{if(!(o||be||u.some(gt=>gt.role==="user"))){Vo.current=!0;try{sessionStorage.setItem(Me,"1")}catch{}Z(v),xn()}},Math.max(0,t.proactiveDelaySeconds)*1e3);return()=>clearTimeout(Ne)},[t.proactiveMessage]),J(()=>{const v=an.current;if(!o||!v)return;const N=u[u.length-1],le=Date.now()<rt.current;N?.role==="user"||W||le?(requestAnimationFrame(()=>{v.scrollTop=v.scrollHeight}),xe(!1),le&&we(!0)):xe(!0)},[u,o,l,W]);const jo=R(!0);jo.current=W,J(()=>{const v=an.current;if(!(!o||!v))return yc(v,{isAtBottom:()=>jo.current,onUnseen:()=>xe(!0)})},[o,ze]);const vp=O(()=>{const v=an.current;if(!v)return;if(Ht.current&&!ze){we(!0),xe(!1);return}const N=v.scrollHeight-v.scrollTop-v.clientHeight<80;we(N),N&&xe(!1)},[ze]),Gt=O(()=>{const v=an.current;v&&(v.scrollTop=v.scrollHeight),xe(!1),we(!0)},[]),Aa=O(()=>{rt.current=Date.now()+3e3,requestAnimationFrame(Gt)},[Gt]);J(()=>{if(!o||ze||!at||et==="connecting")return;rt.current=Date.now()+6e4,Gt();const v=requestAnimationFrame(()=>{Gt(),requestAnimationFrame(Gt)}),N=[80,180,360].map(le=>window.setTimeout(Gt,le));return()=>{cancelAnimationFrame(v),N.forEach(le=>window.clearTimeout(le))}},[d,u,o,Gt,l,at,ze,et]);const Ho=O(()=>{Ot.current?.querySelector(".cf-textarea")?.focus()},[]),Jn=O((v,N)=>{yt(v),w.current&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>yt(null),3e3),N&&!Tt.current&&Se(N)},[Se]),Ma=O(v=>{const N=te.current;if(N)return N;Aa();const le=L(v);return te.current=le,$(le,{content:se.current||v,pending:!0,streaming:!1}),le},[L,Aa,$]),Ut=O(()=>{const v=te.current;if(v){if(se.current){$(v,{content:se.current,pending:!0});return}te.current=null,P(v)}},[$,P]),Kt=O(()=>{Pe.current&&(Pe.current=!1,j(!1)),Ye.current&&(Ye.current=!1,X())},[j,X]),lt=O(()=>{Ht.current=!1,Ct.current?.stop("call-ended"),Ct.current=null,Ye.current=!1,Pe.current=!1,Tt.current=!1,E.current=null,G.current=!1;const v=te.current;te.current=null,se.current="",v&&P(v),w.current&&window.clearTimeout(w.current),yt(null),tn(!1),xt({mic:"off",processing:!1}),nn(0),Rt(!1),qt(!1),Vt(!1),Xe(!1),ht(null),ye()},[P,ye]),xp=O(()=>{_t&&ht(null),Xe(!_t)},[_t]),yp=O(v=>{ht(v),Xe(!0)},[]),_p=O(v=>{jt(v),Xe(!0)},[]),Ia=O(()=>{const v=Dt,N=Pt;ht(null),jt(null),Xe(!1),window.requestAnimationFrame(()=>{(N?Ot.current?.querySelector(`[data-explanation-message="${N}"]`)?.querySelector('[data-testid="analytics-explanation-expand"]'):Array.from(Ot.current?.querySelectorAll("[data-visualization-message]")??[]).find(Me=>Me.dataset.visualizationMessage===v))?.focus()})},[Dt,Pt]),wp=O(()=>{ht(null),jt(null),Xe(!1)},[]),Wo=O((v,N,le=!1)=>{if(Aa(),N&&($(N,{content:v,pending:!1,streaming:!1}),te.current===N&&(te.current=null)),se.current="",le){ye(),De.current(v,{forceVoicePlayback:!0,userMessageId:N});return}Ht.current&&(Y()?De.current(v,{forceVoicePlayback:!0,userMessageId:N}):st.current(v,{forceVoicePlayback:!0,userMessageId:N}))},[Aa,Y,$,ye]),Mt=O(v=>{Z(v),Se(v)},[Z,Se]),Go=O(()=>{if(b.current=Date.now(),yt(null),Ee.current){Pe.current=!0,j(!0);return}Ye.current||(Ye.current=Y()),Ma("Listening...")},[j,Ma,Y]),Ko=O(v=>{const N=te.current;if(!N||Pe.current)return;const le=[se.current,v].filter(Boolean).join(" ");$(N,{content:`${le} ...`,pending:!0})},[$]),Yo=O(v=>{b.current=Date.now();const N=[se.current,v.text].map(It=>It.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if((Pe.current||v.overlappedOutput)&&Oc(v.text,kt.current)){Ut(),Kt();return}if(!N||su(N)||cu(N)){const It=Pe.current||Ye.current;Ut(),Kt(),It||Jn("misunderstood");return}Pe.current&&(Pe.current=!1,M(),ye());const Me=E.current;if(Me){se.current="",Ut();const It=No(N);if(Ku.test(It)||Me==="end"&&Zu.test(It)){E.current=null,ne.current(Me);return}if(Yu.test(It)){E.current=null,Mt("Okay, never mind — what would you like to know?");return}Mt(Xu(Me));return}const Ne=Ju(N);if(Ne){if(se.current="",Ut(),Kt(),Ne.confident){ne.current(Ne.action);return}E.current=Ne.action,Mt(`Just to confirm — you want me to ${zo[Ne.action]}? Please say yes or no.`);return}const gt=Ma(N);$(gt,{content:N,pending:!0});const yn=Ye.current;Ye.current=!1,Wo(N,gt,yn)},[Ma,$,Kt,Wo,Ut,Jn,Mt,M,ye]),Zo=O(v=>{b.current=Date.now();const N=Pe.current||Ye.current;if(Ut(),Kt(),!(N||v.overlappedOutput||v.reason==="too-short")){if(v.reason==="transcribe-failed"){Jn("misunderstood","I couldn't transcribe that. Please try again, or type your question.");return}Jn("noise")}},[Kt,Ut,Jn]),Xn=R({speechStart:Go,partial:Ko,turn:Yo,noise:Zo});Xn.current={speechStart:Go,partial:Ko,turn:Yo,noise:Zo};const Jo=O(()=>{navigator.mediaDevices?.enumerateDevices().then(v=>{Wn(v.filter(N=>N.kind==="audioinput").map((N,le)=>({deviceId:N.deviceId,label:N.label||`Microphone ${le+1}`})))}).catch(()=>{})},[]),kp=O(()=>{if(Ht.current){lt();return}if(Ho(),!c?.allowVoiceInput||!c.talkbackMode||c.talkbackMode==="text"||re.current||be||ze)return;b.current=Date.now(),Tt.current=!1,Ht.current=!0,Vt(!1),Rt(!0),qt(!1),tn(!1);let v=!1;const N=new qi({deviceId:_e.current||void 0,transcribe:async({audio:le,mimeType:Me,durationSeconds:Ne})=>{const gt=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||void 0;return iu(await ct.current(le,Me,gt,Ne))},listener:{state:le=>{xt(le),le.mic!=="starting"&&le.mic!=="off"&&qt(!0),!v&&le.mic==="listening"&&(v=!0,Jo())},speechStart:()=>Xn.current.speechStart(),partial:({text:le})=>Xn.current.partial(le),turn:le=>Xn.current.turn(le),noise:le=>Xn.current.noise(le),level:le=>{const Me=performance.now();Me-z.current<Wu||(z.current=Me,nn(le))}}});Ct.current=N,N.setOutputActive(Ee.current),N.start()},[lt,be,Ho,c,Jo,ze]),Ea=O(()=>{const v=!Tt.current;Tt.current=v,Vt(v),Ct.current?.setMuted(v),v?(se.current="",Ut(),Kt()):b.current=Date.now()},[Kt,Ut]),Xo=O(v=>{switch(b.current=Date.now(),v){case"end":G.current=!0,Mt("Okay — ending our call now. Goodbye!"),window.setTimeout(()=>{G.current&&(G.current=!1,lt())},2e3);break;case"mute":{Tt.current||Ea(),Mt("Muted. Tap the mic button when you want me to listen again.");break}case"minimize":At(),Mt("Minimized — I'm still listening. Tap the call pill to bring the chat back.");break;case"expand":Xe(!0),Mt("Sure — expanding the view.");break;case"shrink":ht(null),Xe(!1),Mt("Okay — back to the smaller view.");break}},[At,lt,Mt,Ea]);J(()=>{ne.current=Xo},[Xo]);const Qo=R(!1);J(()=>{Qo.current&&!d&&G.current&&(G.current=!1,lt()),Qo.current=d},[d,lt]);const Sp=O(v=>{_e.current=v,ee(v),Ct.current?.selectDevice(v||void 0)},[]),$p=O(()=>{!Ht.current||Tt.current||(Pe.current=!1,Ye.current=!1,M(),ye(),b.current=Date.now())},[M,ye]);J(()=>{Ct.current?.setOutputActive(d),b.current=Date.now()},[d]),J(()=>{if(et!=="denied")return;const v=window.setTimeout(()=>lt(),3500);return()=>window.clearTimeout(v)},[lt,et]),J(()=>{if(!at)return;const v=window.setInterval(()=>{const N=Ct.current;!N||Tt.current||re.current||Ee.current||N.snapshot.mic==="hearing"||N.snapshot.processing||Date.now()-b.current<Hu||(Ct.current?.log.add("call-timeout"),tn(!0),window.setTimeout(()=>lt(),2400))},5e3);return()=>window.clearInterval(v)},[lt,at]);const Tp=at&&!ft&&(l||d);J(()=>()=>lt(),[lt]);const[Cp,Ap]=S(""),es=R(!1);J(()=>{if(es.current&&!l){const v=[...u].reverse().find(N=>N.role==="assistant"&&!N.streaming&&!N.pending&&N.content);v&&Ap(v.content)}es.current=l},[l,u]),$n(()=>{if(!o)return;const v=Ot.current,N=mt||rn?v?.querySelector(".cf-confirm__card"):Wt?v?.querySelector(".cf-history"):null;if(!N)return;const le=N.getRootNode(),Me="activeElement"in le?le.activeElement:document.activeElement;(!Me||!N.contains(Me))&&N.querySelector('button, [href], textarea, input, [tabindex]:not([tabindex="-1"])')?.focus()},[rn,mt,o,Wt]),J(()=>{if(!o)return;const v=Ot.current,N=mt||rn?v?.querySelector(".cf-confirm__card"):Wt?v?.querySelector(".cf-history"):null,le=v?.querySelectorAll(":scope > .cf-header, :scope > .cf-panel__video, :scope > .cf-panel__chat");le?.forEach(Ne=>{N?(Ne.setAttribute("inert",""),Ne.setAttribute("aria-hidden","true")):(Ne.removeAttribute("inert"),Ne.removeAttribute("aria-hidden"))}),N||requestAnimationFrame(()=>v?.querySelector(".cf-textarea")?.focus());const Me=Ne=>{if(Ne.key==="Escape"){Ne.preventDefault();const ea=Bo.current;if(ea.confirmEnd){Ft(!1);return}if(ea.confirmClear){on(!1);return}if(ea.showHistory){sn(!1);return}At();return}if(Ne.key!=="Tab"||!N)return;const gt=N.querySelectorAll('button, [href], textarea, input, [tabindex]:not([tabindex="-1"])'),yn=Array.from(gt).filter(ea=>!ea.hasAttribute("disabled"));if(yn.length===0)return;const It=yn[0],rs=yn[yn.length-1],is=N.getRootNode()instanceof ShadowRoot?N.getRootNode().activeElement:document.activeElement;Ne.shiftKey&&is===It?(Ne.preventDefault(),rs.focus()):!Ne.shiftKey&&is===rs&&(Ne.preventDefault(),It.focus())};return v?.addEventListener("keydown",Me),()=>{v?.removeEventListener("keydown",Me),le?.forEach(Ne=>{Ne.removeAttribute("inert"),Ne.removeAttribute("aria-hidden")})}},[o,At,mt,rn,Wt]),J(()=>{const v=Ot.current;v&&(o?v.removeAttribute("inert"):v.setAttribute("inert",""))},[o]);const za=t.accentColor??t.themeTokens?.accent??c?.accentColor,ts=t.themeTokens?.accentText??Vu(za,t.themeTokens?.background??(ue==="dark"?"#0f1c27":"#ffffff")),Mp={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)`}:{}},Ip=v=>m(v),Ep=[...u].reverse().find(v=>v.role==="user"&&v.content.trim())?.content??"",Na=u.some(v=>v.role==="user"),ns=!!(c?.allowVoiceInput&&c?.talkbackMode&&c.talkbackMode!=="text"),as=ns,Qn=!ze&&as&&!Na?Ca.filter((v,N)=>!(N===0&&v.role==="assistant")):Ca,zp=f==="human"&&y?y:c?.agentName??i.chatName,Np=f==="human"?i.liveSupport:f==="queued"?i.waitingForTeam:c?.offline?i.statusOffline:i.statusOnline,Ar=!be&&!ze?c?.availableActions:void 0,Rp=!be&&!ze?c?.actions:void 0,Mr=at&&!bn&&et==="connecting"&&!ze;return r(ql,{value:i,children:r(Vl,{value:t.locale,children:r("div",{class:"cf-root",dir:t.dir,"data-theme":ue,"data-align":t.alignment,"data-display":"floating",style:Mp,children:[_t&&o&&r("div",{class:"cf-theater-backdrop",onClick:wp}),r("div",{ref:Ot,class:`cf-panel ${o?"is-open":""} ${at?"cf-panel--call":""} ${Mr?"cf-panel--voice-connecting":""} ${_t&&o?"cf-panel--theater":""} ${Kn||Yn?"cf-panel--analytics-focus":""}`,role:"dialog","aria-modal":"false","aria-label":`${i.chatName}: ${c?.agentName??i.assistantName}`,"aria-hidden":!o,children:[Ge&&o&&r(pu,{state:Ge,onClose:me}),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:zp}),r("div",{class:`cf-header__status ${f==="ai"&&c?.offline?"cf-header__status--offline":""}`,children:r("span",{class:"cf-header__status-text",children:Np})})]}),r("div",{class:"cf-header__actions",children:[He.length>0&&r("button",{type:"button",class:"cf-header__btn","aria-label":i.pastConversations,title:i.pastConversations,"aria-pressed":Wt,onClick:()=>sn(v=>!v),children:r(dd,{})}),Na&&!be&&!ze&&r("button",{type:"button",class:"cf-header__btn","aria-label":i.endChat,title:i.endChat,onClick:mp,children:r(br,{})}),t.sound&&ve&&r("button",{type:"button",class:"cf-header__btn","aria-label":pe?i.unmuteSounds:i.muteSounds,"aria-pressed":pe,onClick:wt,children:pe?r(od,{}):r(id,{})}),r("button",{type:"button",class:"cf-header__btn cf-header__close","aria-label":i.closeChat,onClick:At,children:r(pn,{})})]})]}),r("div",{class:"cf-panel__video",children:Kn?r("div",{class:"cf-analytics-focus",role:"region","aria-label":i.expandedAnalyticsResult,children:r(vo,{visualization:Kn,expanded:!0,onFollowUp:v=>{Ia(),m(v)},onClose:Ia})}):Yn?.visualization?r("div",{class:"cf-analytics-focus",role:"region","aria-label":i.expandedAnalyticsResult,children:r(Gd,{visualization:Yn.visualization,onClose:Ia,onFollowUp:v=>{Ia(),m(v)},onFeedback:ze?void 0:q,transport:ze?void 0:C("widget"),onOpenSource:t.onOpenAnalyticsSource})}):!ze&&as?r(Td,{persona:c,starters:[],onPick:m,onFocusComposer:kp,speaking:d,voiceState:et,replyPending:at&&l&&!d,pinned:!0,muted:ft,onToggleMute:Ea,onEndCall:lt,onTalkNow:$p,showTalkNow:Tp,micLevel:Lt,theaterMode:_t,onToggleTheater:xp,onMinimize:At,audioDevices:Hn,selectedAudioDeviceId:vn,onSelectAudioDevice:Sp,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:an,role:"log",onScroll:vp,children:[Qn.map((v,N)=>r(Wd,{msg:v,persona:c,isLast:!ze&&N===Qn.length-1,visitor:p,hasEmail:g,lastQuestion:Ep,showActions:!ze&&N===Qn.length-1&&!!(v.handoffOffered||v.selectedAction),onPickReply:Ip,onSubmitForm:oe,onDemoSlots:Ae,onConfirmHostedBooking:Ue,onRetry:U,ratable:!ze&&Qn.slice(0,N).some(le=>le.role==="user"),onRate:D,onExplanationFeedback:ze?void 0:q,explanationTransport:ze?void 0:C("widget"),onOpenAnalyticsSource:t.onOpenAnalyticsSource,onExpandVisualization:ze?void 0:yp,onExpandExplanation:ze?void 0:_p,onOpenAttachment:he,onReconnect:!ze&&!be&&Fe&&v.id===Qe?_:void 0},v.id)),!Na&&!ze&&r(ce,{children:[Qn.length===0&&r(qu,{name:c?.agentName??i.assistantName,greeting:c?.greeting}),r(Vd,{items:I,onPick:m}),r(jd,{items:x})]}),Be&&r("button",{type:"button",class:"cf-newmsg",onClick:Gt,children:[r(md,{}),i.newMessages]})]}),r("div",{class:"cf-sr-live","aria-live":"polite","aria-atomic":"true",children:Cp}),l&&!be&&!ze&&r("div",{class:"cf-stopbar",children:r("button",{type:"button",class:"cf-stop",onClick:M,children:[r(ld,{}),i.stop]})}),ze?r("div",{class:"cf-ended",children:r("button",{type:"button",class:"cf-ended__btn",onClick:H,children:i.backToChat})}):be?r("div",{class:"cf-ended",children:[r("p",{class:"cf-ended__text",children:i.conversationEnded}),t.csat&&Na?hp?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:()=>{fe("up"),qo(!0)},children:r(oo,{})}),r("button",{type:"button",class:"cf-csat__btn","aria-label":i.feedbackNotHelpful,onClick:()=>{fe("down"),qo(!0)},children:r(so,{})})]}):null,r("button",{type:"button",class:"cf-ended__btn",onClick:bp,children:i.startNewChat})]}):r(ce,{children:[h?r("div",{class:"cf-live-typing","aria-live":"polite",children:Ve(i.agentTyping,{name:h})}):null,Ar&&Ar.length>0&&r("div",{class:"cf-footer-actions",children:r(go,{actions:Ar,descriptors:Rp,visitor:p,onSubmitForm:oe,onDemoSlots:Ae,onConfirmHostedBooking:Ue,scheduler:c?.scheduler,translations:t.actionTranslations})},"footer-actions"),r(ru,{draftStore:fp,onSend:m,onSendGif:T,onTyping:F,disabled:l,allowVoice:ns,onTranscribe:ke,gifEnabled:ge,onSearchGifs:Ie,allowAttach:t.attachments,analyzeAttachments:!0,onUpload:Ce,onPreviewAttachment:de},"composer")]}),!be&&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"})]})]}),mt&&r("div",{class:"cf-confirm",onClick:()=>Ft(!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,()=>Ft(!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:()=>Ft(!1),children:i.cancel}),r("button",{type:"button",class:"cf-confirm__btn cf-confirm__btn--danger",onClick:gp,children:i.endConfirmCta})]})]})},"confirm-end"),Wt&&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:He.map(v=>r("button",{type:"button",class:`cf-history__item ${v.sessionId===k?"is-active":""}`,onClick:()=>{V(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"),rn&&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),ae()},children:i.clearDeviceDataCta})]})]})},"confirm-clear")]}),at&&!o?r(nu,{persona:c,voiceState:et,muted:ft,onToggleMute:Ea,onEndCall:lt,micLevel:Lt,onExpand:xn}):_t&&o?null:!t.hideDefaultLauncher&&r("button",{ref:Ta,type:"button",class:"cf-launcher","aria-label":o?i.closeChat:We>0?`${i.openChat}. ${We===1?i.unreadMessage:Ve(i.unreadMessages,{count:String(We)})}`:i.openChat,"aria-expanded":o,onClick:Zn,children:[t.launcherIcon?r("img",{class:"cf-launcher__img",src:t.launcherIcon,alt:""}):r(Yl,{}),!o&&We>0&&r("span",{class:"cf-launcher__badge","aria-hidden":"true",children:We>99?"99+":We})]})]})})})},ep="https://api.accurixtech.com",tp=()=>typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en",np=(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]},ap=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()||tp(),n=np(e.translations,t);return{token:e.token,chatSurface:e.chatSurface??"floating",analyticsContextToken:e.analyticsContextToken,identityToken:e.identityToken,getIdentityToken:e.getIdentityToken,apiBaseUrl:(e.apiBaseUrl??ep).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:Bl({...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:Hl(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=`
177
173
  :host {
178
174
  all: initial;
179
175
  }
@@ -318,7 +314,7 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
318
314
  /* Grid (not flex) so theater mode below can reflow header/video/chat into a
319
315
  two-column split purely in CSS, without reordering the DOM. */
320
316
  display: grid;
321
- grid-template-columns: 1fr;
317
+ grid-template-columns: minmax(0, 1fr);
322
318
  grid-template-rows: auto auto minmax(0, 1fr);
323
319
  grid-template-areas: 'header' 'video' 'chat';
324
320
  overflow: hidden;
@@ -616,6 +612,7 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
616
612
  .cf-msg {
617
613
  display: flex;
618
614
  gap: 8px;
615
+ min-width: 0;
619
616
  max-width: 100%;
620
617
  animation: cf-msg-in 0.32s cubic-bezier(0.22, 1, 0.36, 1) both;
621
618
  }
@@ -669,6 +666,7 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
669
666
  .cf-msg__bubble p { margin: 0 0 8px; }
670
667
  .cf-msg__bubble p:last-child { margin-bottom: 0; }
671
668
  .cf-msg__col { min-width: 0; max-width: 85%; display: flex; flex-direction: column; gap: 8px; align-items: flex-start; }
669
+ .cf-msg__col--actions { flex: 1; max-width: 100%; }
672
670
  .cf-msg--user .cf-msg__col { align-items: flex-end; }
673
671
  .cf-artifact {
674
672
  width: min(100%, 560px);
@@ -1108,6 +1106,9 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1108
1106
  display: flex;
1109
1107
  flex-direction: column;
1110
1108
  gap: 8px;
1109
+ width: 100%;
1110
+ min-width: 0;
1111
+ max-width: 100%;
1111
1112
  }
1112
1113
 
1113
1114
  .cf-form {
@@ -1115,6 +1116,7 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1115
1116
  flex-direction: column;
1116
1117
  gap: 8px;
1117
1118
  width: 100%;
1119
+ min-width: 0;
1118
1120
  max-width: 300px;
1119
1121
  padding: 12px;
1120
1122
  border-radius: 14px;
@@ -1123,9 +1125,11 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1123
1125
  animation: cf-msg-in 0.2s ease both;
1124
1126
  }
1125
1127
  .cf-form__title { font-size: 13.5px; font-weight: 700; color: var(--cf-fg, var(--cf-text)); }
1126
- .cf-form__as { font-size: 12.5px; color: var(--cf-muted); margin-top: -2px; }
1128
+ .cf-form__as { font-size: 12.5px; color: var(--cf-muted); margin-top: -2px; overflow-wrap: anywhere; }
1127
1129
  .cf-form__input {
1128
1130
  width: 100%;
1131
+ min-width: 0;
1132
+ max-width: 100%;
1129
1133
  padding: 9px 11px;
1130
1134
  border: 1.5px solid var(--cf-border);
1131
1135
  border-radius: 10px;
@@ -1245,14 +1249,17 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1245
1249
  .cf-phone__option-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1246
1250
  .cf-phone__option-code { color: var(--cf-muted); font-variant-numeric: tabular-nums; }
1247
1251
  .cf-phone__empty { padding: 12px 8px; color: var(--cf-muted); font-size: 12px; text-align: center; }
1248
- .cf-form__actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 2px; }
1252
+ .cf-form__actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; margin-top: 2px; }
1249
1253
  .cf-form__submit {
1254
+ min-height: 36px;
1255
+ max-width: 100%;
1250
1256
  padding: 8px 14px;
1251
1257
  border-radius: 10px;
1252
1258
  font-size: 13.5px;
1253
1259
  font-weight: 600;
1254
1260
  background: linear-gradient(135deg, var(--cf-accent, #2f7f55) 0%, var(--cf-accent-2, #2f7de8) 160%);
1255
1261
  color: var(--cf-accent-ink);
1262
+ overflow-wrap: anywhere;
1256
1263
  transition: opacity 0.15s ease, transform 0.1s ease;
1257
1264
  }
1258
1265
  .cf-form__submit:disabled { opacity: 0.45; cursor: default; }
@@ -1428,8 +1435,9 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1428
1435
 
1429
1436
  /* ---------- Demo booking picker ---------- */
1430
1437
  .cf-booking { max-width: 320px; }
1431
- .cf-booking__hint { font-size: 12.5px; color: var(--cf-muted); margin-top: -2px; }
1438
+ .cf-booking__hint { font-size: 12.5px; color: var(--cf-muted); margin-top: -2px; line-height: 1.45; overflow-wrap: anywhere; }
1432
1439
  .cf-booking__dur { font-weight: 600; color: var(--cf-text); }
1440
+ .cf-booking__timezone { display: block; margin-top: 3px; font-size: 11.5px; }
1433
1441
  .cf-booking__state {
1434
1442
  padding: 12px;
1435
1443
  border: 1px dashed var(--cf-border);
@@ -1443,6 +1451,9 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1443
1451
  .cf-booking__dates {
1444
1452
  display: flex;
1445
1453
  gap: 6px;
1454
+ width: 100%;
1455
+ min-width: 0;
1456
+ max-width: 100%;
1446
1457
  overflow-x: auto;
1447
1458
  padding-bottom: 4px;
1448
1459
  scrollbar-width: thin;
@@ -1476,7 +1487,9 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1476
1487
  .cf-booking__dom { font-size: 15px; font-weight: 700; line-height: 1.1; }
1477
1488
  .cf-booking__slots {
1478
1489
  display: grid;
1479
- grid-template-columns: repeat(3, 1fr);
1490
+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 80px), 1fr));
1491
+ width: 100%;
1492
+ min-width: 0;
1480
1493
  gap: 6px;
1481
1494
  max-height: 156px;
1482
1495
  overflow-y: auto;
@@ -1485,7 +1498,9 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1485
1498
  .cf-booking__slots::-webkit-scrollbar { width: 6px; }
1486
1499
  .cf-booking__slots::-webkit-scrollbar-thumb { background: var(--cf-border); border-radius: 3px; }
1487
1500
  .cf-booking__slot {
1488
- padding: 8px 0;
1501
+ min-width: 0;
1502
+ min-height: 36px;
1503
+ padding: 8px 4px;
1489
1504
  border-radius: 9px;
1490
1505
  border: 1px solid var(--cf-border);
1491
1506
  background: var(--cf-bg);
@@ -1771,6 +1786,9 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1771
1786
  white-space: nowrap;
1772
1787
  }
1773
1788
  .cf-action-drawer {
1789
+ width: 100%;
1790
+ min-width: 0;
1791
+ max-width: 100%;
1774
1792
  border: 1px solid color-mix(in oklab, var(--cf-border) 86%, var(--cf-accent));
1775
1793
  border-radius: 18px 18px 12px 12px;
1776
1794
  padding: 7px;
@@ -1791,18 +1809,24 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1791
1809
  background: color-mix(in oklab, var(--cf-muted) 42%, transparent);
1792
1810
  }
1793
1811
  .cf-action-drawer__head {
1812
+ position: sticky;
1813
+ top: -7px;
1814
+ z-index: 1;
1794
1815
  display: flex;
1795
1816
  align-items: center;
1796
1817
  justify-content: space-between;
1797
1818
  gap: 10px;
1798
1819
  padding: 0 3px 6px;
1820
+ background: var(--cf-bg);
1799
1821
  color: var(--cf-text);
1800
1822
  }
1801
1823
  .cf-action-drawer__head strong {
1802
1824
  display: block;
1803
1825
  font-size: 13px;
1804
1826
  line-height: 1.2;
1827
+ overflow-wrap: anywhere;
1805
1828
  }
1829
+ .cf-action-drawer__head > div { min-width: 0; }
1806
1830
  .cf-action-drawer__eyebrow {
1807
1831
  display: block;
1808
1832
  margin-bottom: 2px;
@@ -1814,6 +1838,7 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1814
1838
  }
1815
1839
  .cf-action-drawer__close {
1816
1840
  display: inline-flex;
1841
+ flex-shrink: 0;
1817
1842
  align-items: center;
1818
1843
  justify-content: center;
1819
1844
  width: 28px;
@@ -1927,6 +1952,13 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1927
1952
  background: transparent;
1928
1953
  box-shadow: none;
1929
1954
  }
1955
+ .cf-action-drawer .cf-form__actions {
1956
+ position: sticky;
1957
+ bottom: -7px;
1958
+ z-index: 1;
1959
+ padding-top: 8px;
1960
+ background: var(--cf-bg);
1961
+ }
1930
1962
  .cf-footer-actions .cf-actions {
1931
1963
  display: grid;
1932
1964
  grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -1951,6 +1983,14 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
1951
1983
  .cf-footer-actions .cf-booking {
1952
1984
  max-width: none;
1953
1985
  }
1986
+ .cf-body .cf-action-drawer,
1987
+ .cf-footer-actions .cf-action-drawer {
1988
+ max-height: min(420px, 45dvh);
1989
+ overflow-y: auto;
1990
+ overflow-x: hidden;
1991
+ overscroll-behavior: contain;
1992
+ scrollbar-width: thin;
1993
+ }
1954
1994
 
1955
1995
  @keyframes cf-drawer-up {
1956
1996
  from {
@@ -3353,8 +3393,8 @@ ${z}`.trim(),w,z)},[L,yt,Nt]),tn=O(()=>{const b=s.current&&!s.current.signal.abo
3353
3393
  .cf-analytics-explanation .cf-xp { font-size: 12px; }
3354
3394
  .cf-analytics-explanation.is-expanded .cf-xp { font-size: 14px; }
3355
3395
  .cf-analytics-explanation .cf-xp__headline { font-size: 15px; }
3356
- ${Cl("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)"})}
3357
- ${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']"})}
3358
3398
 
3359
3399
  @media (max-width: 639px) {
3360
3400
  .cf-panel.cf-panel--analytics-focus {
@@ -3475,4 +3515,4 @@ ${xc("cf",{bg:"var(--cf-bg)",surface:"var(--cf-surface)",surface2:"var(--cf-surf
3475
3515
  max-height: calc(100dvh - 24px);
3476
3516
  }
3477
3517
  }
3478
- `,Cr="centrinfo-widget";class rp extends HTMLElement{constructor(){super(...arguments);B(this,"controls",null);B(this,"composerDraftStore",{value:""})}mountWith(n){const a=ap(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=Lc(a);Jr(r(Qu,{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,rp);const ip=(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=>ip(e);let Do=null;const Po=e=>{Do?.destroy();const t=Lo(e);return Do=t,t},op=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},sp=e=>{if(e)try{const t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch{return}},cp=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:op(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:sp(t("data-user"))}:null},lp=document.currentScript?.src||document.querySelector('script[src*="centrinfo-widget"]')?.src||"",Oo=e=>new URL(e,lp||location.href).href;Fs(()=>import(Oo("centrinfo-widget-charts.js"))),Rc(()=>import(Oo("centrinfo-widget-dev.js")));const dp=e=>{typeof document>"u"||(document.readyState!=="loading"?e():document.addEventListener("DOMContentLoaded",e,{once:!0}))},up=()=>{const e=document.currentScript??document.querySelector("script[data-token]");if(!e)return;const t=cp(e);t&&Po(t)};dp(()=>{try{up()}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})({});