@accurix/centrinfo-widget 5.1.0 → 5.1.1

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 Pp=Object.defineProperty;var Op=(St,$t,Jt)=>$t in St?Pp(St,$t,{enumerable:!0,configurable:!0,writable:!0,value:Jt}):St[$t]=Jt;var q=(St,$t,Jt)=>Op(St,typeof $t!="symbol"?$t+"":$t,Jt);const $t={notComparable:"Not comparable yet"},Jt=e=>!e||e==="observed"||e==="confirmed_zero",Ir=(e,t)=>{let n=typeof e.value=="number"&&Number.isFinite(e.value)?e.value:null,a=typeof t.value=="number"&&Number.isFinite(t.value)?t.value:null;return e.status==="missing"||t.status==="missing"||n===null||a===null?{kind:"not_comparable",reason:"missing",label:$t.notComparable}:Jt(e.status)?Jt(t.status)?a===0?{kind:"not_comparable",reason:"previous_zero",label:n===0?"No change (0)":n>0?"Up from 0":"Down from 0"}:{kind:"change",percent:(n-a)/Math.abs(a)*100}:{kind:"not_comparable",reason:"previous_no_records",label:$t.notComparable}:{kind:"not_comparable",reason:"current_no_records",label:`${e.label?.trim()||"Current period"}: no records yet`}},yn=e=>e&&["day","week","month","quarter","year"].includes(e)?e:"period",Er=e=>e==="day"?"vs yesterday at this time":`vs same point last ${yn(e)}`,os=(e,t)=>{if(!e.cutoffAt)return;let n=new Date(e.cutoffAt);if(Number.isNaN(n.getTime()))return;let a=e.timezone||void 0,i="";try{i=new Intl.DateTimeFormat(t,{...e.grain==="day"?{}:{weekday:"short",day:"numeric",month:"short"},hour:"2-digit",minute:"2-digit",timeZone:a}).format(n)}catch{i=n.toISOString()}let o=e.grain==="day"?"on both days":`in both ${yn(e.grain)}s`,s=e.cutoffSource==="data_as_of"?", the time of the latest record":"";return`Compared up to ${i} ${o}${s}${a?` (${a})`:""}`},zr=(e,t,n,a={format:String})=>{if(!e||!e.comparisonBasis||e.comparisonBasis==="complete")return;let i=e.comparisonBasis,o=Ir(t,n);if(o.kind==="not_comparable"&&o.reason!=="previous_zero")return{basis:i,kind:"neutral",tone:"neutral",label:o.label,copy:"",reason:o.reason};let s=a.format,c=e.currentPeriod?.label||t.label||"Current period",d=e.previousPeriod?.label||n.label||"Previous period",l=typeof t.value=="number"?t.value:e.currentValue,u=typeof e.previousFullValue=="number"?e.previousFullValue:typeof n.value=="number"?n.value:void 0,p=e.grain==="day"?"full day":`full ${yn(e.grain)}`,m=u===void 0?void 0:`${d} ${p}: ${s(u)}`,f=u===void 0?void 0:`${p.charAt(0).toUpperCase()}${p.slice(1)}: ${s(u)}`;if(i==="like_for_like"&&typeof e.previousToDateValue=="number"&&typeof l=="number"){let h=Ir({value:l,status:t.status},{value:e.previousToDateValue,status:"observed"}),I=os(e,a.locale);if(h.kind==="change"){let x=h.percent;return{basis:i,kind:"change",percent:x,tone:x===0?"neutral":x>0?"positive":"negative",label:`${x>0?"↑":x<0?"↓":"→"} ${Math.abs(x).toFixed(1)}%`,copy:Er(e.grain),secondary:m,compactSecondary:f,title:I}}return{basis:i,kind:"neutral",tone:"neutral",label:h.label,copy:Er(e.grain),secondary:m,compactSecondary:f,title:I,reason:h.reason}}if(i==="not_comparable")return{basis:i,kind:"neutral",tone:"neutral",label:"Not comparable",copy:e.reason||"",reason:e.reason};let _=[typeof l=="number"?`${c} so far: ${s(l)}`:`${c}: in progress`];return u!==void 0&&_.push(`${d}: ${s(u)} (${p})`),{basis:"current_in_progress_no_time",kind:"neutral",tone:"neutral",label:_.join(" · "),copy:"",title:e.reason,reason:e.reason}},Nr=e=>e?.grain==="day"?"Yesterday at this time":`Same point last ${yn(e?.grain)}`,Ra=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?"":e.toISOString().slice(0,10);let t=typeof e=="string"?e.trim():"";return/^\d{4}-\d{2}-\d{2}/.test(t)?t.slice(0,10):""},Rr=(e,t)=>{let n=Ra(t);if(!(!n||!e)){if(e.previousPeriod?.start&&Ra(e.previousPeriod.start)===n)return"previous";if(e.currentPeriod?.start&&Ra(e.currentPeriod.start)===n)return"current"}},Lr=(e,t,n,a={format:String})=>{if(!e||!e.series?.length||!e.comparisonBasis||e.comparisonBasis==="complete")return;let i=Rr(e,t);if(!i)return;let o=String(n??""),s=e.series.find(d=>d.key===o);if(!s)return;let c=e.comparisonBasis;if(i==="previous"){let d=c==="like_for_like"&&typeof s.previousToDateValue=="number";return{side:i,basis:c,toDate:d,plotValue:d?s.previousToDateValue:void 0,fullValue:s.previousFullValue}}return{side:i,basis:c,toDate:!1,display:zr({...e,currentValue:s.currentValue,previousToDateValue:s.previousToDateValue,previousFullValue:s.previousFullValue},{value:s.currentValue,status:s.currentValue===void 0?"missing":"observed"},{value:s.previousFullValue,status:s.previousFullValue===void 0?"missing":"observed"},a)}},La=e=>!!(e&&e.seriesField&&e.series?.length&&e.comparisonBasis&&e.comparisonBasis!=="complete"&&e.comparisonBasis!=="not_comparable"),ss=e=>{if(!La(e))return;let t=e.currentPeriod?.label||"Current period";return e.comparisonBasis==="like_for_like"?`${t} so far, compared with ${Nr(e).toLowerCase()}`:`${t} so far; the previous period is shown in full, so the bars are not like for like`},cs=(e,t,n)=>{if(!t)return[];if(t.side==="previous")return typeof t.fullValue=="number"&&t.toDate?[`Full ${e?.grain==="day"?"day":yn(e?.grain)}: ${n(t.fullValue)}`]:[];let a=t.display;return a?a.kind==="change"&&a.percent!==void 0?[`${a.label} ${a.copy}`.trim()]:a.kind==="neutral"&&a.label&&t.basis==="like_for_like"?[a.label]:[]:[]},na="__previous_to_date",ls="Previous to date",Dr=(e,t)=>{let n=e.trim().toLowerCase(),a=t.trim().toLowerCase();return n===a||n.endsWith(`.${a}`)||a.endsWith(`.${n}`)},ds=e=>{let t=e.periodComparison,n=e.rows;if(!n?.length||!La(t)||t.comparisonBasis!=="like_for_like"||!t.series?.some(p=>typeof p.previousToDateValue=="number"))return e;let a=e.columnMetadata??[],i=e.columns?.filter(Boolean)??(a.length?a.map(p=>String(p.key??p.name??"")).filter(Boolean):Object.keys(n[0]??{}));if(i.includes(na))return e;let o=i.find(p=>Dr(t.seriesField,p));if(!o)return e;let s=p=>a.find(m=>(m.key??m.name)===p),c=i.find(p=>{let m=s(p);return m?.semanticRole==="date"||m?.role==="date"||m?.dataType==="date"||m?.dataType==="datetime"}),d=(t.measureField?i.find(p=>Dr(t.measureField,p)):void 0)??i.find(p=>s(p)?.semanticRole==="measure"),l=n.map(p=>{let m=c?Rr(t,p[c]):"current",f=t.series?.find(h=>h.key===String(p[o]??"")),_=m&&typeof f?.previousToDateValue=="number"?f.previousToDateValue:null;return{...p,[na]:_}}),u={...(d?s(d):void 0)??{dataType:"number",semanticRole:"measure"},key:na,name:void 0,label:ls,aggregation:"none",sourceField:void 0,priority:"secondary",groupable:!1,filterable:!1};return{...e,rows:l,columns:e.columns?[...e.columns,na]:e.columns,columnMetadata:a.length?[...a,u]:e.columnMetadata}},us=e=>!!(e?.lastPeriodInProgress||e?.caveats?.some(t=>t.code==="incomplete_final_period")||e?.periodComparison?.currentPeriod?.inProgress),ps="In progress";var aa,Re,Pr,Vt,Or,Fr,Ur,Da,ra,_n,Br,Pa,Oa,Fa,qr,ia={},oa=[],fs=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,sa=Array.isArray;function Rt(e,t){for(var n in t)e[n]=t[n];return e}function Ua(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function hs(e,t,n){var a,i,o,s={};for(o in t)o=="key"?a=t[o]:o=="ref"?i=t[o]:s[o]=t[o];if(arguments.length>2&&(s.children=arguments.length>3?aa.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(o in e.defaultProps)s[o]===void 0&&(s[o]=e.defaultProps[o]);return ca(e,s,a,i,null)}function ca(e,t,n,a,i){var o={type:e,props:t,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Pr,__i:-1,__u:0};return i==null&&Re.vnode!=null&&Re.vnode(o),o}function se(e){return e.children}function la(e,t){this.props=e,this.context=t}function cn(e,t){if(t==null)return e.__?cn(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?cn(e):null}function ms(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,a=[],i=[],o=Rt({},t);o.__v=t.__v+1,Re.vnode&&Re.vnode(o),qa(e.__P,o,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,a,n??cn(t),!!(32&t.__u),i),o.__v=t.__v,o.__.__k[o.__i]=o,Kr(a,o,i),t.__e=t.__=null,o.__e!=n&&Vr(o)}}function Vr(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),Vr(e)}function Ba(e){(!e.__d&&(e.__d=!0)&&Vt.push(e)&&!da.__r++||Or!=Re.debounceRendering)&&((Or=Re.debounceRendering)||Fr)(da)}function da(){try{for(var e,t=1;Vt.length;)Vt.length>t&&Vt.sort(Ur),e=Vt.shift(),t=Vt.length,ms(e)}finally{Vt.length=da.__r=0}}function jr(e,t,n,a,i,o,s,c,d,l,u){var p,m,f,_,h,I,x,g=a&&a.__k||oa,T=t.length;for(d=gs(n,t,g,d,T),p=0;p<T;p++)(f=n.__k[p])!=null&&(m=f.__i!=-1&&g[f.__i]||ia,f.__i=p,I=qa(e,f,m,i,o,s,c,d,l,u),_=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&ja(m.ref,null,f),u.push(f.ref,f.__c||_,f)),h==null&&_!=null&&(h=_),(x=!!(4&f.__u))||m.__k===f.__k?(d=Hr(f,d,e,x),x&&m.__e&&(m.__e=null)):typeof f.type=="function"&&I!==void 0?d=I:_&&(d=_.nextSibling),f.__u&=-7);return n.__e=h,d}function gs(e,t,n,a,i){var o,s,c,d,l,u=n.length,p=u,m=0;for(e.__k=new Array(i),o=0;o<i;o++)(s=t[o])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[o]=ca(null,s,null,null,null):sa(s)?s=e.__k[o]=ca(se,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=ca(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[o]=s,d=o+m,s.__=e,s.__b=e.__b+1,c=null,(l=s.__i=bs(s,n,d,p))!=-1&&(p--,(c=n[l])&&(c.__u|=2)),c==null||c.__v==null?(l==-1&&(i>u?m--:i<u&&m++),typeof s.type!="function"&&(s.__u|=4)):l!=d&&(l==d-1?m--:l==d+1?m++:(l>d?m--:m++,s.__u|=4))):e.__k[o]=null;if(p)for(o=0;o<u;o++)(c=n[o])!=null&&(2&c.__u)==0&&(c.__e==a&&(a=cn(c)),Zr(c,c));return a}function Hr(e,t,n,a){var i,o;if(typeof e.type=="function"){for(i=e.__k,o=0;i&&o<i.length;o++)i[o]&&(i[o].__=e,t=Hr(i[o],t,n,a));return t}e.__e!=t&&(a&&(t&&e.type&&!t.parentNode&&(t=cn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function bs(e,t,n,a){var i,o,s,c=e.key,d=e.type,l=t[n],u=l!=null&&(2&l.__u)==0;if(l===null&&c==null||u&&c==l.key&&d==l.type)return n;if(a>(u?1:0)){for(i=n-1,o=n+1;i>=0||o<t.length;)if((l=t[s=i>=0?i--:o++])!=null&&(2&l.__u)==0&&c==l.key&&d==l.type)return s}return-1}function Wr(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||fs.test(t)?n:n+"px"}function ua(e,t,n,a,i){var o,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof a=="string"&&(e.style.cssText=a=""),a)for(t in a)n&&t in n||Wr(e.style,t,"");if(n)for(t in n)a&&n[t]==a[t]||Wr(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(Br,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+o]=n,n?a?n[_n]=a[_n]:(n[_n]=Pa,e.addEventListener(t,o?Fa:Oa,o)):e.removeEventListener(t,o?Fa:Oa,o);else{if(i=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Gr(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[ra]==null)t[ra]=Pa++;else if(t[ra]<n[_n])return;return n(Re.event?Re.event(t):t)}}}function qa(e,t,n,a,i,o,s,c,d,l){var u,p,m,f,_,h,I,x,g,T,V,P,ee,Z,Y,z=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(d=!!(32&n.__u),o=[c=t.__e=n.__e]),(u=Re.__b)&&u(t);e:if(typeof z=="function")try{if(x=t.props,g=z.prototype&&z.prototype.render,T=(u=z.contextType)&&a[u.__c],V=u?T?T.props.value:u.__:a,n.__c?I=(p=t.__c=n.__c).__=p.__E:(g?t.__c=p=new z(x,V):(t.__c=p=new la(x,V),p.constructor=z,p.render=xs),T&&T.sub(p),p.state||(p.state={}),p.__n=a,m=p.__d=!0,p.__h=[],p._sb=[]),g&&p.__s==null&&(p.__s=p.state),g&&z.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Rt({},p.__s)),Rt(p.__s,z.getDerivedStateFromProps(x,p.__s))),f=p.props,_=p.state,p.__v=t,m)g&&z.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),g&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(g&&z.getDerivedStateFromProps==null&&x!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(x,V),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(x,p.__s,V)===!1){t.__v!=n.__v&&(p.props=x,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(te){te&&(te.__=t)}),oa.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(x,p.__s,V),g&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,_,h)})}if(p.context=V,p.props=x,p.__P=e,p.__e=!1,P=Re.__r,ee=0,g)p.state=p.__s,p.__d=!1,P&&P(t),u=p.render(p.props,p.state,p.context),oa.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,P&&P(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++ee<25);p.state=p.__s,p.getChildContext!=null&&(a=Rt(Rt({},a),p.getChildContext())),g&&!m&&p.getSnapshotBeforeUpdate!=null&&(h=p.getSnapshotBeforeUpdate(f,_)),Z=u!=null&&u.type===se&&u.key==null?Yr(u.props.children):u,c=jr(e,sa(Z)?Z:[Z],t,n,a,i,o,s,c,d,l),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),I&&(p.__E=p.__=null)}catch(te){if(t.__v=null,d||o!=null)if(te.then){for(t.__u|=d?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;o[o.indexOf(c)]=null,t.__e=c}else{for(Y=o.length;Y--;)Ua(o[Y]);Va(t)}else t.__e=n.__e,t.__k=n.__k,te.then||Va(t);Re.__e(te,t,n)}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=vs(n.__e,t,n,a,i,o,s,d,l);return(u=Re.diffed)&&u(t),128&t.__u?void 0:c}function Va(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Va))}function Kr(e,t,n){for(var a=0;a<n.length;a++)ja(n[a],n[++a],n[++a]);Re.__c&&Re.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(o){o.call(i)})}catch(o){Re.__e(o,i.__v)}})}function Yr(e){return typeof e!="object"||e==null||e.__b>0?e:sa(e)?e.map(Yr):e.constructor!==void 0?null:Rt({},e)}function vs(e,t,n,a,i,o,s,c,d){var l,u,p,m,f,_,h,I=n.props||ia,x=t.props,g=t.type;if(g=="svg"?i="http://www.w3.org/2000/svg":g=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),o!=null){for(l=0;l<o.length;l++)if((f=o[l])&&"setAttribute"in f==!!g&&(g?f.localName==g:f.nodeType==3)){e=f,o[l]=null;break}}if(e==null){if(g==null)return document.createTextNode(x);e=document.createElementNS(i,g,x.is&&x),c&&(Re.__m&&Re.__m(t,o),c=!1),o=null}if(g==null)I===x||c&&e.data==x||(e.data=x);else{if(o=g=="textarea"&&x.defaultValue!=null?null:o&&aa.call(e.childNodes),!c&&o!=null)for(I={},l=0;l<e.attributes.length;l++)I[(f=e.attributes[l]).name]=f.value;for(l in I)f=I[l],l=="dangerouslySetInnerHTML"?p=f:l=="children"||l in x||l=="value"&&"defaultValue"in x||l=="checked"&&"defaultChecked"in x||ua(e,l,null,f,i);for(l in x)f=x[l],l=="children"?m=f:l=="dangerouslySetInnerHTML"?u=f:l=="value"?_=f:l=="checked"?h=f:c&&typeof f!="function"||I[l]===f||ua(e,l,f,I[l],i);if(u)c||p&&(u.__html==p.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),jr(t.type=="template"?e.content:e,sa(m)?m:[m],t,n,a,g=="foreignObject"?"http://www.w3.org/1999/xhtml":i,o,s,o?o[0]:n.__k&&cn(n,0),c,d),o!=null)for(l=o.length;l--;)Ua(o[l]);c&&g!="textarea"||(l="value",g=="progress"&&_==null?e.removeAttribute("value"):_!=null&&(_!==e[l]||g=="progress"&&!_||g=="option"&&_!=I[l])&&ua(e,l,_,I[l],i),l="checked",h!=null&&h!=e[l]&&ua(e,l,h,I[l],i))}return e}function ja(e,t,n){try{if(typeof e=="function"){var a=typeof e.__u=="function";a&&e.__u(),a&&t==null||(e.__u=e(t))}else e.current=t}catch(i){Re.__e(i,n)}}function Zr(e,t,n){var a,i;if(Re.unmount&&Re.unmount(e),(a=e.ref)&&(a.current&&a.current!=e.__e||ja(a,null,t)),(a=e.__c)!=null){if(a.componentWillUnmount)try{a.componentWillUnmount()}catch(o){Re.__e(o,t)}a.base=a.__P=null}if(a=e.__k)for(i=0;i<a.length;i++)a[i]&&Zr(a[i],t,n||typeof e.type!="function");n||Ua(e.__e),e.__c=e.__=e.__e=void 0}function xs(e,t,n){return this.constructor(e,n)}function Jr(e,t,n){var a,i,o,s;t==document&&(t=document.documentElement),Re.__&&Re.__(e,t),i=(a=!1)?null:t.__k,o=[],s=[],qa(t,e=t.__k=hs(se,null,[e]),i||ia,ia,t.namespaceURI,i?null:t.firstChild?aa.call(t.childNodes):null,o,i?i.__e:t.firstChild,a,s),Kr(o,e,s)}function Ha(e){function t(n){var a,i;return this.getChildContext||(a=new Set,(i={})[t.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){a=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&a.forEach(function(s){s.__e=!0,Ba(s)})},this.sub=function(o){a.add(o);var s=o.componentWillUnmount;o.componentWillUnmount=function(){a&&a.delete(o),s&&s.call(o)}}),n.children}return t.__c="__cC"+qr++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,a){return n.children(a)}).contextType=t,t}aa=oa.slice,Re={__e:function(e,t,n,a){for(var i,o,s;t=t.__;)if((i=t.__c)&&!i.__)try{if((o=i.constructor)&&o.getDerivedStateFromError!=null&&(i.setState(o.getDerivedStateFromError(e)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,a||{}),s=i.__d),s)return i.__E=i}catch(c){e=c}throw e}},Pr=0,la.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Rt({},this.state),typeof e=="function"&&(e=e(Rt({},n),this.props)),e&&Rt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Ba(this))},la.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Ba(this))},la.prototype.render=se,Vt=[],Fr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ur=function(e,t){return e.__v.__b-t.__v.__b},da.__r=0,Da=Math.random().toString(8),ra="__d"+Da,_n="__a"+Da,Br=/(PointerCapture)$|Capture$/i,Pa=0,Oa=Gr(!1),Fa=Gr(!0),qr=0;var Xt,Pe,Wa,Xr,wn=0,Qr=[],je=Re,ei=je.__b,ti=je.__r,ni=je.diffed,ai=je.__c,ri=je.unmount,ii=je.__;function kn(e,t){je.__h&&je.__h(Pe,e,wn||t),wn=0;var n=Pe.__H||(Pe.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function $(e){return wn=1,ys(si,e)}function ys(e,t,n){var a=kn(Xt++,2);if(a.t=e,!a.__c&&(a.__=[si(void 0,t),function(c){var d=a.__N?a.__N[0]:a.__[0],l=a.t(d,c);d!==l&&(a.__N=[l,a.__[1]],a.__c.setState({}))}],a.__c=Pe,!Pe.__f)){var i=function(c,d,l){if(!a.__c.__H)return!0;var u=a.__c.__H.__.filter(function(m){return m.__c});if(u.every(function(m){return!m.__N}))return!o||o.call(this,c,d,l);var p=a.__c.props!==c;return u.some(function(m){if(m.__N){var f=m.__[0];m.__=m.__N,m.__N=void 0,f!==m.__[0]&&(p=!0)}}),o&&o.call(this,c,d,l)||p};Pe.__f=!0;var o=Pe.shouldComponentUpdate,s=Pe.componentWillUpdate;Pe.componentWillUpdate=function(c,d,l){if(this.__e){var u=o;o=void 0,i(c,d,l),o=u}s&&s.call(this,c,d,l)},Pe.shouldComponentUpdate=i}return a.__N||a.__}function X(e,t){var n=kn(Xt++,3);!je.__s&&Ya(n.__H,t)&&(n.__=e,n.u=t,Pe.__H.__h.push(n))}function Sn(e,t){var n=kn(Xt++,4);!je.__s&&Ya(n.__H,t)&&(n.__=e,n.u=t,Pe.__h.push(n))}function R(e){return wn=5,Be(function(){return{current:e}},[])}function Be(e,t){var n=kn(Xt++,7);return Ya(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function F(e,t){return wn=8,Be(function(){return e},t)}function Ga(e){var t=Pe.context[e.__c],n=kn(Xt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(Pe)),t.props.value):e.__}function _s(){for(var e;e=Qr.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(pa),t.__h.some(Ka),t.__h=[]}catch(n){t.__h=[],je.__e(n,e.__v)}}}je.__b=function(e){Pe=null,ei&&ei(e)},je.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ii&&ii(e,t)},je.__r=function(e){ti&&ti(e),Xt=0;var t=(Pe=e.__c).__H;t&&(Wa===Pe?(t.__h=[],Pe.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(pa),t.__h.some(Ka),t.__h=[],Xt=0)),Wa=Pe},je.diffed=function(e){ni&&ni(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Qr.push(t)!==1&&Xr===je.requestAnimationFrame||((Xr=je.requestAnimationFrame)||ws)(_s)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Wa=Pe=null},je.__c=function(e,t){t.some(function(n){try{n.__h.some(pa),n.__h=n.__h.filter(function(a){return!a.__||Ka(a)})}catch(a){t.some(function(i){i.__h&&(i.__h=[])}),t=[],je.__e(a,n.__v)}}),ai&&ai(e,t)},je.unmount=function(e){ri&&ri(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(a){try{pa(a)}catch(i){t=i}}),n.__H=void 0,t&&je.__e(t,n.__v))};var oi=typeof requestAnimationFrame=="function";function ws(e){var t,n=function(){clearTimeout(a),oi&&cancelAnimationFrame(t),setTimeout(e)},a=setTimeout(n,35);oi&&(t=requestAnimationFrame(n))}function pa(e){var t=Pe,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Pe=t}function Ka(e){var t=Pe;e.__c=e.__(),Pe=t}function Ya(e,t){return!e||e.length!==t.length||t.some(function(n,a){return n!==e[a]})}function si(e,t){return typeof t=="function"?t(e):t}var ks=0;function r(e,t,n,a,i,o){t||(t={});var s,c,d=t;if("ref"in d)for(c in d={},t)c=="ref"?s=t[c]:d[c]=t[c];var l={type:e,props:d,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ks,__i:-1,__u:0,__source:i,__self:o};if(typeof e=="function"&&(s=e.defaultProps))for(c in s)d[c]===void 0&&(d[c]=s[c]);return Re.vnode&&Re.vnode(l),l}const fa=(e,t=11)=>{let n=0;for(let a of e)n+=(a.codePointAt(0)??0)>11904?1:.58;return Math.ceil(n*t)},Ss=(e,t=12,n=20)=>Math.max(n,Math.ceil(e)+t),$s=(e,t=12,n=8)=>Math.ceil(t+e+n),Ts=(e,t,n=11)=>e.length===0||Math.max(...e.map(a=>fa(a,n)))<=t-4?{kind:"native"}:e.length>12?{kind:"auto"}:Math.floor((t-4)/(.58*n))>=6?{kind:"truncate",width:Math.max(16,Math.floor(t-4))}:{kind:"rotate",rotate:40,width:72},Za=e=>Array.isArray(e)?e:e?[e]:[],Cs=(e,t)=>{let n=[];for(let a of e)if(Array.isArray(a.data))for(let i of a.data){let o=i;i&&typeof i=="object"&&!Array.isArray(i)&&(o=i.value),Array.isArray(o)&&(o=o[1]),typeof o=="number"&&Number.isFinite(o)&&n.push(o)}return n},As=(e,t,n)=>{let a=e.axisLabel?.formatter,i=Cs(t),o=typeof e.min=="number"?e.min:Math.min(0,...i),s=typeof e.max=="number"?e.max:Math.max(0,...i)*1.1,c=i.length||e.min!==void 0?[o,s]:[];return c.length?Math.max(...c.map(d=>{let l=String(d);try{typeof a=="function"&&(l=String(a(d)))}catch{}return fa(l)})):fa("00000")},Ms=(e,t)=>{if(!(t>0)||Array.isArray(e.grid))return e;let n=Za(e.xAxis),a=Za(e.yAxis),i=a[0]?.type==="category",o=i?a[0]:n[0],s=i?n[0]:a[0];if(!o||o.type!=="category"||!s||s.type!=="value")return e;let c=t<420,d=Za(e.series),l={...e.grid??{}},u=(o.data??[]).map(h=>String(h&&typeof h=="object"?h.value??"":h)),p={...e,grid:l},m={...o},f={...s},_=0;if(i)c&&(_=Math.min(t*.35,90),m={...m,axisLabel:{...o.axisLabel,width:Math.floor(_),overflow:"truncate",ellipsis:"…"}},l.left=8);else{let h=As(s,d);if(_=h+8,c&&!s.name)l.left=8;else if(s.name){let I=Ss(h);f={...f,nameGap:Math.min(s.nameGap??I,I)},_+=18}}if(!i){let h=typeof l.left=="number"?l.left:0,I=typeof l.right=="number"?l.right:0,x=Ts(u,Math.max(40,t-h-I-_)/Math.max(1,u.length)),g=o.axisLabel?.fontSize??11,T=g+2;if(x.kind==="truncate"||x.kind==="rotate"){let V=x.kind==="rotate"?x.rotate:0;if(m.axisLabel={...o.axisLabel,interval:0,hideOverlap:!1,rotate:V,width:x.width,overflow:"truncate",ellipsis:"…"},V){let P=Math.max(0,...u.map(Z=>fa(Z,g))),ee=Math.min(x.width,P);T=Math.ceil(ee*Math.sin(V*Math.PI/180))+g}}o.name&&c?m.nameGap=Math.min(o.nameGap??99,$s(T,6,4)):c&&l.containLabel===!0&&typeof l.bottom=="number"&&(l.bottom=Math.min(l.bottom,8))}return i?(p.yAxis=Array.isArray(e.yAxis)?[m,...a.slice(1)]:m,p.xAxis=Array.isArray(e.xAxis)?[f,...n.slice(1)]:f):(p.xAxis=Array.isArray(e.xAxis)?[m,...n.slice(1)]:m,p.yAxis=Array.isArray(e.yAxis)?[f,...a.slice(1)]:f),p},Is=/^(\d{4})-(\d{2})-(\d{2})$/,Es=/^(\d{4})-(\d{2})$/,zs=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?$/,Ns=/(?:Z|[+-]\d{2}:?\d{2})$/i,ci=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:{date:e,calendar:!1,hasTime:!0};if(typeof e=="number"&&Number.isFinite(e))return{date:new Date(e),calendar:!1,hasTime:!0};if(typeof e!="string")return null;let t=e.trim(),n=Is.exec(t);if(n)return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]))),calendar:!0,hasTime:!1};if(n=Es.exec(t),n)return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,1)),calendar:!0,hasTime:!1};if(n=zs.exec(t),n&&!Ns.test(t))return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]),Number(n[4]),Number(n[5]),Number(n[6]??0))),calendar:!0,hasTime:!0};if(!/^\d{4}-\d{2}-\d{2}T/.test(t))return null;let a=new Date(t);return Number.isNaN(a.getTime())?null:{date:a,calendar:!1,hasTime:!0}},Rs=e=>{if(e){if(/h/i.test(e)&&/:/.test(e))return"hour";if(/d{2}/i.test(e))return"day";if(/q/i.test(e))return"quarter";if(/M{2,}/.test(e))return"month";if(/y{2,}/i.test(e))return"year"}},li=e=>{let t=e.map(ci).filter(a=>a!==null);if(t.length===0)return;let n=a=>a.date.getUTCHours()+a.date.getUTCMinutes();return t.some(a=>a.hasTime&&n(a)!==0)?t.every(a=>a.date.getUTCMinutes()===0)?"hour":void 0:t.length>1&&t.every(a=>a.date.getUTCDate()===1)?"month":"day"},Qt=(e,t)=>{try{return new Intl.DateTimeFormat(e,t)}catch{return new Intl.DateTimeFormat(e,{...t,timeZone:"UTC"})}},di=(e,t,n={})=>{let a=ci(e);if(!a)return;let i=t?.grain??Rs(t?.formatPattern)??n.grain,o=a.calendar?"UTC":n.timezone||void 0,{date:s}=a;switch(i){case"year":return Qt(n.locale,{year:"numeric",timeZone:o}).format(s);case"quarter":{let c=Number(Qt("en-US",{month:"numeric",timeZone:o}).format(s)),d=Qt(n.locale,{year:"numeric",timeZone:o}).format(s);return`Q${Math.floor((c-1)/3)+1} ${d}`}case"month":return Qt(n.locale,{month:"short",year:"numeric",timeZone:o}).format(s);case"week":case"day":return Qt(n.locale,{day:"numeric",month:"short",year:"numeric",timeZone:o}).format(s);case"hour":return Qt(n.locale,{day:"numeric",month:"short",hour:"numeric",minute:"2-digit",timeZone:o}).format(s);default:return Qt(n.locale,{dateStyle:"medium",...a.hasTime?{timeStyle:"short"}:{},timeZone:o}).format(s)}},ui=e=>{let t=e?/\.([0#]+)/.exec(e):null;if(!t)return;let n=t[1];return{min:(n.match(/0/g)??[]).length,max:n.length}},Ja=(e,t)=>{let n=ui(e);return n?{minimumFractionDigits:n.min,maximumFractionDigits:n.max}:{maximumFractionDigits:t}},$n=e=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()){let t=Number(e);if(Number.isFinite(t))return t}return null},pi=(e,t)=>t&&Math.abs(e)>=1e4?"compact":"standard",fi=(e,t={})=>new Intl.NumberFormat(t.locale,{notation:pi(e,t.compact),...Ja(t.pattern,t.maxFractionDigits??2)}).format(e),Ls=(e,t,n={})=>{let a=t?.trim().toUpperCase();if(a&&/^[A-Z]{3}$/.test(a))try{return new Intl.NumberFormat(n.locale,{style:"currency",currency:a,notation:pi(e,n.compact),...ui(n.pattern)?Ja(n.pattern,2):{}}).format(e)}catch{}return fi(e,{...n,maxFractionDigits:2})},Ds=(e,t={})=>{let n=!!(t.pattern&&/(?<!\\)%/.test(t.pattern)),a=Ja(t.pattern,2);return new Intl.NumberFormat(t.locale,{style:"percent",...a}).format(n?e:e/100)},Xa=(e,t,n={})=>{let{locale:a,compact:i}=n;return t?.dataType==="currency"?Ls(e,t.currencyCode||n.currencyCode,{locale:a,compact:i,pattern:t.formatPattern}):t?.dataType==="percent"?Ds(e,{locale:a,pattern:t.formatPattern}):fi(e,{locale:a,compact:i,pattern:t?.formatPattern,maxFractionDigits:n.maxFractionDigits})},Ps=(e,t,n={})=>{if(e==null||e==="")return"—";if(t?.dataType==="date"||t?.dataType==="datetime"){let a=di(e,t,n);if(a)return a}if(t?.dataType==="currency"||t?.dataType==="percent"){let a=$n(e);if(a!==null)return Xa(a,t,n)}return typeof e=="number"&&Number.isFinite(e)?Xa(e,t,{...n,maxFractionDigits:4}):typeof e=="boolean"?e?n.yes??"Yes":n.no??"No":String(e)},ha={resultDetails:"Result details",liveMetric:"Live metric",currentValue:"Current value",noMatchTitle:"No matching data",noMatchBody:"No approved records matched this question.",chartType:"Chart type",chooseChartType:"Choose chart type",aggregate:"Aggregate",aggregateTitle:"Ask for a new governed calculation",aggregateCharge:"New governed answer. Query charges may apply.",chartFallback:"Chart",chartLine:"Line",chartBar:"Bar",chartStackedBar:"Stacked bar",chartLineHint:"Best for change over time.",chartBarHint:"Compare categories or ranked values.",chartStackedBarHint:"Compare totals and their parts.",aggregationSum:"Total",aggregationAvg:"Average",aggregationMin:"Minimum",aggregationMax:"Maximum",aggregationCount:"Total count",aggregationCountDistinct:"Unique count",download:"Download",downloadData:"Download this data",expandTable:"Expand table",expandChart:"Expand chart",restoreView:"Restore assistant view",aboutResult:"About this result",aboutPeriod:"Period",aboutResults:"Results",aboutChecked:"Checked",aboutTimezone:"Timezone",aboutSourceData:"Source data",aboutFilters:"Filters",rowOne:"{count} row",rowMany:"{count} rows",filtersOne:"{count} applied filter",filtersMany:"{count} applied filters",filtersApplied:"{count} applied",notSet:"Not set",noValue:"No value",yes:"Yes",no:"No",chartValues:"Values",chartTitle:"{measure} by {dimension}",seriesLimited:"Showing {shown} of {total} series.",summaryLatest:"Latest ({category}): {values}.",summaryNoTrend:"No numeric trend values are available.",summaryHighest:"Highest: {category}, {series} {value}.",summaryNoComparison:"No numeric comparison values are available.",zoomControls:"Chart zoom controls",zoomIn:"Zoom in chart",zoomOut:"Zoom out chart",zoomReset:"Reset chart zoom",zoomResetShort:"Reset",zoomNone:"No chart points",zoomAllOne:"All {count} point",zoomAllMany:"All {count} points",zoomRange:"{start} – {end} · {visible} of {count} points",inProgress:"in progress",newContent:"New content",updatedAt:"Updated {time}",liveData:"Live data",viewData:"View data",hideData:"Hide data",inProgressLegend:"In progress",governedResult:"Governed result"},vt=(e,t)=>e.replace(/\{(\w+)\}/g,(n,a)=>String(t[a]??"")),Os=e=>Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!=null)),Qa=e=>({...ha,...Os(e),explanation:{...e?.explanation}});let hi=()=>Promise.resolve().then(()=>Fo),Tn=null,mi=!1;const Fs=e=>{hi=e,Tn=null,mi=!0},Us=()=>(Tn||(Tn=hi().catch(e=>{throw Tn=null,e})),Tn),en={background:"#ffffff",border:"#dce4e9",muted:"#5b7186",surface:"#ffffff",text:"#0f1e2a",colors:["#2f7f55","#2563eb","#b45309","#7c3aed"]},gi="cf-widget-category-zoom",bi=.68,ln=e=>({startIndex:0,endIndex:Math.max(0,e-1)}),Cn=(e,t)=>{if(t<=0)return ln(0);let n=t-1,a=Math.max(0,Math.min(n,Math.floor(Math.min(e.startIndex,e.endIndex))));return{startIndex:a,endIndex:Math.max(a,Math.min(n,Math.floor(Math.max(e.startIndex,e.endIndex))))}},vi=(e,t,n)=>{let a=Cn(e,n);if(n<=2)return ln(n);let i=a.endIndex-a.startIndex+1,o=t==="in"?Math.max(2,Math.floor(i*bi)):Math.min(n,Math.ceil(i/bi));if(o===i)return a;let s=(a.startIndex+a.endIndex)/2,c=n-o,d=Math.max(0,Math.min(c,Math.round(s-(o-1)/2)));return{startIndex:d,endIndex:d+o-1}},Bs=(e,t,n=ha)=>{let a=e.length;if(a===0)return n.zoomNone;let i=Cn(t,a);return i.startIndex===0&&i.endIndex===a-1?vt(a===1?n.zoomAllOne:n.zoomAllMany,{count:a}):vt(n.zoomRange,{start:e[i.startIndex]??"",end:e[i.endIndex]??"",visible:i.endIndex-i.startIndex+1,count:a})},qs=e=>{let t=e.replaceAll("_"," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim();return t?`${t.charAt(0).toUpperCase()}${t.slice(1)}`:"Value"},Vs=e=>{let t=new Set,n=[];return e.forEach(a=>{let i=a?.trim();!i||t.has(i)||(t.add(i),n.push(i))}),n},er=$n,An=e=>{if(e===null)return"null:";if(e===void 0)return"undefined:";if(typeof e=="object")try{return`object:${JSON.stringify(e)}`}catch{return"object:"}return`${typeof e}:${String(e)}`},Mn=(e,t)=>t?e.columnMetadata?.find(n=>n.key===t):void 0,tr=(e,t)=>{let n=Mn(e,t);if(!n||n.currencyCode||n.dataType!=="currency")return n;let a=e.currency;return a?.code&&!a.isMixed?{...n,currencyCode:a.code}:n},In=(e,t)=>Mn(e,t)?.label?.trim()||qs(t),js=(e,t,n,a)=>({locale:t,timezone:e.timezone||e.periodComparison?.timezone,grain:a,yes:n.yes,no:n.no}),xi=e=>e?.dataType==="date"||e?.dataType==="datetime"||e?.semanticRole==="date",yi=(e,t,n)=>{let a=Mn(e,t);if(xi(a))return a?.grain??e.periodComparison?.grain??li(n.map(i=>i[t]))},_i=(e,t,n,a,i,o)=>{if(n==null||n==="")return a.notSet;let s=Mn(e,t);if(s?.dataType==="boolean"){let c=String(n).trim().toLowerCase();return n===!1||n===0||["0","false","no"].includes(c)?a.no:a.yes}if(xi(s)){let c=di(n,s,js(e,i,a,o));if(c)return c}return String(n)},tn=(e,t,n,a=!1,i)=>Xa(e,t,{locale:i,compact:a,currencyCode:n?.currency?.code&&!n.currency.isMixed?n.currency.code:void 0}),Hs=(e,t)=>{if(e.presentation==="table"||e.presentation==="kpi")return null;if(t)return t;let n=e.chartRecommendation?.type;return n==="line"||n==="bar"||n==="stacked_bar"?n:e.type==="line"||e.type==="bar"||e.type==="stacked_bar"?e.type:null},wi=e=>e.chartRecommendation?.categoryField?.trim()||e.label?.trim()||e.columnMetadata?.find(t=>["date","dimension","geography","boolean"].includes(t.semanticRole))?.key||e.columns?.[0],ki=e=>e.chartRecommendation?.seriesField?.trim()||e.seriesField?.trim()||e.series?.trim()||void 0,Si=(e,t,n)=>{let a=Vs([...e.chartRecommendation?.valueFields??[],...e.valueFields??[],e.value,...e.columnMetadata?.filter(o=>o.semanticRole==="measure").map(o=>o.key)??[]]),i=new Set([...e.columns??[],...e.columnMetadata?.map(o=>o.key)??[],...Object.keys(e.rows?.[0]??{})]);return a.filter(o=>o!==t&&o!==n&&i.has(o)).filter(o=>e.rows?.some(s=>er(s[o])!==null))},Ws=(e,t,n,a,i,o,s)=>{let c=i?` ${vt(o.seriesLimited,{shown:a.length,total:a.length+i})}`:"",d=(u,p)=>tn(u,p,e,!1,s);if(t==="line"){let u=n.length-1,p=a.map(m=>{let f=m.values[u];return f==null?null:`${m.name}: ${d(f,m.valueColumn)}`}).filter(m=>!!m);return p.length?`${vt(o.summaryLatest,{category:n[u]??"",values:p.join("; ")})}${c}`:`${o.summaryNoTrend}${c}`}let l;return a.forEach(u=>{u.values.forEach((p,m)=>{p===null||l&&p<=l.value||(l={category:n[m]??o.notSet,series:u,value:p})})}),l?`${vt(o.summaryHighest,{category:l.category,series:l.series.name,value:d(l.value,l.series.valueColumn)})}${c}`:`${o.summaryNoComparison}${c}`},nr=(e,t,n={})=>{let a=Qa(n.labels),i=n.locale,o=Hs(e,t),s=wi(e),c=e.rows??[];if(!o||!s||c.length===0)return null;let d=ki(e),l=Si(e,s,d);if(l.length===0)return null;let u=l.length===1?d:void 0,p=yi(e,s,c),m=l[0],f=u&&La(e.periodComparison)&&(!e.periodComparison.measureField||!m||m===e.periodComparison.measureField||m.endsWith(`.${e.periodComparison.measureField}`)||e.periodComparison.measureField.endsWith(`.${m}`))?e.periodComparison:void 0,_=(()=>{if(!f?.seriesField||!u)return;let U=(B,A)=>B===A||B.endsWith(`.${A}`)||A.endsWith(`.${B}`);if(U(f.seriesField,s))return{group:s,time:u,timeIsSeries:!0};if(U(f.seriesField,u))return{group:u,time:s,timeIsSeries:!1}})(),h=U=>tn(U,tr(e,m??""),e,!1,i),I=U=>f&&_?Lr(f,U[_.time],U[_.group],{format:h,locale:i}):void 0,x=(U,B)=>f?.comparisonBasis==="like_for_like"&&Lr(f,U,f.series?.[0]?.key)?.side==="previous"?Nr(f):B,g=[],T=new Set;c.forEach(U=>{let B=An(U[s]);if(T.has(B))return;T.add(B);let A=_i(e,s,U[s],a,i,p);g.push({key:B,label:_&&!_.timeIsSeries?x(U[s],A):A})});let V=g.map(U=>U.label),P=0,ee;if(u){let U=[],B=new Set;c.forEach(y=>{let D=An(y[u]);if(B.has(D))return;B.add(D);let S=_i(e,u,y[u],a,i,yi(e,u,c));U.push({key:D,label:_?.timeIsSeries?x(y[u],S):S})});let A=U.slice(0,4);P=Math.max(0,U.length-A.length);let N=l[0];ee=A.map(y=>{let D=new Map,S=new Map;return c.forEach(O=>{if(An(O[u])!==y.key)return;let ue=An(O[s]);if(!D.has(ue)){let oe=I(O);S.set(ue,oe),D.set(ue,oe?.side==="previous"&&oe.plotValue!==void 0?oe.plotValue:er(O[N]))}}),{field:N,name:y.label,values:g.map(O=>D.get(O.key)??null),valueColumn:tr(e,N),..._?{points:g.map(O=>S.get(O.key))}:{}}})}else P=Math.max(0,l.length-4),ee=l.slice(0,4).map(U=>({field:U,name:In(e,U),values:c.map(B=>er(B[U])),valueColumn:tr(e,U)}));if(ee.length===0)return null;let Z=In(e,s),Y=a.chartValues;u?Y=In(e,l[0]):ee.length===1&&(Y=ee[0].name);let z=e.title?.trim()||vt(a.chartTitle,{measure:Y,dimension:Z}),te;if(Mn(e,s)?.semanticRole==="date"&&g.length>1&&us(e)){let U="";c.forEach(A=>{let N=String(A[s]??"");N>U&&(U=N)});let B=g.findIndex(A=>A.key===An(U));B>=0&&(te=B)}return{type:o,title:z,xAxisTitle:Z,yAxisTitle:Y,categories:V,series:ee,omittedSeriesCount:P,inProgressIndex:te,..._&&f?{comparison:f,comparisonNote:ss(f)}:{},locale:i,labels:a,summary:Ws(e,o,V,ee,P,a,i)}},ar=[{value:"sum",label:"Total"},{value:"avg",label:"Average"},{value:"min",label:"Minimum"},{value:"max",label:"Maximum"},{value:"count",label:"Total count"},{value:"count_distinct",label:"Unique count"}],Gs={sum:"aggregationSum",avg:"aggregationAvg",min:"aggregationMin",max:"aggregationMax",count:"aggregationCount",count_distinct:"aggregationCountDistinct"},Ks=(e,t=ha)=>String(t[Gs[e]]),$i=(e,t)=>{let n=e.columnMetadata?.find(a=>a.key===t)?.allowedAggregations;return n?.length?ar.filter(a=>n.includes(a.value)):[...ar]},Ys=(e,t,n)=>{let a=wi(e);if(!a||!Si(e,a,ki(e)).includes(t)||!$i(e,t).some(o=>o.value===n))return;let i=ar.find(o=>o.value===n)?.label;if(i)return`Using the same approved data, filters, and period as "${e.title?.trim()||e.label?.trim()||"the previous chart"}", calculate ${i.toLowerCase()} of ${In(e,t)} for each ${In(e,a)}. Return a chart and show a table if this app permits it.`},Zs=(e,t=ha)=>{if(e.presentation==="table"||e.presentation==="kpi")return[];let n=nr(e);if(!n)return[];let a=[{type:"line",label:t.chartLine,hint:t.chartLineHint},{type:"bar",label:t.chartBar,hint:t.chartBarHint}];return n.series.length>1&&a.push({type:"stacked_bar",label:t.chartStackedBar,hint:t.chartStackedBarHint}),a},Js=e=>t=>{let n=e.inProgressIndex??-1,a=(Array.isArray(t)?t:[t]).filter(s=>{if(!s||typeof s!="object")return!1;let c=String(s.seriesId??"").startsWith("in-progress:"),d=s.dataIndex,l=s.value;return c?d===n:!(d===n&&l==null)}),i=String(a[0]?.axisValueLabel??a[0]?.name??""),o=s=>s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");return[i?`<strong>${o(i)}</strong>`:"",...a.map(s=>{let c=e.series[Math.floor(Number(s.seriesIndex)/2)]??e.series[0];return`${String(s.marker??"")}${o(String(s.seriesName??""))}: ${o(tn(s.value,c?.valueColumn,void 0,!1,e.locale))}`})].filter(Boolean).join("<br/>")},Xs=e=>t=>{let n=(Array.isArray(t)?t:[t]).filter(s=>!!s&&typeof s=="object"),a=s=>s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),i=String(n[0]?.axisValueLabel??n[0]?.name??""),o=n.flatMap(s=>{let c=e.series[Number(s.seriesIndex)]??e.series[0],d=c?.points?.[Number(s.dataIndex)],l=u=>tn(u,c?.valueColumn,void 0,!1,e.locale);return[`${String(s.marker??"")}${a(String(s.seriesName??""))}: ${a(l(s.value))}`,...cs(e.comparison,d,l).map(u=>`<span style="opacity:.75">${a(u)}</span>`)]});return[i?`<strong>${a(i)}</strong>`:"",...o].filter(Boolean).join("<br/>")},Qs=(e,{expanded:t=!1,reducedMotion:n=!1,theme:a=en,zoomWindow:i=ln(e.categories.length)}={})=>{let o=e.series.length>1||e.type==="line"&&(e.inProgressIndex??0)>0,s=e.type==="stacked_bar",c=e.categories.length>2,d=Cn(i,e.categories.length);return{animation:!n,animationDuration:n?0:260,aria:{enabled:!0,decal:{show:!0},label:{description:`${e.title}. ${e.summary}`}},backgroundColor:"transparent",color:a.colors,textStyle:{color:a.text,fontFamily:"inherit"},grid:{top:o?t?48:42:14,right:12,bottom:t?18:10,left:10,containLabel:!0},legend:{show:o,type:"scroll",top:0,left:"center",itemWidth:12,itemHeight:8,textStyle:{color:a.muted,fontSize:t?11:10}},tooltip:{trigger:"axis",...e.type==="line"&&(e.inProgressIndex??0)>0?{formatter:Js(e)}:e.comparison?{formatter:Xs(e)}:{},triggerOn:"mousemove|click",confine:!0,backgroundColor:a.surface,borderColor:a.border,borderWidth:1,textStyle:{color:a.text,fontSize:12},axisPointer:{type:"line",lineStyle:{color:a.muted,opacity:.5}}},dataZoom:c?[{id:gi,type:"inside",xAxisIndex:0,startValue:d.startIndex,endValue:d.endIndex,minValueSpan:1,filterMode:"filter",disabled:!0}]:void 0,xAxis:{type:"category",data:e.categories,name:e.xAxisTitle,nameLocation:"middle",nameGap:t?38:32,nameTextStyle:{color:a.muted,fontSize:t?11:10},axisLine:{lineStyle:{color:a.border}},axisTick:{show:!1},axisLabel:{color:a.muted,fontSize:t?11:9,hideOverlap:!0,interval:"auto",rotate:!t&&e.categories.length>5?28:0,formatter:l=>l.length>(t?18:11)?`${l.slice(0,t?16:9)}…`:l}},yAxis:{type:"value",name:e.yAxisTitle,nameLocation:"middle",nameGap:t?52:44,nameTextStyle:{color:a.muted,fontSize:t?11:10},axisLabel:{color:a.muted,fontSize:t?11:9,formatter:l=>tn(l,e.series[0]?.valueColumn,void 0,!0,e.locale)},axisLine:{show:!1},axisTick:{show:!1},splitNumber:4,splitLine:{lineStyle:{color:a.border,opacity:.75}}},series:e.series.flatMap((l,u)=>{let p=e.inProgressIndex??-1,m={type:e.type==="line"?"line":"bar",name:l.name,data:l.values,stack:s?"total":void 0,connectNulls:!1,showSymbol:e.type==="line"&&e.categories.length<=18,symbol:"circle",symbolSize:t?7:6,smooth:!1,maxBarWidth:t?38:28,lineStyle:e.type==="line"?{width:t?3:2.5}:void 0,itemStyle:e.type==="line"?{borderColor:a.background,borderWidth:2}:{borderRadius:s?0:[4,4,0,0]},emphasis:{focus:"series"},tooltip:{valueFormatter:_=>tn(_,l.valueColumn,void 0,!1,e.locale)}};if(p<0)return[m];let f=a.colors[u%a.colors.length];return e.type==="line"?p===0?[m]:[{...m,lineStyle:{...m.lineStyle,color:f},itemStyle:{...m.itemStyle,color:f},data:l.values.map((_,h)=>h===p?null:_)},{...m,id:`in-progress:${u}`,name:e.labels.inProgressLegend||ps,showSymbol:!0,symbol:"emptyCircle",lineStyle:{width:t?3:2.5,type:"dashed",color:f,opacity:.6},itemStyle:{color:f,opacity:.6},data:l.values.map((_,h)=>h===p||h===p-1?_:null)}]:[{...m,data:l.values.map((_,h)=>h===p?{value:_,itemStyle:{opacity:.45,borderType:"dashed",borderWidth:1.5,borderColor:f}}:_)}]})}},ec=e=>{let t=getComputedStyle(e),n=(c,d)=>{for(let l of c){let u=t.getPropertyValue(l).trim();if(u)return u}return d},[a,i,o,s]=en.colors;return{background:n(["--rv-bg","--cf-bg"],en.background),border:n(["--rv-border","--cf-border"],en.border),muted:n(["--rv-muted","--cf-muted"],en.muted),surface:n(["--rv-surface","--cf-surface"],en.surface),text:n(["--rv-text","--cf-text"],en.text),colors:[n(["--rv-chart-1","--rv-accent","--cf-accent"],a),n(["--rv-chart-2"],i),n(["--rv-chart-3"],o),n(["--rv-chart-4"],s)]}},tc=["data-theme","data-color-scheme","class","style"],nc=(e,t)=>{let n=[];if(typeof matchMedia<"u"){let a=matchMedia("(prefers-color-scheme: dark)");a.addEventListener?.("change",t),n.push(()=>a.removeEventListener?.("change",t))}if(typeof MutationObserver<"u"){let a=new MutationObserver(t),i=e;for(;i;){i instanceof Element&&a.observe(i,{attributes:!0,attributeFilter:tc});let o=i.parentNode;i=o instanceof ShadowRoot?o.host:o}n.push(()=>a.disconnect())}return()=>n.forEach(a=>a())},ac=({model:e,expanded:t=!1,classPrefix:n="cf"})=>{let a=R(null),i=R(null),[o,s]=$(()=>({model:e,window:ln(e.categories.length)})),[c,d]=$(!1),l=o.model===e?Cn(o.window,e.categories.length):ln(e.categories.length),u=R(l);u.current=l;let p=Y=>{let z=Cn(Y,e.categories.length);u.current=z,s({model:e,window:z}),i.current?.dispatchAction({type:"dataZoom",dataZoomId:gi,startValue:z.startIndex,endValue:z.endIndex})},[m,f]=$(!1),[_,h]=$(0),[I,x]=$(0);X(()=>{let Y=a.current;if(Y)return nc(Y,()=>x(z=>z+1))},[]),X(()=>{let Y=a.current;if(!Y)return;let z=!1,te=null;return Us().then(({init:U})=>{if(z||!Y.isConnected||!mi&&typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("jsdom"))return;let B=U(Y,null,{renderer:"canvas",devicePixelRatio:Math.min(window.devicePixelRatio||1,2)});i.current=B;let A=()=>{B.resize(),h(Math.round(Y.clientWidth/40))},N=typeof ResizeObserver>"u"?null:new ResizeObserver(A);N?.observe(Y),N||window.addEventListener("resize",A,{passive:!0}),te=()=>{N?.disconnect(),N||window.removeEventListener("resize",A),B.dispose(),i.current=null},f(!0)}).catch(()=>{z||d(!0)}),()=>{z=!0,te?.()}},[]),X(()=>{let Y=a.current,z=i.current;if(!Y||!z)return;let te=typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;z.setOption(Ms(Qs(e,{expanded:t,reducedMotion:te,theme:ec(Y),zoomWindow:u.current}),Y.clientWidth),{lazyUpdate:!0,notMerge:!0}),z.resize()},[t,e,m,I,_]);let g=e.labels,T=!c&&e.categories.length>2,V=l.endIndex-l.startIndex+1,P=l.startIndex===0&&l.endIndex===e.categories.length-1,ee=T&&V>2,Z=T&&!P;return r(se,{children:[r("div",{ref:a,class:`${n}-analytics-echart${t?" is-expanded":""}`,role:"img","aria-label":`${e.title}. ${e.summary}`,"data-chart-status":c?"fallback":"ready",children:c?r("span",{class:`${n}-analytics-echart__fallback`,children:e.summary}):null}),e.comparisonNote?r("p",{class:`${n}-analytics-comparison-note`,"data-comparison-note":!0,style:"margin:4px 2px 0;font-size:11px;color:var(--rv-muted,#5b7186)",children:e.comparisonNote}):null,T?r("div",{class:`${n}-analytics-zoom`,children:[r("span",{class:`${n}-analytics-zoom__range`,"aria-live":"polite","aria-atomic":"true",children:Bs(e.categories,l,g)}),r("div",{class:`${n}-analytics-zoom__controls`,role:"group","aria-label":g.zoomControls,children:[r("button",{type:"button","aria-label":g.zoomOut,title:g.zoomOut,disabled:!Z,onClick:()=>p(vi(u.current,"out",e.categories.length)),children:"−"}),r("button",{type:"button",class:`${n}-analytics-zoom__reset`,"aria-label":g.zoomReset,title:g.zoomReset,disabled:P,onClick:()=>p(ln(e.categories.length)),children:g.zoomResetShort}),r("button",{type:"button","aria-label":g.zoomIn,title:g.zoomIn,disabled:!ee,onClick:()=>p(vi(u.current,"in",e.categories.length)),children:"+"})]})]}):null]})},En=e=>{let t=e.replaceAll("_"," ").replace(/([a-z])([A-Z])/g,"$1 $2").trim();return t?`${t.charAt(0).toUpperCase()}${t.slice(1)}`:"Value"},Ti=(e,t)=>(t?.length?t:Object.keys(e[0]??{})).map(n=>typeof n=="string"?{key:n,label:En(n)}:{...n,label:n.label?.trim()||En(n.key)}),rr=(e,t,n,a={})=>Ps(e,n,{...a,locale:t??a.locale}),Ci=e=>{let t=String(e??"");return/[",\r\n]/.test(t)?`"${t.replaceAll('"','""')}"`:t},rc=(e,t)=>{let n=Ti(e,t);return[n.map(a=>Ci(a.label)).join(","),...e.map(a=>n.map(i=>Ci(a[i.key])).join(","))].join(`\r
2
+ `)},Ai=({label:e,options:t,value:n,onChange:a,classPrefix:i})=>{let o=R(null),s=R(null),[c,d]=$(n),[l,u]=$(!1);X(()=>d(n),[n]);let p=f=>`${i}-${f}`,m=f=>{d(f),o.current&&(o.current.dataset.value=f,o.current.open=!1,o.current.querySelector("summary")?.focus()),a?.(f)};return r("details",{ref:o,"data-result-popover":!0,"data-result-select":!0,"data-value":c,class:p("sdk-select"),onToggle:f=>{let _=f.currentTarget.open;u(_);let h=s.current;if(h){if(h.setAttribute("popover","manual"),!_){typeof h.hidePopover=="function"&&h.matches(":popover-open")&&h.hidePopover();return}typeof h.showPopover=="function"&&!h.matches(":popover-open")&&h.showPopover(),requestAnimationFrame(()=>{if(!o.current?.open||!h.isConnected)return;let I=o.current.querySelector("summary").getBoundingClientRect(),x=Math.max(I.width,Math.min(220,innerWidth-24)),g=Math.min(h.scrollHeight,240);h.style.width=`${x}px`,h.style.left=`${Math.max(12,Math.min(I.left,innerWidth-x-12))}px`,h.style.top=`${I.bottom+g+6<=innerHeight-12?I.bottom+6:Math.max(12,I.top-g-6)}px`})}},children:[r("summary",{class:p("sdk-select-trigger"),role:"combobox","aria-label":e,"aria-haspopup":"listbox","aria-expanded":l,children:[r("span",{children:t.find(([f])=>f===c)?.[1]??c}),r("span",{"aria-hidden":"true",children:"⌄"})]}),r("div",{ref:s,class:p("sdk-select-list"),role:"listbox","aria-label":e,popover:"manual",children:t.map(([f,_])=>r("button",{type:"button",role:"option","aria-selected":f===c,onClick:()=>m(f),children:_},f))})]})},ic=(e,t,n)=>{let a=n.value.trim();if(!a)return!0;let i=String(e??""),o=typeof e=="number"?e:NaN,s=Number(a),c=!Number.isNaN(o)&&!Number.isNaN(s)?o-s:i.localeCompare(a,void 0,{numeric:!0,sensitivity:"base"});switch(n.operator){case"equals":return c===0;case"not_equals":return c!==0;case"gt":return c>0;case"gte":return c>=0;case"lt":return c<0;case"lte":return c<=0;default:return i.toLocaleLowerCase().includes(a.toLocaleLowerCase())||t.toLocaleLowerCase().includes(a.toLocaleLowerCase())}},oc=({rows:e,columns:t,maxRows:n=100,locale:a,format:i,expanded:o=!1,classPrefix:s="cr",pageSize:c=10})=>{let d=Be(()=>Ti(e,t),[t,e]),l=d.map(k=>k.key).join("\0"),[u,p]=$(()=>d.map(k=>k.key)),[m,f]=$(""),[_,h]=$(),[I,x]=$("asc"),[g,T]=$({}),[V,P]=$(),[ee,Z]=$([]),[Y,z]=$({}),[te,U]=$(()=>d.map(k=>k.key)),[B,A]=$(!1),[N,y]=$([]),[D,S]=$("table"),[O,ue]=$(1),[oe,Fe]=$(c),_e=R(null);X(()=>{let k=j=>{let G=j.composedPath();_e.current?.querySelectorAll("details[data-result-popover][open]").forEach(ne=>{G.includes(ne)||(ne.open=!1)})},K=j=>{let G=[..._e.current?.querySelectorAll("details[data-result-popover][open]")??[]].at(-1);j.key!=="Escape"||!G||(G.open=!1,G.querySelector("summary")?.focus(),j.preventDefault())};return document.addEventListener("pointerdown",k),document.addEventListener("keydown",K),()=>{document.removeEventListener("pointerdown",k),document.removeEventListener("keydown",K)}},[]),X(()=>{p(d.map(k=>k.key)),h(void 0),T({}),P(void 0),Z([]),z({}),U(d.map(k=>k.key)),y([]),ue(1)},[l]);let Te=te.map(k=>d.find(K=>K.key===k)).filter(k=>!!(k&&u.includes(k.key))),Le=Be(()=>{let k=m.toLocaleLowerCase(a),K=e.map((j,G)=>({row:j,index:G})).filter(({row:j})=>Te.some(G=>rr(j[G.key],a,G,i).toLocaleLowerCase(a).includes(k))&&Object.entries(g).every(([G,ne])=>{let ye=d.find(Se=>Se.key===G);return ic(j[G],rr(j[G],a,ye,i),ne)}));return _?K.sort((j,G)=>{let ne=j.row[_],ye=G.row[_],Se=typeof ne=="number"?ne:NaN,et=typeof ye=="number"?ye:NaN,Ye=!Number.isNaN(Se)&&!Number.isNaN(et)?Se-et:String(ne??"").localeCompare(String(ye??""),a,{numeric:!0,sensitivity:"base"});return I==="asc"?Ye:-Ye}):K},[Te,g,i,a,m,d,e,I,_]),Ie=Le.slice(0,Math.max(1,n)),Ce=Math.max(1,Math.ceil(Ie.length/oe)),ve=Math.min(O,Ce),Xe=o?Ie:Ie.slice((ve-1)*oe,ve*oe),ge=Xe.length>0&&Xe.every(({index:k})=>N.includes(k)),ie=k=>`${s}-${k}`,He=()=>{p(d.map(k=>k.key)),U(d.map(k=>k.key)),z({}),h(void 0),x("asc"),T({}),P(void 0),Z([]),A(!1),f(""),y([]),S("table"),ue(1)};if(e.length===0||d.length===0)return r("div",{class:ie("table-note"),children:"No rows returned."});let We=k=>{let K=new Set(Xe.map(({index:j})=>j));y(j=>k?[...new Set([...j,...K])]:j.filter(G=>!K.has(G)))};return r("section",{ref:_e,class:ie("data-table"),children:[r("div",{class:ie("table-fields"),children:[r("strong",{children:"Fields"}),r("div",{class:ie("field-list"),children:d.map(k=>r("span",{class:ie("field-chip"),children:k.label},k.key))}),r("span",{class:ie("table-field-count"),children:[e.length.toLocaleString(a)," rows"]})]}),r("div",{class:ie("table-controls"),children:[r("label",{class:ie("table-search"),children:[r("span",{"aria-hidden":"true",children:"⌕"}),r("input",{type:"search",value:m,placeholder:"Search this result...","aria-label":"Search this result",onInput:k=>{f(k.currentTarget.value.trim()),ue(1)}})]}),r("div",{class:ie("table-modes"),role:"group","aria-label":"Table display mode",children:["table","matrix"].map(k=>r("button",{type:"button",class:`${ie("segment")}${D===k?" is-active":""}`,"aria-pressed":D===k,onClick:()=>S(k),children:k==="table"?"Table":"Matrix"},k))})]}),r("div",{class:ie("table-column-bar"),children:[r("details",{"data-result-popover":!0,class:ie("column-picker"),children:[r("summary",{children:"Columns"}),r("div",{class:ie("column-menu"),children:te.map((k,K)=>{let j=d.find(G=>G.key===k);return j?r("div",{class:ie("column-picker-row"),children:[r("label",{children:[r("input",{type:"checkbox",checked:u.includes(j.key),onChange:G=>{let ne=G.currentTarget.checked;p(ye=>ne?[...new Set([...ye,j.key])]:ye.length>1?ye.filter(Se=>Se!==j.key):ye)}}),r("span",{children:Y[j.key]||j.label})]}),r("button",{type:"button","aria-label":`Move ${j.label} left`,disabled:K===0,onClick:()=>U(G=>{let ne=[...G];return[ne[K-1],ne[K]]=[ne[K],ne[K-1]],ne}),children:"↑"}),r("button",{type:"button","aria-label":`Move ${j.label} right`,disabled:K===te.length-1,onClick:()=>U(G=>{let ne=[...G];return[ne[K+1],ne[K]]=[ne[K],ne[K+1]],ne}),children:"↓"})]},j.key):null})})]}),r("button",{type:"button",class:ie("table-view-button"),"aria-pressed":B,onClick:()=>A(k=>!k),children:B?"Comfortable rows":"Compact rows"}),r("button",{type:"button",class:ie("table-view-button"),onClick:He,children:"Reset view"})]}),Object.keys(g).length?r("div",{class:ie("table-filter-bar"),children:Object.entries(g).map(([k,K])=>{let j=d.find(G=>G.key===k);return r("button",{type:"button",class:ie("table-filter-chip"),"aria-label":`Clear ${j?.label??k} filter`,onClick:()=>T(G=>{let ne={...G};return delete ne[k],ne}),children:[Y[k]||j?.label||k," ",K.operator.replaceAll("_"," ")," ",K.value," ×"]},k)})}):null,r("div",{class:ie("table-wrap"),role:"region","aria-label":"Scrollable result table",tabIndex:0,children:r("table",{class:`${ie("table")}${D==="matrix"?" is-matrix":""}${B?" is-compact":""}`,children:[r("caption",{class:ie("visually-hidden"),children:["Result table with ",Le.length," ",Le.length===1?"row":"rows"]}),r("thead",{children:r("tr",{children:[r("th",{class:ie("select-cell"),children:r("input",{type:"checkbox","aria-label":"Select all visible rows",checked:ge,onChange:k=>We(k.currentTarget.checked)})}),Te.map(k=>r("th",{scope:"col",class:V===k.key?"is-pinned":void 0,style:V===k.key?{left:"34px"}:void 0,"aria-sort":_===k.key?I==="asc"?"ascending":"descending":"none",children:[r("button",{type:"button",class:ie("table-sort"),"aria-label":`Sort by ${k.label}`,onClick:()=>{_===k.key?x(K=>K==="asc"?"desc":"asc"):(h(k.key),x("asc")),ue(1)},children:[r("span",{children:Y[k.key]||k.label}),r("span",{class:ie("sort-direction"),"aria-hidden":"true",children:_===k.key?I==="asc"?"↑":"↓":"↕"})]}),r("details",{"data-result-popover":!0,class:ie("table-column-menu"),onToggle:K=>{let j=K.currentTarget,G=j.querySelector(`.${ie("table-column-panel")}`);if(G?.setAttribute("popover","manual"),!j.open){G&&typeof G.hidePopover=="function"&&G.matches(":popover-open")&&G.hidePopover(),j.querySelectorAll("details[data-result-select][open]").forEach(ne=>{ne.open=!1});return}_e.current?.querySelectorAll("details[data-result-popover][open]").forEach(ne=>{ne!==j&&!j.contains(ne)&&(ne.open=!1)}),G&&typeof G.showPopover=="function"&&!G.matches(":popover-open")&&G.showPopover(),requestAnimationFrame(()=>{if(!j.open||!j.isConnected)return;let ne=j.querySelector("summary")?.getBoundingClientRect();if(!ne||!G)return;let{width:ye,height:Se}=G.getBoundingClientRect(),et=ne.bottom+Se+5<=innerHeight-12?ne.bottom+5:ne.top-Se-5;G.style.left=`${Math.max(12,Math.min(ne.right-ye,innerWidth-ye-12))}px`,G.style.top=`${Math.max(12,Math.min(et,innerHeight-Se-12))}px`})},children:[r("summary",{"aria-label":`Actions for ${k.label}`,children:"⋯"}),r("div",{class:ie("table-column-panel"),popover:"manual",children:[r("strong",{children:Y[k.key]||k.label}),r("button",{type:"button",onClick:()=>{h(k.key),x("asc"),ue(1)},children:"Sort ascending"}),r("button",{type:"button",onClick:()=>{h(k.key),x("desc"),ue(1)},children:"Sort descending"}),r("span",{children:"Filter values"}),r(Ai,{classPrefix:s,label:`Filter operator for ${k.label}`,value:g[k.key]?.operator??"contains",options:[["contains","Contains"],["equals","Equals"],["not_equals","Does not equal"],["gt","Greater than"],["gte","At least"],["lt","Less than"],["lte","At most"]]}),r("input",{type:"text","aria-label":`Filter value for ${k.label}`,defaultValue:g[k.key]?.value??"",placeholder:"Enter a value"}),r("button",{type:"button",onClick:K=>{let j=K.currentTarget.parentElement,G=j.querySelector('input[aria-label^="Filter value"]').value.trim(),ne=j.querySelector("[data-result-select]").dataset.value;T(ye=>{let Se={...ye};return G?Se[k.key]={operator:ne,value:G}:delete Se[k.key],Se}),ue(1),K.currentTarget.closest("details").open=!1},children:"Apply filter"}),r("button",{type:"button",onClick:K=>{P(j=>j===k.key?void 0:k.key),U(j=>[k.key,...j.filter(G=>G!==k.key)]),K.currentTarget.closest("details").open=!1},children:V===k.key?"Unpin column":"Pin column"}),r("button",{type:"button",onClick:K=>{Z(j=>j.includes(k.key)?j.filter(G=>G!==k.key):[...j,k.key]),K.currentTarget.closest("details").open=!1},children:ee.includes(k.key)?"Do not wrap text":"Wrap text"}),r("input",{type:"text","aria-label":`Display name for ${k.label}`,defaultValue:Y[k.key]||k.label,maxLength:80}),r("button",{type:"button",onClick:K=>{let j=K.currentTarget.parentElement.querySelector('input[aria-label^="Display name"]').value.trim();z(G=>({...G,[k.key]:j||k.label||k.key})),K.currentTarget.closest("details").open=!1},children:"Apply display name"})]})]})]},k.key))]})}),r("tbody",{children:Xe.map(({row:k,index:K})=>r("tr",{class:N.includes(K)?"is-selected":void 0,children:[r("td",{class:ie("select-cell"),children:r("input",{type:"checkbox","aria-label":`Select row ${K+1}`,checked:N.includes(K),onChange:j=>y(G=>j.currentTarget.checked?[...new Set([...G,K])]:G.filter(ne=>ne!==K))})}),Te.map(j=>r("td",{class:`${ee.includes(j.key)?"is-wrapped":""} ${V===j.key?"is-pinned":""}`.trim(),style:V===j.key?{left:"34px"}:void 0,children:rr(k[j.key],a,j,i)},j.key))]},K))})]})}),r("div",{class:ie("table-summary"),children:[r("span",{children:Ie.length?`${((ve-1)*oe+1).toLocaleString(a)}-${Math.min(ve*oe,Ie.length).toLocaleString(a)} of ${Le.length.toLocaleString(a)}`:`0 of ${Le.length.toLocaleString(a)}`}),o?r("span",{children:e.length>n?`First ${n.toLocaleString(a)} rows available`:"All returned rows loaded"}):r("div",{class:ie("table-pagination"),"aria-label":"Table pagination",children:[r("label",{children:[r("span",{children:"Rows"}),r(Ai,{classPrefix:s,label:"Rows per page",value:String(oe),options:[["10","10"],["25","25"],["50","50"]],onChange:k=>{Fe(Number(k)),ue(1)}})]}),r("button",{type:"button","aria-label":"Previous page",disabled:ve<=1,onClick:()=>ue(k=>Math.max(1,k-1)),children:"‹"}),r("span",{children:[ve," / ",Ce]}),r("button",{type:"button","aria-label":"Next page",disabled:ve>=Ce,onClick:()=>ue(k=>Math.min(Ce,k+1)),children:"›"})]})]})]})},sc=(e,t,n)=>{let a=Qa(t),i=[],o=e.reportingPeriod?.label?.trim();o&&i.push({label:a.aboutPeriod,value:o});let s=e.rowCount??e.rows?.length;typeof s=="number"&&i.push({label:a.aboutResults,value:vt(s===1?a.rowOne:a.rowMany,{count:s})});let c=e.explanation?.checkedAt??e.freshness?.answeredAt,d=e.explanation?.timezone??e.timezone??e.reportingPeriod?.timezone;if(c){let u=new Date(c),p=c;if(!Number.isNaN(u.getTime()))try{p=new Intl.DateTimeFormat(n,{dateStyle:"medium",timeStyle:"short",...d?{timeZone:d}:{}}).format(u)}catch{p=u.toLocaleString(n)}i.push({label:a.aboutChecked,value:p})}d&&i.push({label:a.aboutTimezone,value:d});let l=e.explanation?.dataFreshness?.status??e.freshness?.status;return l&&l!=="unknown"&&i.push({label:a.aboutSourceData,value:l.replaceAll("_"," ")}),e.appliedFilters?.length&&i.push({label:a.aboutFilters,value:vt(a.filtersApplied,{count:e.appliedFilters.length})}),i},Mi=e=>e.columns?.length?e.columns:Object.keys(e.rows?.[0]??{}),cc=e=>{let t=e.rows??[],n=e.currency?.code&&!e.currency.isMixed?e.currency.code:void 0;return Mi(e).map(a=>{let i=e.columnMetadata?.find(s=>s.key===a);if(!i)return{key:a,label:En(a)};let o=i.dataType==="date"||i.dataType==="datetime"||i.semanticRole==="date";return{key:a,label:i.label,dataType:i.dataType,currencyCode:i.currencyCode||(i.dataType==="currency"?n:void 0),formatPattern:i.formatPattern,grain:o?i.grain??e.periodComparison?.grain??li(t.map(s=>s[a])):void 0}})},lc=(e,t)=>{let n=e.rows?.[0]??{};return e.chartRecommendation?.valueFields?.[0]??e.valueFields?.[0]??e.value??e.columnMetadata?.find(a=>a.semanticRole==="measure"&&a.key in n)?.key??t.find(a=>$n(n[a])!==null)??t[1]??t[0]},dc=(e,t,n="analytics-result.csv")=>{if(typeof document>"u"||e.length===0)return;let a=rc(t,e),i=URL.createObjectURL(new Blob([a],{type:"text/csv;charset=utf-8"})),o=document.createElement("a");o.href=i,o.download=n,o.click(),URL.revokeObjectURL(i)},dn=new Set,Ii=e=>{let t=e.composedPath();dn.forEach(n=>{n.isOpen()&&!n.contains(t)&&n.close(!1)})},Ei=e=>{if(e.key==="Escape"){for(let t of dn)if(t.isOpen()){t.close(!0),e.preventDefault();return}}},uc=e=>(dn.size===0&&typeof document<"u"&&(document.addEventListener("pointerdown",Ii),document.addEventListener("keydown",Ei)),dn.add(e),()=>{dn.delete(e),dn.size===0&&typeof document<"u"&&(document.removeEventListener("pointerdown",Ii),document.removeEventListener("keydown",Ei))}),ma=({children:e,size:t=15})=>r("svg",{viewBox:"0 0 24 24",width:t,height:t,fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false",children:e}),pc=()=>r(ma,{children:r("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})}),fc=()=>r(ma,{children:r("path",{d:"M18 6 6 18M6 6l12 12"})}),zi=()=>r(ma,{size:13,children:r("path",{d:"m6 9 6 6 6-6"})}),hc=()=>r(ma,{size:13,children:r("path",{d:"m5 12 5 5L20 7"})}),Ni=({type:e,className:t})=>r("svg",{viewBox:"0 0 32 32","aria-hidden":"true",class:t,fill:"none",children:[r("path",{d:"M6 26h21M6 7v19",stroke:"var(--rv-muted)","stroke-width":"1.4","stroke-linecap":"round"}),e==="line"?r("path",{d:"M8 21c4-7 7 2 11-6 2.5-5 4.5-2 7-7",stroke:"var(--rv-chart-2)","stroke-width":"2.1","stroke-linecap":"round","stroke-linejoin":"round"}):e==="stacked_bar"?r(se,{children:[9,15,21].map((n,a)=>r("g",{children:[r("rect",{x:n,y:18-a*2,width:"4",height:8+a*2,fill:"var(--rv-chart-2)",rx:"0.6"}),r("rect",{x:n,y:13-a,width:"4",height:"5",fill:"var(--rv-chart-3)",rx:"0.6"}),r("rect",{x:n,y:9-a,width:"4",height:"4",fill:"var(--rv-chart-1)",rx:"0.6"})]},n))}):r(se,{children:[r("rect",{x:"9",y:"18",width:"4",height:"8",fill:"var(--rv-chart-2)",rx:"0.7"}),r("rect",{x:"15",y:"13",width:"4",height:"13",fill:"var(--rv-chart-2)",rx:"0.7"}),r("rect",{x:"21",y:"8",width:"4",height:"18",fill:"var(--rv-chart-2)",rx:"0.7"})]})]}),Ri=e=>{let[t,n]=$(!1),a=R(null),i=R(null),o=R(t);return o.current=t,X(()=>uc({isOpen:()=>o.current,contains:s=>!!(a.current&&s.includes(a.current)||i.current&&s.includes(i.current)),close:s=>{n(!1),s&&a.current?.focus()}}),[]),Sn(()=>{if(!t)return;let s=()=>{let c=a.current,d=i.current;if(!c||!d)return;d.style.left="0px",d.style.top="0px";let l=d.getBoundingClientRect(),u=c.getBoundingClientRect(),p=document.documentElement.clientWidth||window.innerWidth,m=document.documentElement.clientHeight||window.innerHeight,f=getComputedStyle(c).direction==="rtl",_=e==="end"===f?u.left:u.right-l.width;_=Math.max(8,Math.min(_,p-l.width-8));let h=u.bottom+7;h+l.height>m-8&&u.top-7-l.height>8&&(h=u.top-7-l.height),d.style.left=`${_-l.left}px`,d.style.top=`${h-l.top}px`};return s(),window.addEventListener("resize",s),window.addEventListener("scroll",s,!0),i.current?.querySelector('[aria-selected="true"], button')?.focus({preventScroll:!0}),()=>{window.removeEventListener("resize",s),window.removeEventListener("scroll",s,!0)}},[t,e]),{open:t,setOpen:n,triggerRef:a,layerRef:i}},mc=({visualization:e,field:t,prefix:n,labels:a,locale:i,headerTitle:o})=>{let s=e.rows??[],c=e.columnMetadata?.find(x=>x.key===t),d=t?s[0]?.[t]:void 0,l=$n(d),u=x=>tn(x,c,e,!1,i),p=l===null?String(d??a.noValue):u(l),m=e.periodComparison,f=!m?.measureField||m.measureField===t,_=t?$n(s[1]?.[t]):null,h=l!==null&&m&&f?zr(m,{value:l,status:"observed",label:m.currentPeriod?.label},{value:_??m.previousFullValue??m.previousToDateValue,status:"observed",label:m.previousPeriod?.label},{format:u,locale:i}):void 0,I=c?.label??(t?En(t):a.currentValue);return r("section",{class:`${n}-analytics-kpi`,"aria-label":o??I,"data-testid":"analytics-kpi",children:[r("div",{class:`${n}-analytics-kpi__label`,children:I}),r("div",{class:`${n}-analytics-kpi__value`,children:p}),h?r(se,{children:[r("div",{class:`${n}-analytics-kpi__change is-${h.tone}`,"data-comparison-basis":h.basis,title:h.title,children:[r("span",{children:h.label}),h.copy?r("span",{class:`${n}-analytics-kpi__copy`,children:h.copy}):null]}),h.secondary?r("div",{class:`${n}-analytics-kpi__secondary`,children:h.secondary}):null]}):null]})},gc=({visualization:e,classPrefix:t,labels:n,locale:a,expanded:i=!1,onExpand:o,onClose:s,expandControlId:c,onFollowUp:d,onDownload:l,headerActions:u,children:p,dataToggle:m,cardRef:f,maxTableRows:_=100})=>{let h=Be(()=>Qa(n),[n]),I=Be(()=>nr(e,void 0,{labels:h,locale:a}),[e,h,a]),[x,g]=$(I?.type);X(()=>g(I?.type),[I]);let[T,V]=$(!1),P=Be(()=>Zs(e,h),[e,h]),ee=Be(()=>nr(e,x,{labels:h,locale:a}),[e,x,h,a]),Z=x??ee?.type??I?.type,Y=P.find(ge=>ge.type===Z),z=[...new Set(ee?.series.map(ge=>ge.field)??[])],te=Ri("end"),U=Ri("start"),B=e.rows??[],A=Mi(e),N=Be(()=>ds(e),[e]),y=Be(()=>cc(N),[N]),D=Be(()=>({locale:a,timezone:e.timezone||e.periodComparison?.timezone,yes:h.yes,no:h.no}),[a,e.timezone,e.periodComparison?.timezone,h]),S=sc(e,h,a),O=l===!1||!e.downloadAvailable?null:()=>(l??dc)(A,B),ue=S.length?r("details",{class:`${t}-analytics-inspect`,children:[r("summary",{children:h.aboutResult}),r("dl",{children:S.map(ge=>r("div",{children:[r("dt",{children:ge.label}),r("dd",{children:ge.value})]},ge.label))})]}):null,oe=(()=>{let ge=e.freshness?.answeredAt,ie=ge?new Date(ge):null;return!ie||Number.isNaN(ie.getTime())?h.liveData:vt(h.updatedAt,{time:new Intl.DateTimeFormat(a,{hour:"numeric",minute:"2-digit"}).format(ie)})})(),Fe=e.rowCount??B.length,_e=e.appliedFilters?.length??0,Te=r("div",{class:`${t}-analytics-meta`,"data-testid":"analytics-result-meta",role:"group","aria-label":h.resultDetails,children:[r("span",{children:[r("span",{"aria-hidden":"true",class:`${t}-analytics-meta__dot`}),oe]}),e.reportingPeriod?.label?r("span",{children:e.reportingPeriod.label}):null,r("span",{children:vt(Fe===1?h.rowOne:h.rowMany,{count:Fe})}),_e>0?r("span",{children:vt(_e===1?h.filtersOne:h.filtersMany,{count:_e})}):null]}),Le=(ge,ie,He,We=h.expandChart)=>r("div",{class:`${t}-analytics-result`,children:[r("section",{ref:f,class:`${t}-analytics-visualization${i?" is-expanded":""}`,"aria-label":ge,children:[r("div",{class:`${t}-analytics-visualization__header`,children:[r("div",{children:[r("div",{class:`${t}-analytics-visualization__title`,children:ge}),Te]}),r("div",{class:`${t}-analytics-visualization__actions`,children:[He,u,i&&s?r("button",{type:"button",class:`${t}-analytics-visualization__close`,"aria-label":h.restoreView,title:h.restoreView,onClick:s,children:r(fc,{})}):o&&e.expandable!==!1?r("button",{type:"button",class:`${t}-analytics-visualization__expand`,"aria-label":We,title:We,"data-visualization-message":c,onClick:o,children:r(pc,{})}):null]})]}),ie,ue,p]}),r("div",{class:`${t}-analytics-layer`,children:[d?r("div",{ref:U.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:"fixed"},role:"menu","aria-label":h.aggregate,hidden:!U.open,children:z.flatMap(k=>$i(e,k).map(K=>{let j=e.columnMetadata?.find(G=>G.key===k)?.label??En(k);return r("button",{type:"button",role:"menuitem",onClick:()=>{let G=Ys(e,k,K.value);G&&d(G),U.setOpen(!1)},children:r("span",{class:`${t}-analytics-chart-picker__copy`,children:[r("strong",{children:[Ks(K.value,h)," · ",j]}),r("small",{children:h.aggregateCharge})]})},`${k}:${K.value}`)}))}):null,r("div",{ref:te.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:"fixed"},role:"listbox","aria-label":h.chartType,hidden:!te.open,children:P.map(k=>{let K=k.type===Z;return r("button",{type:"button",role:"option","aria-selected":K,class:K?"is-selected":"",onClick:()=>{g(k.type),te.setOpen(!1),te.triggerRef.current?.focus()},children:[r("span",{class:`${t}-analytics-chart-picker__icon`,children:r(Ni,{type:k.type,className:`${t}-chart-type-icon`})}),r("span",{class:`${t}-analytics-chart-picker__copy`,children:[r("strong",{children:k.label}),r("small",{children:k.hint})]}),K?r(hc,{}):null]},k.type)})})]})]}),Ie=r(oc,{rows:N.rows??B,columns:y,maxRows:_,expanded:i,classPrefix:t,locale:a,format:D}),Ce=()=>e.tableAvailable===!1||A.length===0?null:Le(e.title?.trim()||h.resultDetails,r(se,{children:Ie}),O?r("button",{type:"button",class:`${t}-analytics-visualization__download`,onClick:O,children:h.download}):null,h.expandTable);if(B.length===0)return r(se,{children:[r("section",{class:`${t}-analytics-empty`,role:"status","data-testid":"analytics-empty-state",children:[r("p",{children:h.noMatchTitle}),r("p",{children:h.noMatchBody})]}),ue,p]});if(e.presentation==="table"||!e.presentation&&e.type==="table")return Ce()??r(se,{children:p});let ve=m&&e.tableAvailable!==!1?r("button",{type:"button",class:`${t}-analytics-visualization__download`,"aria-expanded":T,onClick:()=>V(ge=>{let ie=!ge;return m.onToggle?.(ie),ie}),children:T?h.hideData:h.viewData}):null,Xe=T?r("div",{class:`${t}-analytics-data`,children:Ie}):null;return e.presentation==="kpi"||!e.presentation&&e.type==="kpi"?Le(h.liveMetric,r(se,{children:[r(mc,{visualization:e,field:lc(e,A),prefix:t,labels:h,locale:a}),ve,Xe]})):ee?Le(ee.title,r(se,{children:[r(ac,{model:ee,expanded:i,classPrefix:t}),O?r("button",{type:"button",class:`${t}-analytics-visualization__download`,onClick:O,children:h.downloadData}):null,ve,Xe]}),r(se,{children:[d?r("div",{class:`${t}-analytics-chart-picker ${t}-analytics-chart-picker--aggregation`,children:r("button",{type:"button",ref:U.triggerRef,"aria-haspopup":"menu","aria-expanded":U.open,"aria-label":h.aggregate,title:h.aggregateTitle,onClick:()=>{te.setOpen(!1),U.setOpen(!U.open)},children:[r("span",{class:`${t}-analytics-chart-picker__current`,children:r("span",{children:h.aggregate})}),r(zi,{})]})}):null,P.length>1?r("div",{class:`${t}-analytics-chart-picker`,children:r("button",{type:"button",ref:te.triggerRef,"aria-haspopup":"listbox","aria-expanded":te.open,"aria-label":h.chooseChartType,title:h.chooseChartType,onClick:()=>{U.setOpen(!1),te.setOpen(!te.open)},children:[r("span",{class:`${t}-analytics-chart-picker__current`,children:[r(Ni,{type:Z??ee.type,className:`${t}-chart-type-icon`}),r("span",{children:Y?.label??h.chartFallback})]}),r(zi,{})]})}):null]})):Ce()??r(se,{children:p})},bc=["#2563eb","#b45309","#7c3aed"],vc=["#60a5fa","#fbbf24","#a78bfa"],xc=(e,t)=>{let n=`.${e}-analytics-visualization`,a=`.${e}-analytics-result`,i=`.${e}-analytics-chart-picker`,o=`.${e}-analytics-kpi`;return`
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
+ `},yc=(e,t)=>{if(typeof MutationObserver>"u")return()=>{};let n=e.scrollHeight,a=0,i=()=>{a=0;let s=e.scrollHeight,c=s>n,d=t.isAtBottom();n=s,c&&(d?(e.scrollTop=e.scrollHeight,t.onFollow?.()):t.onUnseen?.())},o=new MutationObserver(()=>{a||(a=typeof requestAnimationFrame=="function"?requestAnimationFrame(i):setTimeout(i,0))});return o.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>{o.disconnect(),a&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(a)}};class un extends Error{constructor(n,a,i){super(a);q(this,"status");q(this,"retryAfterSeconds");this.status=n,this.retryAfterSeconds=i,this.name="ApiError"}}const ir=()=>({agentName:"Accurix",greeting:"Hi! 👋 How can I help you today?",widgetModule:"chat",assistantMediaKind:"image",soundEnabled:!0,voiceOutputEnabled:!1,talkbackMode:"text",allowVoiceInput:!1,memoryEnabled:!0,memoryRetentionDays:30,memoryMessageCap:50,availableActions:[]}),_c="Sara is an AI assistant; answers may be imperfect.",wc="Accurix is an AI assistant; answers may be imperfect.",Li=e=>{typeof console>"u"||console.warn(`[centrinfo-widget] Could not load saved widget configuration from the API (${e}). Showing default widget chrome. Check data-token, data-api-base, CORS, and backend availability.`)},or=(e,t={})=>{const a=e.disclaimerText?.trim()?.toLowerCase(),i=t.agentName?.trim()||e.agentName?.trim()||"Accurix",o=t.agentAvatarUrl?.trim()||e.agentAvatarUrl?.trim();return{...e,allowVoiceInput:!!(e.allowVoiceInput&&e.talkbackMode&&e.talkbackMode!=="text"),voiceOutputEnabled:!!(e.voiceOutputEnabled&&e.talkbackMode&&e.talkbackMode!=="text"),agentName:i,agentAvatarUrl:o||void 0,disclaimerText:a===_c.toLowerCase()||a?.includes("sara is an ai assistant")?wc:e.disclaimerText}},kc=15e3,Sc=6e4,$c=12e4,Tc=["/transcribe","/speak","/attachments","/stream"],Cc=["/book-demo","/schedule-callback"],Ac=e=>{const t=e.split("?")[0]??e;return Cc.some(n=>t.includes(`/public-chat${n}`))?$c:Tc.some(n=>t.includes(`/public-chat${n}`))||t.endsWith("/public-chat")?Sc:kc},Mc=e=>{const t=e.headers?.get?.("Retry-After"),n=t?Number(t):NaN;return Number.isFinite(n)&&n>=0?n:void 0},Ic=e=>{try{const t=e.split(".")[1];if(!t)return null;const n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),a=JSON.parse(n).exp;return typeof a=="number"&&Number.isFinite(a)?a*1e3:null}catch{return null}};class Ec{constructor(t,n,a,i,o={},s,c,d="floating"){q(this,"baseUrl");q(this,"token");q(this,"gifApiKey");q(this,"analyticsContextToken");q(this,"bootstrapOverrides");q(this,"identityToken");q(this,"identityTokenProvider");q(this,"chatSurface");q(this,"cachedIdentity",null);q(this,"identityFlight",null);this.baseUrl=t,this.token=n,this.gifApiKey=a,this.analyticsContextToken=i,this.bootstrapOverrides=o,this.identityToken=s,this.identityTokenProvider=c,this.chatSurface=d}async currentIdentityToken(){if(!this.identityTokenProvider)return this.identityToken;const t=this.cachedIdentity;return t&&Date.now()<t.refreshAt?t.token:(this.identityFlight??(this.identityFlight=(async()=>{try{const n=(await this.identityTokenProvider()??"").trim();this.identityToken=n||void 0;const a=n?Ic(n):null;return this.cachedIdentity=n&&a!==null?{token:n,refreshAt:a-6e4}:null,this.identityToken}finally{this.identityFlight=null}})()),this.identityFlight)}async fetchT(t,n={}){const a=new AbortController;let i=!1;const o=setTimeout(()=>{i=!0,a.abort()},Ac(t)),s=n.signal,c=()=>a.abort();s?.aborted?a.abort():s?.addEventListener("abort",c,{once:!0});try{return await fetch(t,{...n,signal:a.signal})}catch(d){throw i&&!s?.aborted?new un(408,"The request took too long. Please try again."):d}finally{clearTimeout(o),s?.removeEventListener("abort",c)}}headers(t=!0){const n={Authorization:`Bearer ${this.token}`};return t&&(n["Content-Type"]="application/json"),n}async json(t){let n;try{n=await t.json()}catch{n=void 0}if(!t.ok){const a=Nc(n)??`request failed (${t.status})`;throw new un(t.status,a,Mc(t))}return n?.data??n}async bootstrap(){try{const t=await this.fetchT(`${this.baseUrl}/public-chat/bootstrap`,{headers:this.headers(!1)});if(!t.ok)return Li(`bootstrap request failed with ${t.status}`),or(ir(),this.bootstrapOverrides);const n=await this.json(t);return or({...ir(),...n},this.bootstrapOverrides)}catch(t){return Li(t instanceof Error?t.message:"bootstrap request failed"),or(ir(),this.bootstrapOverrides)}}async history(){const t=await this.currentIdentityToken();if(!t)return{conversations:[]};const n=await this.fetchT(`${this.baseUrl}/public-chat/history`,{method:"POST",headers:this.headers(),body:JSON.stringify({identityToken:t,surface:this.chatSurface})}),a=await this.json(n);return{activeSessionId:a.activeSessionId,conversations:Array.isArray(a.conversations)?a.conversations:[]}}async stream(t,n,a){const i=await this.currentIdentityToken(),o=await this.fetchT(`${this.baseUrl}/public-chat/stream`,{method:"POST",headers:this.headers(),body:JSON.stringify({question:t,sessionId:n,clientMessageId:a.clientMessageId,attachmentId:a.attachmentId,attachmentIds:a.attachmentIds,voicePlaybackRequested:!!a.voicePlaybackRequested,analyticsContextToken:this.analyticsContextToken,identityToken:i,surface:this.chatSurface}),signal:a.signal});return!o.ok||!o.body?((o.status===429||o.status===401)&&await this.json(o),this.send(t,n,a)):Rc(o.body,a)}async liveEvents(t,n){const a=`sessionId=${encodeURIComponent(t)}&after=${encodeURIComponent(n)}`,i=await this.fetchT(`${this.baseUrl}/public-chat/live-events?${a}`,{headers:this.headers(!1)}),o=await this.json(i);return{mode:o.mode??"ai",assignedAgentName:o.assignedAgentName,agentTyping:!!o.agentTyping,agentTypingName:o.agentTypingName,conversationEnded:!!o.conversationEnded,events:o.events??[]}}async typing(t,n){try{const a=await this.fetchT(`${this.baseUrl}/public-chat/typing`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:t,isTyping:n})});if(!a.ok)try{await a.text()}catch{}}catch{}}async presence(t){try{await this.fetchT(`${this.baseUrl}/public-chat/presence`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:t})})}catch{}}async send(t,n,a){const i=await this.currentIdentityToken(),o=await this.fetchT(`${this.baseUrl}/public-chat`,{method:"POST",headers:this.headers(),body:JSON.stringify({question:t,sessionId:n,clientMessageId:a.clientMessageId,attachmentId:a.attachmentId,attachmentIds:a.attachmentIds,voicePlaybackRequested:!!a.voicePlaybackRequested,analyticsContextToken:this.analyticsContextToken,identityToken:i,surface:this.chatSurface}),signal:a.signal}),s=await this.json(o);return a.onChunk(s.answer??""),{answer:s.answer??"",sources:s.sources??[],suggestedReplies:s.suggestedReplies??[],availableActions:s.availableActions??[],actions:s.actions??[],selectedAction:s.selectedAction,handoffOffered:s.handoffOffered??!1,requestedContactFields:Di(s.requestedContactFields),conversationEnded:s.conversationEnded??!1,liveMode:s.liveMode,assignedAgentName:s.assignedAgentName,audioBase64:s.audioBase64,mimeType:s.mimeType,visualization:s.visualization,artifacts:s.artifacts}}async action(t,n,a){const i=a?.trim()||(t==="contact-support"?"inquiry":t),o=await this.fetchT(`${this.baseUrl}/public-chat/${i}`,{method:"POST",headers:this.headers(),body:JSON.stringify(n)}),s=await this.json(o);return{ok:!0,note:s?.note,receipt:s?.receipt,booking:s?.booking,caseReference:s?.caseReference||void 0,inquiryId:s?.inquiryId||s?.inquiry?.id||void 0}}async confirmHostedBooking(t){const n=await this.fetchT(`${this.baseUrl}/public-chat/book-demo/confirm`,{method:"POST",headers:this.headers(),body:JSON.stringify(t)}),a=await this.json(n);if(!a?.booking)throw new Error("Calendar booking confirmation was unavailable.");return{...a.booking,receipt:a.receipt}}async speak(t){const n=await this.fetchT(`${this.baseUrl}/public-chat/speak`,{method:"POST",headers:this.headers(),body:JSON.stringify({text:t})}),a=await this.json(n);return{providerReady:!!a.providerReady,message:a.message,audioBase64:a.audioBase64,mimeType:a.mimeType}}async identify(t,n){if(!(!t||!n))try{const a=await this.fetchT(`${this.baseUrl}/public-chat/identify`,{method:"POST",headers:this.headers(),body:JSON.stringify(zc(t,n))});if(!a.ok)try{await a.text()}catch{}}catch{}}async transcribe(t,n,a,i){const o=await this.fetchT(`${this.baseUrl}/public-chat/transcribe`,{method:"POST",headers:this.headers(),body:JSON.stringify({audioBase64:t,mimeType:n,languageHint:a,durationSeconds:i})});return(await this.json(o)).text??""}async transcribeAudio(t,n,a,i){const o=new FormData;o.append("audio",t,"voice-recording"),o.append("mimeType",n||t.type||"audio/webm"),a&&o.append("languageHint",a),i!==void 0&&Number.isFinite(i)&&o.append("durationSeconds",String(i));const s=await this.fetchT(`${this.baseUrl}/public-chat/transcribe`,{method:"POST",headers:this.headers(!1),body:o});return(await this.json(s)).text??""}async endConversation(t){try{const n=await this.fetchT(`${this.baseUrl}/public-chat/end`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:t})});if(!n.ok)try{await n.text()}catch{}}catch{}}async sendFeedback(t){try{const n=await this.fetchT(`${this.baseUrl}/public-chat/feedback`,{method:"POST",headers:this.headers(),body:JSON.stringify(t)});if(!n.ok)try{await n.text()}catch{}}catch{}}async sendExplanationFeedback(t){const n=await this.fetchT(`${this.baseUrl}/public-chat/explanation-feedback`,{method:"POST",headers:this.headers(),body:JSON.stringify(t)});await this.json(n)}async fetchExplanation(t,n,a="widget",i){const o=await this.fetchT(`${this.baseUrl}/public-chat/analytics-explanations/${encodeURIComponent(t)}?sessionId=${encodeURIComponent(n)}&surface=${a}`,{method:"GET",headers:this.headers(!1),signal:i});return this.explanationJob(o,t)}async retryExplanation(t,n,a="widget"){const i=await this.fetchT(`${this.baseUrl}/public-chat/analytics-explanations/${encodeURIComponent(t)}/retry`,{method:"POST",headers:this.headers(),body:JSON.stringify({sessionId:n,surface:a})});return this.explanationJob(i,t)}async explanationJob(t,n){return t.status===404||t.status===410?{status:"failed",explanationId:n,retryAvailable:!1}:this.json(t)}async uploadAttachment(t,n,a,i,o){const s=await this.fetchT(`${this.baseUrl}/public-chat/attachments`,{method:"POST",headers:this.headers(),body:JSON.stringify({fileBase64:t,mimeType:n,filename:a,sessionId:i,analyze:o})});return this.json(s)}async fetchAttachment(t,n){const a=await this.fetchT(`${this.baseUrl}/public-chat/attachments/${encodeURIComponent(t)}?sessionId=${encodeURIComponent(n)}`,{headers:this.headers(!1)});if(!a.ok)throw new un(a.status,"This file is no longer available.");return a.blob()}async demoSlots(t,n){const a=`from=${encodeURIComponent(t)}&to=${encodeURIComponent(n)}`,i=await this.fetchT(`${this.baseUrl}/public-chat/demo-slots?${a}`,{headers:this.headers(!1)});if(!i.ok){const s=new Error("Calendar availability is temporarily unavailable.");throw s.status=i.status,s}const o=await this.json(i);return{status:o?.status,reason:o?.reason,timezone:o?.timezone,slotDurationMinutes:o?.slotDurationMinutes,available:o?.available,taken:o?.taken??[],busy:o?.busy??[]}}async searchGifs(t){if(!this.gifApiKey)return[];const a=`https://tenor.googleapis.com/v2/search?q=${encodeURIComponent(t.trim()||"trending")}&key=${this.gifApiKey}&limit=24&media_filter=tinygif,gif&contentfilter=high`;try{const i=await this.fetchT(a,{});return i.ok?((await i.json()).results??[]).map(s=>({id:s.id,url:s.media_formats?.gif?.url??s.media_formats?.tinygif?.url??"",preview:s.media_formats?.tinygif?.url??s.media_formats?.gif?.url??"",alt:s.content_description||"GIF"})).filter(s=>s.url):[]}catch{return[]}}}const zc=(e,t)=>{const n={...t.customAttributes??{},...t.metadata??{}};t.createdAt!==void 0&&(n.createdAt=t.createdAt),t.avatarUrl&&(n.avatarUrl=t.avatarUrl),t.company&&(n.company=t.company);const a={sessionId:e},i=t.externalId??t.userId;return i&&(a.externalId=i),t.email&&(a.email=t.email),t.firstName&&(a.firstName=t.firstName),t.lastName&&(a.lastName=t.lastName),t.name&&(a.name=t.name),t.phone&&(a.phone=t.phone),Object.keys(n).length>0&&(a.metadata=n),a},Nc=e=>{const t=e?.message;if(Array.isArray(t))return t.join(", ");if(typeof t=="string")return t},Rc=async(e,t)=>{const n=e.getReader(),a=new TextDecoder,i={answer:"",sources:[],suggestedReplies:[],availableActions:[],handoffOffered:!1,requestedContactFields:[],conversationEnded:!1};let o="";for(;;){const{done:s,value:c}=await n.read();if(s)break;o+=a.decode(c,{stream:!0});let d;for(;(d=o.indexOf(`
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,d);o=o.slice(d+2);const u=Lc(l);if(u){if(u.event==="error")throw new un(502,u.data?.message??"stream error");if(u.event==="chunk"&&typeof u.data?.text=="string")i.answer+=u.data.text,t.onChunk(u.data.text);else if(u.event==="reset")i.answer="",t.onReset?.();else if(u.event==="final"&&u.data)typeof u.data.answer=="string"&&(i.answer=u.data.answer),i.sources=u.data.sources??[],i.suggestedReplies=u.data.suggestedReplies??[],i.availableActions=u.data.availableActions??[],i.actions=u.data.actions??[],i.selectedAction=u.data.selectedAction,i.handoffOffered=!!u.data.handoffOffered,i.requestedContactFields=Di(u.data.requestedContactFields),i.conversationEnded=!!u.data.conversationEnded,i.liveMode=u.data.liveMode,i.assignedAgentName=u.data.assignedAgentName,i.visualization=u.data.visualization,i.artifacts=u.data.artifacts,i.audioBase64=u.data.audioBase64,i.mimeType=u.data.mimeType,t.onTextReady?.();else if(u.event==="audio"&&u.data)typeof u.data.seq=="number"?(i.liveAudio=!0,t.onAudioSegment?.({seq:u.data.seq,audioBase64:u.data.audioBase64??"",mimeType:u.data.mimeType,text:typeof u.data.text=="string"?u.data.text:void 0})):(i.audioBase64=u.data.audioBase64,i.mimeType=u.data.mimeType);else if(u.event==="done")return i}}}return i},Lc=e=>{let t="message";const n=[];for(const a of e.split(`
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}}},Di=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[];let sr=()=>Promise.resolve().then(()=>Fo);const Dc=e=>{sr=e},Pi=e=>new Ec(e.apiBaseUrl,e.token,e.gifApiKey,e.analyticsContextToken,{agentName:e.agentName,agentAvatarUrl:e.agentAvatarUrl},e.identityToken,e.getIdentityToken,e.chatSurface),Oi=e=>{const t=n=>(...a)=>e().then(i=>i[n].apply(i,a));return{bootstrap:t("bootstrap"),history:t("history"),stream:t("stream"),liveEvents:t("liveEvents"),presence:t("presence"),typing:t("typing"),action:t("action"),speak:t("speak"),transcribe:t("transcribe"),searchGifs:t("searchGifs"),demoSlots:t("demoSlots"),identify:t("identify"),endConversation:t("endConversation"),sendFeedback:t("sendFeedback"),sendExplanationFeedback:t("sendExplanationFeedback"),uploadAttachment:t("uploadAttachment")}},Pc=e=>e.demo?Oi(async()=>new(await sr()).MockTransport):e.preview?Oi(async()=>{const{PreviewTransport:t}=await sr();return new t(Pi(e),e.strings)}):Pi(e),cr=16e3;class Oc{constructor(t){q(this,"ratio");q(this,"position",0);q(this,"carry",[]);this.ratio=t/cr}process(t){if(this.ratio===1)return t.slice();const n=this.carry.length?Float32Array.from([...this.carry,...t]):t,a=[];let i=this.position;for(;i+this.ratio<=n.length;){const s=Math.floor(i),c=Math.min(n.length,Math.floor(i+this.ratio));let d=0;for(let l=s;l<c;l+=1)d+=n[l]??0;a.push(c>s?d/(c-s):0),i+=this.ratio}const o=Math.floor(i);return this.carry=Array.from(n.subarray(o)),this.position=i-o,Float32Array.from(a)}}const Fc=(e,t=cr)=>{const n=e.reduce((c,d)=>c+d.length,0),a=new ArrayBuffer(44+n*2),i=new DataView(a),o=(c,d)=>{for(let l=0;l<d.length;l+=1)i.setUint8(c+l,d.charCodeAt(l))};o(0,"RIFF"),i.setUint32(4,36+n*2,!0),o(8,"WAVE"),o(12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),o(36,"data"),i.setUint32(40,n*2,!0);let s=44;for(const c of e)for(let d=0;d<c.length;d+=1){const l=Math.max(-1,Math.min(1,c[d]??0));i.setInt16(s,l<0?l*32768:l*32767,!0),s+=2}return new Blob([a],{type:"audio/wav"})},Fi=e=>e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(t=>t.length>1),Uc=(e,t)=>{const n=Fi(e);if(n.length===0||!t.trim())return!1;const a=new Set(Fi(t));return n.filter(i=>a.has(i)).length/n.length>=.7},Ui=e=>{const t=e.replace(/```[\s\S]*?```/g,"").split(`
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()},Bc=(e,t)=>{const n=t?.explanation,a=[n?.summary?.trim()||n?.headline?.trim(),n?.businessMeaning?.trim(),...n?.limitations??[]].filter(o=>!!o?.trim()),i=a.length?[...new Set(a)].join(`
79
+ `):e;return Ui(i)||(i.trim()?"The detailed results are available in the chat.":"")},Bi=300,qc=()=>{const e=globalThis;if(e.__voiceDebug)return!0;try{return e.localStorage?.getItem("accurix.voiceDebug")==="1"}catch{return!1}};class Vc{constructor(t=()=>Date.now()){q(this,"now");q(this,"entries",[]);q(this,"startedAt");this.now=t,this.startedAt=t(),globalThis.__accurixVoiceLog=()=>this.list()}add(t,n){const a={at:Math.round(this.now()-this.startedAt),event:t,detail:n};this.entries.push(a),this.entries.length>Bi&&this.entries.splice(0,this.entries.length-Bi),qc()&&console.debug(`VOICEDBG ${t} ${n?JSON.stringify(n):""}`)}list(){return this.entries.slice()}}const lr=cr/50,st=20,jc=500,Hc=120,Wc=300,Gc=280,Kc=600,Yc=300,Zc=12e3,Jc=25e3,Xc=300,Qc=2e4,el=60,tl=400,nl=250,dr=8e-4,al=.1,rl=2.8,il=1.8,ol=.006,sl=.004,cl=1.8,ll=1.4,dl=2e3,ul=2e3;class pl{constructor(t){q(this,"options");q(this,"endSilenceMs");q(this,"pending",new Float32Array(0));q(this,"levels",[]);q(this,"framesSinceFloor",0);q(this,"floor",dr*4);q(this,"recentSpeech",[]);q(this,"preroll",[]);q(this,"silentMs",0);q(this,"inputSilent",!1);q(this,"outputActive",!1);q(this,"turns",[]);q(this,"nextTurnId",1);this.options=t,this.endSilenceMs=t.endSilenceMs??ul}get hearing(){return this.current()?.capturing??!1}get processing(){return this.turns.some(t=>!t.capturing&&!t.cancelled)}feed(t){let n=t;this.pending.length&&(n=new Float32Array(this.pending.length+t.length),n.set(this.pending),n.set(t,this.pending.length));let a=0;for(;a+lr<=n.length;)this.frame(n.slice(a,a+lr)),a+=lr;this.pending=n.slice(a)}setOutputActive(t){this.outputActive!==t&&(this.outputActive=t,this.options.log.add("output",{active:t}))}finishTurn(){const t=this.current();t&&(t.capturing?this.endTurn(t,"done"):t.closed||(t.closed=!0,t.endedBy="done",this.options.log.add("turn-done",{turn:t.id})))}reset(t){for(const n of this.turns)n.cancelled=!0;this.turns.length&&this.options.log.add("turns-dropped",{reason:t,count:this.turns.length}),this.turns=[],this.preroll=[],this.recentSpeech=[],this.pending=new Float32Array(0),this.options.onChange()}current(){return this.turns[this.turns.length-1]}frame(t){let n=0,a=0;for(let p=0;p<t.length;p+=1){const m=t[p]??0;n+=m*m,a=Math.max(a,Math.abs(m))}const i=Math.sqrt(n/t.length);this.trackInputSilence(a);const o=this.current();!o?.capturing&&!this.outputActive&&this.trackFloor(i);const s=this.outputActive,c=Math.max(ol,this.floor*rl)*(s?cl:1),d=Math.max(sl,this.floor*il)*(s?ll:1),l=i>=c,u=i>=d;if(!o?.capturing){for(this.preroll.push(t);this.preroll.length*st>jc;)this.preroll.shift();this.recentSpeech.push(l);const p=(s?Kc:Wc)/st;for(;this.recentSpeech.length>p;)this.recentSpeech.shift();const m=this.recentSpeech.filter(Boolean).length*st;m>=(s?Gc:Hc)&&this.beginCapture(m);return}o.chunk.push(t),o.chunkMs+=st,o.durationMs+=st,l&&(o.voicedMs+=st,o.chunkVoicedMs+=st),o.quietMs=u?0:o.quietMs+st,s&&(o.overlappedOutput=!0),o.quietMs>=this.endSilenceMs?this.endTurn(o,"silence"):(o.chunkMs>=Jc||o.chunkMs>=Zc&&o.quietMs>=Xc||o.chunkMs>=Qc&&o.quietMs>=el)&&this.cutChunk(o)}trackFloor(t){if(this.levels.push(t),this.levels.length>nl&&this.levels.shift(),this.framesSinceFloor+=1,this.framesSinceFloor<10&&this.levels.length>10)return;this.framesSinceFloor=0;const n=this.levels.slice().sort((a,i)=>a-i);this.floor=Math.max(dr,n[Math.floor(n.length*al)]??dr)}trackInputSilence(t){this.silentMs=t===0?this.silentMs+st:0;const n=this.silentMs>=dl;n!==this.inputSilent&&(this.inputSilent=n,this.options.log.add("input-silent",{silent:n}),this.options.onInputSilent?.(n))}beginCapture(t){const n=this.current();let a;n&&!n.capturing&&!n.closed?(a=n,a.capturing=!0,this.options.log.add("turn-resumed",{turn:a.id})):(a={id:this.nextTurnId++,capturing:!0,closed:!1,endedBy:"silence",chunk:[],chunkMs:0,chunkVoicedMs:0,quietMs:0,voicedMs:0,durationMs:0,overlappedOutput:this.outputActive,results:[],chunkCount:0,cancelled:!1},this.turns.push(a),this.options.log.add("turn-start",{turn:a.id,overOutput:this.outputActive}),this.options.listener.speechStart?.({turnId:a.id,overlappedOutput:this.outputActive})),a.chunk.push(...this.preroll),a.chunkMs+=this.preroll.length*st,a.durationMs+=this.preroll.length*st,a.voicedMs+=t,a.chunkVoicedMs+=t,a.quietMs=0,this.preroll=[],this.recentSpeech=[],this.options.onChange()}endTurn(t,n){const a=Math.max(0,Math.floor((t.quietMs-tl)/st));if(a>0&&(t.chunk.splice(t.chunk.length-Math.min(a,t.chunk.length)),t.chunkMs=t.chunk.length*st),t.capturing=!1,t.endedBy=n,n==="done"&&(t.closed=!0),this.options.log.add("turn-end",{turn:t.id,by:n,ms:t.durationMs,voicedMs:t.voicedMs}),t.chunkCount===0&&t.voicedMs<Yc){this.turns=this.turns.filter(i=>i!==t),this.options.log.add("turn-noise",{turn:t.id,reason:"too-short"}),this.options.listener.noise?.({id:t.id,reason:"too-short",overlappedOutput:t.overlappedOutput}),this.options.onChange();return}this.cutChunk(t),this.options.onChange(),this.settle()}cutChunk(t){if(t.chunk.length===0)return;const n=t.chunk,a=t.chunkCount;t.chunkCount+=1,t.results[a]=void 0,t.chunk=[];const i=n.length*st,o=t.chunkVoicedMs;if(t.chunkMs=0,t.chunkVoicedMs=0,o===0&&a>0){t.results[a]="";return}this.options.log.add("chunk",{turn:t.id,index:a,ms:i}),this.options.transcribe({audio:Fc(n),mimeType:"audio/wav",durationSeconds:i/1e3,turnId:t.id,chunkIndex:a}).then(s=>(s??"").trim(),()=>null).then(s=>{if(t.cancelled)return;t.results[a]=s,this.options.log.add("chunk-text",{turn:t.id,index:a,chars:s===null?-1:s.length});const c=[];for(const d of t.results){if(d===void 0)break;d&&c.push(d)}c.length&&this.options.listener.partial?.({turnId:t.id,text:c.join(" ")}),this.settle()})}settle(){for(;this.turns.length;){const t=this.turns[0];if(!t||t.capturing||t.results.some(o=>o===void 0))return;this.turns.shift();const n=t.results.filter(o=>typeof o=="string"&&o!==""),a=t.results.every(o=>o===null),i=n.join(" ").replace(/\s+/g," ").trim();if(i)this.options.log.add("turn",{turn:t.id,chars:i.length,by:t.endedBy}),this.options.listener.turn?.({id:t.id,text:i,durationMs:t.durationMs,endedBy:t.endedBy,overlappedOutput:t.overlappedOutput});else{const o=a?"transcribe-failed":"empty-transcript";this.options.log.add("turn-noise",{turn:t.id,reason:o}),this.options.listener.noise?.({id:t.id,reason:o,overlappedOutput:t.overlappedOutput})}this.options.onChange()}}}const fl=2048,hl=[300,1e3,2500],ml=()=>typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof globalThis.AudioContext=="function",gl=e=>{const t=e?.name;return t==="NotAllowedError"||t==="SecurityError"?"permission-denied":t==="NotFoundError"||t==="OverconstrainedError"?"no-device":"error"};class qi{constructor(t){q(this,"options");q(this,"log",new Vc);q(this,"turns");q(this,"mic","off");q(this,"reason");q(this,"muted",!1);q(this,"inputSilent",!1);q(this,"stream",null);q(this,"context",null);q(this,"source",null);q(this,"processor",null);q(this,"sink",null);q(this,"downsampler",null);q(this,"deviceId");q(this,"generation",0);q(this,"recoveryAttempt",0);q(this,"recoveryTimer",null);q(this,"lastSnapshot","");q(this,"groupId");q(this,"onTrackEnded",()=>{this.log.add("track-ended"),this.recover("track-ended")});q(this,"onTrackMuteChange",()=>{const t=this.stream?.getAudioTracks()[0];this.log.add("track-mute-change",{muted:!!t?.muted}),this.refreshMic()});q(this,"onContextState",()=>{const t=this.context?.state;this.log.add("audio-state",{state:t}),(t==="suspended"||t==="interrupted")&&this.context?.resume().catch(()=>{}),this.refreshMic()});q(this,"onDeviceChange",()=>{this.checkDevices()});this.options=t,this.deviceId=t.deviceId,this.turns=new pl({transcribe:t.transcribe,listener:t.listener,log:this.log,endSilenceMs:t.endSilenceMs,onChange:()=>this.publish(),onInputSilent:n=>{this.inputSilent=n,this.publish()}})}get snapshot(){let t=this.mic,n=this.reason;return t==="listening"&&this.inputSilent&&(t="unavailable",n="input-silent"),t==="listening"&&this.turns.hearing&&(t="hearing"),{mic:t,processing:this.turns.processing,reason:t==="unavailable"?n:void 0}}get active(){return this.mic!=="off"}async start(){this.mic==="off"&&(this.log.add("start"),this.mediaDevices()?.addEventListener("devicechange",this.onDeviceChange),await this.open("start"))}stop(t="stopped"){this.mic!=="off"&&(this.log.add("stop",{reason:t}),this.generation+=1,this.clearRecovery(),this.mediaDevices()?.removeEventListener("devicechange",this.onDeviceChange),this.turns.reset(t),this.close(),this.context?.close().catch(()=>{}),this.context=null,this.setMic("off"))}setMuted(t){if(!(this.muted===t||this.mic==="off")){this.muted=t,this.log.add(t?"mute":"unmute");for(const n of this.stream?.getAudioTracks()??[])n.enabled=!t;t?(this.turns.reset("muted"),this.setMic("muted")):this.refreshMic()}}finishTurn(){this.log.add("done-pressed"),this.turns.finishTurn()}setOutputActive(t){this.turns.setOutputActive(t)}async selectDevice(t){t!==this.deviceId&&(this.deviceId=t,this.mic!=="off"&&(this.log.add("device-selected"),this.turns.reset("device-selected"),this.close(),await this.open("device-selected")))}mediaDevices(){return this.options.media?.mediaDevices??(typeof navigator<"u"?navigator.mediaDevices:void 0)}async open(t){const n=++this.generation;this.setMic("starting");const a=this.options.media?.getUserMedia??(ml()?o=>navigator.mediaDevices.getUserMedia(o):null);if(!a){this.unavailable("unsupported");return}let i;try{i=await a({audio:{...this.deviceId?{deviceId:{exact:this.deviceId}}:{},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1}})}catch(o){if(n!==this.generation)return;const s=gl(o);if(this.log.add("mic-open-failed",{why:t,reason:s}),s==="no-device"&&this.deviceId){this.deviceId=void 0,await this.open("default-device");return}this.unavailable(s);return}if(n!==this.generation){i.getTracks().forEach(o=>o.stop());return}try{this.connect(i)}catch(o){this.log.add("audio-setup-failed",{message:String(o?.name??"error")}),i.getTracks().forEach(s=>s.stop()),this.unavailable("error");return}this.recoveryAttempt=0,this.groupId=i.getAudioTracks()[0]?.getSettings?.().groupId,this.log.add("mic-open",{why:t}),this.refreshMic()}connect(t){this.stream=t;for(const a of t.getAudioTracks())a.enabled=!this.muted,a.addEventListener("ended",this.onTrackEnded),a.addEventListener("mute",this.onTrackMuteChange),a.addEventListener("unmute",this.onTrackMuteChange);const n=this.context??this.options.media?.createAudioContext?.()??new globalThis.AudioContext;this.context||(this.context=n,n.addEventListener("statechange",this.onContextState)),n.state==="suspended"&&n.resume().catch(()=>{}),this.downsampler=new Oc(n.sampleRate),this.source=n.createMediaStreamSource(t),this.processor=n.createScriptProcessor(fl,1,1),this.sink=n.createGain(),this.sink.gain.value=0,this.processor.onaudioprocess=a=>{if(this.muted||!this.downsampler)return;const i=this.downsampler.process(a.inputBuffer.getChannelData(0));if(this.turns.feed(i),this.options.listener.level&&i.length){let o=0;for(const s of i)o+=s*s;this.options.listener.level(Math.sqrt(o/i.length))}},this.source.connect(this.processor),this.processor.connect(this.sink),this.sink.connect(n.destination)}close(){this.processor&&(this.processor.onaudioprocess=null),this.source?.disconnect(),this.processor?.disconnect(),this.sink?.disconnect(),this.source=null,this.processor=null,this.sink=null;for(const t of this.stream?.getTracks()??[])t.removeEventListener("ended",this.onTrackEnded),t.removeEventListener("mute",this.onTrackMuteChange),t.removeEventListener("unmute",this.onTrackMuteChange),t.stop();this.stream=null,this.inputSilent=!1}refreshMic(){if(this.mic==="off")return;if(this.muted)return this.setMic("muted");const t=this.stream?.getAudioTracks()[0];if(!t||t.readyState!=="live")return this.unavailable("device-lost");if(t.muted)return this.unavailable("track-muted");if(this.context&&this.context.state!=="running")return this.unavailable("audio-suspended");this.reason=void 0,this.setMic("listening")}unavailable(t){this.reason=t,this.setMic("unavailable")}setMic(t){this.mic!==t&&this.log.add("mic",{state:t,reason:t==="unavailable"?this.reason:void 0}),this.mic=t,this.publish()}publish(){const t=this.snapshot,n=JSON.stringify(t);n!==this.lastSnapshot&&(this.lastSnapshot=n,this.options.listener.state?.(t))}recover(t){if(this.mic==="off"||this.recoveryTimer)return;const n=hl[this.recoveryAttempt];if(this.turns.reset(t),this.close(),n===void 0){this.log.add("mic-recovery-gave-up",{why:t}),this.unavailable("device-lost");return}this.recoveryAttempt+=1,this.unavailable("device-lost"),this.log.add("mic-recovering",{why:t,attempt:this.recoveryAttempt}),this.recoveryTimer=setTimeout(()=>{this.recoveryTimer=null,this.mic!=="off"&&this.open(t)},n)}clearRecovery(){this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,this.recoveryAttempt=0}async checkDevices(){const t=this.stream?.getAudioTracks()[0];if(!t||t.readyState!=="live"){this.log.add("device-change",{live:!1}),this.recover("device-change");return}let n=[];try{n=(await this.mediaDevices()?.enumerateDevices()??[]).filter(s=>s.kind==="audioinput")}catch{return}const a=n.some(s=>!this.groupId||s.groupId===this.groupId),i=n.find(s=>s.deviceId==="default"),o=!this.deviceId&&i!==void 0&&this.groupId!==void 0&&i.groupId!==this.groupId;this.log.add("device-change",{live:!0,ours:a,defaultMoved:o}),(!a||o)&&this.recover("device-change")}}const ur=e=>!!(e?.headline?.trim()||e?.summary?.trim()),bl=(e,t={})=>{const n=e?.explanation??void 0,a=e?.businessAnalysis?.explanation??void 0,i=[t.requested??void 0,n?.source==="ai_grounded"?n:void 0,a,n];for(const o of i)if(o&&ur(o))return o;return t.fallback?.()},xt={eyebrow:"Answer from your data",provenanceAI:"AI-assisted · evidence checked",provenanceGoverned:"Based on current values",comparison:"Comparison",conclusions:"What we can conclude",whyItMatters:"Why it matters",limits:"Important limits",investigate:"Investigate further",evidenceList:"Evidence checked",causes:"Possible causes",causesHint:"Not proven causes",howToCheck:"How to check:",recommendations:"Recommended next steps",watch:"Watch:",outlook:"Outlook",followUps:"Ask a follow-up",sourceNoteAI:"AI-assisted wording, checked against the live values shown here.",sourceNoteGoverned:"Based only on the live values shown here.",evidence:"Evidence",evidenceMetric:"Metric",evidencePeriod:"Period",evidenceTimezone:"Timezone",evidenceFilters:"Filters",evidenceValue:"Value",evidenceStatus:"Status",evidenceSource:"Source",evidenceChecked:"Checked",openSource:"Open source",closeEvidence:"Close evidence details",citationLabel:"Show evidence",sourceCard:"This card",sourceSupportingQuery:"Supporting query",feedbackPrompt:"Was this explanation helpful?",feedbackHelpful:"Helpful explanation",feedbackNotHelpful:"Unhelpful explanation",feedbackReasonsPrompt:"What went wrong? (optional)",feedbackCommentPlaceholder:"Anything else? (optional)",feedbackSubmit:"Send feedback",feedbackThanks:"Thanks for the feedback.",feedbackUndo:"Undo",feedbackError:"Feedback could not be saved. Try again.",notComparable:"Not comparable yet",basicExplanation:"Basic explanation",preparingDetailed:"Preparing a detailed explanation…",detailedReady:"Detailed explanation ready.",detailedUnavailable:"A detailed explanation is not available right now.",detailedRetry:"Try again",region:"Explanation",inProgress:"in progress",expand:"Expand explanation",collapse:"Collapse explanation",reasonWrongNumbers:"Wrong numbers",reasonMissingComparison:"Missing comparison",reasonUnclear:"Unclear",reasonTooLong:"Too long"},Vi=[{id:"wrong_numbers",label:"Wrong numbers"},{id:"missing_comparison",label:"Missing comparison"},{id:"unclear",label:"Unclear"},{id:"too_long",label:"Too long"}],pr=500,vl=e=>e==="ai_grounded"||e==="rag_deterministic_analysis",ji=e=>{switch(e){case"confirmed_zero":return"confirmed 0";case"empty_bucket":case"unconfirmed_zero":return"no records yet";case"missing":return"missing";default:return""}},Hi=e=>{switch(e){case"confirmed_zero":return"confirmed";case"empty_bucket":case"unconfirmed_zero":return"caution";case"missing":return"missing";default:return"neutral"}},xl=e=>{const t=(e??"").trim().toLowerCase().replaceAll("-","_");return t==="low"||t==="low_quality"?"Low-confidence forecast":t==="medium"||t==="directional"?"Directional forecast":t==="high"||t==="validated"||t==="trusted"?"Validated forecast":"Forecast estimate"},Wi=/^\d{4}-\d{2}-\d{2}$/,ga=(e,t,n,a)=>{try{return new Intl.DateTimeFormat(t,a?{...n,timeZone:a}:n).format(e)}catch{return new Intl.DateTimeFormat(t,n).format(e)}},Gi=(e,t)=>ga(e,"en-CA",{year:"numeric",month:"2-digit",day:"2-digit"},t),Ki=(e,t={})=>{const n=e?.trim();if(!n)return"";const a=new Date(n);if(Number.isNaN(a.getTime()))return"";const i={hour:"2-digit",minute:"2-digit",hour12:!1},o=Gi(a,t.timezone)===Gi(t.now??new Date,t.timezone);return ga(a,t.locale,o?i:{...i,month:"short",day:"numeric"},t.timezone)},yl=(e,t={})=>{const n=e.timezone?.trim(),a=Ki(e.checkedAt,{...t,timezone:n});return[n?`Times in ${n}`:"",a?`Checked ${a}`:""].filter(Boolean).join(" · ")},Yi=(e,t,n)=>{const a=e?.trim();if(!a)return"";if(Wi.test(a)){const o=new Date(`${a}T00:00:00Z`);return Number.isNaN(o.getTime())?a:ga(o,t,{day:"numeric",month:"short",year:"numeric"},"UTC")}const i=new Date(a);return Number.isNaN(i.getTime())?a:ga(i,t,{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1},n)},_l=(e,t={})=>{if(!e)return"";const n=e.timezone?.trim()||t.timezone?.trim(),a=Yi(e.start,t.locale,n),i=Yi(e.end,t.locale,n);return a&&i?`${a} – ${i} (end not included)`:a?`From ${a}`:i?`Before ${i}`:""},wl=(e,t,n)=>{if(!e)return{label:"Updated",description:"Source freshness is unavailable.",tone:"neutral"};if(e.status==="current")return{label:"Fresh",description:"Source data is current.",tone:"success"};if(e.status==="no_data")return{label:"No source data",description:"No source data is available for this period or an earlier period.",tone:"neutral"};if(e.status!=="delayed")return{label:"Updated",description:"Source freshness is unavailable.",tone:"neutral"};const a=s=>{if(!s)return"";const c=Wi.test(s)?new Date(`${s}T00:00:00`):new Date(s);return Number.isNaN(c.getTime())?"":new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(c)},i=a(e.dataAsOf),o=a(t);return{label:`${o?`Checked ${o} · `:""}Latest record${i?` ${i}`:""}`,description:`Latest matching record${i?`: ${i}`:" date is unavailable"}. An older record alone does not prove a source delay.`,tone:"neutral"}},Je=(e,t)=>t(String(e??"").replace(/\s+/g," ").trim()).trim(),Zi=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e.toLocaleString(t):"",kl=e=>{const t=[];return e?.liveboardTileId?.trim()&&t.push({kind:"liveboard_tile",id:e.liveboardTileId.trim()}),e?.insightId?.trim()&&t.push({kind:"insight",id:e.insightId.trim()}),e?.queryRunId?.trim()&&t.push({kind:"query_run",id:e.queryRunId.trim()}),t},Sl=(e,t={})=>{const{locale:n}=t,a={...xt,...t.copy},i=t.cleanText??(y=>y),o=e.timezone?.trim()||void 0,s=new Map;for(const y of e.evidenceItems??[])y?.id?.trim()&&!s.has(y.id.trim())&&s.set(y.id.trim(),y);const c=[],d={},l=y=>{const D=y?.trim();if(!D)return;const S=d[D];if(S)return{id:D,index:S.index};const O=s.get(D);if(!O)return;const ue=O.valueStatus,oe=ji(ue)||(ue==="observed"?"observed":""),Fe=O.source?.kind,_e={id:D,index:c.length+1,text:Je(O.text,i),...O.metric?.trim()?{metric:O.metric.trim()}:{},...O.period?.label?.trim()?{periodLabel:O.period.label.trim()}:{},...(()=>{const Te=_l(O.period,{locale:n,timezone:o});return Te?{periodRange:Te}:{}})(),...O.period?.timezone?.trim()||o?{timezone:O.period?.timezone?.trim()||o}:{},...O.filters?.length?{filters:O.filters.map(Te=>Te.trim()).filter(Boolean)}:{},...(()=>{const Te=Zi(O.value,n);return Te?{valueText:Te}:{}})(),...oe?{statusLabel:oe}:{},statusTone:Hi(ue),...O.statusReason?.trim()?{statusReason:Je(O.statusReason,i)}:{},...Fe==="card"?{sourceLabel:xt.sourceCard}:Fe==="supporting_query"?{sourceLabel:xt.sourceSupportingQuery}:{},sourceTargets:kl(O.source),...(()=>{const Te=Ki(O.checkedAt??e.checkedAt,{locale:n,timezone:o,now:t.now});return Te?{checkedText:Te}:{}})()};return _e.filters&&_e.filters.length===0&&delete _e.filters,c.push(_e),d[D]=_e,{id:D,index:_e.index}},u=y=>{const D=new Set,S=[];for(const O of y??[]){const ue=l(O);ue&&!D.has(ue.id)&&(D.add(ue.id),S.push(ue))}return S},p=vl(e.source)||e.level==="detailed",m=Je(e.headline,i)||Je(e.summary,i),f={text:m,citations:u(e.headlineEvidenceIds)},_=Je(e.summary,i),h=_&&_!==m?{text:_,citations:u(e.summaryEvidenceIds)}:void 0;if(!h&&_&&e.summaryEvidenceIds?.length)for(const y of u(e.summaryEvidenceIds))f.citations.some(D=>D.id===y.id)||f.citations.push(y);const I=(e.periods??[]).filter(y=>y?.label?.trim()).map(y=>{const D=y.valueStatus,S=ji(D),O=y.valueText?.trim()||Zi(y.value,n)||(D==="missing"?"—":""),ue=S?y.statusReason?.trim()||s.get(y.evidenceId?.trim()??"")?.statusReason?.trim():"",oe=l(y.evidenceId);return{key:y.evidenceId||`${y.label}-${y.start??""}-${y.end??""}`,label:y.label.trim(),valueText:O,...D?{status:D}:{},statusLabel:S,statusTone:Hi(D),inProgress:!!y.inProgress,current:!!y.current,...ue?{reason:Je(ue,i)}:{},...oe?{citation:oe}:{}}}),x=t.maxConclusions??4,g=(e.evidenceStatements??[]).map(y=>({text:Je(y.text,i),citations:u(y.evidenceIds)})).filter(y=>y.text),T=(g.length>0?g:(e.evidence??[]).map(y=>Je(y,i)).filter(Boolean).map(y=>({text:y,citations:[]}))).filter((y,D,S)=>S.findIndex(O=>O.text===y.text)===D).filter(y=>y.text!==f.text&&y.text!==h?.text).slice(0,x),V=Je(e.businessMeaning,i),P=V?{text:V,citations:u(e.businessMeaningEvidenceIds)}:void 0,ee=[],Z=y=>{y.text&&!ee.some(D=>D.text===y.text)&&ee.push(y)},Y=(e.limitations??[]).map(y=>y.toLowerCase());for(const y of I){const D=Y.some(S=>S.includes(y.label.toLowerCase())&&S.includes("in progress"));y.inProgress&&!D&&Z({kind:"in_progress",text:`${y.label} is still in progress, so its total can still change.`,...y.citation?{citation:y.citation}:{}}),(y.status==="empty_bucket"||y.status==="unconfirmed_zero")&&Z({kind:"no_records",text:`${y.label} has no records yet. This is not a confirmed 0${y.reason?`: ${y.reason.replace(/\.$/,"")}`:""}.`,...y.citation?{citation:y.citation}:{}}),y.status==="missing"&&Z({kind:"missing",text:`${y.label} is missing${y.reason?`: ${y.reason.replace(/\.$/,"")}`:""}.`,...y.citation?{citation:y.citation}:{}})}e.currentPeriodInProgress&&!I.some(y=>y.inProgress)&&Z({kind:"in_progress",text:"The current period is still in progress, so its total can still change."});for(const y of e.missing??[]){if(!y?.label?.trim()||!y.reason?.trim())continue;const D=l(y.evidenceId);Z({kind:"missing",text:$l(y),...D?{citation:D}:{}})}(e.dataFreshness?.status==="delayed"||e.dataFreshness?.status==="no_data")&&Z({kind:"freshness",text:wl(e.dataFreshness,e.checkedAt,n).description});for(const y of e.limitations??[]){const D=Je(y,i);D&&Z({kind:"limitation",text:D})}const z=(e.possibleDrivers??[]).map(y=>({title:Je(y.hypothesis,i),howToCheck:Je(y.howToCheck,i),citations:u(y.evidenceIds)})).filter(y=>y.title).slice(0,t.maxCauses??3),te=(e.recommendations??[]).map(y=>({title:Je(y.action,i),why:Je(y.why,i),...y.successMetric?.trim()?{watch:Je(y.successMetric,i)}:{},citations:u(y.evidenceIds)})).filter(y=>y.title).slice(0,t.maxRecommendations??3),U=Je(e.forecast?.text,i),B=U?{badge:xl(e.forecast?.qualityStatus),text:U,...e.forecast?.limitations?.trim()?{note:Je(e.forecast.limitations,i)}:{}}:void 0,A=(e.followUps??[]).map(y=>Je(y,i)).filter(Boolean).filter((y,D,S)=>S.indexOf(y)===D).slice(0,t.maxFollowUps??4);for(const y of s.keys())l(y);const N=Je(e.conversationalPreface,i);return{...e.explanationId?.trim()?{explanationId:e.explanationId.trim()}:{},ai:p,lead:{eyebrow:a.eyebrow,provenance:p?a.provenanceAI:e.level==="basic"?a.basicExplanation:a.provenanceGoverned,...N?{preface:N}:{},headline:f,...h?{summary:h}:{}},comparison:I,conclusions:T,...P?{businessMeaning:P}:{},limits:ee,checkedLine:yl(e,{locale:n,now:t.now}),investigate:{causes:z,recommendations:te,...B?{outlook:B}:{},followUps:A},hasInvestigate:z.length>0||te.length>0||!!B||A.length>0||c.length>0,evidence:c,evidenceById:d,sourceNote:p?a.sourceNoteAI:a.sourceNoteGoverned}},$l=e=>`${e.label.trim()} could not be established: ${e.reason.trim()}`,Tl=e=>`[${e.index}]`,Cl=(e,t)=>{const n={...xt,...t},a=[];e.metric&&a.push({key:"metric",label:n.evidenceMetric,value:e.metric});const i=[e.periodLabel,e.periodRange].filter(Boolean).join(" · ");i&&a.push({key:"period",label:n.evidencePeriod,value:i}),e.timezone&&a.push({key:"timezone",label:n.evidenceTimezone,value:e.timezone}),e.filters?.length&&a.push({key:"filters",label:n.evidenceFilters,value:e.filters.join("; ")});const o=[e.valueText,e.statusLabel].filter(Boolean).join(" · ");return o&&a.push({key:"value",label:n.evidenceValue,value:o}),e.statusReason&&a.push({key:"reason",label:n.evidenceStatus,value:e.statusReason}),e.sourceLabel&&a.push({key:"source",label:n.evidenceSource,value:e.sourceLabel}),e.checkedText&&a.push({key:"checked",label:n.evidenceChecked,value:e.checkedText}),a},Al=e=>{const t=new Set(Vi.map(i=>i.id)),n=Array.from(e.comment??"").map(i=>{const o=i.charCodeAt(0);return o<32||o>=127&&o<=159?" ":i}).join("").replace(/\s+/g," ").trim(),a=e.rating==="down"?[...new Set(e.reasons??[])].filter(i=>t.has(i)).slice(0,4):[];return{explanationId:e.explanationId,rating:e.rating,...a.length?{reasons:a}:{},...e.rating!=="clear"&&n?{comment:Array.from(n).slice(0,pr).join("")}:{},...e.modelId?{modelId:e.modelId}:{},...typeof e.modelVersion=="number"&&e.modelVersion>0?{modelVersion:e.modelVersion}:{}}},Ml=(e,t)=>{const n=`.${e}-xp`;return`
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 Il{constructor(t,n,a,i={}){q(this,"explanationId");q(this,"submit");q(this,"onChange");q(this,"context");q(this,"state",{phase:"idle",reasons:[],comment:""});this.explanationId=t,this.submit=n,this.onChange=a,this.context=i}set(t){this.state={...this.state,...t},this.onChange(this.state)}async save(t,n){const a=this.state;this.set({phase:"saving",error:void 0});try{await this.submit(Al({explanationId:this.explanationId,...this.context,...t})),this.set({...n,error:void 0})}catch{this.set({phase:a.phase==="details"?"details":"error",rating:a.rating,error:xt.feedbackError})}}vote(t){return this.state.phase==="saving"?Promise.resolve():this.save({rating:t},t==="up"?{phase:"done",rating:t,reasons:[],comment:""}:{phase:"details",rating:t})}toggleReason(t){const n=this.state.reasons.includes(t)?this.state.reasons.filter(a=>a!==t):[...this.state.reasons,t];this.set({reasons:n})}setComment(t){this.set({comment:Array.from(t).slice(0,pr).join("")})}send(){return this.state.phase==="saving"?Promise.resolve():this.save({rating:"down",reasons:this.state.reasons,comment:this.state.comment},{phase:"done",rating:"down"})}undo(){return this.state.phase==="saving"?Promise.resolve():this.save({rating:"clear"},{phase:"idle",rating:void 0,reasons:[],comment:""})}}const Ji={delaysMs:[1e3,2e3,4e3],capMs:45e3},fr=e=>e==="pending"||e==="ready"||e==="failed"?e:"not_requested",El=e=>fr(e?.aiExplanation?.status);class zl{constructor(t,n,a,i={}){q(this,"transport");q(this,"onChange");q(this,"state");q(this,"handle");q(this,"disposed",!1);q(this,"generation",0);q(this,"attempt",0);q(this,"startedAt",0);q(this,"delays");q(this,"capMs");q(this,"now");q(this,"schedule");q(this,"cancelTimer");q(this,"isVisible");q(this,"onSettled");q(this,"inFlight",null);q(this,"pausedAt",null);q(this,"onVisibilityChange",()=>{this.disposed||this.pausedAt===null||!this.isVisible()||(this.startedAt+=this.now()-this.pausedAt,this.pausedAt=null,this.queue())});this.transport=n,this.onChange=a,this.delays=i.delaysMs?.length?i.delaysMs:Ji.delaysMs,this.capMs=i.capMs??Ji.capMs,this.now=i.now??(()=>Date.now()),this.schedule=i.schedule??((c,d)=>setTimeout(c,d)),this.cancelTimer=i.cancel??(c=>clearTimeout(c)),this.isVisible=i.isVisible??(()=>typeof document>"u"||document.visibilityState!=="hidden"),this.onSettled=i.onSettled;const o=El(t),s=o==="pending"&&!n?"not_requested":o;this.state={status:s,explanation:t,retryAvailable:s==="failed"&&this.canRetry(t.aiExplanation?.retryAvailable),retrying:!1,announcement:""}}get explanationId(){return this.state.explanation.aiExplanation?.explanationId||this.state.explanation.explanationId||""}canRetry(t){return!!this.transport?.retry&&t!==!1}set(t){if(this.disposed)return;const n=this.state.status;this.state={...this.state,...t},this.onChange(this.state);const a=this.state.status;a!==n&&(a==="ready"||a==="failed"||a==="not_requested")&&this.onSettled?.(a)}start(){this.state.status!=="pending"||!this.explanationId||(this.disposed=!1,this.startedAt=this.now(),this.attempt=0,typeof document<"u"&&document.addEventListener("visibilitychange",this.onVisibilityChange),this.queue())}queue(){if(this.disposed)return;if(!this.isVisible()){this.pausedAt??(this.pausedAt=this.now());return}const t=this.now()-this.startedAt;if(t>=this.capMs){this.fail(!0);return}const n=this.delays[Math.min(this.attempt,this.delays.length-1)]??4e3;this.attempt+=1;const a=this.generation;this.handle=this.schedule(()=>{this.pollOnce(a)},Math.min(n,Math.max(0,this.capMs-t)))}async pollOnce(t){if(this.disposed||t!==this.generation||!this.transport)return;if(!this.isVisible()){this.pausedAt??(this.pausedAt=this.now());return}const n=new AbortController;this.inFlight=n;try{const a=await this.transport.poll(this.explanationId,n.signal);if(this.disposed||t!==this.generation)return;this.apply(a)}catch{if(this.disposed||t!==this.generation)return;this.queue()}finally{this.inFlight===n&&(this.inFlight=null)}}apply(t){const n=fr(t.status);if(this.applyBasicUpdate(t,n),n==="ready"&&t.explanation&&ur(t.explanation)){this.set({status:"ready",explanation:t.explanation,retryAvailable:!1,retrying:!1,announcement:xt.detailedReady});return}if(n==="pending"){this.state.status!=="pending"&&this.set({status:"pending",retrying:!1,announcement:""}),this.queue();return}if(n==="not_requested"){this.set({status:"not_requested",retryAvailable:!1,retrying:!1,announcement:""});return}this.fail(this.canRetry(t.retryAvailable))}applyBasicUpdate(t,n){const a=t.basic;if(!a||n==="ready"||this.state.status==="ready"||!ur(a))return;const i=this.state.explanation;a.headline===i.headline&&a.summary===i.summary||this.set({explanation:{...a,explanationId:i.explanationId??a.explanationId,aiExplanation:i.aiExplanation,level:i.level}})}fail(t){this.generation+=1,this.set({status:"failed",retryAvailable:t&&this.canRetry(!0),retrying:!1,announcement:xt.detailedUnavailable})}async retry(){if(!this.transport?.retry||this.state.retrying||this.state.status==="ready")return;const t=this.explanationId;if(!t)return;this.generation+=1;const n=this.generation;this.set({retrying:!0,announcement:""});try{const a=await this.transport.retry(t);if(this.disposed||n!==this.generation)return;if(fr(a.status)==="pending"){this.set({status:"pending",retrying:!1,retryAvailable:!1,announcement:xt.preparingDetailed}),this.startedAt=this.now(),this.attempt=0,this.queue();return}this.apply(a)}catch{if(this.disposed||n!==this.generation)return;this.set({status:"failed",retrying:!1,retryAvailable:!1,announcement:xt.detailedUnavailable})}}dispose(){this.disposed=!0,this.generation+=1,this.inFlight?.abort(),this.inFlight=null,this.handle!==void 0&&this.cancelTimer(this.handle),typeof document<"u"&&document.removeEventListener("visibilitychange",this.onVisibilityChange)}}const Xi=Ha(xt),zn=()=>Ga(Xi),Nl=(e,t)=>{const n=R(t);n.current=t;const a=R(()=>{}),i=e.aiExplanation?.explanationId??e.explanationId??"",o=e.aiExplanation?.status==="pending"?"pending":"settled",s=Be(()=>{const u=n.current,p=u?{poll:(m,f)=>n.current.poll(m,f),...u.retry?{retry:(m,f)=>n.current.retry(m,f)}:{}}:void 0;return new zl(e,p,m=>a.current(m),{onSettled:m=>n.current?.settled?.(i,m)})},[i,o,!!t]),[c,d]=$(s.state);return X(()=>(a.current=d,d(s.state),s.start(),()=>s.dispose()),[s]),[c.status==="ready"?c:{...c,explanation:e},s]},Rl=({prefix:e,state:t,onRetry:n})=>{const a=zn();return r("div",{class:`${e}-xp__ai`,"data-ai-status":t.status,children:[t.status==="pending"?r("p",{class:`${e}-xp__ai-note`,children:a.preparingDetailed}):null,t.status==="failed"?r("p",{class:`${e}-xp__ai-note`,children:[a.detailedUnavailable,t.retryAvailable?r("button",{type:"button",class:`${e}-xp__ai-retry`,disabled:t.retrying,onClick:n,children:a.detailedRetry}):null]}):null,r("span",{class:`${e}-xp__sr`,role:"status","aria-live":"polite",children:t.announcement})]})},Ll=({citations:e,step:t,prefix:n,active:a,onToggle:i,evidenceById:o})=>{const s=zn();return e.length===0?null:r(se,{children:e.map(c=>{const d=a?.id===c.id&&a.step===t;return r("button",{type:"button",class:`${n}-xp__cite`,"data-evidence-id":c.id,"aria-expanded":d,"aria-label":`${s.citationLabel} ${c.index}: ${o[c.id]?.text??""}`.trim(),onClick:l=>i(c.id,t,l.currentTarget),children:Tl(c).slice(1,-1)},c.id)})})},Dl=(e,t)=>e.sourceTargets.find(n=>t?t(n):!0),Pl=({evidence:e,prefix:t,onClose:n,onOpenSource:a,canOpenSource:i})=>{const o=zn(),s=R(null);X(()=>{s.current?.focus()},[e.id]);const c=a?Dl(e,i):void 0;return r("div",{ref:s,class:`${t}-xp__evidence-panel`,role:"region",tabIndex:-1,"aria-label":`${o.evidence} ${e.index}`,"data-testid":"analytics-explanation-evidence",onKeyDown:d=>{d.key==="Escape"&&(d.stopPropagation(),n())},children:[r("div",{class:`${t}-xp__evidence-head`,children:[r("p",{class:`${t}-xp__evidence-text`,children:["[",e.index,"] ",e.text]}),r("button",{type:"button",class:`${t}-xp__close`,"aria-label":o.closeEvidence,onClick:n,children:"×"})]}),r("dl",{class:`${t}-xp__evidence-rows`,children:Cl(e,o).map(d=>r("div",{style:{display:"contents"},"data-row":d.key,children:[r("dt",{children:d.label}),r("dd",{children:d.value})]},d.key))}),c&&a?r("div",{class:`${t}-xp__evidence-actions`,children:r("button",{type:"button",class:`${t}-xp__button`,onClick:()=>a(c,e),children:o.openSource})}):null]})},Qi=({down:e})=>r("svg",{viewBox:"0 0 24 24",width:"15",height:"15",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",focusable:"false",style:e?{transform:"scaleY(-1)"}:void 0,children:r("path",{d:"M7 10v11H3V10h4Zm0 0 4-7a2 2 0 0 1 2 2v4h6a2 2 0 0 1 2 2.3l-1.2 7A2 2 0 0 1 17.8 21H7"})}),Ol=(e,t,n)=>t==="wrong_numbers"?e.reasonWrongNumbers:t==="missing_comparison"?e.reasonMissingComparison:t==="unclear"?e.reasonUnclear:t==="too_long"?e.reasonTooLong:n,Fl=({prefix:e,explanationId:t,submit:n,context:a})=>{const i=zn(),[o,s]=$({phase:"idle",reasons:[],comment:""}),c=Be(()=>new Il(t,n,s,a),[t]),d=o.phase==="saving";return r("div",{class:`${e}-xp__feedback`,"data-testid":"analytics-explanation-feedback",children:[o.phase==="done"?r("div",{class:`${e}-xp__feedback-row`,role:"status",children:[r("span",{class:`${e}-xp__feedback-note`,children:i.feedbackThanks}),r("button",{type:"button",class:`${e}-xp__button`,onClick:()=>{c.undo()},children:i.feedbackUndo})]}):r("div",{class:`${e}-xp__feedback-row`,children:[r("span",{class:`${e}-xp__feedback-label`,children:i.feedbackPrompt}),r("button",{type:"button",class:`${e}-xp__vote`,"aria-label":i.feedbackHelpful,"aria-pressed":o.rating==="up",disabled:d,onClick:()=>{c.vote("up")},children:r(Qi,{down:!1})}),r("button",{type:"button",class:`${e}-xp__vote`,"aria-label":i.feedbackNotHelpful,"aria-pressed":o.rating==="down",disabled:d,onClick:()=>{c.vote("down")},children:r(Qi,{down:!0})})]}),o.phase==="details"||d&&o.rating==="down"?r("form",{class:`${e}-xp__feedback-form`,onSubmit:l=>{l.preventDefault(),c.send()},children:[r("fieldset",{class:`${e}-xp__reasons`,children:[r("legend",{children:i.feedbackReasonsPrompt}),Vi.map(l=>r("button",{type:"button",class:`${e}-xp__reason`,"aria-pressed":o.reasons.includes(l.id),onClick:()=>c.toggleReason(l.id),children:Ol(i,l.id,l.label)},l.id))]}),r("textarea",{class:`${e}-xp__comment`,"aria-label":i.feedbackCommentPlaceholder,placeholder:i.feedbackCommentPlaceholder,maxLength:pr,value:o.comment,onInput:l=>c.setComment(l.currentTarget.value)}),r("div",{class:`${e}-xp__feedback-row`,children:r("button",{type:"submit",class:`${e}-xp__button is-primary`,disabled:d,children:i.feedbackSubmit})})]}):null,o.error?r("p",{class:`${e}-xp__feedback-error`,role:"alert",children:o.error}):null]})},eo=({aiTransport:e,...t})=>{const[n,a]=Nl(t.explanation,e),i=Ul(t.explanation),o=Be(()=>({...xt,...t.copy}),[t.copy]);return r(Xi.Provider,{value:o,children:r(Bl,{...t,explanation:n.explanation,aiStatus:i?r(Rl,{prefix:t.classPrefix,state:n,onRetry:()=>{a.retry()}}):null})})},Ul=e=>!!(e.aiExplanation&&e.aiExplanation.status!=="not_requested"),Bl=({explanation:e,aiStatus:t,classPrefix:n,showLead:a=!0,investigateOpen:i=!1,onFollowUp:o,onOpenSource:s,canOpenSource:c,onFeedback:d,feedbackContext:l,onExpand:u,onCollapse:p,expanded:m=!1,...f})=>{const _=zn(),h=R(null),I=R(null),x=R(!1),g=()=>{const A=h.current,N=A?.getRootNode(),y=N&&"activeElement"in N?N.activeElement:null;return!!(A&&y&&A.contains(y))},T=Be(()=>(x.current=g(),Sl(e,{...f,copy:_})),[e,f.locale,f.cleanText,_]),[V,P]=$(),ee=R(null);Sn(()=>{!V||T.evidenceById[V.id]&&h.current?.querySelector('[data-testid="analytics-explanation-evidence"]')||(P(void 0),x.current&&!g()&&(I.current??h.current)?.focus())},[T]);const Z=(A,N,y)=>{ee.current=y,P(D=>D?.id===A&&D.step===N?void 0:{id:A,step:N})},Y=()=>{P(void 0);const A=ee.current;A?.isConnected?A.focus():(I.current??h.current)?.focus()},z=(A,N)=>r(Ll,{citations:A,step:N,prefix:n,active:V,onToggle:Z,evidenceById:T.evidenceById}),te=A=>{if(!V||V.step!==A)return null;const N=T.evidenceById[V.id];return N?r(Pl,{evidence:N,prefix:n,onClose:Y,onOpenSource:s,canOpenSource:c}):null},U=(A,N)=>r(se,{children:[A.text,z(A.citations,N)]}),{investigate:B}=T;return r("section",{ref:h,class:`${n}-xp${m?" is-expanded":""}${u||p?" has-expand":""}`,"data-testid":"analytics-explanation","aria-label":_.region,tabIndex:-1,children:[m&&p?r("button",{type:"button",class:`${n}-xp__expand`,"aria-label":_.collapse,title:_.collapse,onClick:p,children:"×"}):u?r("button",{type:"button",class:`${n}-xp__expand`,"aria-label":_.expand,title:_.expand,"data-testid":"analytics-explanation-expand",onClick:u,children:"⤢"}):null,a?r("div",{class:`${n}-xp__lead`,"data-step":"lead",children:[T.lead.preface?r("p",{class:`${n}-xp__preface`,children:T.lead.preface}):null,r("div",{class:`${n}-xp__meta`,children:[r("span",{class:`${n}-xp__eyebrow`,children:T.lead.eyebrow}),r("span",{class:`${n}-xp__provenance`,children:T.lead.provenance})]}),r("h3",{class:`${n}-xp__headline`,ref:I,tabIndex:-1,children:U(T.lead.headline,"lead")}),T.lead.summary?r("p",{class:`${n}-xp__summary`,children:U(T.lead.summary,"lead")}):null,te("lead")]}):null,t,T.comparison.length>0?r("section",{class:`${n}-xp__step`,"data-step":"comparison",children:[r("h4",{class:`${n}-xp__title`,children:_.comparison}),r("ul",{class:`${n}-xp__periods`,children:T.comparison.map(A=>r("li",{class:`${n}-xp__period`,"data-status":A.status??"observed",children:[r("span",{class:`${n}-xp__period-label`,children:A.label}),A.valueText?r("span",{class:`${n}-xp__period-value`,children:A.valueText}):null,A.statusLabel?r("span",{class:`${n}-xp__chip is-${A.statusTone}`,children:A.statusLabel}):null,A.inProgress?r("span",{class:`${n}-xp__chip is-progress`,children:_.inProgress}):null,A.citation?z([A.citation],"comparison"):null,A.reason?r("small",{class:`${n}-xp__period-reason`,children:A.reason}):null]},A.key))}),te("comparison")]}):null,T.conclusions.length>0||T.businessMeaning?r("section",{class:`${n}-xp__step`,"data-step":"conclusions",children:[r("h4",{class:`${n}-xp__title`,children:_.conclusions}),T.conclusions.length>0?r("ul",{class:`${n}-xp__list`,children:T.conclusions.map(A=>r("li",{children:U(A,"conclusions")},A.text))}):null,T.businessMeaning?r("p",{class:`${n}-xp__meaning`,children:[r("strong",{children:[_.whyItMatters,": "]}),U(T.businessMeaning,"conclusions")]}):null,te("conclusions")]}):null,T.limits.length>0?r("section",{class:`${n}-xp__step`,"data-step":"limits",children:[r("h4",{class:`${n}-xp__title`,children:_.limits}),r("ul",{class:`${n}-xp__list ${n}-xp__limits`,children:T.limits.map(A=>r("li",{"data-kind":A.kind,children:[A.text,A.citation?z([A.citation],"limits"):null]},A.text))}),te("limits")]}):null,T.checkedLine?r("p",{class:`${n}-xp__checked`,"data-step":"checked",children:T.checkedLine}):null,T.hasInvestigate?r("details",{class:`${n}-xp__investigate`,"data-step":"investigate",open:i,children:[r("summary",{children:_.investigate}),r("div",{class:`${n}-xp__investigate-body`,children:[B.causes.length>0?r("div",{class:`${n}-xp__group`,children:[r("div",{class:`${n}-xp__group-head`,children:[r("h4",{class:`${n}-xp__title`,children:_.causes}),r("span",{class:`${n}-xp__hint`,children:_.causesHint})]}),B.causes.map(A=>r("article",{class:`${n}-xp__card`,children:[r("p",{class:`${n}-xp__card-title`,children:[A.title,z(A.citations,"investigate")]}),A.howToCheck?r("p",{class:`${n}-xp__card-body`,children:[_.howToCheck," ",A.howToCheck]}):null]},A.title))]}):null,B.recommendations.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:_.recommendations}),B.recommendations.map(A=>r("article",{class:`${n}-xp__card`,children:[r("p",{class:`${n}-xp__card-title`,children:[A.title,z(A.citations,"investigate")]}),A.why?r("p",{class:`${n}-xp__card-body`,children:A.why}):null,A.watch?r("p",{class:`${n}-xp__card-body`,children:[_.watch," ",A.watch]}):null]},A.title))]}):null,B.outlook?r("div",{class:`${n}-xp__group`,children:[r("div",{class:`${n}-xp__group-head`,children:[r("h4",{class:`${n}-xp__title`,children:_.outlook}),r("span",{class:`${n}-xp__hint`,children:B.outlook.badge})]}),r("p",{class:`${n}-xp__card-body`,children:B.outlook.text}),B.outlook.note?r("p",{class:`${n}-xp__card-body`,children:B.outlook.note}):null]}):null,o&&B.followUps.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:_.followUps}),r("div",{class:`${n}-xp__questions`,children:B.followUps.map(A=>r("button",{type:"button",class:`${n}-xp__question`,onClick:()=>o(A),children:A},A))})]}):null,T.evidence.length>0?r("div",{class:`${n}-xp__group`,children:[r("h4",{class:`${n}-xp__title`,children:_.evidenceList}),r("ul",{class:`${n}-xp__list`,children:T.evidence.map(A=>r("li",{children:[A.text,z([{id:A.id,index:A.index}],"investigate")]},A.id))})]}):null,te("investigate")]})]}):null,r("p",{class:`${n}-xp__source`,children:T.sourceNote}),d&&T.explanationId?r(Fl,{prefix:n,explanationId:T.explanationId,submit:d,context:l}):null]})},ql=[{name:"Smileys",emojis:["😀","😃","😄","😁","😅","😂","🤣","😊","😇","🙂","🙃","😉","😌","😍","🥰","😘","😋","😛","😜","🤪","🤗","🤭","🤔","🤐","😐","😶","😏","🙄","😴","🥳","😎","🤓","🥺","😢","😭","😤","😠","🤯","😬","😱","🤩","🥱"]},{name:"Gestures",emojis:["👍","👎","👌","🤌","✌️","🤞","🤟","🤘","🤙","👈","👉","👆","👇","✋","🖐️","👋","🤝","🙏","💪","👏","🙌","👐","🤲","🫶"]},{name:"Hearts & symbols",emojis:["❤️","🧡","💛","💚","💙","💜","🖤","🤍","💔","❣️","💕","💖","💘","💝","✨","⭐","🌟","💫","🔥","🎉","🎊","✅","❌","⚡","💯","🚀"]},{name:"Animals & nature",emojis:["🐶","🐱","🦊","🐻","🐼","🐨","🦁","🐮","🐸","🐵","🐧","🦄","🐝","🦋","🐢","🐬","🌷","🌸","🌹","🌻","🌳","🍀"]},{name:"Food & drink",emojis:["🍎","🍌","🍉","🍓","🍒","🥑","🍔","🍟","🍕","🌮","🍿","🍩","🍪","🎂","☕","🍵","🍺","🥂","🍷"]},{name:"Objects & travel",emojis:["🚀","✈️","🚗","🏠","📦","📱","💻","⌚","📷","💡","🔑","🎁","📌","✏️","📝","📞","📧","💰","📈","⏰","🔔","🎯","🏆","🎮","🎵","💬","👀"]}],ba={"contact-support":{title:"Contact support",submit:"Request support",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"},{key:"subject",label:"Subject",kind:"text",required:!0},{key:"message",label:"Message",kind:"textarea",required:!0,placeholder:"Describe what you need help with."}]},inquiry:{title:"Leave a message",submit:"Send message",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"},{key:"message",label:"Message",kind:"textarea",required:!0,placeholder:"How can we help?"}]},contact:{title:"Share your details",submit:"Save",fields:[{key:"name",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"email",label:"Email",kind:"email",required:!0,identity:"email"},{key:"phone",label:"Phone",kind:"tel",required:!0,identity:"phone"}]},"book-demo":{title:"Book a demo",submit:"Request demo",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"},{key:"preferredAt",label:"Preferred time",kind:"text",placeholder:"e.g. Thursday 3pm"},{key:"notes",label:"Notes",kind:"textarea",placeholder:"Anything we should know?"}]},"request-callback":{title:"Request a callback",submit:"Request callback",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorPhone",label:"Phone number",kind:"tel",required:!0,identity:"phone"},{key:"topic",label:"Topic",kind:"text",placeholder:"What should we call about?"}]},"schedule-callback":{title:"Schedule a callback",submit:"Schedule callback",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorPhone",label:"Phone number",kind:"tel",required:!0,identity:"phone"},{key:"topic",label:"Topic",kind:"text",placeholder:"What should we call about?"}]},"subscribe-newsletter":{title:"Subscribe",submit:"Subscribe",fields:[{key:"visitorName",label:"Full name",kind:"text",required:!0,identity:"name"},{key:"visitorEmail",label:"Email",kind:"email",required:!0,identity:"email"}]}},hr={openChat:"Open chat",closeChat:"Close chat",closeHistory:"Close conversation history",unreadMessage:"1 unread message",unreadMessages:"{count} unread messages",muteSounds:"Mute sounds",unmuteSounds:"Unmute sounds",statusOnline:"Online · replies instantly",statusOffline:"Away · leave a message",liveSupport:"Live support",reconnectSupport:"Reconnect to support",reconnectPrompt:"I can bring a teammate back into this chat.",waitingForTeam:"AI helping · team notified",assistantName:"Assistant",chatName:"Chat",welcomeLabel:"{name} welcome",welcomeEyebrow:"Ready when you are",welcomePrompt:"Ask a question, leave a message, or book a demo.",agentTyping:"{name} is typing…",expandedAnalyticsResult:"Expanded analytics result",privacyAndData:"Privacy and local data",muteMicrophone:"Mute microphone",unmuteMicrophone:"Unmute microphone",chooseMicrophone:"Choose microphone",defaultMicrophone:"Default microphone",microphone:"Microphone",talkNow:"Talk now",expandView:"Expand view",exitExpandedView:"Exit expanded view",minimizeVoiceChat:"Minimize voice chat",endVoiceChat:"End voice chat",restoreVoiceChat:"Restore voice chat",reopenVoiceChat:"Reopen voice chat with {name}",voiceConnecting:"Connecting…",voiceListening:"Listening…",voiceHearing:"Hearing you…",voiceUnavailable:"Can’t hear you — check your microphone.",voiceProcessing:"Transcribing…",voiceSpeaking:"Speaking…",voiceNoise:"No clear speech heard. Move closer to the mic and try again.",voiceMisunderstood:"Could not transcribe that. Please try again or type your message.",voiceDenied:"Microphone unavailable. Allow access or type your message.",composerPlaceholder:"Type your message…",send:"Send message",emoji:"Emoji",gifs:"GIFs",attachFile:"Attach a file",recordVoice:"Record a voice message",stopRecording:"Stop recording",actionTestMode:"Test mode",stop:"Stop",copy:"Copy",copied:"Copied",retry:"Retry",clearChat:"Clear conversation",clearChatConfirm:"Clear this conversation?",clearChatConfirmBody:"This clears the messages on this device and starts a fresh chat.",clearConfirmCta:"Clear chat",endChat:"End conversation",endChatConfirm:"End this conversation?",endChatConfirmBody:"You won't be able to send more messages in this chat, but you can start a new one anytime.",endConfirmCta:"End conversation",conversationEnded:"This conversation has ended.",startNewChat:"Start a new conversation",pastConversations:"Past conversations",viewingPast:"Viewing a past conversation (read-only)",backToChat:"Back to current chat",historyEnded:"ended",feedbackHelpful:"Helpful",feedbackNotHelpful:"Not helpful",feedbackAnswerPrompt:"Was this answer helpful?",feedbackThanks:"Thanks for the feedback",csatPrompt:"How was this chat?",feedbackCommentPlaceholder:"What went wrong? (optional)",feedbackSend:"Send",cancel:"Cancel",newMessages:"New messages",poweredBy:"Powered by",searchGifs:"Search GIFs…",searchingGifs:"Searching…",noGifs:"No GIFs found",assistantTyping:"Assistant is typing",emptyReply:"Sorry, I couldn't generate a reply.",errorGeneric:"Something went wrong reaching the assistant. Please try again.",errorRateLimit:"You’re sending messages a little fast — give it a second and try again.",resultExpired:"This result is not stored on this device. Ask again to see it.",attaching:"Reading file…",attachTooLarge:"That file is too large (max 5 MB).",attachFailed:"Could not attach that file. Check its type and try again.",attachPreviewTitle:"Preview of {name}",attachOpen:"Preview {name}",attachDownload:"Download",attachPreviewClose:"Close preview",attachPreviewLoading:"Loading file…",attachPreviewFailed:"This file can’t be shown right now. It may have expired.",attachPreviewUnsupported:"This file can’t be previewed here. Download it to open it.",attachAnalysisFailed:"Saved for the team; AI could not read it.",removeAttachment:"Remove attachment",attachLimit:"You can attach up to {count} files to one message.",attachedFiles:"Attached files",removeAttachmentNamed:"Remove {name}",dropFileHere:"Drop the file here",clearDeviceData:"Clear conversations from this device",clearDeviceDataBody:"This removes locally stored conversations and visitor details from this browser. It cannot be undone.",clearDeviceDataCta:"Clear this device",handoffTitle:"Want our team to follow up?",handoffName:"Name (optional)",handoffEmail:"Your email",handoffNotify:"Notify the team",sending:"Sending…",handoffShared:"I’ve shared this with our team — they’ll get back to you at {email}.",formThanks:"Thanks! We’ll be in touch.",caseReference:"Reference: {reference}",formError:"Something went wrong — please try again.",actionContactOptions:"Contact options",actionGetInTouch:"Get in touch",actionMore:"+{count} more",actionNeedHelp:"Need help?",actionChoose:"Choose what you want to do",actionFooter:"We’ll ask for your full name and the best email or phone so the team can reach you.",actionCategorySupport:"Support",actionCategorySales:"Talk to sales",actionCategoryMarketing:"Stay in touch",actionClose:"Close",actionAs:"as {identity}",bookingPickTime:"What time works best?",bookingPickDay:"Pick a day",bookingPickTimeLabel:"Pick a time",bookingDuration:"{count}-minute demo",bookingCallbackDuration:"{count}-minute callback",bookingTimezone:"Times shown in {timezone}",bookingSchedulerFallback:"the scheduler",bookingCheckingAvailability:"Checking calendar availability…",bookingNoSlots:"No available times were found in this booking window.",bookingAvailabilityUnavailable:"Calendar availability is temporarily unavailable. Please try again shortly.",bookingEarlierToday:"Earlier today",bookingCalendarBusy:"Busy on the calendar",bookingAlreadyBooked:"Already booked",bookingNotOffered:"Not offered by the calendar",bookingRequested:"Demo requested for {when}. The team will follow up.",bookingVerificationPending:"We received your request for {when}, but could not verify the calendar booking. The team will check it. Please do not book this time again.",bookingCallbackRequested:"Callback requested for {when}.",bookingCallbackConfirmed:"Your callback is scheduled for {when}.",bookingConfirmed:"Your demo is booked for {when}.",bookingSlotTaken:"That time was just taken — please pick another.",bookingViaProvider:"Pick a time that works for you on {provider}.",bookingOpenScheduler:"Open the scheduler",bookingLinkOpened:"Opening the scheduler — pick a time that suits you. 📅",bookingScheduled:"Your demo is booked. Your booking details are saved in this chat.",bookingBackToChat:"Back to chat",bookingOpenNewTab:"Open in new tab",bookingCloseScheduler:"Close scheduler",bookingLoadingScheduler:"Loading scheduler…",bookingMeetingLink:"Meeting link",bookingManageLink:"Manage booking",bookingCheckingDetails:"Getting your meeting link…",bookingDetailsUnavailable:"We could not verify the booking details yet. Try checking again here; please do not book the same time twice.",bookingUnverifiedLink:"View unverified calendar record",bookingRetryDetails:"Retry",previewReply:"👋 This is a preview — replies here are samples. Publish the widget on your site to chat with the live AI.",previewActionNote:"Preview — nothing was actually sent. This works for real once you publish.",previewBanner:"Preview — sample replies, no AI"},qe=(e,t)=>e.replace(/\{(\w+)\}/g,(n,a)=>t[a]??""),Nn=(e,t,n)=>!t||e.includes(t)?e:`${e} ${qe(n.caseReference,{reference:t})}`,Vl=e=>e?{...hr,...e}:hr,to=Ha(hr),jl=to.Provider,no=Ha(void 0),Hl=no.Provider,mr=()=>Ga(no),Wl=new Set(["ar","he","iw","fa","ur","ps","sd","ug","yi","dv","ckb"]),Gl=(e,t)=>{if(t==="ltr"||t==="rtl")return t;const n=(e??"").trim().toLowerCase().split(/[-_]/)[0]??"";return Wl.has(n)?"rtl":"ltr"},ct=()=>Ga(to),nn=[["AF","Afghanistan","93"],["AL","Albania","355"],["DZ","Algeria","213"],["AS","American Samoa","1684"],["AD","Andorra","376"],["AO","Angola","244"],["AI","Anguilla","1264"],["AG","Antigua and Barbuda","1268"],["AR","Argentina","54"],["AM","Armenia","374"],["AW","Aruba","297"],["AU","Australia","61"],["AT","Austria","43"],["AZ","Azerbaijan","994"],["BS","Bahamas","1242"],["BH","Bahrain","973"],["BD","Bangladesh","880"],["BB","Barbados","1246"],["BY","Belarus","375"],["BE","Belgium","32"],["BZ","Belize","501"],["BJ","Benin","229"],["BM","Bermuda","1441"],["BT","Bhutan","975"],["BO","Bolivia","591"],["BA","Bosnia and Herzegovina","387"],["BW","Botswana","267"],["BR","Brazil","55"],["BN","Brunei","673"],["BG","Bulgaria","359"],["BF","Burkina Faso","226"],["BI","Burundi","257"],["CV","Cabo Verde","238"],["KH","Cambodia","855"],["CM","Cameroon","237"],["CA","Canada","1"],["KY","Cayman Islands","1345"],["CF","Central African Republic","236"],["TD","Chad","235"],["CL","Chile","56"],["CN","China","86"],["CO","Colombia","57"],["KM","Comoros","269"],["CG","Congo","242"],["CD","Congo, Democratic Republic","243"],["CK","Cook Islands","682"],["CR","Costa Rica","506"],["CI","Cote d'Ivoire","225"],["HR","Croatia","385"],["CU","Cuba","53"],["CW","Curacao","599"],["CY","Cyprus","357"],["CZ","Czechia","420"],["DK","Denmark","45"],["DJ","Djibouti","253"],["DM","Dominica","1767"],["DO","Dominican Republic","1809"],["EC","Ecuador","593"],["EG","Egypt","20"],["SV","El Salvador","503"],["GQ","Equatorial Guinea","240"],["ER","Eritrea","291"],["EE","Estonia","372"],["SZ","Eswatini","268"],["ET","Ethiopia","251"],["FO","Faroe Islands","298"],["FJ","Fiji","679"],["FI","Finland","358"],["FR","France","33"],["GF","French Guiana","594"],["PF","French Polynesia","689"],["GA","Gabon","241"],["GM","Gambia","220"],["GE","Georgia","995"],["DE","Germany","49"],["GH","Ghana","233"],["GI","Gibraltar","350"],["GR","Greece","30"],["GL","Greenland","299"],["GD","Grenada","1473"],["GP","Guadeloupe","590"],["GU","Guam","1671"],["GT","Guatemala","502"],["GG","Guernsey","44"],["GN","Guinea","224"],["GW","Guinea-Bissau","245"],["GY","Guyana","592"],["HT","Haiti","509"],["HN","Honduras","504"],["HK","Hong Kong","852"],["HU","Hungary","36"],["IS","Iceland","354"],["IN","India","91"],["ID","Indonesia","62"],["IR","Iran","98"],["IQ","Iraq","964"],["IE","Ireland","353"],["IM","Isle of Man","44"],["IL","Israel","972"],["IT","Italy","39"],["JM","Jamaica","1876"],["JP","Japan","81"],["JE","Jersey","44"],["JO","Jordan","962"],["KZ","Kazakhstan","7"],["KE","Kenya","254"],["KI","Kiribati","686"],["XK","Kosovo","383"],["KW","Kuwait","965"],["KG","Kyrgyzstan","996"],["LA","Laos","856"],["LV","Latvia","371"],["LB","Lebanon","961"],["LS","Lesotho","266"],["LR","Liberia","231"],["LY","Libya","218"],["LI","Liechtenstein","423"],["LT","Lithuania","370"],["LU","Luxembourg","352"],["MO","Macao","853"],["MG","Madagascar","261"],["MW","Malawi","265"],["MY","Malaysia","60"],["MV","Maldives","960"],["ML","Mali","223"],["MT","Malta","356"],["MH","Marshall Islands","692"],["MQ","Martinique","596"],["MR","Mauritania","222"],["MU","Mauritius","230"],["MX","Mexico","52"],["FM","Micronesia","691"],["MD","Moldova","373"],["MC","Monaco","377"],["MN","Mongolia","976"],["ME","Montenegro","382"],["MS","Montserrat","1664"],["MA","Morocco","212"],["MZ","Mozambique","258"],["MM","Myanmar","95"],["NA","Namibia","264"],["NR","Nauru","674"],["NP","Nepal","977"],["NL","Netherlands","31"],["NC","New Caledonia","687"],["NZ","New Zealand","64"],["NI","Nicaragua","505"],["NE","Niger","227"],["NG","Nigeria","234"],["NU","Niue","683"],["KP","North Korea","850"],["MK","North Macedonia","389"],["MP","Northern Mariana Islands","1670"],["NO","Norway","47"],["OM","Oman","968"],["PK","Pakistan","92"],["PW","Palau","680"],["PS","Palestine","970"],["PA","Panama","507"],["PG","Papua New Guinea","675"],["PY","Paraguay","595"],["PE","Peru","51"],["PH","Philippines","63"],["PL","Poland","48"],["PT","Portugal","351"],["PR","Puerto Rico","1787"],["QA","Qatar","974"],["RE","Reunion","262"],["RO","Romania","40"],["RU","Russia","7"],["RW","Rwanda","250"],["KN","Saint Kitts and Nevis","1869"],["LC","Saint Lucia","1758"],["VC","Saint Vincent and the Grenadines","1784"],["WS","Samoa","685"],["SM","San Marino","378"],["ST","Sao Tome and Principe","239"],["SA","Saudi Arabia","966"],["SN","Senegal","221"],["RS","Serbia","381"],["SC","Seychelles","248"],["SL","Sierra Leone","232"],["SG","Singapore","65"],["SK","Slovakia","421"],["SI","Slovenia","386"],["SB","Solomon Islands","677"],["SO","Somalia","252"],["ZA","South Africa","27"],["KR","South Korea","82"],["SS","South Sudan","211"],["ES","Spain","34"],["LK","Sri Lanka","94"],["SD","Sudan","249"],["SR","Suriname","597"],["SE","Sweden","46"],["CH","Switzerland","41"],["SY","Syria","963"],["TW","Taiwan","886"],["TJ","Tajikistan","992"],["TZ","Tanzania","255"],["TH","Thailand","66"],["TL","Timor-Leste","670"],["TG","Togo","228"],["TO","Tonga","676"],["TT","Trinidad and Tobago","1868"],["TN","Tunisia","216"],["TR","Turkey","90"],["TM","Turkmenistan","993"],["TC","Turks and Caicos Islands","1649"],["TV","Tuvalu","688"],["UG","Uganda","256"],["UA","Ukraine","380"],["AE","United Arab Emirates","971"],["GB","United Kingdom","44"],["US","United States","1"],["UY","Uruguay","598"],["UZ","Uzbekistan","998"],["VU","Vanuatu","678"],["VA","Vatican City","39"],["VE","Venezuela","58"],["VN","Vietnam","84"],["VG","Virgin Islands, British","1284"],["VI","Virgin Islands, U.S.","1340"],["YE","Yemen","967"],["ZM","Zambia","260"],["ZW","Zimbabwe","263"]].map(([e,t,n])=>({iso:e,name:t,dial:n})),ao=e=>[...e.toUpperCase()].map(t=>String.fromCodePoint(127397+t.charCodeAt(0))).join(""),Kl=()=>{let e="";try{if(Intl.DateTimeFormat().resolvedOptions().timeZone==="Africa/Lagos"&&(e="NG"),!e){const t=navigator.languages?.[0]||navigator.language;e=new Intl.Locale(t).region||""}}catch{e=""}return nn.find(t=>t.iso===e)??nn.find(t=>t.iso==="US")},Yl=e=>{const t=Kl(),n=e?.trim()??"";if(!n.startsWith("+"))return{country:t,national:n.replace(/\D/g,"")};const a=n.replace(/\D/g,""),i=[...nn].sort((o,s)=>s.dial.length-o.dial.length).find(o=>a.startsWith(o.dial))??t;return{country:i,national:a.slice(i.dial.length)}},ro=(e,t)=>{const n=t.replace(/\D/g,"").replace(/^0+/,"");return n?`+${e.dial}${n}`:""},Zl=e=>{const t=e.replace(/\D/g,"");return e.startsWith("+")&&t.length>=8&&t.length<=15},$e=(e,t)=>r("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",...t,children:e}),Jl=e=>r("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",...e,children:r("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M5 3.25h14A3.75 3.75 0 0 1 22.75 7v6A3.75 3.75 0 0 1 19 16.75h-7.19l-4.26 3.84A.75.75 0 0 1 6.25 20v-3.32A3.75 3.75 0 0 1 2.25 13V7A3.75 3.75 0 0 1 6 3.25Zm3 7.75a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Zm4 0a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Zm4 0a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Z"})}),pn=e=>$e(r("path",{d:"m6 9 6 6 6-6"}),e),Xl=e=>$e(r(se,{children:[r("path",{d:"m22 2-7 20-4-9-9-4Z"}),r("path",{d:"M22 2 11 13"})]}),e),Rn=e=>$e(r(se,{children:[r("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),r("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),r("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),e),Ql=e=>$e(r(se,{children:[r("path",{d:"M9 9v1a3 3 0 0 0 4.24 2.73"}),r("path",{d:"M15 5.5V5a3 3 0 0 0-5.94-.6"}),r("path",{d:"M19 10v2a7 7 0 0 1-9.9 6.36"}),r("path",{d:"M5 10v2a6.98 6.98 0 0 0 1.11 3.79"}),r("line",{x1:"12",y1:"19",x2:"12",y2:"22"}),r("line",{x1:"2",y1:"2",x2:"22",y2:"22"})]}),e),Ln=e=>$e(r(se,{children:[r("path",{d:"M15 3h6v6"}),r("path",{d:"M10 14 21 3"}),r("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]}),e),ed=e=>$e(r(se,{children:[r("rect",{x:"3",y:"4",width:"18",height:"18",rx:"2"}),r("line",{x1:"16",y1:"2",x2:"16",y2:"6"}),r("line",{x1:"8",y1:"2",x2:"8",y2:"6"}),r("line",{x1:"3",y1:"10",x2:"21",y2:"10"})]}),e),gr=e=>$e(r(se,{children:[r("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),r("path",{d:"m22 7-10 5L2 7"})]}),e),td=e=>$e(r("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z"}),e),io=e=>$e(r(se,{children:[r("path",{d:"M4 14v-2a8 8 0 0 1 16 0v2"}),r("path",{d:"M18 19h-2"}),r("rect",{x:"3",y:"13",width:"4",height:"6",rx:"2"}),r("rect",{x:"17",y:"13",width:"4",height:"6",rx:"2"})]}),e),nd=e=>$e(r(se,{children:[r("path",{d:"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4Z"}),r("path",{d:"M8 9h8M8 13h5"})]}),e),ad=e=>$e(r(se,{children:[r("path",{d:"M3 4h18M4 4v12h16V4M12 16v5M8 21h8"}),r("path",{d:"m8 12 2.5-2.5 2 2L16 8"})]}),e),rd=e=>$e(r(se,{children:[r("path",{d:"M15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6"}),r("path",{d:"M3 9h12M7 2v4M12 2v4"}),r("circle",{cx:"17",cy:"17",r:"4"}),r("path",{d:"M17 15v2l1.5 1"})]}),e),id=e=>$e(r(se,{children:[r("path",{d:"M4 4h16v16H5a3 3 0 0 1-3-3V6"}),r("path",{d:"M8 8h8M8 12h8M8 16h5"})]}),e),od=e=>$e(r(se,{children:[r("circle",{cx:"12",cy:"12",r:"9"}),r("path",{d:"M8.5 14.5a4 4 0 0 0 7 0"}),r("line",{x1:"9",y1:"9.5",x2:"9.01",y2:"9.5"}),r("line",{x1:"15",y1:"9.5",x2:"15.01",y2:"9.5"})]}),e),Dn=e=>$e(r(se,{children:[r("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),e),sd=e=>$e(r(se,{children:[r("path",{d:"M11 5 6 9H2v6h4l5 4z"}),r("path",{d:"M15.5 8.5a5 5 0 0 1 0 7"}),r("path",{d:"M19 5a9 9 0 0 1 0 14"})]}),e),cd=e=>$e(r(se,{children:[r("path",{d:"M11 5 6 9H2v6h4l5 4z"}),r("line",{x1:"22",y1:"9",x2:"16",y2:"15"}),r("line",{x1:"16",y1:"9",x2:"22",y2:"15"})]}),e),fn=e=>$e(r("path",{d:"M20 6 9 17l-5-5"}),e),ld=e=>$e(r(se,{children:[r("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),r("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),e),dd=e=>$e(r(se,{children:[r("path",{d:"M1 4v6h6"}),r("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"})]}),e),ud=e=>$e(r("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"}),e),va=e=>$e(r("path",{d:"M21.44 11.05 12.25 20.24a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"}),e),br=e=>$e(r(se,{children:[r("path",{d:"M18.36 6.64a9 9 0 1 1-12.73 0"}),r("line",{x1:"12",y1:"2",x2:"12",y2:"12"})]}),e),pd=e=>$e(r(se,{children:[r("circle",{cx:"12",cy:"12",r:"9"}),r("path",{d:"M12 7v5l3 2"})]}),e),oo=e=>$e(r(se,{children:[r("path",{d:"M7 10v12"}),r("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),e),so=e=>$e(r(se,{children:[r("path",{d:"M17 14V2"}),r("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),e),fd=e=>$e(r(se,{children:[r("path",{d:"M15 3h6v6"}),r("path",{d:"M9 21H3v-6"}),r("path",{d:"M21 3l-7 7"}),r("path",{d:"M3 21l7-7"})]}),e),hd=e=>$e(r(se,{children:[r("path",{d:"M9 3v6H3"}),r("path",{d:"M15 21v-6h6"}),r("path",{d:"M9 9 2 2"}),r("path",{d:"M15 15l7 7"})]}),e),md=e=>$e(r(se,{children:[r("rect",{x:"3",y:"4",width:"18",height:"14",rx:"2"}),r("rect",{x:"11",y:"11",width:"8",height:"6",rx:"1",fill:"currentColor",stroke:"none"})]}),e),gd=e=>$e(r(se,{children:[r("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2"}),r("path",{d:"M12 15V9"}),r("path",{d:"m8.5 12.5 3.5-3.5 3.5 3.5"})]}),e),bd=e=>$e(r(se,{children:[r("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),r("path",{d:"m19 12-7 7-7-7"})]}),e),co=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\(https?:\/\/[^\s)]+\))|(\[[^\]]+\]\([^\s)]+\))|(https?:\/\/[^\s)]+)/g,vd=e=>e.replace(/([^\n])\s+((?:[-*•]|\d+\.)\s+)(?=(?:\*\*[^*\n]{1,80}\*\*|[A-Z][A-Za-z0-9/& -]{1,50}:))/g,`$1
164
+ $2`),hn=e=>{const t=[];let n=0,a=0,i;for(co.lastIndex=0;(i=co.exec(e))!==null;){i.index>n&&t.push(e.slice(n,i.index));const o=i[0];if(o.startsWith("`"))t.push(r("code",{class:"cf-md-code",children:o.slice(1,-1)},a++));else if(o.startsWith("**"))t.push(r("strong",{children:o.slice(2,-2)},a++));else if(o.startsWith("[")&&!/\]\(https?:\/\//.test(o))t.push(/^\[([^\]]+)\]/.exec(o)?.[1]??o);else if(o.startsWith("[")){const s=/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/.exec(o),c=s?s[1]:o,d=s?s[2]:"#";t.push(r("a",{href:d,target:"_blank",rel:"noopener noreferrer nofollow",children:c},a++))}else t.push(r("a",{href:o,target:"_blank",rel:"noopener noreferrer nofollow",children:o},a++));n=i.index+o.length}return n<e.length&&t.push(e.slice(n)),t},xd=/^(```|#{1,6}\s|\s*[-*•]\s|\s*\d+\.\s)/,yd=(e,t,n)=>{const a=`cf-md-h cf-md-h--${Math.min(e,6)}`;return e<=2?r("h3",{class:a,children:t},n):e===3?r("h4",{class:a,children:t},n):r("h5",{class:a,children:t},n)},_d=e=>{const t=vd(e.replace(/\r\n/g,`
165
165
  `)).split(`
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,`
166
+ `),n=[];let a=0,i=0;for(;i<t.length;){const o=t[i];if(o.trim().startsWith("```")){const u=[];for(i++;i<t.length&&!t[i].trim().startsWith("```");)u.push(t[i]),i++;i++,n.push(r("pre",{class:"cf-md-pre",children:r("code",{children:u.join(`
167
+ `)})},a++));continue}if(o.trim()===""){i++;continue}const s=/^(#{1,6})\s+(.*)$/.exec(o);if(s){n.push(yd(s[1].length,hn(s[2]),a++)),i++;continue}if(/^\s*[-*•]\s+/.test(o)){const u=[];for(;i<t.length&&/^\s*[-*•]\s+/.test(t[i]);)u.push(r("li",{children:hn(t[i].replace(/^\s*[-*•]\s+/,""))},u.length)),i++;n.push(r("ul",{class:"cf-md-list",children:u},a++));continue}if(/^\s*\d+\.\s+/.test(o)){const u=[];for(;i<t.length&&/^\s*\d+\.\s+/.test(t[i]);)u.push(r("li",{children:hn(t[i].replace(/^\s*\d+\.\s+/,""))},u.length)),i++;n.push(r("ol",{class:"cf-md-list",children:u},a++));continue}const c=[o];for(i++;i<t.length&&t[i].trim()!==""&&!xd.test(t[i]);)c.push(t[i]),i++;const d=c.join(" ");if(/:\s*$/.test(d)&&i<t.length&&/^(?:\s*[-*•]\s+|\s*\d+\.\s+)/.test(t[i])){const u=/^(.*[.!?])\s+([^.!?]{2,120}:)$/.exec(d);u&&n.push(r("p",{children:hn(u[1])},a++)),n.push(r("p",{class:"cf-md-list-intro",children:hn(u?.[2]??d)},a++))}else n.push(r("p",{children:hn(d)},a++))}return n},xa=e=>bl(e),lo=()=>{const e=R(null);return X(()=>{const t=requestAnimationFrame(()=>e.current?.scrollIntoView?.({block:"end"}));return()=>cancelAnimationFrame(t)},[]),e},wd=e=>e.trim().split(/\s+/).slice(0,2).map(t=>t[0]?.toUpperCase()??"").join("")||"🤖",Pn=e=>{const t=e?.avatarId?.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-");return t?` cf-avatar-preset--${t}`:""},kd={"support-guide":"SG","sales-host":"SH","calm-advisor":"CA","technical-guide":"TG","school-desk":"SD","front-office":"FO"},ya=e=>{const t=e?.avatarId?.trim().toLowerCase();return t&&kd[t]||(e?wd(e.agentName):"·")},uo=({persona:e,small:t,hideWhenMissing:n})=>{const a=t?"cf-msg__avatar":"cf-header__avatar",i=e?.agentAvatarUrl?.trim();return i?r("span",{class:a,children:r("img",{src:i,alt:""})}):n?null:r("span",{class:`${a}${Pn(e)}`,children:ya(e)})},Sd=()=>{const e=ct(),[t,n]=$(0),a=["Understanding your question","Checking approved information","Preparing your answer"];return X(()=>{const i=[window.setTimeout(()=>n(1),1800),window.setTimeout(()=>n(2),5e3)];return()=>i.forEach(o=>window.clearTimeout(o))},[]),r("div",{class:"cf-msg__bubble cf-typing","aria-label":e.assistantTyping,children:[r("span",{class:"cf-typing__label","aria-live":"polite",children:a[t]}),r("span",{class:"cf-typing__dot"}),r("span",{class:"cf-typing__dot"}),r("span",{class:"cf-typing__dot"})]})},$d=3,Td=({msg:e})=>{if(!e.sources||e.sources.length===0)return null;const t=new Set,n=[];for(const o of e.sources){const s=(o.url||o.title||"").toLowerCase();!s||t.has(s)||o.url&&e.content.includes(o.url)||(t.add(s),n.push(o))}if(n.length===0)return null;const a=n.slice(0,$d),i=n.length-a.length;return r("div",{class:"cf-sources",children:[a.map((o,s)=>o.url?r("a",{class:"cf-source",href:o.url,target:"_blank",rel:"noopener noreferrer nofollow",title:o.title||o.url,children:[r(Ln,{}),r("span",{children:o.title||o.url})]},s):r("span",{class:"cf-source",title:o.title,children:[r(Ln,{}),r("span",{children:o.title})]},s)),i>0&&r("span",{class:"cf-source cf-source--more",children:["+",i," more"]})]})},Cd=({replies:e,onPick:t})=>e&&e.length>0?r("div",{class:"cf-chips",children:e.map((n,a)=>r("button",{type:"button",class:"cf-chip",onClick:()=>t(n),children:n},a))}):null,Ad=({persona:e,starters:t,onPick:n,onFocusComposer:a,speaking:i,voiceState:o="idle",replyPending:s=!1,pinned:c=!1,muted:d=!1,onToggleMute:l,onEndCall:u,onTalkNow:p,showTalkNow:m=!1,micLevel:f=0,theaterMode:_=!1,onToggleTheater:h,onMinimize:I,audioDevices:x=[],selectedAudioDeviceId:g="",onSelectAudioDevice:T,connectingOnly:V=!1})=>{if(!e)return null;const P=!!(e.allowVoiceInput&&e.talkbackMode&&e.talkbackMode!=="text");if(!(P||e.widgetModule==="assistant"))return null;const Z=e.agentAvatarUrl?.trim()||"",Y=e.assistantMediaUrl?.trim()||Z,z=e.assistantMediaKind==="video"&&!!Y,te=t.slice(0,3),U=o!=="idle",B=o!=="idle"?"End voice chat":`Speak with ${e.agentName}`,A=c&&P&&!U&&!i,N=o==="connecting"||o==="processing"||U&&s,y=["cf-assistant-card__stage","cf-assistant-card__stage--local",U?"is-live":"",N?"is-thinking":"",mn(o)&&!d?"is-listening":"",i||o==="speaking"?"is-speaking":"",d?"is-muted":""].filter(Boolean).join(" "),D=mn(o)&&!d?{"--cf-listen":String(Math.max(.18,Math.min(1,f*8)))}:void 0,S=N&&r("span",{class:"cf-call-ripple","aria-hidden":"true",children:[r("span",{}),r("span",{}),r("span",{})]});if(V)return r("div",{class:"cf-assistant-card cf-assistant-card--connecting","aria-live":"polite",children:[r("div",{class:"cf-assistant-card__connecting-avatar",children:[Z?r("img",{src:Z,alt:""}):r("span",{class:`cf-assistant-card__connecting-face${Pn(e)}`,children:ya(e)}),S]}),r("div",{class:"cf-assistant-card__connecting-copy",children:[r("span",{class:"cf-assistant-card__connecting-eyebrow",children:e.agentName}),r("strong",{children:"Connecting with the AI…"})]})]});const O=U&&u&&r(au,{voiceState:o,muted:d,onToggleMute:l??(()=>{}),onEndCall:u,onTalkNow:p??(()=>{}),showTalkNow:m,micLevel:f,theaterMode:_,onToggleTheater:h??(()=>{}),onMinimize:I??(()=>{}),audioDevices:x,selectedAudioDeviceId:g,onSelectAudioDevice:T??(()=>{})});return A?r("div",{class:"cf-assistant-card cf-assistant-card--pinned cf-assistant-card--compact",children:r("button",{type:"button",class:"cf-assistant-card__compact-speak",onClick:a,children:[Z?r("span",{class:"cf-assistant-card__compact-avatar",children:r("img",{src:Z,alt:""})}):null,r("span",{class:"cf-assistant-card__compact-mic","aria-hidden":"true",children:r(Rn,{})}),r("span",{class:"cf-assistant-card__compact-label",children:B})]})}):r("div",{class:`cf-assistant-card ${c?"cf-assistant-card--pinned":""} ${i?"is-speaking":""}`,children:[(Y||P)&&r("div",{class:y,style:D,children:[r("div",{class:`cf-assistant-card__media ${Y?"cf-assistant-card__media--uploaded":"cf-assistant-card__media--generated"}${Pn(e)}`,children:[z?r("video",{src:Y,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):Y?r("img",{src:Y,alt:""}):r("div",{class:`cf-assistant-card__avatar-stage${Pn(e)}`,children:r("div",{class:"cf-assistant-card__face",children:[r("span",{class:"cf-assistant-card__initials",children:ya(e)}),r("span",{class:"cf-assistant-card__eye cf-assistant-card__eye--left"}),r("span",{class:"cf-assistant-card__eye cf-assistant-card__eye--right"}),r("span",{class:"cf-assistant-card__mouth"})]})}),Y&&!z&&r("span",{class:"cf-assistant-card__mouth cf-assistant-card__mouth--overlay"}),r("span",{class:"cf-avatar-aura cf-avatar-aura--one","aria-hidden":"true"}),r("span",{class:"cf-avatar-aura cf-avatar-aura--two","aria-hidden":"true"}),r("span",{class:"cf-avatar-listen-ring","aria-hidden":"true"}),r("span",{class:"cf-avatar-wave","aria-hidden":"true",children:[r("span",{}),r("span",{}),r("span",{}),r("span",{})]})]}),S,U&&r("span",{class:"cf-call-status",role:"status","aria-live":"polite",children:xr(o)}),P&&(O||r("button",{type:"button",class:"cf-assistant-card__speak",onClick:a,children:[r(Rn,{}),B]}))]}),!c&&r(se,{children:[e.agentDescription?r("p",{class:"cf-assistant-card__copy",children:e.agentDescription}):r("p",{class:"cf-assistant-card__copy",children:e.greeting}),te.length>0&&r("div",{class:"cf-assistant-card__chips",children:te.map(ue=>r("button",{type:"button",class:"cf-assistant-card__chip",onClick:()=>n(ue),children:ue},ue))}),e.disclaimerText||e.assistantPrivacyUrl?r("p",{class:"cf-assistant-card__privacy",children:[e.disclaimerText||"This chat may be recorded for quality and support.",e.assistantPrivacyUrl?r(se,{children:[" ",r("a",{href:e.assistantPrivacyUrl,target:"_blank",rel:"noopener noreferrer nofollow",children:"Privacy Policy"})]}):null]}):null]})]})},Md={calendar:ed,"calendar-clock":rd,headset:io,mail:gr,message:nd,newsletter:id,phone:td,presentation:ad,lifebuoy:io},Id=e=>Md[e]??gr,Ed=e=>{if(e.id==="public_contact_support")return"contact-support";switch(e.endpoint){case"book-demo":return"book-demo";case"request-callback":return"request-callback";case"schedule-callback":return"schedule-callback";case"subscribe-newsletter":return"subscribe-newsletter";case"contact":return"contact";default:return"inquiry"}},zd={public_contact_support:{label:"Contact support",description:"Send your request to the support team.",category:"support",icon:"headset",endpoint:"inquiry"},public_submit_inquiry:{label:"Leave a message",description:"Send your question and contact details.",category:"support",icon:"message",endpoint:"inquiry"},public_book_demo:{label:"Book a demo",description:"Request a demo from the team.",category:"sales",icon:"presentation",endpoint:"book-demo"},public_request_callback:{label:"Request a callback",description:"Ask the next available sales teammate to call you.",category:"sales",icon:"phone",endpoint:"request-callback"},public_schedule_callback:{label:"Schedule a callback",description:"Choose an available date and time for a call.",category:"sales",icon:"calendar-clock",endpoint:"schedule-callback"},public_subscribe_newsletter:{label:"Subscribe",description:"Get product updates.",category:"marketing",icon:"newsletter",endpoint:"subscribe-newsletter"}},Nd=(e,t,n={})=>Array.isArray(e)?e.filter(a=>a.readiness!=="unavailable").map(a=>po(a,n[a.id])):(t??[]).flatMap(a=>{const i=zd[a];if(!i)return[];const o=Ed({...i,id:a}),s=ba[o];return[{...i,id:a,presentation:o==="book-demo"||o==="schedule-callback"?"booking":"form",formTitle:s.title,submitLabel:s.submit,fields:s.fields,delivery:"",prompt:"",shortLabel:i.label.toLowerCase(),enabled:!0,readiness:"available",legacyFallback:!0}]}).map(a=>po(a,n[a.id])),po=(e,t)=>{if(!t)return e;const n=t.fields??{};return{...e,...Object.fromEntries(Object.entries(t).filter(([a,i])=>a!=="fields"&&i!==void 0)),fields:e.fields.map(a=>({...a,...n[a.key]}))}},Rd=(e,t)=>{const n=e.map(a=>a.label);return n.length===0?t.actionGetInTouch:n.length<=3?n.join(", "):`${n.slice(0,2).join(", ")} ${qe(t.actionMore,{count:String(n.length-2)})}`},fo=({label:e,required:t,value:n,onInput:a})=>{const i=Be(()=>Yl(n),[]),[o,s]=$(i.country.iso),[c,d]=$(i.national),[l,u]=$(!1),[p,m]=$(""),f=R(null),_=nn.find(x=>x.iso===o)??i.country,h=Be(()=>{const x=p.trim().toLowerCase().replace(/^\+/,"");return x?nn.filter(g=>g.name.toLowerCase().includes(x)||g.iso.toLowerCase().includes(x)||g.dial.includes(x)):nn},[p]);X(()=>{if(!l)return;const x=T=>{f.current&&!T.composedPath().includes(f.current)&&u(!1)},g=T=>{T.key==="Escape"&&u(!1)};return document.addEventListener("pointerdown",x),document.addEventListener("keydown",g),()=>{document.removeEventListener("pointerdown",x),document.removeEventListener("keydown",g)}},[l]);const I=x=>{const g=nn.find(T=>T.iso===x)??_;s(g.iso),u(!1),m(""),a(ro(g,c))};return r("div",{class:"cf-phone",role:"group","aria-label":`${e}${t?" *":""}`,ref:f,children:[r("span",{class:"cf-phone__label",children:[e,t?" *":""]}),r("div",{class:"cf-phone__control",children:[r("button",{type:"button",class:"cf-phone__country","aria-label":`${_.name}, +${_.dial}. Choose country and calling code`,"aria-haspopup":"listbox","aria-expanded":l,onClick:()=>u(x=>!x),children:[r("span",{"aria-hidden":"true",children:ao(_.iso)}),r("span",{class:"cf-phone__country-code",children:["+",_.dial]}),r(pn,{})]}),r("input",{class:"cf-phone__input",type:"tel",inputMode:"numeric",pattern:"[0-9]*",autoComplete:"tel-national",maxLength:15,placeholder:"8028509941",value:c,"aria-label":e,onInput:x=>{const g=x.target,T=g.value.replace(/\D/g,"");g.value=T,d(T),a(ro(_,T))}})]}),l?r("div",{class:"cf-phone__menu",children:[r("input",{class:"cf-phone__search",type:"search",placeholder:"Search country or code","aria-label":"Search countries",value:p,autoFocus:!0,onInput:x=>m(x.target.value)}),r("div",{class:"cf-phone__options",role:"listbox","aria-label":"Countries",children:h.length>0?h.map(x=>r("button",{type:"button",class:`cf-phone__option ${x.iso===_.iso?"is-selected":""}`,role:"option","aria-selected":x.iso===_.iso,onClick:()=>I(x.iso),children:[r("span",{"aria-hidden":"true",children:ao(x.iso)}),r("span",{class:"cf-phone__option-name",children:x.name}),r("span",{class:"cf-phone__option-code",children:["+",x.dial]})]},x.iso)):r("div",{class:"cf-phone__empty",children:"No countries found"})})]}):null]})},Ld=({field:e,value:t,onInput:n})=>{if(e.kind==="tel")return r(fo,{label:e.label,required:e.required,value:t,onInput:n});const a=e.placeholder??e.label,i={class:"cf-form__input",placeholder:e.required?`${a} *`:a,value:t,"aria-label":e.label,onInput:o=>n(o.target.value)};return e.kind==="textarea"?r("textarea",{rows:2,...i}):r("input",{type:e.kind,...i})},Dd=({spec:e,visitor:t,onSubmit:n,onCancel:a})=>{const i=ct(),o=lo(),[s,c]=$(()=>{const x={};for(const g of e.fields)g.identity&&t[g.identity]&&(x[g.key]=t[g.identity]);return x}),[d,l]=$("idle"),[u,p]=$(""),m=x=>!!(x.identity&&t[x.identity]?.trim()),f=e.fields.filter(x=>!m(x)),_=f.every(x=>!x.required||(s[x.key]?.trim()??"")!==""),h=t.email||t.name||"",I=async()=>{if(!_||d==="submitting")return;l("submitting");const x={},g={};for(const T of e.fields){const V=s[T.key]?.trim();V&&(x[T.key]=V,T.identity&&(g[T.identity]=V))}try{const T=await n(x,g);p(Nn(T.note||i.formThanks,T.caseReference,i)),l("done")}catch{l("error")}};return d==="done"?r("div",{class:"cf-form cf-form--done",children:[r(fn,{}),r("span",{children:u})]}):r("div",{class:"cf-form",ref:o,children:[f.length===0&&h&&r("div",{class:"cf-form__as",children:qe(i.actionAs,{identity:h})}),f.map(x=>r(Ld,{field:x,value:s[x.key]??"",onInput:g=>c(T=>({...T,[x.key]:g}))},x.key)),d==="error"&&r("div",{class:"cf-form__err",children:i.formError}),r("div",{class:"cf-form__actions",children:[a&&r("button",{type:"button",class:"cf-form__cancel",onClick:a,children:i.cancel}),r("button",{type:"button",class:"cf-form__submit",disabled:!_||d==="submitting",onClick:I,children:d==="submitting"?i.sending:e.submit})]})]})},ho=e=>String(e).padStart(2,"0"),Pd=()=>{const e=[];for(let t=9;t<=17;t++)e.push(`${ho(t)}:00`),e.push(`${ho(t)}:30`);return e},Od=e=>{const t=new Date;return t.setHours(0,0,0,0),Array.from({length:e},(n,a)=>{const i=new Date(t);return i.setDate(t.getDate()+a),i})},Fd=(e,t)=>{const[n,a]=t.split(":").map(Number),i=new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,a??0);try{return new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",timeZoneName:"short"}).format(i)}catch{return`${e.toDateString()} ${t}`}},Lt=(e,t)=>{const[n,a]=t.split(":").map(Number);return new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,a??0)},Ud=(e,t)=>{const n=Lt(e,t);try{return new Intl.DateTimeFormat(void 0,{hour:"numeric",minute:"2-digit"}).format(n)}catch{return t}},_a=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{return""}},mo=(e,t)=>{try{const n=new URL(e);return n.searchParams.set("embed_type","Inline"),globalThis.location?.hostname&&n.searchParams.set("embed_domain",globalThis.location.hostname),t.name?.trim()&&n.searchParams.set("name",t.name.trim()),t.email?.trim()&&n.searchParams.set("email",t.email.trim()),n.toString()}catch{return e}},Bd=(e,t)=>{if(!t?.contentWindow||e.source!==t.contentWindow)return!1;try{const n=new URL(e.origin).hostname;if(n!=="calendly.com"&&!n.endsWith(".calendly.com"))return!1}catch{return!1}return!!(e.data&&typeof e.data=="object"&&typeof e.data.event=="string")},qd=({actionId:e,fields:t=ba["book-demo"].fields,visitor:n,onSubmit:a,onCancel:i,onDemoSlots:o,onConfirmHostedBooking:s,scheduler:c,title:d,submitLabel:l})=>{const u=e==="public_schedule_callback",p=u?ba["schedule-callback"]:ba["book-demo"],m=d?.trim()||p.title,f=ct(),_=lo(),h=!!(!u&&c?.connected&&c.provider==="calendly"),I=h?f.bookingOpenScheduler:l?.trim()||p.submit,x=!!(c?.connected&&c.mode==="event"&&!h&&(c.availability===void 0||c.availability.calendarIds.length>0)),g=Math.min(60,Math.max(1,c?.availability?.bookingWindowDays??14)),T=Be(()=>Od(g),[g]),[V,P]=$(null),[ee,Z]=$(x?"loading":"request_only"),[Y,z]=$(c?.availability?.slotDurationMinutes??30),[te,U]=$(_a()||c?.availability?.timezone||""),B=Be(()=>x?ee!=="available"||V===null?[]:[...new Set([...V].map(Q=>{const he=new Date(Q);return`${String(he.getHours()).padStart(2,"0")}:${String(he.getMinutes()).padStart(2,"0")}`}))].sort():Pd(),[V,ee,x]),A=Be(()=>{const Q=Date.now();for(let he=0;he<T.length;he++)if(B.some(we=>Lt(T[he],we).getTime()>Q))return he;return 0},[T,B]),[N,y]=$(A),[D,S]=$(null),[O,ue]=$(n.name??""),[oe,Fe]=$(n.email??""),[_e,Te]=$(n.phone??""),[Le,Ie]=$(""),[Ce,ve]=$("idle"),[Xe,ge]=$(""),[ie,He]=$(!1),[We,k]=$(""),[K,j]=$("scheduler"),[G,ne]=$(null),[ye,Se]=$("idle"),[et,Ye]=$(""),[tt,at]=$(""),[M,pe]=$(""),de=R(null),fe=async(Q,he,we)=>{Se("loading");try{const ce=await s?.(Q,he,we);if(!ce?.confirmed)throw new Error("booking confirmation unavailable");const be=ce?.meetingUrl||ce?.eventLink||"",wt=ce?.rescheduleUrl||ce?.cancelUrl||"";k(be||wt),j(be?"meeting":"manage"),Se("idle"),He(!1),ge(Nn(f.bookingScheduled,tt,f))}catch{Se("error"),He(!0),ge(f.bookingDetailsUnavailable)}};X(()=>{if(!et)return;const Q=he=>{if(!Bd(he,de.current)||he.data.event!=="calendly.event_scheduled")return;const we=he.data.payload,ce=we?.event?.uri?.trim()||"",be=we?.invitee?.uri?.trim()||"";M&&ce&&be?(ne({eventUri:ce,inviteeUri:be}),fe(M,ce,be),ge(f.bookingCheckingDetails)):(Se("error"),He(!0),ge(f.bookingDetailsUnavailable)),Ye(""),ve("done")};return window.addEventListener("message",Q),()=>window.removeEventListener("message",Q)},[s,tt,M,et,f]),X(()=>{if(!x||ee!=="available"||V===null)return;const Q=T.findIndex(he=>B.some(we=>V.has(Lt(he,we).getTime())));Q>=0&&y(Q)},[V,ee,T,x,B]);const Oe=!!(!u&&c?.connected&&(c.mode==="link"||c.provider==="calendly")),Ge=async()=>{if(Ce==="submitting"||Ce==="scheduling"||!n.name?.trim()&&!O.trim()||!n.email?.trim()&&!oe.trim())return;ve("submitting");const Q={};oe.trim()&&(Q.email=oe.trim()),O.trim()&&(Q.name=O.trim());try{const he=await a({...oe.trim()?{visitorEmail:oe.trim()}:{},...O.trim()?{visitorName:O.trim()}:{}},Q),we=he.booking?.schedulingLink||c?.bookingLink||"";if(!we){ve("error");return}k(we),j("scheduler"),at(he.caseReference||""),pe(he.inquiryId||""),Ye(mo(we,{name:O.trim()||n.name,email:oe.trim()||n.email})),ve("scheduling")}catch{ve("error")}},[ht,pt]=$(new Set),[yt,Dt]=$([]),[_t,Vn]=$(0),[an,rt]=$(!1);X(()=>{if(!o)return;let Q=!0;const he=new Date,we=new Date;return we.setDate(we.getDate()+g+1),o(he.toISOString(),we.toISOString()).then(ce=>{if(Q)if(pt(new Set(ce.taken.map(be=>Date.parse(be)).filter(be=>!Number.isNaN(be)))),Dt(ce.busy.map(be=>[Date.parse(be.start),Date.parse(be.end)]).filter(([be,wt])=>!Number.isNaN(be)&&!Number.isNaN(wt))),z(ce.slotDurationMinutes??30),U(_a()||ce.timezone||""),x){if(ce.status!=="available"||!Array.isArray(ce.available)){P(null),Z("unavailable");return}P(new Set(ce.available.map(be=>Date.parse(be)).filter(be=>!Number.isNaN(be)))),Z("available")}else Z(ce.status??"request_only")}).catch(()=>{!Q||!x||(P(null),Z("unavailable"))}),()=>{Q=!1}},[g,x,o,_t]);const Pt=!!n.email?.trim(),bn=!!n.name?.trim(),jt=!!n.phone?.trim(),mt=_e,Ht=!!D&&(!x||ee==="available")&&(bn||O.trim()!=="")&&(u?jt||Zl(mt):Pt||oe.trim()!==""),Ot=(u?n.phone||n.name:n.email||n.name)||"",gt=Q=>t.find(he=>he.key===Q),dt=gt("visitorName")?.label||p.fields.find(Q=>Q.key==="visitorName").label,Qe=gt("visitorEmail")?.label||f.handoffEmail,Ft=gt("visitorPhone"),it=gt("topic"),Ut=Q=>ht.has(Lt(T[N],Q).getTime()),Wt=Q=>Lt(T[N],Q).getTime()<=Date.now(),jn=Y*60*1e3,Hn=Q=>{const he=Lt(T[N],Q).getTime(),we=he+jn;return yt.some(([ce,be])=>he<be&&we>ce)},Wn=Q=>!x||V?.has(Lt(T[N],Q).getTime())===!0,Gn=async()=>{if(!Ht||Ce==="submitting"||!D)return;ve("submitting"),rt(!1);const Q=Lt(T[N],D),he=Fd(T[N],D),we={};O.trim()&&(we.name=O.trim()),u?mt&&(we.phone=mt):oe.trim()&&(we.email=oe.trim());try{const ce=await a(u?{bestTime:he,slotAt:Q.toISOString(),visitorTimezone:_a()||"UTC",...mt?{visitorPhone:mt}:{},...O.trim()?{visitorName:O.trim()}:{},...Le.trim()?{topic:Le.trim()}:{}}:{preferredAt:he,slotAt:Q.toISOString(),visitorTimezone:_a()||"UTC",...oe.trim()?{visitorEmail:oe.trim()}:{},...O.trim()?{visitorName:O.trim()}:{}},we);if(!u&&ce.booking?.mode==="link"&&ce.booking.schedulingLink?.trim()){const be=ce.booking.schedulingLink.trim();k(be),at(ce.caseReference||""),pe(ce.inquiryId||""),Ye(mo(be,{name:O.trim()||n.name,email:oe.trim()||n.email})),ve("scheduling");return}if(ce.booking?.confirmed)ge(Nn(ce.note||qe(u?f.bookingCallbackConfirmed:f.bookingConfirmed,{when:he}),ce.caseReference,f)),k(ce.booking.meetingUrl||ce.booking.rescheduleUrl||ce.booking.cancelUrl||ce.booking.eventLink||""),j(ce.booking.meetingUrl||ce.booking.eventLink?"meeting":"manage");else if(ce.booking?.verificationPending){He(!0);const be=ce.booking.eventLink||ce.booking.meetingUrl||"";/^https?:\/\//i.test(be)&&(k(be),j("unverified")),ge(Nn(ce.note||qe(f.bookingVerificationPending,{when:he}),ce.caseReference,f))}else ge(Nn(ce.note||qe(u?f.bookingCallbackRequested:f.bookingRequested,{when:he}),ce.caseReference,f));ve("done")}catch(ce){ce?.status===409?(pt(be=>new Set(be).add(Q.getTime())),S(null),rt(!0),Vn(be=>be+1),ve("idle")):ve("error")}},Tt=()=>{Ye(""),ve("idle"),i?.()};return Ce==="scheduling"&&et?r("div",{class:"cf-scheduler-overlay",role:"dialog","aria-modal":"true","aria-label":m,children:[r("header",{class:"cf-scheduler-overlay__head",children:[r("button",{type:"button",class:"cf-scheduler-overlay__back",onClick:Tt,children:f.bookingBackToChat}),r("strong",{children:m}),r("div",{class:"cf-scheduler-overlay__tools",children:[r("a",{href:We,target:"_blank",rel:"noopener noreferrer",children:[f.bookingOpenNewTab," ",r(Ln,{})]}),r("button",{type:"button","aria-label":f.bookingCloseScheduler,onClick:Tt,children:r(Dn,{})})]})]}),r("div",{class:"cf-scheduler-overlay__body",children:[r("div",{class:"cf-scheduler-overlay__loading",children:f.bookingLoadingScheduler}),r("iframe",{ref:de,class:"cf-scheduler-overlay__frame",src:et,title:m,allow:"camera; microphone; fullscreen; payment"})]})]}):Ce==="done"?r("div",{class:`cf-form cf-form--done${ie?" cf-form--pending":""}`,role:ie?"alert":"status",children:[!ie&&r(fn,{}),r("span",{children:Xe}),ye==="loading"&&r("span",{role:"status",children:f.bookingCheckingDetails}),ye==="error"&&r("div",{class:"cf-booking__receipt-error",role:"alert",children:[r("span",{children:f.bookingDetailsUnavailable}),G&&M&&s&&r("button",{type:"button",class:"cf-booking__back",onClick:()=>{fe(M,G.eventUri,G.inviteeUri)},children:f.bookingRetryDetails})]}),We&&r("a",{class:"cf-booking__link",href:We,target:"_blank",rel:"noopener noreferrer",children:[K==="meeting"?f.bookingMeetingLink:K==="manage"?f.bookingManageLink:K==="unverified"?f.bookingUnverifiedLink:f.bookingOpenScheduler," ",r(Ln,{}),r("span",{class:"cf-booking__url",children:We})]}),i&&r("button",{type:"button",class:"cf-booking__back",onClick:i,children:f.bookingBackToChat})]}):Oe?r("div",{class:"cf-form cf-booking",ref:_,children:[r("div",{class:"cf-booking__hint",children:qe(f.bookingViaProvider,{provider:c?.label??f.bookingSchedulerFallback})}),Pt?Ot?r("div",{class:"cf-form__as",children:qe(f.actionAs,{identity:Ot})}):null:r(se,{children:[!n.name?.trim()&&r("input",{class:"cf-form__input",type:"text",placeholder:`${dt} *`,value:O,"aria-label":dt,onInput:Q=>ue(Q.target.value)}),r("input",{class:"cf-form__input",type:"email",placeholder:`${Qe} *`,value:oe,"aria-label":Qe,onInput:Q=>Fe(Q.target.value)})]}),Ce==="error"&&r("div",{class:"cf-form__err",children:f.formError}),r("div",{class:"cf-form__actions",children:[i&&r("button",{type:"button",class:"cf-form__cancel",onClick:i,children:f.cancel}),r("button",{type:"button",class:"cf-form__submit",disabled:Ce==="submitting"||!n.name?.trim()&&O.trim()===""||!Pt&&oe.trim()==="",onClick:Ge,children:Ce==="submitting"?f.sending:f.bookingOpenScheduler})]})]}):r("div",{class:"cf-form cf-booking",ref:_,children:[r("div",{class:"cf-booking__hint",children:[f.bookingPickTime," ·"," ",r("span",{class:"cf-booking__dur",children:qe(u?f.bookingCallbackDuration:f.bookingDuration,{count:String(Y)})}),te?r("span",{class:"cf-booking__timezone",children:qe(f.bookingTimezone,{timezone:te})}):null]}),x&&ee==="loading"?r("div",{class:"cf-booking__state",role:"status",children:f.bookingCheckingAvailability}):null,x&&ee==="unavailable"?r("div",{class:"cf-form__err",role:"alert",children:f.bookingAvailabilityUnavailable}):null,x&&ee==="available"&&B.length===0?r("div",{class:"cf-booking__state",role:"status",children:f.bookingNoSlots}):null,B.length>0?r("div",{class:"cf-booking__dates",role:"tablist","aria-label":f.bookingPickDay,children:T.map((Q,he)=>r("button",{type:"button",role:"tab","aria-selected":he===N,disabled:x&&ee==="available"&&!B.some(we=>V?.has(Lt(Q,we).getTime())),class:`cf-booking__date ${he===N?"is-selected":""}`,onClick:()=>{y(he),S(null)},children:[r("span",{class:"cf-booking__dow",children:Q.toLocaleDateString(void 0,{weekday:"short"})}),r("span",{class:"cf-booking__dom",children:Q.getDate()})]},he))}):null,B.length>0?r("div",{class:"cf-booking__slots",role:"listbox","aria-label":f.bookingPickTimeLabel,children:B.map(Q=>{const he=Wt(Q),we=Hn(Q),ce=Ut(Q),be=Wn(Q),wt=ce||he||we||!be;return r("button",{type:"button",role:"option","aria-selected":D===Q,disabled:wt,title:he?f.bookingEarlierToday:we?f.bookingCalendarBusy:ce?f.bookingAlreadyBooked:be?void 0:f.bookingNotOffered,class:`cf-booking__slot ${D===Q?"is-selected":""} ${wt?"is-taken":""}`,onClick:()=>S(Q),children:Ud(T[N],Q)},Q)})}):null,an&&r("div",{class:"cf-form__err",children:f.bookingSlotTaken}),Ot?r("div",{class:"cf-form__as",children:qe(f.actionAs,{identity:Ot})}):null,!bn&&r("input",{class:"cf-form__input",type:"text",placeholder:`${dt} *`,value:O,"aria-label":dt,onInput:Q=>ue(Q.target.value)}),u&&!jt&&r(fo,{label:Ft?.label??"Phone number",required:!0,value:_e,onInput:Te}),u&&it?r("input",{class:"cf-form__input",type:"text",placeholder:it.placeholder||it.label,value:Le,"aria-label":it.label,onInput:Q=>Ie(Q.target.value)}):null,!u&&!Pt&&r(se,{children:r("input",{class:"cf-form__input",type:"email",placeholder:`${Qe} *`,value:oe,"aria-label":Qe,onInput:Q=>Fe(Q.target.value)})}),Ce==="error"&&r("div",{class:"cf-form__err",children:f.formError}),r("div",{class:"cf-form__actions",children:[i&&r("button",{type:"button",class:"cf-form__cancel",onClick:i,children:f.cancel}),r("button",{type:"button",class:"cf-form__submit",disabled:!Ht||Ce==="submitting",onClick:Gn,children:Ce==="submitting"?f.sending:I})]})]})},go=({actions:e,descriptors:t,visitor:n,onSubmitForm:a,onDemoSlots:i,onConfirmHostedBooking:o,scheduler:s,exclude:c=[],openAction:d,showTrigger:l=!0,translations:u={},onClose:p})=>{const m=ct(),[f,_]=$(null),[h,I]=$(!1),x=R(null),g=R(null),T=R(!1),V=R(null),P=R(void 0),ee=R(!1),Z=Be(()=>`cf-actions-${Math.random().toString(36).slice(2,9)}`,[]),Y=Be(()=>Nd(t,e,u).filter(N=>!c.includes(N.id)&&!c.includes(N.endpoint)),[t,e,c,u]);X(()=>{if(!d){P.current=void 0;return}P.current!==d&&Y.some(N=>N.id===d)&&(P.current=d,ee.current=!0,_(d),I(!0))},[d,Y]);const z=f?Y.find(N=>N.id===f):void 0,te=F(()=>{if(p){p();return}T.current=!0,V.current=x.current||g.current?.closest(".cf-panel")?.querySelector(".cf-footer-actions .cf-action-trigger, .cf-textarea")||null,ee.current=!1,_(null),I(!1)},[p]),U=F(()=>{ee.current?te():p?p():_(null)},[p,te]);Sn(()=>{h||!T.current||(T.current=!1,V.current?.focus(),V.current=null)},[h]);const B=R({drawerOpen:h,activeId:f});if(B.current={drawerOpen:h,activeId:f},X(()=>{const N=y=>{if(y.key!=="Escape")return;const{drawerOpen:D,activeId:S}=B.current;!D&&!S||(y.stopPropagation(),S?U():te())};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[U,te]),X(()=>{if(!h)return;const N=g.current;if(!N)return;N.querySelector("button, input, textarea, select")?.focus({preventScroll:!0});let y;const D=()=>{cancelAnimationFrame(y),y=requestAnimationFrame(()=>N.scrollIntoView?.({block:"nearest"}))};D();const S=N.closest(".cf-body")&&typeof ResizeObserver=="function"?new ResizeObserver(D):null;return S?.observe(N),()=>{cancelAnimationFrame(y),S?.disconnect()}},[h,f]),Y.length===0||!l&&!h)return null;const A=h?z?r("div",{ref:g,id:Z,class:"cf-action-drawer is-open",role:"dialog","aria-modal":"false","aria-label":z.formTitle||z.label,children:[r("div",{class:"cf-action-drawer__handle","aria-hidden":"true"}),r("div",{class:"cf-action-drawer__head",children:[r("div",{children:[r("strong",{children:z.formTitle||z.label}),z.legacyFallback?r("small",{class:"cf-action-test-mode",children:m.actionTestMode}):null]}),r("button",{type:"button",class:"cf-action-drawer__close","aria-label":m.actionClose,onClick:U,children:r(Dn,{})})]}),z.readiness==="degraded"&&z.readinessNote?r("p",{class:"cf-action-drawer__note cf-action-drawer__note--warn",role:"status",children:z.readinessNote}):null,z.presentation==="booking"||z.endpoint==="book-demo"||z.endpoint==="schedule-callback"?r(qd,{actionId:z.id,fields:z.fields,visitor:n,title:z.formTitle,submitLabel:z.submitLabel,onCancel:U,onSubmit:(N,y)=>a(z.id,N,y,z.endpoint),onDemoSlots:i,onConfirmHostedBooking:o,scheduler:s}):r(Dd,{spec:{title:z.formTitle||z.label,submit:z.submitLabel,fields:z.endpoint==="request-callback"?z.fields.filter(N=>N.key!=="bestTime"):z.fields},visitor:n,onCancel:U,onSubmit:(N,y)=>a(z.id,N,y,z.endpoint)})]}):r("div",{ref:g,id:Z,class:"cf-action-drawer cf-action-drawer--menu",role:"dialog","aria-modal":"false","aria-label":m.actionChoose,children:[r("div",{class:"cf-action-drawer__handle","aria-hidden":"true"}),r("div",{class:"cf-action-drawer__head",children:[r("div",{children:[r("span",{class:"cf-action-drawer__eyebrow",children:m.actionNeedHelp}),r("strong",{children:m.actionChoose})]}),r("button",{type:"button",class:"cf-action-drawer__close","aria-label":m.actionClose,onClick:te,children:r(Dn,{})})]}),r("div",{class:"cf-action-drawer__grid",children:Y.map(N=>{const y=Id(N.icon);return r("button",{type:"button",class:"cf-action-card",onClick:()=>{ee.current=!1,_(N.id)},children:[r("span",{class:`cf-action-card__icon cf-action-card__icon--${N.category}`,children:r(y,{})}),r("span",{class:"cf-action-card__copy",children:[r("strong",{children:N.label}),N.legacyFallback?r("small",{class:"cf-action-test-mode",children:m.actionTestMode}):null,r("small",{children:N.description}),N.readiness==="degraded"&&N.readinessNote?r("small",{class:"cf-action-card__warn",children:N.readinessNote}):null]}),r(pn,{})]},N.id)})}),r("p",{class:"cf-action-drawer__note",children:m.actionFooter})]}):null;return r("div",{class:"cf-action-shell",children:[l&&r("button",{ref:x,type:"button",class:"cf-action-trigger",hidden:h,"aria-expanded":h,"aria-controls":Z,onClick:()=>h?te():I(!0),children:[r("span",{class:"cf-action-trigger__icon",children:r(gr,{})}),r("span",{class:"cf-action-trigger__copy",children:[r("strong",{children:m.actionContactOptions}),r("small",{children:Rd(Y,m)})]}),r(pn,{})]}),A]})},Vd=({hasEmail:e,visitor:t,question:n,onSubmitForm:a})=>{const i=ct(),[o,s]=$(!1),[c,d]=$(!1),[l,u]=$(t.name??""),[p,m]=$(t.email??"");if(e)return r("div",{class:"cf-handoff cf-handoff--done",children:[r(fn,{}),r("span",{children:"We’ve alerted the team. If someone is available, they can continue here."})]});if(o){const _=t.email||p;return r("div",{class:"cf-handoff cf-handoff--done",children:[r(fn,{}),r("span",{children:qe(i.handoffShared,{email:_})})]})}const f=async()=>{if(!(!p.trim()||c)){d(!0);try{await a("inquiry",{visitorEmail:p.trim(),...l.trim()?{visitorName:l.trim()}:{},message:n||"I had a question the assistant couldn’t answer.",subject:"Help request from chat"},{email:p.trim(),name:l.trim()||void 0}),s(!0)}catch{d(!1)}}};return r("div",{class:"cf-handoff",children:[r("div",{class:"cf-handoff__title",children:i.handoffTitle}),r("input",{class:"cf-form__input",type:"text",placeholder:i.handoffName,value:l,"aria-label":i.handoffName,onInput:_=>u(_.target.value)}),r("input",{class:"cf-form__input",type:"email",placeholder:`${i.handoffEmail} *`,value:p,"aria-label":i.handoffEmail,onInput:_=>m(_.target.value)}),r("button",{type:"button",class:"cf-form__submit",disabled:!p.trim()||c,onClick:f,children:c?i.sending:i.handoffNotify})]})},jd=({text:e})=>{const t=ct(),[n,a]=$(!1);return r("button",{type:"button",class:"cf-tool",onClick:async()=>{try{await navigator.clipboard.writeText(e),a(!0),setTimeout(()=>a(!1),1500)}catch{}},"aria-label":t.copy,children:[n?r(fn,{}):r(ld,{}),n?t.copied:t.copy]})},Hd=({items:e,onPick:t})=>e.length===0?null:r("div",{class:"cf-starters",children:e.map((n,a)=>r("button",{type:"button",class:"cf-starter",onClick:()=>t(n),children:n},a))}),Wd=({items:e})=>{const t=e.filter(n=>n.label.trim()&&n.url.trim()).slice(0,4);return t.length===0?null:r("div",{class:"cf-featured-links",children:t.map((n,a)=>r("a",{class:"cf-featured-link",href:n.url,target:"_blank",rel:"noopener noreferrer nofollow",title:n.label,children:[r(Ln,{}),r("span",{children:n.label})]},`${n.url}-${a}`))})},Gd=({msg:e,onRate:t})=>{const n=ct(),[a,i]=$(!1),[o,s]=$(""),c=e.feedback,d=()=>{t(e.id,"up"),i(!1)},l=()=>{t(e.id,"down"),i(!0)},u=()=>{t(e.id,"down",o.trim()),i(!1)};return r("div",{class:"cf-feedback",children:[r("div",{class:"cf-feedback__row",children:[r("span",{class:"cf-feedback__label",children:n.feedbackAnswerPrompt}),r("button",{type:"button",class:`cf-feedback__btn ${c==="up"?"is-active":""}`,"aria-label":`${n.feedbackHelpful} answer`,"aria-pressed":c==="up",onClick:d,children:r(oo,{})}),r("button",{type:"button",class:`cf-feedback__btn ${c==="down"?"is-active":""}`,"aria-label":`${n.feedbackNotHelpful} answer`,"aria-pressed":c==="down",onClick:l,children:r(so,{})}),c&&!a&&r("span",{class:"cf-feedback__thanks",children:n.feedbackThanks})]}),a&&c==="down"&&r("div",{class:"cf-feedback__comment",children:[r("textarea",{class:"cf-feedback__input",rows:2,placeholder:n.feedbackCommentPlaceholder,value:o,onInput:p=>s(p.target.value)}),r("button",{type:"button",class:"cf-feedback__send",onClick:u,children:n.feedbackSend})]})]})},bo=e=>e.attachments??(e.attachmentName?[{id:e.attachmentId,name:e.attachmentName}]:[]),Kd=({msg:e,persona:t,isLast:n,visitor:a,hasEmail:i,lastQuestion:o,showActions:s,onPickReply:c,onSubmitForm:d,onDemoSlots:l,onConfirmHostedBooking:u,onRetry:p,ratable:m,onRate:f,onExpandVisualization:_,onExpandExplanation:h,onReconnect:I,onOpenAttachment:x,onExplanationFeedback:g,explanationTransport:T,onOpenAnalyticsSource:V})=>{const P=ct(),ee=mr(),Z=e.role==="user",Y=e.liveEventType??"",z=e.content.trim().toLowerCase(),te=Y==="handoff_queued"||Y==="agent_joined"||Y==="agent_left"||Y==="ai_handback"||Y==="conversation_ended"||z.includes("joined the chat")||z.includes("left the chat")||z.includes("support agents will be with you"),U=e.role==="system"||te,B=e.requestedContactFields?.includes("email")===!0,A=n&&!Z&&!U&&!e.reconnectOffer&&!!(e.handoffOffered||B),N=A&&!i?["inquiry"]:[],y=!e.pending&&!e.streaming,D=[...e.artifacts??[],...e.visualization&&!(e.artifacts??[]).some(S=>S.type==="visualization")?[{type:"visualization",visualization:e.visualization}]:[]];return U?r("div",{class:"cf-msg cf-msg--system",children:r("div",{class:"cf-system-event",children:[r("div",{class:"cf-system-event__mark","aria-hidden":"true"}),r("div",{class:"cf-system-event__text",children:e.content}),I&&r("button",{type:"button",class:"cf-system-event__action",onClick:I,children:P.reconnectSupport}),e.createdAt&&r("div",{class:"cf-system-event__time",children:new Date(e.createdAt).toLocaleString(void 0,{day:"2-digit",month:"short",year:"numeric",hour:"numeric",minute:"2-digit"})})]})}):r("div",{class:`cf-msg cf-msg--${Z?"user":"agent"}`,children:[!Z&&r(uo,{persona:t,small:!0}),r("div",{class:`cf-msg__col${!Z&&s?" cf-msg__col--actions":""}`,children:[e.pending&&e.content===""?r(Sd,{}):e.imageUrl?r("div",{class:"cf-msg__bubble cf-msg__bubble--media",children:[r("img",{class:"cf-msg__media",src:e.imageUrl,alt:"GIF"}),e.content&&r("span",{class:"cf-msg__caption",children:e.content})]}):r("div",{class:"cf-msg__bubble",children:[Z?e.content:_d(e.content),e.streaming&&r("span",{class:"cf-caret","aria-hidden":"true"})]}),Z?null:D.map((S,O)=>S.type==="visualization"&&S.visualization?r(vo,{visualization:S.visualization,onFollowUp:c,onExpand:_?()=>_(e.id):void 0,expandControlId:e.id},`visualization-${O}`):S.type==="image"&&(S.data||S.uri?.startsWith("https://"))&&["image/png","image/jpeg","image/webp"].includes(S.mimeType??"")?r("figure",{class:"cf-artifact",children:[S.title?r("figcaption",{children:S.title}):null,r("img",{src:S.uri||`data:${S.mimeType};base64,${S.data}`,alt:S.altText||S.caption||S.title||"Tool result"}),S.caption&&S.caption!==S.title?r("p",{children:S.caption}):null]},`image-${O}`):S.type==="video"&&S.uri?.startsWith("https://")&&(S.mimeType??"").startsWith("video/")?r("figure",{class:"cf-artifact",children:[S.title?r("figcaption",{children:S.title}):null,r("video",{controls:!0,preload:"metadata",playsInline:!0,src:S.uri}),S.caption&&S.caption!==S.title?r("p",{children:S.caption}):null]},`video-${O}`):S.type==="resource_link"&&S.uri?.startsWith("https://")?r("a",{class:"cf-artifact-link",href:S.uri,target:"_blank",rel:"noopener noreferrer nofollow",children:[r("strong",{children:S.title||S.name||"Open result"}),S.caption?r("span",{children:S.caption}):null]},`link-${O}`):null),!Z&&e.resultExpired&&!e.visualization?r("p",{class:"cf-analytics-expired","data-testid":"analytics-result-expired",children:[e.resultExpired.title?r("strong",{children:[e.resultExpired.title,". "]}):null,P.resultExpired]}):null,!Z&&e.visualization&&xa(e.visualization)?r("div",{class:"cf-analytics-explanation","data-testid":"inline-analytics-explanation","data-explanation-message":e.id,children:r(eo,{classPrefix:"cf",copy:P.analytics?.explanation,locale:ee,onExpand:h?()=>h(e.id):void 0,explanation:xa(e.visualization),onFollowUp:c,onFeedback:g,aiTransport:T,canOpenSource:S=>!!V&&(S.kind==="liveboard_tile"||S.kind==="insight"),onOpenSource:V?S=>{(S.kind==="liveboard_tile"||S.kind==="insight")&&V({kind:S.kind,id:S.id,...e.visualization?.appliedFilters?.length?{appliedFilters:e.visualization.appliedFilters}:{}})}:void 0,maxFollowUps:3,showLead:(()=>{const S=xa(e.visualization).headline?.trim().toLocaleLowerCase();return!S||!e.content.toLocaleLowerCase().includes(S)})()})}):null,Z&&bo(e).length>0&&r("div",{class:"cf-attach-row cf-attach-row--sent",children:bo(e).map((S,O)=>x?r("button",{type:"button",class:"cf-attach-chip cf-attach-chip--open",title:qe(P.attachOpen,{name:S.name}),"aria-label":qe(P.attachOpen,{name:S.name}),onClick:()=>x(e,S,O),children:[r(va,{}),r("span",{children:S.name})]},`${S.id??S.name}-${O}`):r("div",{class:"cf-attach-chip",title:S.name,children:[r(va,{}),r("span",{children:S.name})]},`${S.id??S.name}-${O}`))}),!Z&&r(se,{children:[y&&(e.error||e.content)&&r("div",{class:"cf-msg__actions",children:[r("div",{class:"cf-msg__tools",children:e.error?r("button",{type:"button",class:"cf-tool",onClick:()=>p(e.id,e.retryText??""),children:[r(dd,{}),P.retry]}):r(jd,{text:e.content})}),m&&!e.error&&e.content?r(Gd,{msg:e,onRate:f}):null]}),r(Td,{msg:e}),n&&r(Cd,{replies:e.suggestedReplies,onPick:c}),A&&r(Vd,{hasEmail:i,visitor:a,question:o,onSubmitForm:d}),s&&r(go,{showTrigger:!1,actions:e.availableActions,descriptors:e.actions,openAction:e.selectedAction,visitor:a,onSubmitForm:d,onDemoSlots:l,onConfirmHostedBooking:u,scheduler:t?.scheduler,exclude:N})]})]})]})},Yd=({visualization:e,onClose:t,onFollowUp:n,onFeedback:a,transport:i,onOpenSource:o})=>{const s=ct(),c=mr(),d=xa(e);return d?r("div",{class:"cf-analytics-explanation is-expanded","data-testid":"expanded-analytics-explanation",children:r(eo,{classPrefix:"cf",explanation:d,copy:s.analytics?.explanation,locale:c,expanded:!0,onCollapse:t,onFollowUp:n,onFeedback:a,aiTransport:i,canOpenSource:l=>!!o&&(l.kind==="liveboard_tile"||l.kind==="insight"),onOpenSource:o?l=>{(l.kind==="liveboard_tile"||l.kind==="insight")&&o({kind:l.kind,id:l.id,...e.appliedFilters?.length?{appliedFilters:e.appliedFilters}:{}})}:void 0})}):null},vo=({visualization:e,expanded:t=!1,onExpand:n,onClose:a,onFollowUp:i,expandControlId:o})=>{const s=ct(),c=mr();return r(gc,{visualization:e,classPrefix:"cf",labels:s.analytics,locale:c,expanded:t,onExpand:n,onClose:a,onFollowUp:i,expandControlId:o})},xo=e=>new Promise((t,n)=>{const a=new FileReader;a.onload=()=>t(String(a.result).split(",")[1]??""),a.onerror=n,a.readAsDataURL(e)}),Zd=({onPick:e})=>r("div",{class:"cf-picker cf-emoji",children:ql.map(t=>r("div",{class:"cf-emoji__group",children:[r("div",{class:"cf-emoji__label",children:t.name}),r("div",{class:"cf-emoji__grid",children:t.emojis.map((n,a)=>r("button",{type:"button",class:"cf-emoji__btn",onClick:()=>e(n),"aria-label":n,children:n},a))})]},t.name))}),Jd=({onSearch:e,onPick:t})=>{const n=ct(),[a,i]=$(""),[o,s]=$([]),[c,d]=$(!0);return X(()=>{let l=!0;d(!0);const u=setTimeout(()=>{e(a).then(p=>l&&(s(p),d(!1))).catch(()=>l&&(s([]),d(!1)))},300);return()=>{l=!1,clearTimeout(u)}},[a,e]),r("div",{class:"cf-picker cf-gif",children:[r("input",{class:"cf-gif__search",placeholder:n.searchGifs,value:a,"aria-label":n.searchGifs,onInput:l=>i(l.target.value)}),r("div",{class:"cf-gif__grid",children:c?r("div",{class:"cf-gif__hint",children:n.searchingGifs}):o.length===0?r("div",{class:"cf-gif__hint",children:n.noGifs}):o.map(l=>r("button",{type:"button",class:"cf-gif__item",onClick:()=>t(l.url),"aria-label":l.alt,children:r("img",{src:l.preview,alt:l.alt,loading:"lazy"})},l.id))}),r("div",{class:"cf-gif__powered",children:"via Tenor"})]})},Xd=5*1024*1024,vr=5,Qd="image/png,image/jpeg,image/webp,image/gif,application/pdf",eu=15e3,mn=e=>e==="listening"||e==="hearing",xr=e=>{switch(e){case"connecting":return"Connecting with AI…";case"listening":return"Listening now — go ahead.";case"hearing":return"Hearing you…";case"unavailable":return"I can’t hear you — check your microphone.";case"speaking":return"AI is speaking — talk to interrupt.";case"processing":return"Working on it — keep talking to add more.";case"noise":return"I couldn't hear clear words. Try again closer to the mic.";case"misunderstood":return"I didn't understand that. Please try again.";case"denied":return"Microphone access is blocked. Allow the mic or type your question.";case"muted":return"Muted — tap the mic to unmute.";case"timeout":return"Didn't hear anything for a while — ending the call.";default:return""}},tu=.004,yo=({muted:e,listening:t,micLevel:n,onToggleMute:a})=>{const i=t&&n>=tu;return r("button",{type:"button",class:`cf-call-btn ${e?"is-muted":""} ${t?"is-listening":""} ${i?"is-hot":""}`,"aria-label":e?"Unmute microphone":"Mute microphone","aria-pressed":e,onClick:a,style:t?{"--cf-wave":String(Math.max(.2,Math.min(1,n*6)))}:void 0,children:e?r(Ql,{}):r(Rn,{})})},nu=({audioDevices:e,selectedAudioDeviceId:t,onSelectAudioDevice:n})=>{const[a,i]=$(!1),[o,s]=$(null),c=R(null);X(()=>{if(!a)return;const l=u=>{c.current&&!u.composedPath().includes(c.current)&&i(!1)};return document.addEventListener("pointerdown",l),()=>document.removeEventListener("pointerdown",l)},[a]),Sn(()=>{if(!a){s(null);return}const l=c.current;if(!l)return;let u=new DOMRect(0,0,window.innerWidth,window.innerHeight);for(let I=l.parentElement;I;I=I.parentElement){const x=getComputedStyle(I);if(x.overflow!=="visible"||x.overflowY!=="visible"){u=I.getBoundingClientRect();break}}const p=l.getBoundingClientRect(),m=8,f=u.bottom-p.bottom-m*2,_=p.top-u.top-m*2,h=_>f;s({up:h,maxHeight:Math.max(72,Math.floor(h?_:f))})},[a]);const d=[{deviceId:"",label:"Default microphone"},...e];return r("div",{class:"cf-call-more",ref:c,children:[r("button",{type:"button",class:"cf-call-btn cf-call-btn--microphones","aria-label":"Choose microphone","aria-expanded":a,onClick:()=>i(l=>!l),children:r(pn,{})}),a&&r("div",{class:`cf-call-menu${o?.up?" cf-call-menu--up":""}`,role:"menu",style:o?{maxHeight:`${o.maxHeight}px`}:{visibility:"hidden"},children:[r("div",{class:"cf-call-menu__label",children:"Microphone"}),d.map(l=>r("button",{type:"button",role:"menuitemradio","aria-checked":l.deviceId===t,class:`cf-call-menu__item ${l.deviceId===t?"is-active":""}`,onClick:()=>{n(l.deviceId),i(!1)},children:[l.deviceId===t?r(fn,{}):r("span",{class:"cf-call-menu__spacer"}),r("span",{children:l.label})]},l.deviceId))]})]})},au=({voiceState:e,muted:t,onToggleMute:n,onEndCall:a,onTalkNow:i,showTalkNow:o,micLevel:s,theaterMode:c,onToggleTheater:d,onMinimize:l,audioDevices:u,selectedAudioDeviceId:p,onSelectAudioDevice:m})=>r("div",{class:"cf-call-controls",children:[r(yo,{muted:t,listening:mn(e)&&!t,micLevel:s,onToggleMute:n}),r(nu,{audioDevices:u,selectedAudioDeviceId:p,onSelectAudioDevice:m}),o&&r("button",{type:"button",class:"cf-call-btn cf-call-btn--talk","aria-label":"Talk now",onClick:i,children:r(Rn,{})}),r("button",{type:"button",class:"cf-call-btn","aria-label":c?"Exit expanded view":"Expand view","aria-pressed":c,onClick:d,children:c?r(hd,{}):r(fd,{})}),r("button",{type:"button",class:"cf-call-btn","aria-label":"Minimize voice chat",onClick:l,children:r(md,{})}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--end","aria-label":"End voice chat",onClick:a,children:r(br,{})})]}),ru=({persona:e,voiceState:t,muted:n,onToggleMute:a,onEndCall:i,micLevel:o,onExpand:s})=>{const c=m=>m.stopPropagation(),d=e?.assistantMediaUrl?.trim()||e?.agentAvatarUrl?.trim()||"",l=e?.assistantMediaKind==="video"&&!!d,u=e?.agentName||"Assistant",p=["cf-floating-call-card",mn(t)&&!n?"is-listening":"",t==="speaking"?"is-speaking":"",t==="processing"||t==="connecting"?"is-thinking":"",n?"is-muted":""].filter(Boolean).join(" ");return r("div",{class:p,style:mn(t)&&!n?{"--cf-listen":String(Math.max(.18,Math.min(1,o*8)))}:void 0,role:"button",tabIndex:0,"aria-label":`Reopen voice chat with ${u}`,onClick:s,onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),s())},children:[r("div",{class:"cf-floating-call-card__media","aria-hidden":"true",children:d?l?r("video",{src:d,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):r("img",{src:d,alt:""}):r("div",{class:`cf-floating-call-card__avatar${Pn(e)}`,children:[r("span",{children:ya(e)}),r("span",{class:"cf-floating-call-card__eye cf-floating-call-card__eye--left"}),r("span",{class:"cf-floating-call-card__eye cf-floating-call-card__eye--right"}),r("span",{class:"cf-floating-call-card__mouth"})]})}),r("div",{class:"cf-floating-call-card__shade","aria-hidden":"true"}),r("span",{class:"cf-floating-call-card__status",role:"status","aria-live":"polite",children:xr(t)}),r("div",{class:"cf-floating-call-card__controls",onClick:c,onKeyDown:c,role:"presentation",children:[r(yo,{muted:n,listening:mn(t)&&!n,micLevel:o,onToggleMute:a}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--restore","aria-label":"Restore voice chat",onClick:m=>{c(m),s()},children:r(gd,{})}),r("button",{type:"button",class:"cf-call-btn cf-call-btn--end","aria-label":"End voice chat",onClick:m=>{c(m),i()},children:r(br,{})})]})]})},iu=(e,t)=>{switch(e){case"connecting":return t.voiceConnecting;case"listening":return t.voiceListening;case"hearing":return t.voiceHearing;case"unavailable":return t.voiceUnavailable;case"processing":return t.voiceProcessing;case"speaking":return t.voiceSpeaking;case"noise":return t.voiceNoise;case"misunderstood":return t.voiceMisunderstood;case"denied":return t.voiceDenied;default:return xr(e)}},ou=({draftStore:e,onSend:t,onSendGif:n,onTyping:a,disabled:i,allowVoice:o,onTranscribe:s,gifEnabled:c,onSearchGifs:d,allowAttach:l,analyzeAttachments:u=!0,onUpload:p,voiceStartSignal:m=0,onVoiceStateChange:f,onPreviewAttachment:_})=>{const h=ct(),[I,x]=$(()=>e.value),g=M=>{const pe=typeof M=="function"?M(I):M;e.value=pe,x(pe)},[T,V]=$(!1),[P,ee]=$(!1),[Z,Y]=$("idle"),[z,te]=$("none"),[U,B]=$([]),A=R([]);A.current=U;const N=R(0),[y,D]=$(!1),[S,O]=$(!1),[ue,oe]=$(""),Fe=R(null),_e=R(null),Te=R(null),Le=R(0),Ie=R(null),Ce=R(void 0),ve=M=>{Y(M),f?.(M)},Xe=()=>{Ce.current&&window.clearTimeout(Ce.current),Ce.current=void 0};X(()=>{const M=Fe.current;M&&(M.style.height="auto",M.style.height=`${Math.min(M.scrollHeight,110)}px`)},[I]),X(()=>()=>{for(const M of A.current)M.previewUrl&&URL.revokeObjectURL(M.previewUrl)},[]);const ge=M=>{B(pe=>{const de=pe.find(fe=>fe.key===M);return de?.previewUrl&&URL.revokeObjectURL(de.previewUrl),pe.filter(fe=>fe.key!==M)})},ie=()=>B([]);X(()=>{if(z==="none")return;const M=pe=>{_e.current&&!pe.composedPath().includes(_e.current)&&te("none")};return document.addEventListener("pointerdown",M),()=>document.removeEventListener("pointerdown",M)},[z]);const He=M=>te(pe=>pe===M?"none":M),We=M=>{const pe=Fe.current;if(!pe){g(Oe=>Oe+M);return}const de=pe.selectionStart??I.length,fe=pe.selectionEnd??I.length;g(I.slice(0,de)+M+I.slice(fe)),requestAnimationFrame(()=>{pe.focus();const Oe=de+M.length;pe.setSelectionRange(Oe,Oe)})},k=M=>{te("none"),n(M)},K=async M=>{if(M.length===0)return;oe("");const pe=Le.current,de=vr-A.current.length-N.current;if(de<=0){oe(qe(h.attachLimit,{count:String(vr)}));return}const fe=M.slice(0,de);N.current+=fe.length,D(!0);for(const Oe of fe){if(pe!==Le.current)break;try{await j(Oe,pe)}finally{pe===Le.current&&(N.current-=1,D(N.current>0))}}pe===Le.current&&M.length>fe.length&&oe(qe(h.attachLimit,{count:String(vr)}))},j=async(M,pe)=>{if(M.size>Xd){oe(h.attachTooLarge);return}if(!p){oe(h.attachFailed);return}try{const de=await xo(M);if(pe!==Le.current)return;const fe=await p(de,M.type||"application/octet-stream",M.name,u);if(pe!==Le.current)return;const Oe={key:`${fe.id||M.name}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,id:fe.id,analysisFailed:fe.analysisFailed,name:M.name,text:fe.text,mimeType:M.type||"application/octet-stream",size:M.size,previewUrl:M.type.startsWith("image/")?URL.createObjectURL(M):void 0,file:M};B(Ge=>[...Ge,Oe])}catch(de){if(pe!==Le.current)return;de instanceof un&&de.status===413?oe(h.attachTooLarge):de instanceof un&&[400,415,503].includes(de.status)?oe(de.message):oe(h.attachFailed)}},G=async M=>{const pe=M.target,de=Array.from(pe.files??[]);pe.value="",await K(de)},ne=()=>{Le.current+=1,N.current=0,D(!1),oe("")},ye=(!!I.trim()||U.length>0)&&!i&&!y&&!P,Se=()=>{ye&&(t(I,U.length>0?{attachments:U.map(M=>({id:M.id,name:M.name,text:M.text,file:M.file}))}:void 0),a?.(!1),g(""),ie(),oe(""))},et=M=>{const pe=M.trim();if(!pe||i){ve("misunderstood");return}const de=I.trim(),fe=de?`${de} ${pe}`:pe;t(fe),a?.(!1),g(""),ie(),oe(""),ve("idle")},Ye=M=>{if(M.key==="Enter"&&!M.shiftKey){if(i)return;M.preventDefault(),Se()}else M.key==="Escape"&&z!=="none"&&(M.preventDefault(),M.stopPropagation(),te("none"))},tt=()=>{Xe(),Ie.current?.stop("dictation-ended"),Ie.current=null,V(!1),ee(!1)},at=async()=>{const M=Ie.current;if(M){const{mic:fe,processing:Oe}=M.snapshot;fe==="hearing"||Oe?M.finishTurn():(tt(),ve("idle"));return}const pe=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||void 0;ve("connecting");const de=new qi({transcribe:async({audio:fe,mimeType:Oe,durationSeconds:Ge})=>s(await xo(fe),Oe,pe,Ge),listener:{state:({mic:fe,processing:Oe,reason:Ge})=>{if(Ie.current===de){if(fe==="unavailable"){if(Ge==="permission-denied"||Ge==="unsupported"||Ge==="no-device"||Ge==="error"){tt(),ve("denied");return}ve("unavailable");return}V(fe==="listening"||fe==="hearing"),ee(Oe),fe==="starting"?ve("connecting"):Oe&&fe!=="hearing"?ve("processing"):fe==="hearing"?ve("hearing"):fe==="listening"&&ve("listening")}},speechStart:()=>Xe(),turn:fe=>{Ie.current===de&&(tt(),et(fe.text))},noise:fe=>{Ie.current===de&&(tt(),ve(fe.reason==="transcribe-failed"?"misunderstood":"noise"))}}});Ie.current=de,Ce.current=window.setTimeout(()=>{Ie.current===de&&(tt(),ve("noise"))},eu),await de.start()};return X(()=>{!m||!o||i||T||P||at()},[m]),X(()=>()=>{Xe(),Ie.current?.stop("unmounted"),Ie.current=null},[]),r("div",{class:`cf-composer ${S?"is-dragging":""}`,ref:_e,onDragEnter:M=>{l&&(M.preventDefault(),O(!0))},onDragOver:M=>{l&&M.preventDefault()},onDragLeave:M=>{M.currentTarget===M.target&&O(!1)},onDrop:M=>{l&&(M.preventDefault(),O(!1),K(Array.from(M.dataTransfer?.files??[])))},children:[z==="emoji"&&r(Zd,{onPick:We}),z==="gif"&&r(Jd,{onSearch:d,onPick:k}),(U.length>0||y||ue)&&r("div",{class:"cf-attach-row",role:"list","aria-label":h.attachedFiles,children:[U.map(M=>r("span",{class:"cf-attach-chip",role:"listitem",title:M.name,children:[r("button",{type:"button",class:"cf-attach-open","aria-label":qe(h.attachOpen,{name:M.name}),disabled:!_,onClick:()=>_?.(M.file,M.name),children:[M.previewUrl?r("img",{class:"cf-attach-preview",src:M.previewUrl,alt:""}):r(va,{}),r("span",{class:"cf-attach-copy",children:[r("span",{children:M.name}),r("small",{children:M.analysisFailed?h.attachAnalysisFailed:`${Math.max(1,Math.ceil(M.size/1024))} KB`})]})]}),r("button",{type:"button",class:"cf-attach-x","aria-label":qe(h.removeAttachmentNamed,{name:M.name}),onClick:()=>ge(M.key),children:r(Dn,{})})]},M.key)),y&&r("span",{class:"cf-attach-status",children:[r("span",{children:h.attaching}),r("button",{type:"button",onClick:ne,children:h.cancel})]}),ue&&!y&&r("span",{class:"cf-attach-status cf-attach-status--err",children:ue})]}),Z!=="idle"&&r("div",{class:"cf-voice-state","aria-live":"polite",children:[r("span",{class:`cf-voice-state__dot ${T?"is-live":""}`}),iu(Z,h)]}),r("div",{class:"cf-composer__field",children:[r("button",{type:"button",class:`cf-iconbtn ${z==="emoji"?"is-active":""}`,"aria-label":h.emoji,"aria-pressed":z==="emoji",onClick:()=>He("emoji"),children:z==="emoji"?r(Dn,{}):r(od,{})}),c&&r("button",{type:"button",class:`cf-iconbtn cf-gifbtn ${z==="gif"?"is-active":""}`,"aria-label":h.gifs,"aria-pressed":z==="gif",onClick:()=>He("gif"),children:r("span",{class:"cf-gif-label",children:"GIF"})}),l&&r(se,{children:[r("input",{ref:Te,type:"file",class:"cf-file-input",accept:Qd,multiple:!0,onChange:G,tabIndex:-1,"aria-hidden":"true"}),r("button",{type:"button",class:"cf-iconbtn","aria-label":h.attachFile,disabled:y,onClick:()=>Te.current?.click(),children:r(va,{})})]}),r("textarea",{ref:Fe,class:"cf-textarea",rows:1,placeholder:h.composerPlaceholder,value:I,"aria-label":h.composerPlaceholder,"aria-busy":i,onInput:M=>{const pe=M.target.value;g(pe),a?.(!!pe.trim())},onPaste:M=>{const pe=Array.from(M.clipboardData?.files??[]);!l||pe.length===0||(M.preventDefault(),K(pe))},onKeyDown:Ye}),o&&r("button",{type:"button",class:`cf-iconbtn cf-mic ${T?"is-recording":""}`,"aria-label":T?h.stopRecording:h.recordVoice,"aria-pressed":T,disabled:P||i,onClick:at,children:r(Rn,{})}),r("button",{type:"button",class:"cf-send","aria-label":h.send,disabled:!ye,onClick:Se,children:r(Xl,{})})]})]})},su=e=>e.replace(/\[[^\]]{0,60}\]/g," ").replace(/\(([^)]{0,60})\)/g,(t,n)=>_o.has(n.trim().toLowerCase().replace(/[.!?,…]+$/,"").replace(/\s+/g," "))?" ":t).replace(/\*[^*]{0,60}\*/g," ").replace(/\s+/g," ").trim(),_o=new Set(["background noise","engine noise","noise","inaudible","unintelligible","silence","no speech","static","music","laughter","applause","wind","breathing","click","clicks","clicking","mouse click","mouse clicks","beep","beeps","beeping","tap","taps","tapping","typing","keyboard typing","cough","coughing","sigh","hmm","mm","mmm","uh","um","ah","oh"]),cu=/^\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?(?:\s*(?:-|–|—|to|-->)\s*\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?)?$/,lu=e=>{const t=e.trim().toLowerCase().replace(/[()[\]*]/g," ").replace(/[.!?,…]+$/,"").replace(/\s+/g," ").trim();return!t||/^(?:sh+\s*)+$/.test(t)||cu.test(t)?!0:_o.has(t)},du=e=>{const t=e.trim().toLowerCase().replace(/\s+/g," ");return t?/^(?:transcribe|transcription|transcribed text)[.!:]*$/.test(t)?!0:t.includes("transcribe this audio recording verbatim")||t.includes("preserve the spoken language and any code-switching")||t.includes("output only the transcribed text, no commentary"):!1};let wo=!0,On=null;const uu=e=>{wo=e},pu=()=>{const e=typeof window<"u"?window.AudioContext??window.webkitAudioContext:void 0;if(!e)return null;if(!On)try{On=new e}catch{return null}return On.state==="suspended"&&On.resume(),On},Fn=(e,t,n,a,i,o)=>{const s=e.createOscillator(),c=e.createGain();s.type=i,s.frequency.setValueAtTime(t,n),s.connect(c),c.connect(e.destination),c.gain.setValueAtTime(1e-4,n),c.gain.exponentialRampToValueAtTime(o,n+.012),c.gain.exponentialRampToValueAtTime(1e-4,n+a),s.start(n),s.stop(n+a+.03)},gn=e=>{if(!wo)return;const t=pu();if(!t)return;const n=t.currentTime;try{e==="open"?(Fn(t,523,n,.12,"sine",.05),Fn(t,784,n+.08,.16,"sine",.05)):e==="send"?Fn(t,660,n,.08,"triangle",.04):e==="receive"&&(Fn(t,880,n,.1,"sine",.045),Fn(t,1175,n+.09,.14,"sine",.045))}catch{}},fu=e=>e.startsWith("image/")?"image":e==="application/pdf"?"pdf":"other",hu=({state:e,onClose:t})=>{const n=ct(),a=R(null);X(()=>{a.current?.focus();const o=s=>{s.key==="Escape"&&(s.stopPropagation(),t())};return document.addEventListener("keydown",o,!0),()=>document.removeEventListener("keydown",o,!0)},[t]);const i=e.status==="ready"?fu(e.mimeType):"other";return r("div",{class:"cf-preview",role:"dialog","aria-modal":"true","aria-label":qe(n.attachPreviewTitle,{name:e.name}),onClick:o=>{o.target===o.currentTarget&&t()},children:r("div",{class:"cf-preview__frame",children:[r("div",{class:"cf-preview__bar",children:[r("span",{class:"cf-preview__name",title:e.name,children:e.name}),e.status==="ready"&&r("a",{class:"cf-preview__btn",href:e.url,download:e.name,children:n.attachDownload}),r("button",{ref:a,type:"button",class:"cf-preview__btn cf-preview__close","aria-label":n.attachPreviewClose,onClick:t,children:"✕"})]}),r("div",{class:"cf-preview__body",children:[e.status==="loading"&&r("p",{class:"cf-preview__note",children:n.attachPreviewLoading}),e.status==="error"&&r("p",{class:"cf-preview__note",children:n.attachPreviewFailed}),e.status==="ready"&&i==="image"&&r("img",{class:"cf-preview__image",src:e.url,alt:e.name}),e.status==="ready"&&i==="pdf"&&r("iframe",{class:"cf-preview__pdf",src:e.url,title:e.name}),e.status==="ready"&&i==="other"&&r("p",{class:"cf-preview__note",children:n.attachPreviewUnsupported})]})]})})},mu=e=>new Promise((t,n)=>{const a=new FileReader;a.onload=()=>t(String(a.result??"").split(",")[1]??""),a.onerror=()=>n(a.error),a.readAsDataURL(e)}),gu=(e,t)=>e?.status===429?t.errorRateLimit:t.errorGeneric,yr=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),wa=(e,t)=>{const n=yr(),a={stage:e,durationMs:Math.max(0,n-t)};try{performance.measure(`centrinfo-widget:${e}`,{start:t,end:n})}catch{}return typeof window<"u"&&typeof CustomEvent<"u"&&window.dispatchEvent(new CustomEvent("centrinfo:performance",{detail:a})),a},bu=/!?\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,vu=/https?:\/\/[^\s)]+/g,ko=e=>Ui(e).replace(bu,"$1").replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/(^|[\s([{])\*([^*\n]{1,120})\*(?=[\s.,;:!?)}\]]|$)/g,"$1$2").replace(/(^|[\s([{])_([^_\n]{1,120})_(?=[\s.,;:!?)}\]]|$)/g,"$1$2").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s{0,3}[-*+]\s+/gm,"").replace(/^\s{0,3}\d+\.\s+/gm,"").replace(/\s+\*/g," ").replace(/\*\s+/g," ").replace(/[*_]{2,}/g,"").replace(vu,t=>t.replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/$/,"")).replace(/[ \t]+\n/g,`
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(),xu=(e,t)=>ko(Bc(e,t)),yu=45e3,_r=e=>e.type==="visualization",_u=e=>{const t=!!e.visualization,n=(e.artifacts??[]).some(_r);if(!t&&!n)return e;const{visualization:a,artifacts:i,...o}=e,s=(i??[]).filter(d=>!_r(d)),c=a?.title??(i??[]).find(_r)?.visualization?.title??e.resultExpired?.title;return{...o,...s.length>0?{artifacts:s}:{},resultExpired:c?{title:c}:{}}},wr=e=>e.map(_u),wu=(e,t=Date.now())=>{const n=e.visualization?.explanation?.aiExplanation;if(!e.visualization?.explanation||!n||n.status!=="pending")return e;const a=e.createdAt?Date.parse(e.createdAt):NaN;return Number.isFinite(a)&&t-a<yu?e:{...e,visualization:{...e.visualization,explanation:{...e.visualization.explanation,aiExplanation:{...n,status:"failed",retryAvailable:!1}}}}},ku=e=>e instanceof DOMException&&(e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED"),Su=(e,t,n,a)=>{let i=a;for(let o=0;o<4&&i.length>0;o+=1)try{return e.setItem(t,n(i)),!0}catch(s){if(!ku(s))return!1;i=i.slice(Math.ceil(i.length/2))}try{e.removeItem(t)}catch{}return!1},$u=(e,t)=>{if(e)try{const n=[];for(let a=0;a<e.length;a+=1){const i=e.key(a);i?.startsWith(t)&&n.push(i)}for(const a of n){const i=e.getItem(a);if(!i)continue;const o=JSON.parse(i);if(!Array.isArray(o.messages))continue;const s=wr(o.messages);s.some((c,d)=>c!==o.messages[d])&&e.setItem(a,JSON.stringify({...o,messages:s}))}}catch{}},Tu=(e,t=()=>Date.now())=>{let n=null,a=null,i=Number.NEGATIVE_INFINITY;const o=()=>{a!==null&&(clearTimeout(a),a=null);const s=n;n=null,s&&(i=t(),s())};return{schedule:s=>{if(n=s,a!==null)return;const c=e-(t()-i);c<=0?o():a=setTimeout(o,c)},flush:o,cancel:()=>{a!==null&&clearTimeout(a),a=null,n=null}}},lt=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.round(Math.random()*1e9)}`,ka=(e,t)=>{typeof console>"u"||console.warn(`[centrinfo-widget] ${e}`,t??{})},So=(e,t,n,a,i=1,o,s=!1,c,d)=>{e.current?.pause(),e.current=null,typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel(),t.current=null;const l=()=>{const h=o?.trim();if(!s||!h||typeof window>"u"||!("speechSynthesis"in window)||typeof SpeechSynthesisUtterance>"u")return!1;const I=new SpeechSynthesisUtterance(h);let x=!1;const g=()=>{x||(x=!0,t.current===I&&(t.current=null,d?.()))};return I.rate=i,I.lang=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en-US",I.onend=g,I.onerror=g,t.current=I,c?.(),window.speechSynthesis.cancel(),window.speechSynthesis.speak(I),!0};if(!n||typeof Audio>"u")return l();const u=new Audio(`data:${a||"audio/mpeg"};base64,${n}`);let p=!1,m=!1;const f=()=>{p||(p=!0,e.current===u&&(e.current=null,d?.()))},_=()=>{if(!p){if(m||e.current!==u){f();return}p=!0,e.current=null,l()||d?.()}};return u.playbackRate=i,u.onended=f,u.onerror=_,e.current=u,u.play().then(()=>{if(!p){if(e.current!==u){f();return}m=!0,c?.(Number.isFinite(u.duration)?u.duration*1e3:void 0)}}).catch(_),!0},Cu=e=>{try{return e==="none"?null:e==="session"?sessionStorage:localStorage}catch{return null}},Au=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)},Mu=e=>{try{const t=e?.split(".")[1];if(!t)return;const n=t.replace(/-/g,"+").replace(/_/g,"/"),a=JSON.parse(atob(n.padEnd(Math.ceil(n.length/4)*4,"=")));for(const i of["sub","external_user_id","user_id"]){const o=a[i];if(typeof o=="string"&&o.trim())return o.trim()}}catch{}},Iu=e=>{const t=e.user?.externalId?.trim()||e.user?.userId?.trim()||e.user?.email?.trim().toLowerCase()||Mu(e.identityToken)||(e.identityToken||e.getIdentityToken?"authenticated":"anonymous");return`${e.token.slice(0,12)}:${e.chatSurface}:${Au(t)}`},Un=e=>`${e.chatSurface}:${lt()}`,Eu=e=>e.slice(0,12),Bn=e=>`centrinfo:session:${e}`,kr=e=>`centrinfo:visitor:${e}`,Sa=(e,t)=>`centrinfo:chat:${e}:${t}`,Sr=e=>`centrinfo:history:${e}`,zu=1e3,$o=20,$r=720*60*60*1e3,Nu=1440*60*1e3,Ru=(e,t)=>{try{return JSON.parse(e?.getItem(kr(t))||"{}")}catch{return{}}},Lu=(e,t,n)=>{if(!e)return Un(n);try{const a=Bn(t),i=e.getItem(a);if(i)return i;const o=Un(n);return e.setItem(a,o),o}catch{return Un(n)}},To=(e,t,n)=>{if(!e)return{};try{const a=e.getItem(Sa(t,n));return a?JSON.parse(a):{}}catch{return{}}},Co=(e,t,n)=>{const{ts:a,expiresAt:i,messages:o}=To(e,t,n);return Array.isArray(o)?typeof i=="number"&&Date.now()>i?[]:typeof a=="number"&&Date.now()-a>$r?[]:wr(o):[]},Du=(e,t,n)=>{const{ts:a,expiresAt:i,messages:o,ended:s}=To(e,t,n);return!Array.isArray(o)||o.length===0||typeof i=="number"&&Date.now()>i||typeof a=="number"&&Date.now()-a>$r?!1:s===!0||typeof a=="number"&&Date.now()-a>Nu},Pu=e=>Number.isFinite(e??NaN)?Math.max(5,Math.min(200,Math.round(e))):50,Ou=e=>Number.isFinite(e??NaN)?Math.max(1,Math.min(365,Math.round(e)))*24*60*60*1e3:$r,Ao=(e,t,n,a,i,o,s,c)=>{if(e)try{if(!o){e.removeItem(Sa(t,n));return}const d=a.filter(u=>!u.pending).slice(-s);if(d.length===0)return;const l=Date.now();Su(e,Sa(t,n),u=>JSON.stringify({ts:l,expiresAt:l+c,messages:wr(u),ended:i}),d)}catch{}},Fu=(e,t)=>{if(!e)return[];try{const n=e.getItem(Sr(t)),a=n?JSON.parse(n):[];return Array.isArray(a)?a:[]}catch{return[]}},$a=(e,t,n)=>{if(e)try{e.setItem(Sr(t),JSON.stringify(n.slice(0,$o)))}catch{}},Mo=(e,t)=>{if(e)try{const n=`centrinfo:chat:${t}:`,a=new Set([Bn(t),kr(t),Sr(t)]),i=[];for(let o=0;o<e.length;o++){const s=e.key(o);s&&(a.has(s)||s.startsWith(n))&&i.push(s)}i.forEach(o=>e.removeItem(o))}catch{}},Uu=e=>{const a=(e.find(i=>i.role==="user"&&i.content.trim())?.content||e.find(i=>i.content.trim())?.content||"").trim().replace(/\s+/g," ");return a.length>60?a.slice(0,60)+"…":a||"Conversation"},Bu=e=>({id:`live:${e.id}`,role:e.type==="chat"||e.type==="ai_resume"?"assistant":"system",content:e.content,authorName:e.authorName,liveEventType:e.type,createdAt:e.createdAt,offerReconnect:e.type==="ai_handback"&&e.reconnectOffered===!0}),Io=e=>(e??[]).find(t=>t.category==="support"&&t.enabled&&t.readiness!=="unavailable"&&(t.liveHandoff??t.id==="public_contact_support")),qu=(e,t)=>{if(t==="ai")for(let n=e.length-1;n>=0;n--){const a=e[n];if(a){if(a.reconnectOffer)return;if(a.liveEventType==="ai_handback")return a.offerReconnect?a.id:void 0}}},Vu=(e,t,n=!0)=>{const a=R(Cu(t.persistence)).current,i=Iu(t),o=R(Lu(a,i,t)),s=R(null),c=R(null),d=R(null),l=R(null),u=R(null),p=R(null),m=R(new Map),f=R(!1),_=R(void 0),h=R(null),I=R({}),x=R({}),[g,T]=$(null),[V,P]=$(()=>Co(a,i,o.current)),ee=R(null);ee.current||(ee.current=Tu(zu));const Z=R(V.length>0),Y=R(V.some(b=>b.role==="user")),[z,te]=$(!1),[U,B]=$(!1),[A,N]=$({status:"idle"}),y=R({}),[D,S]=$(()=>Du(a,i,o.current)),[O,ue]=$(()=>Ru(a,i)),[oe,Fe]=$(()=>Fu(a,i)),[_e,Te]=$(null),[Le,Ie]=$([]),[Ce,ve]=$("ai"),[Xe,ge]=$(void 0),[ie,He]=$(void 0),We=R(new Date().toISOString()),k=R(void 0),K=R(!1),j=R(0),G=R(O);X(()=>{G.current=O},[O]);const ne=g?.memoryEnabled!==!1,ye=Pu(g?.memoryMessageCap),Se=Ou(g?.memoryRetentionDays),et=F(()=>{s.current?.abort(),ee.current?.cancel(),Mo(a,i),Mo(a,Eu(t.token));const b=Un(t);o.current=b;try{a?.setItem(Bn(i),b)}catch{}Te(null),Ie([]),S(!1),Fe([]),ue({}),ve("ai"),ge(void 0),He(void 0),We.current=new Date().toISOString(),P(g?[{id:lt(),role:"assistant",content:g.greeting,availableActions:g.availableActions,actions:g.actions}]:[])},[a,i,t.token,g]),Ye=F(b=>{try{a?.setItem(kr(i),JSON.stringify(b))}catch{}},[a,i]),tt=F(b=>{const w=(b.email??"").trim().toLowerCase(),E=(G.current.email??"").trim().toLowerCase();w&&E&&w!==E&&et();const C={};b.email?.trim()&&(C.email=b.email.trim()),b.phone?.trim()&&(C.phone=b.phone.trim());const J=[b.firstName,b.lastName].filter(me=>!!me?.trim()).join(" ").trim()||b.name?.trim()||"";J&&(C.name=J),Object.keys(C).length>0&&ue(me=>{const ae={...C,...me};return Ye(ae),ae}),e.identify(o.current,b).catch(()=>{})},[e,Ye,et]),at=R(0),M=F(b=>{at.current=Date.now(),T(b),P(w=>{if(w.length===0)return[{id:lt(),role:"assistant",content:b.greeting,availableActions:b.availableActions,actions:b.actions}];const E=w.some(H=>H.role==="user"),C=w[0];return!E&&C?.role==="assistant"?[{...C,content:b.greeting,availableActions:b.availableActions,actions:b.actions},...w.slice(1)]:w})},[]);X(()=>{if(g?.memoryEnabled===!1){ee.current?.cancel();try{a?.removeItem(Sa(i,o.current))}catch{}$a(a,i,[]),Fe([]),Te(null),Ie([]),P(b=>Z.current?(Z.current=!1,g?[{id:lt(),role:"assistant",content:g.greeting,availableActions:g.availableActions,actions:g.actions}]:[]):b)}},[g,a,i]);const pe=F(async()=>{const b=await e.bootstrap();M(b)},[M,e]);X(()=>{let b=!0;const w=E=>E.messages.map(C=>wu({id:C.id,role:C.role,content:C.content,authorName:C.authorName,liveEventType:C.messageType,offerReconnect:C.messageType==="ai_handback"&&C.reconnectOffered===!0,sources:C.sources,visualization:C.visualization,artifacts:C.artifacts,createdAt:C.createdAt}));return e.history().then(E=>{if(!b||E.conversations.length===0)return;const C=E.conversations.map(ae=>({sessionId:ae.sessionId,ts:Date.parse(ae.lastSeenAt)||Date.now(),title:ae.title,ended:ae.ended}));for(const ae of E.conversations)Ao(a,i,ae.sessionId,w(ae),ae.ended,!0,ye,Se);$a(a,i,C),Fe(C);const H=E.conversations.find(ae=>ae.sessionId===E.activeSessionId);if(!H||Y.current)return;const J=w(H);o.current=H.sessionId,Z.current=J.length>0;try{a?.setItem(Bn(i),H.sessionId)}catch{}const me=J[J.length-1]?.createdAt;me&&(We.current=me),S(H.ended),P(J)}).catch(()=>{}),()=>{b=!1}},[ye,Se,i,a,e]),X(()=>{let b=!0;return at.current=Date.now(),e.bootstrap().then(w=>{b&&M(w)}),t.user&&tt(t.user),()=>{b=!1}},[M,e]),X(()=>{const b=t.configRefreshSeconds;if(!n||b<=0||typeof window>"u")return;let w=!0,E=!1;const C=Math.max(10,b)*1e3,H=()=>typeof document>"u"||document.visibilityState!=="hidden",J=async()=>{if(!(!w||E||!H())){E=!0;try{await pe()}catch{}finally{E=!1}}};Date.now()-at.current>=C&&J();const me=window.setInterval(J,C),ae=()=>{J()},xe=()=>{J()};return window.addEventListener("focus",ae),document?.addEventListener?.("visibilitychange",xe),()=>{w=!1,window.clearInterval(me),window.removeEventListener("focus",ae),document?.removeEventListener?.("visibilitychange",xe)}},[n,t.configRefreshSeconds,pe]),X(()=>{const b=o.current;ee.current.schedule(()=>Ao(a,i,b,V,D,ne,ye,Se))},[V,D,a,i,ne,ye,Se]),X(()=>{const b=ee.current,w=()=>{document.visibilityState==="hidden"&&b.flush()};return document.addEventListener("visibilitychange",w),window.addEventListener("pagehide",b.flush),()=>{document.removeEventListener("visibilitychange",w),window.removeEventListener("pagehide",b.flush),b.flush()}},[]),X(()=>{$u(a,"centrinfo:chat:")},[a]),X(()=>{if(!n||D||_e)return;const b=()=>{document.visibilityState==="visible"&&e.presence(o.current)};b();const w=window.setInterval(b,1e4);return document.addEventListener("visibilitychange",b),()=>{window.clearInterval(w),document.removeEventListener("visibilitychange",b)}},[n,D,e,_e]),X(()=>{if(!n||D||_e)return;let b=!0,w=!1,E=0,C;const H=()=>{C!==void 0&&window.clearTimeout(C),!(!b||document.hidden)&&(C=window.setTimeout(()=>{J()},Math.min(3e4,2200*2**E)))},J=async()=>{if(!(w||document.hidden||!b)){w=!0;try{const ae=await e.liveEvents(o.current,We.current);if(!b)return;if(E=0,ve(ae.mode),ge(ae.assignedAgentName||void 0),He(ae.agentTyping?ae.agentTypingName||ae.assignedAgentName||"Agent":void 0),ae.conversationEnded){S(!0),ve("ai"),ge(void 0),He(void 0),P(xe=>xe.some(re=>re.id==="live:conversation-ended")?xe:[...xe,{id:"live:conversation-ended",role:"system",content:t.strings.conversationEnded,liveEventType:"conversation_ended",createdAt:new Date().toISOString()}]);return}if(ae.events.length>0){let xe=We.current,re=Date.parse(xe);const ot=ae.events.map(Ue=>{const Ve=Date.parse(Ue.createdAt);return Number.isFinite(Ve)&&Ve>re&&(re=Ve,xe=Ue.createdAt),Bu(Ue)});We.current=xe,P(Ue=>{const Ve=new Set(Ue.map(nt=>nt.id)),Ze=ot.filter(nt=>!Ve.has(nt.id));return Ze.length>0?[...Ue,...Ze]:Ue}),ot.some(Ue=>Ue.role==="assistant")&&gn("receive")}}catch{E=Math.min(E+1,4)}finally{w=!1,H()}}},me=()=>{document.hidden?C!==void 0&&window.clearTimeout(C):J()};return document.addEventListener("visibilitychange",me),document.hidden||J(),()=>{b=!1,C!==void 0&&window.clearTimeout(C),document.removeEventListener("visibilitychange",me)}},[n,t.strings.conversationEnded,e,D,_e]),X(()=>{if(!ne){$a(a,i,[]),Fe(w=>w.length>0?[]:w);return}V.some(w=>w.role==="user")&&Fe(w=>{const E=o.current,H=[{sessionId:E,ts:Date.now(),title:Uu(V),ended:D},...w.filter(J=>J.sessionId!==E)];return $a(a,i,H),H.slice(0,$o)})},[V,D,a,i,ne]);const de=F((b,w)=>{P(E=>E.map(C=>C.id===b?{...C,...w}:C))},[]),fe=F(()=>{_.current!==void 0&&typeof window<"u"&&window.clearInterval(_.current),_.current=void 0},[]),Oe=F((b,w)=>{fe(),delete I.current[b],h.current===b&&(h.current=null),de(b,{content:w,pending:!1,streaming:!1})},[fe,de]),Ge=F((b,w,E)=>{const C=w.trim();if(!C||typeof window>"u"){Oe(b,C);return}fe(),h.current=b;const H=C.match(/\S+\s*/g)??[C],J=E&&E>0?E:H.length*95,me=Math.max(28,Math.min(150,J/Math.max(H.length,1)));let ae=0;de(b,{content:"",pending:!1,streaming:!0}),_.current=window.setInterval(()=>{ae+=1;const xe=H.slice(0,ae).join("");de(b,{content:xe,pending:!1,streaming:ae<H.length}),ae>=H.length&&(fe(),delete I.current[b],h.current===b&&(h.current=null),de(b,{content:C,pending:!1,streaming:!1}))},me)},[fe,Oe,de]),ht=F(()=>{const b=h.current;fe(),h.current=null;const w=I.current;I.current={};for(const[E,C]of Object.entries(w))de(E,{content:C,pending:!1,streaming:!1});b&&!(b in w)&&de(b,{pending:!1,streaming:!1})},[fe,de]),pt=F(b=>{if(D||_e||Ce==="ai"||typeof window>"u")return;if(k.current!==void 0&&window.clearTimeout(k.current),!b){if(!K.current)return;K.current=!1,j.current=0,e.typing(o.current,!1).catch(()=>{});return}const w=Date.now();(!K.current||w-j.current>2500)&&(K.current=!0,j.current=w,e.typing(o.current,!0).catch(()=>{})),k.current=window.setTimeout(()=>{K.current&&(K.current=!1,j.current=0,e.typing(o.current,!1).catch(()=>{}))},1600)},[e,D,_e,Ce]);X(()=>()=>{k.current!==void 0&&typeof window<"u"&&window.clearTimeout(k.current)},[]),X(()=>()=>fe(),[fe]);const yt=F((b,w,E={})=>{ht(),te(!0);const C=yr();let H=!1;const J=new AbortController;s.current=J;const me=!!(g?.allowVoiceInput&&g?.voiceOutputEnabled&&g.talkbackMode!=="text"),ae=!!E.forceVoicePlayback,xe=W=>{ae&&N(Ae=>Ae.agentId===w?{status:W,agentId:w}:Ae)};ae&&N({status:"answering",agentId:w});const re={pending:new Map,nextSeq:0,highestSeq:-1,playing:!1,ended:!1,started:!1,stopped:!1,utterance:null},ot=()=>{p.current===Mt&&(p.current=null),re.started&&(re.started=!1,B(!1),xe("done"))},Ue=()=>{re.stopped||re.started||(re.started=!0,wa("voice-first-audio",C),B(!0),xe("speaking"))},Ve=()=>typeof window<"u"&&"speechSynthesis"in window&&typeof SpeechSynthesisUtterance<"u",Ze=()=>{l.current&&re.playing&&(l.current.pause(),l.current=null),re.utterance&&(u.current===re.utterance&&(u.current=null),re.utterance=null,Ve()&&window.speechSynthesis.cancel()),re.playing=!1},nt=(W,Ae)=>{const Ee=W?.trim();if(!Ee||!Ve())return!1;const ke=new SpeechSynthesisUtterance(Ee);return ke.rate=g?.voiceSpeed??1,ke.lang=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en-US",ke.onstart=Ue,ke.onend=Ae,ke.onerror=Ae,re.utterance=ke,u.current=ke,window.speechSynthesis.speak(ke),f.current&&window.speechSynthesis.pause(),!0},ft=()=>{for(;!re.stopped&&!re.playing;){let W=re.pending.get(re.nextSeq);if(!W&&re.ended&&re.pending.size>0&&(re.nextSeq=Math.min(...re.pending.keys()),W=re.pending.get(re.nextSeq)),!W){re.ended&&ot();return}if(re.pending.delete(re.nextSeq),re.nextSeq+=1,De(W))return}},De=W=>{let Ae=!1;const Ee=()=>{Ae||(Ae=!0,u.current===re.utterance&&(u.current=null),re.utterance=null,re.playing=!1,ft())};if(!W.audioBase64||typeof Audio>"u")return re.playing=nt(W.text,Ee),re.playing;const ke=new Audio(`data:${W.mimeType||"audio/mpeg"};base64,${W.audioBase64}`);ke.playbackRate=g?.voiceSpeed??1,ke.volume=f.current?.2:1,re.playing=!0,l.current=ke;let Ke=!1,Bt=!1;const It=()=>{Ae||Bt||(Bt=!0,l.current===ke&&(l.current=null),!(!Ke&&!re.stopped&&nt(W.text,Ee))&&Ee())};return ke.onended=()=>{l.current===ke&&(l.current=null),Ee()},ke.onerror=It,ke.play().then(()=>{Ke=!0,Ue()}).catch(It),!0},Mt=()=>{re.stopped=!0,re.pending.clear(),Ze(),ot()};e.stream(b,o.current,{voicePlaybackRequested:!!E.forceVoicePlayback,clientMessageId:E.clientMessageId,attachmentId:E.attachmentId,attachmentIds:E.attachmentIds,signal:J.signal,onChunk:W=>{W&&!H&&(H=!0,wa("data-first-chunk",C)),E.forceVoicePlayback&&W&&(x.current[w]=!0),P(Ae=>Ae.map(Ee=>Ee.id===w?{...Ee,content:Ee.content+W,pending:!1,streaming:!0}:Ee))},onTextReady:()=>{P(W=>W.map(Ae=>Ae.id===w?{...Ae,pending:!1,streaming:!1}:Ae))},onReset:()=>{P(W=>W.map(Ae=>Ae.id===w?{...Ae,content:"",pending:!0,streaming:!1}:Ae)),re.pending.clear(),re.nextSeq=re.highestSeq+1,Ze()},onAudioSegment:W=>{!ae||re.stopped||W.seq<re.nextSeq||re.pending.has(W.seq)||(p.current=Mt,re.highestSeq=Math.max(re.highestSeq,W.seq),re.pending.set(W.seq,W),ft())}}).then(W=>{if(n&&!W.conversationEnded&&typeof document<"u"&&document.visibilityState==="visible"&&e.presence(o.current),W.liveMode&&(ve(W.liveMode),ge(W.assignedAgentName||void 0)),W.liveMode&&W.liveMode!=="ai"&&!W.answer.trim()){P(ke=>ke.filter(Ke=>Ke.id!==w)),xe("done");return}const Ae=!!x.current[w];delete x.current[w];const Ee=!!(E.forceVoicePlayback&&me&&!W.liveAudio&&W.audioBase64&&W.answer.trim()&&!Ae);if(Ee&&(I.current[w]=W.answer),P(ke=>ke.map(Ke=>Ke.id===w?{...Ke,content:Ee?"":W.answer||Ke.content||t.strings.emptyReply,pending:!1,streaming:Ee,error:!1,retryText:void 0,sources:W.sources,suggestedReplies:W.suggestedReplies,availableActions:W.availableActions,actions:W.actions,selectedAction:W.selectedAction,handoffOffered:W.handoffOffered,requestedContactFields:W.requestedContactFields,visualization:W.visualization,artifacts:W.artifacts}:Ke)),gn("receive"),W.liveAudio?(re.ended=!0,ft()):E.forceVoicePlayback&&!W.audioBase64&&ka(me?"Talkback expected backend TTS audio, but the chat response did not include audioBase64.":"Talkback voice was requested, but the loaded widget token config does not enable provider TTS.",{voiceOutputEnabled:g?.voiceOutputEnabled,talkbackMode:g?.talkbackMode,voiceProvider:g?.voiceProvider,hasAudioBase64:!!W.audioBase64}),E.forceVoicePlayback&&!W.liveAudio){const ke=So(l,u,W.audioBase64,W.mimeType,g?.voiceSpeed??1,xu(W.answer,W.visualization),!0,Ke=>{B(!0),xe("speaking"),Ee&&Ge(w,W.answer,Ke)},()=>{B(!1),xe("done"),Ee&&Oe(w,W.answer)});ke||xe("done"),Ee&&!ke&&Oe(w,W.answer)}W.answer&&t.onMessage?.({role:"assistant",content:W.answer}),W.handoffOffered&&t.onHandoff?.(),W.conversationEnded&&S(!0)}).catch(W=>{if(J.signal.aborted){re.stopped||Mt(),delete x.current[w],P(Ee=>Ee.flatMap(ke=>ke.id!==w?[ke]:ke.content.trim()?[{...ke,pending:!1,streaming:!1}]:[])),xe("done");return}xe("failed"),delete x.current[w];const Ae=gu(W,t.strings);de(w,{content:Ae,pending:!1,streaming:!1,error:!0,retryText:b})}).finally(()=>{wa("data-complete",C),delete x.current[w],s.current===J&&(te(!1),s.current=null,c.current?.agentId===w&&(c.current=null))})},[e,n,t,de,g?.allowVoiceInput,g?.talkbackMode,g?.voiceOutputEnabled,g?.voiceSpeed,ht]),Dt=F((b,w={})=>{const E=b.trim(),{imageUrl:C,attachmentName:H,attachmentText:J,attachmentId:me,attachmentFile:ae,forceVoicePlayback:xe,userMessageId:re}=w,ot=w.attachments??(H||me||J?[{id:me,name:H??"",text:J,file:ae}]:[]);if(!E&&!C&&ot.length===0||s.current&&!s.current.signal.aborted||D)return;Y.current=!0;let Ue=E;!Ue&&ot.length>0&&(Ue="Please look at the attached file."),!Ue&&C&&(Ue=C);const Ve=ot.map(De=>({id:De.id,name:De.name})),Ze=ot.flatMap(De=>De.id?[De.id]:[]),nt={id:re||lt(),role:"user",content:E,imageUrl:C,attachments:Ve.length>0?Ve:void 0};ot.forEach((De,Mt)=>{De.file&&(m.current.set(`${nt.id}:${Mt}`,De.file),De.id&&m.current.set(De.id,De.file))});const ft=lt();P(De=>[...!!(re&&De.some(Ae=>Ae.id===re))?De.map(Ae=>Ae.id===re?{...Ae,content:E,pending:!1,streaming:!1,imageUrl:C,attachments:nt.attachments}:Ae):[...De,nt],{id:ft,role:"assistant",content:"",pending:!0}]),gn("send"),t.onMessage?.({role:"user",content:Ue}),y.current[ft]=nt.id,c.current={userId:nt.id,agentId:ft,text:E,backendText:Ue},yt(Ue,ft,{forceVoicePlayback:xe,clientMessageId:nt.id,attachmentId:Ze[0],attachmentIds:Ze})},[D,t,yt]),_t=F((b,w,E,C,H)=>{const J=lt();P(me=>[...me.filter(ae=>ae.id!==b.agentId&&(!C.userMessageId||ae.id!==C.userMessageId)).map(ae=>ae.id===b.userId?{...ae,content:w,pending:!1,streaming:!1}:ae),{id:J,role:"assistant",content:"",pending:!0}]),H&&t.onMessage?.({role:"user",content:H}),y.current[J]=b.userId,c.current={userId:b.userId,agentId:J,text:w,backendText:E},yt(E,J,{forceVoicePlayback:C.forceVoicePlayback,clientMessageId:lt()})},[t,yt]),Vn=F((b,w={})=>{const E=b.trim();if(!E||D)return;const C=s.current&&!s.current.signal.aborted?c.current:null,H=C??d.current;if(d.current=null,!H){Dt(E,w);return}C&&s.current?.abort(),_t(H,`${H.text} ${E}`.replace(/\s+/g," ").trim(),`${H.backendText}
171
+ ${E}`.trim(),w,E)},[D,_t,Dt]),an=F(()=>{const b=s.current&&!s.current.signal.aborted?c.current:null;return b?(d.current=b,s.current?.abort(),!0):!1},[]),rt=F(()=>{const b=d.current;d.current=null,!(!b||D)&&_t(b,b.text,b.backendText,{forceVoicePlayback:!0})},[D,_t]),Pt=F(()=>s.current?.abort(),[]),bn=F(b=>{f.current=b;const w=l.current;w&&(w.volume=b?.2:1),u.current&&typeof window<"u"&&"speechSynthesis"in window&&(b?window.speechSynthesis.pause():window.speechSynthesis.resume())},[]),jt=F(()=>{p.current?.(),p.current=null,f.current=!1,ht(),N(b=>b.status==="speaking"||b.status==="answering"?{...b,status:"done"}:b),l.current?.pause(),l.current=null,typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel(),u.current=null,B(!1)},[ht]),mt=F(b=>{const w=ko(b);if(!w)return Promise.resolve(!1);ht();const E=!!(g?.allowVoiceInput&&g?.voiceOutputEnabled&&g.talkbackMode!=="text"),C=(H,J)=>new Promise(me=>{let ae=!1;So(l,u,H,J,g?.voiceSpeed??1,w,!0,()=>{ae=!0,B(!0)},()=>{B(!1),me(ae)})||(B(!1),me(!1))});return E?e.speak(w).then(H=>H.audioBase64?C(H.audioBase64,H.mimeType):(ka("Talkback prompt TTS did not return provider audio.",{providerReady:H.providerReady,message:H.message,voiceProvider:g?.voiceProvider,voiceOutputEnabled:g?.voiceOutputEnabled,talkbackMode:g?.talkbackMode}),C())).catch(H=>(ka("Talkback prompt TTS request failed before audio playback.",{error:H instanceof Error?H.message:String(H),voiceProvider:g?.voiceProvider,voiceOutputEnabled:g?.voiceOutputEnabled,talkbackMode:g?.talkbackMode}),C())):(ka("Talkback prompt wanted voice, but the loaded widget token config has provider TTS disabled.",{voiceOutputEnabled:g?.voiceOutputEnabled,talkbackMode:g?.talkbackMode,voiceProvider:g?.voiceProvider}),C())},[g?.allowVoiceInput,g?.talkbackMode,g?.voiceOutputEnabled,g?.voiceSpeed,ht,e]),Ht=F((b,w,E={})=>{if(z||D||!w)return;de(b,{content:"",pending:!0,streaming:!1,error:!1}),gn("send");const C=V.findIndex(J=>J.id===b),H=C>0?V[C-1]:void 0;yt(w,b,{...E,clientMessageId:y.current[b]??(H?.role==="user"?H.id:void 0)})},[z,D,V,de,yt]),Ot=F((b,w,E)=>{de(b,{feedback:w});const C=V.findIndex(me=>me.id===b),H=C>=0?V[C]?.content:void 0;let J;for(let me=C-1;me>=0;me--)if(V[me]?.role==="user"){J=V[me]?.content;break}e.sendFeedback({sessionId:o.current,messageId:b,rating:w,comment:E,question:J,answer:H}).catch(()=>{})},[e,de,V]),gt=F(b=>{const w=b.content.trim();if(!w)return;const E=b.id.trim()||lt();P(C=>C.some(H=>H.id===E)?C:[...C,{id:E,role:"assistant",content:w,createdAt:new Date().toISOString()}])},[]),dt=F(async(b,w,E={},C)=>{t.onAction?.(b);const H=b==="public_contact_support"||b==="public_submit_inquiry"?{actionId:b}:{},J=await e.action(b,{sessionId:o.current,...w,...H},C),me={};return E.name?.trim()&&(me.name=E.name.trim()),E.email?.trim()&&(me.email=E.email.trim()),E.phone?.trim()&&(me.phone=E.phone.trim()),Object.keys(me).length>0&&(ue(ae=>{const xe={...ae,...me};return Ye(xe),xe}),me.email&&b!=="contact"&&e.action("contact",{sessionId:o.current,...me}).catch(()=>{})),gt({id:J.receipt?.id||lt(),content:J.receipt?.content||J.note||(J.caseReference?`Action completed.
172
+ Reference: ${J.caseReference}`:"Action completed.")}),gn("receive"),J},[e,t,Ye,gt]),Qe=F(async(b,w,E)=>{const C=await e.confirmHostedBooking?.({sessionId:o.current,inquiryId:b,eventUri:w,inviteeUri:E});return C?.receipt&&gt(C.receipt),C},[e,gt]),Ft=F(b=>{const w=b.trim();w&&P(E=>E.some(C=>C.role==="assistant"&&C.content===w)?E:[...E,{id:lt(),role:"assistant",content:w}])},[]),it=F(()=>{const b=Io(g?.actions);return b?(P(w=>[...w,{id:lt(),role:"assistant",content:t.strings.reconnectPrompt,actions:[b],selectedAction:b.id,handoffOffered:!0,reconnectOffer:!0,createdAt:new Date().toISOString()}]),!0):!1},[t.strings.reconnectPrompt,g?.actions]),Ut=F(b=>{Y.current=!0;const w=lt();return P(E=>[...E,{id:w,role:"user",content:b.trim(),pending:!0}]),w},[]),Wt=F((b,w)=>{P(E=>E.map(C=>C.id===b?{...C,...w}:C))},[]),jn=F(b=>{P(w=>w.filter(E=>E.id!==b))},[]),Hn=F(async(b,w="widget")=>{if(!e.sendExplanationFeedback)throw new Error("Explanation feedback is unavailable.");await e.sendExplanationFeedback({...b,sessionId:o.current,surface:w})},[e]),Wn=F((b="widget")=>{const w=e.fetchExplanation?.bind(e);if(!w)return;const E=e.retryExplanation?.bind(e),C=H=>H;return{poll:async(H,J)=>C(await w(H,o.current,b,J)),settled:(H,J)=>{J!=="not_requested"&&P(me=>me.map(ae=>{const xe=ae.visualization?.explanation?.aiExplanation;return!xe||(xe.explanationId??ae.visualization?.explanation?.explanationId)!==H||xe.status===J?ae:{...ae,visualization:{...ae.visualization,explanation:{...ae.visualization.explanation,aiExplanation:{...xe,status:J}}}}}))},...E?{retry:async H=>C(await E(H,o.current,b))}:{}}},[e]),Gn=F((b,w)=>{e.sendFeedback({sessionId:o.current,messageId:"__csat__",rating:b,comment:w}).catch(()=>{})},[e]),Tt=F(async(b,w,E,C)=>{const H=yr();try{if(typeof b!="string"&&e.transcribeAudio)return await e.transcribeAudio(b,w,E,C);const J=typeof b=="string"?b:await mu(b);return await e.transcribe(J,w,E,C)}finally{wa("voice-transcription",H)}},[e]),Q=F(async(b,w,E=0)=>{const C=m.current.get(`${b.id}:${E}`)??(w.id?m.current.get(w.id):void 0);if(C)return C;if(!w.id||!e.fetchAttachment)throw new Error("This file is no longer available.");return e.fetchAttachment(w.id,o.current)},[e]),he=F((b,w,E,C)=>e.uploadAttachment?e.uploadAttachment(b,w,E,o.current,C):Promise.reject(new Error("File upload is unavailable")),[e]),we=F(b=>e.searchGifs(b),[e]),ce=F((b,w)=>e.demoSlots(b,w),[e]),be=F(b=>Dt("",{imageUrl:b}),[Dt]),wt=t.demo||!!t.gifApiKey,rn=F(()=>{s.current?.abort(),S(!0),e.endConversation(o.current).catch(()=>{})},[e]),Kn=F(()=>{s.current?.abort();const b=Un(t);o.current=b;try{a?.setItem(Bn(i),b)}catch{}Te(null),Ie([]),S(!1),ve("ai"),ge(void 0),He(void 0),We.current=new Date().toISOString(),P(g?[{id:lt(),role:"assistant",content:g.greeting,availableActions:g.availableActions,actions:g.actions}]:[])},[a,i,g]),Gt=F(b=>{if(ne){if(b===o.current){Te(null);return}Ie(Co(a,i,b)),Te(b)}},[a,i,ne]),Ct=F(()=>{Te(null),Ie([])},[]),At=t.starters.length>0?t.starters:g?.starterQuestions??[],kt=g?.featuredLinks??[];return{persona:g,messages:V,sending:z,assistantSpeaking:U,voiceReply:A,visitor:O,starters:At,featuredLinks:kt,hasEmail:!!O.email,liveMode:Ce,assignedAgentName:Xe,agentTypingName:ie,send:Dt,amend:Vn,hold:an,resumeHeld:rt,duckSpeaking:bn,sendGif:be,notifyTyping:pt,stop:Pt,retry:Ht,rateMessage:Ot,rateExplanation:Hn,explanationTransport:Wn,injectAssistant:Ft,reconnectSupport:it,appendUserDraft:Ut,patchMessage:Wt,removeMessage:jn,submitCsat:Gn,submitForm:dt,confirmHostedBooking:Qe,transcribe:Tt,uploadAttachment:he,loadAttachment:Q,searchGifs:we,demoSlots:ce,gifEnabled:wt,identify:tt,ended:D,endConversation:rn,startNew:Kn,history:ne?oe:[],viewingSessionId:_e,viewMessages:Le,openConversation:Gt,closeHistoryView:Ct,shutdown:et,stopSpeaking:jt,speakAssistantText:mt}},ju=({name:e,greeting:t})=>{const n=ct();return r("section",{class:"cf-empty-welcome","aria-label":qe(n.welcomeLabel,{name:e}),children:[r("span",{class:"cf-empty-welcome__eyebrow",children:n.welcomeEyebrow}),r("h2",{children:e}),r("p",{children:t||n.welcomePrompt})]})},Tr=(e,t,n)=>{if(e.key==="Escape"){e.preventDefault(),e.stopPropagation(),n();return}if(e.key!=="Tab")return;const a=Array.from(t.querySelectorAll('button, [href], textarea, input, select, [tabindex]:not([tabindex="-1"])')).filter(l=>!l.hasAttribute("disabled")&&l.getAttribute("aria-hidden")!=="true"&&l.tabIndex>=0);if(a.length===0)return;const i=t.getRootNode(),o=e.composedPath()[0],s=o instanceof HTMLElement?o:"activeElement"in i?i.activeElement:document.activeElement,c=a[0],d=a[a.length-1];e.shiftKey&&(s===c||!t.contains(s))?(e.preventDefault(),e.stopPropagation(),d.focus()):!e.shiftKey&&(s===d||!t.contains(s))&&(e.preventDefault(),e.stopPropagation(),c.focus())},Ta=new Map,Eo=e=>{if(!e||typeof document>"u"||typeof CanvasRenderingContext2D>"u")return;const t=document.createElement("canvas").getContext("2d");if(!t)return;t.fillStyle="#010203",t.fillStyle=e;const n=t.fillStyle;if(n==="#010203"&&e.trim().toLowerCase()!=="#010203")return;const a=n.match(/^#([\da-f]{6})$/i)?.[1];if(a)return[Number.parseInt(a.slice(0,2),16),Number.parseInt(a.slice(2,4),16),Number.parseInt(a.slice(4,6),16),1];const i=n.match(/^rgba?\(([\d.]+)[, ]+([\d.]+)[, ]+([\d.]+)(?:[, /]+([\d.]+))?\)$/i);if(!i)return;const o=i.slice(1,5).map(Number);if(!o.some(s=>!Number.isFinite(s)))return[o[0],o[1],o[2],o[3]??1]},Hu=(e,t="#ffffff")=>{const n=`${e??""}|${t}`;if(Ta.has(n))return Ta.get(n);const a=Eo(e),i=Eo(t)??[255,255,255,1];if(!a){Ta.set(n,void 0);return}const o=a[3],c=a.slice(0,3).map((m,f)=>m*o+i[f]*(1-o)).map(m=>{const f=m/255;return f<=.04045?f/12.92:((f+.055)/1.055)**2.4}),d=c[0]*.2126+c[1]*.7152+c[2]*.0722,l=1.05/(d+.05),u=(d+.05)/.059,p=l>=u?"#ffffff":"#0f1e2a";return Ta.set(n,p),p},Wu=e=>{const[t,n]=$("light");return X(()=>{if(e!=="auto"||typeof matchMedia>"u")return;const a=matchMedia("(prefers-color-scheme: dark)"),i=()=>n(a.matches?"dark":"light");return i(),a.addEventListener("change",i),()=>a.removeEventListener("change",i)},[e]),e==="auto"?t:e},Gu=6e4,Ku=90,zo={end:"end the call",mute:"mute your microphone",minimize:"minimize the chat",expand:"expand the view",shrink:"exit the expanded view"},No=e=>e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s']/gu," ").replace(/\s+/g," ").trim(),Yu=[{action:"shrink",re:/\b(?:exit|leave|quit|close)\b[\s\w]*\b(?:full ?screen|expanded|theat(?:er|re))\b|\bshrink\b|\bsmaller view\b/},{action:"end",re:/\b(?:end|close|stop|finish|hang ?up|quit|exit)\b[\s\w]*\b(?:call|chat|conversation|convo|session|talking)\b|\bhang ?up\b|\bgood ?bye\b|^bye(?: bye)?$/},{action:"mute",re:/\bmute\b|\bstop listening\b/},{action:"minimize",re:/\bminimi[sz]e\b|\bhide\b[\s\w]*\b(?:chat|call|window|widget)\b/},{action:"expand",re:/\bexpand\b|\bmaximi[sz]e\b|\bfull ?screen\b|\btheat(?:er|re) mode\b|\bbigger view\b/}],Zu=/^(?:yes|yeah|yep|yup|sure|correct|confirm|affirmative|go ahead|do it|please do|ok(?:ay)?)\b/,Ju=/^(?:no|nope|nah|cancel|never ?mind|don'?t|stop)\b/,Xu=/^(?:end|close|stop|finish|hang ?up|quit|exit|bye|good ?bye)\b/,Qu=e=>{const t=No(e);if(!t)return null;for(const{action:n,re:a}of Yu)if(a.test(t)){const i=t.split(" ").length;return{action:n,confident:n==="end"?i<=10:i<=6}}return null},ep=e=>`I didn't catch yes or no. Say yes to ${zo[e]}, or no to keep talking.`,tp=({transport:e,config:t,bindControls:n,composerDraftStore:a})=>{const i=t.strings,[o,s]=$(t.openByDefault),{persona:c,messages:d,sending:l,assistantSpeaking:u,visitor:p,hasEmail:m,liveMode:f,assignedAgentName:_,agentTypingName:h,starters:I,featuredLinks:x,send:g,sendGif:T,notifyTyping:V,stop:P,amend:ee,hold:Z,resumeHeld:Y,duckSpeaking:z,retry:te,rateMessage:U,rateExplanation:B,explanationTransport:A,injectAssistant:N,reconnectSupport:y,appendUserDraft:D,patchMessage:S,removeMessage:O,submitCsat:ue,submitForm:oe,confirmHostedBooking:Fe,transcribe:_e,uploadAttachment:Te,loadAttachment:Le,searchGifs:Ie,demoSlots:Ce,gifEnabled:ve,identify:Xe,ended:ge,endConversation:ie,startNew:He,history:We,viewingSessionId:k,viewMessages:K,openConversation:j,closeHistoryView:G,shutdown:ne,stopSpeaking:ye,speakAssistantText:Se}=Vu(e,t,o),et=qu(d,f),[Ye,tt]=$(null),at=R(0),M=F((v,L,le)=>{le===at.current&&tt({status:"ready",name:L,url:URL.createObjectURL(v),mimeType:v.type||"application/octet-stream"})},[]),pe=F((v,L,le)=>{const Me=L.name,Ne=++at.current;tt({status:"loading",name:Me}),Le(v,L,le).then(bt=>M(bt,Me,Ne),()=>{Ne===at.current&&tt({status:"error",name:Me})})},[Le,M]),de=F((v,L)=>M(v,L,++at.current),[M]),fe=F(()=>{at.current+=1,tt(null)},[]);X(()=>()=>{Ye?.status==="ready"&&URL.revokeObjectURL(Ye.url)},[Ye]);const Oe=!!Io(c?.actions),[Ge,ht]=$(0),[pt,yt]=$({mic:"off",processing:!1}),[Dt,_t]=$(null),[Vn,an]=$(!1),[rt,Pt]=$(!1),[bn,jt]=$(!1),[mt,Ht]=$(!1),[Ot,gt]=$(0),[dt,Qe]=$(!1),[Ft,it]=$(null),[Ut,Wt]=$(null),[jn,Hn]=$([]),[Wn,Gn]=$(""),[Tt,Q]=$(()=>{try{return localStorage.getItem("centrinfo:muted")==="1"}catch{return!1}}),he=Wu(t.theme),we=c?.soundEnabled??!0;X(()=>{uu(t.sound&&we&&!Tt)},[t.sound,we,Tt]);const ce=F(()=>{Q(v=>{const L=!v;try{localStorage.setItem("centrinfo:muted",L?"1":"0")}catch{}return L})},[]),be=R(null),wt=R(null),rn=R(null),Kn=R(0),Gt=R(!1),Ct=R(!1),At=R(null),kt=R(0),b=R(void 0),w=R(0),E=R(null),C=R(!1),H=R(null),J=R(""),me=R(()=>{}),ae=R(""),xe=R(l),re=R(g);re.current=g;const ot=R(ee);ot.current=ee;const Ue=R(_e);Ue.current=_e;const Ve=R(!1),Ze=R(!1),nt=R("");nt.current=[...d].reverse().find(v=>v.role==="assistant")?.content??"";const ft=R(u);xe.current=l,ft.current=u;const De=rt?Vn?"timeout":mt||pt.mic==="muted"?"muted":pt.mic==="unavailable"?pt.reason==="permission-denied"||pt.reason==="unsupported"?"denied":"unavailable":pt.mic==="off"||pt.mic==="starting"?"connecting":pt.mic==="hearing"?"hearing":u?"speaking":Dt??(pt.processing||l?"processing":"listening"):"idle",[Mt,W]=$(!0),[Ae,Ee]=$(!1),ke=R(0),[Ke,Bt]=$(!1),[It,on]=$(!1),Uo=R(null),[Kt,sn]=$(!1),hp=R({value:""}),mp=a??hp.current,Bo=R({confirmEnd:Ke,confirmClear:It,showHistory:Kt});Bo.current={confirmEnd:Ke,confirmClear:It,showHistory:Kt};const[gp,qo]=$(!1),ze=!!k,Ca=ze?K:d,Yn=Ca.find(v=>v.id===Ft&&v.visualization)?.visualization,Zn=Ca.find(v=>v.id===Ut&&v.visualization);X(()=>{!Ut||Zn||(Wt(null),Qe(!1))},[Ut,Zn]),X(()=>{!Ft||Yn||(it(null),Qe(!1))},[Yn,Ft]);const vn=F(()=>{s(!0),ht(0),gn("open"),t.onOpen?.(),t.onShow?.()},[t]),Et=F(()=>{s(!1),Qe(!1),it(null),t.onClose?.(),t.onHide?.(),wt.current?.focus()},[t]),Jn=F(()=>o?Et():vn(),[o,vn,Et]),bp=F(()=>Bt(!0),[]),vp=F(()=>{ie(),Bt(!1)},[ie]),xp=F(()=>{He(),Ee(!1),W(!0)},[He]);X(()=>{Ke&&Uo.current?.focus()},[Ke]),X(()=>{n({open:vn,close:Et,toggle:Jn,identify:Xe,startNew:He,endConversation:ie,shutdown:ne})},[n,vn,Et,Jn,Xe,He,ie,ne]),X(()=>{const v=d.filter(L=>L.role==="assistant"&&!L.pending).length;if(o){Kn.current=v;return}v>Kn.current&&ht(v-Kn.current)},[d,o]),X(()=>{t.onUnreadChange?.(Ge)},[Ge,t]),X(()=>{const v=t.sessionDurationMinutes;if(!v||v<=0)return;const L=setTimeout(()=>ne(),v*60*1e3);return()=>clearTimeout(L)},[t.sessionDurationMinutes,d,o,ne]),X(()=>{const v=t.customLauncherSelector;if(!v||typeof document>"u")return;let L=[];try{L=Array.from(document.querySelectorAll(v))}catch{return}const le=Me=>{Me.preventDefault(),Jn()};return L.forEach(Me=>Me.addEventListener("click",le)),()=>L.forEach(Me=>Me.removeEventListener("click",le))},[t.customLauncherSelector,Jn]);const Vo=R(!1);X(()=>{const v=t.proactiveMessage?.trim();if(!v||Vo.current)return;const L=t.proactiveOnPaths??[],le=typeof location<"u"?location.pathname:"";if(L.length>0&&!L.some(bt=>le.includes(bt)))return;const Me=`centrinfo:proactive:${t.token.slice(0,12)}`;try{if(sessionStorage.getItem(Me)==="1")return}catch{}const Ne=setTimeout(()=>{if(!(o||ge||d.some(bt=>bt.role==="user"))){Vo.current=!0;try{sessionStorage.setItem(Me,"1")}catch{}N(v),vn()}},Math.max(0,t.proactiveDelaySeconds)*1e3);return()=>clearTimeout(Ne)},[t.proactiveMessage]),X(()=>{const v=rn.current;if(!o||!v)return;const L=d[d.length-1],le=Date.now()<ke.current;L?.role==="user"||Mt||le?(requestAnimationFrame(()=>{v.scrollTop=v.scrollHeight}),Ee(!1),le&&W(!0)):Ee(!0)},[d,o,l,Mt]);const jo=R(!0);jo.current=Mt,X(()=>{const v=rn.current;if(!(!o||!v))return yc(v,{isAtBottom:()=>jo.current,onUnseen:()=>Ee(!0)})},[o,ze]);const yp=F(()=>{const v=rn.current;if(!v)return;if(Gt.current&&!ze){W(!0),Ee(!1);return}const L=v.scrollHeight-v.scrollTop-v.clientHeight<80;W(L),L&&Ee(!1)},[ze]),Yt=F(()=>{const v=rn.current;v&&(v.scrollTop=v.scrollHeight),Ee(!1),W(!0)},[]),Aa=F(()=>{ke.current=Date.now()+3e3,requestAnimationFrame(Yt)},[Yt]);X(()=>{if(!o||ze||!rt||De==="connecting")return;ke.current=Date.now()+6e4,Yt();const v=requestAnimationFrame(()=>{Yt(),requestAnimationFrame(Yt)}),L=[80,180,360].map(le=>window.setTimeout(Yt,le));return()=>{cancelAnimationFrame(v),L.forEach(le=>window.clearTimeout(le))}},[u,d,o,Yt,l,rt,ze,De]);const Ho=F(()=>{be.current?.querySelector(".cf-textarea")?.focus()},[]),Xn=F((v,L)=>{_t(v),b.current&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>_t(null),3e3),L&&!Ct.current&&Se(L)},[Se]),Ma=F(v=>{const L=H.current;if(L)return L;Aa();const le=D(v);return H.current=le,S(le,{content:J.current||v,pending:!0,streaming:!1}),le},[D,Aa,S]),qt=F(()=>{const v=H.current;if(v){if(J.current){S(v,{content:J.current,pending:!0});return}H.current=null,O(v)}},[S,O]),Zt=F(()=>{Ze.current&&(Ze.current=!1,z(!1)),Ve.current&&(Ve.current=!1,Y())},[z,Y]),ut=F(()=>{Gt.current=!1,At.current?.stop("call-ended"),At.current=null,Ve.current=!1,Ze.current=!1,Ct.current=!1,E.current=null,C.current=!1;const v=H.current;H.current=null,J.current="",v&&O(v),b.current&&window.clearTimeout(b.current),_t(null),an(!1),yt({mic:"off",processing:!1}),gt(0),Pt(!1),jt(!1),Ht(!1),Qe(!1),it(null),ye()},[O,ye]),_p=F(()=>{dt&&it(null),Qe(!dt)},[dt]),wp=F(v=>{it(v),Qe(!0)},[]),kp=F(v=>{Wt(v),Qe(!0)},[]),Ia=F(()=>{const v=Ft,L=Ut;it(null),Wt(null),Qe(!1),window.requestAnimationFrame(()=>{(L?be.current?.querySelector(`[data-explanation-message="${L}"]`)?.querySelector('[data-testid="analytics-explanation-expand"]'):Array.from(be.current?.querySelectorAll("[data-visualization-message]")??[]).find(Me=>Me.dataset.visualizationMessage===v))?.focus()})},[Ft,Ut]),Sp=F(()=>{it(null),Wt(null),Qe(!1)},[]),Wo=F((v,L,le=!1)=>{if(Aa(),L&&(S(L,{content:v,pending:!1,streaming:!1}),H.current===L&&(H.current=null)),J.current="",le){ye(),ot.current(v,{forceVoicePlayback:!0,userMessageId:L});return}Gt.current&&(Z()?ot.current(v,{forceVoicePlayback:!0,userMessageId:L}):re.current(v,{forceVoicePlayback:!0,userMessageId:L}))},[Aa,Z,S,ye]),zt=F(v=>{N(v),Se(v)},[N,Se]),Go=F(()=>{if(kt.current=Date.now(),_t(null),ft.current){Ze.current=!0,z(!0);return}Ve.current||(Ve.current=Z()),Ma("Listening...")},[z,Ma,Z]),Ko=F(v=>{const L=H.current;if(!L||Ze.current)return;const le=[J.current,v].filter(Boolean).join(" ");S(L,{content:`${le} ...`,pending:!0})},[S]),Yo=F(v=>{kt.current=Date.now();const L=[J.current,v.text].map(Nt=>Nt.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if((Ze.current||v.overlappedOutput)&&Uc(v.text,nt.current)){qt(),Zt();return}if(!L||lu(L)||du(L)){const Nt=Ze.current||Ve.current;qt(),Zt(),Nt||Xn("misunderstood");return}Ze.current&&(Ze.current=!1,P(),ye());const Me=E.current;if(Me){J.current="",qt();const Nt=No(L);if(Zu.test(Nt)||Me==="end"&&Xu.test(Nt)){E.current=null,me.current(Me);return}if(Ju.test(Nt)){E.current=null,zt("Okay, never mind — what would you like to know?");return}zt(ep(Me));return}const Ne=Qu(L);if(Ne){if(J.current="",qt(),Zt(),Ne.confident){me.current(Ne.action);return}E.current=Ne.action,zt(`Just to confirm — you want me to ${zo[Ne.action]}? Please say yes or no.`);return}const bt=Ma(L);S(bt,{content:L,pending:!0});const xn=Ve.current;Ve.current=!1,Wo(L,bt,xn)},[Ma,S,Zt,Wo,qt,Xn,zt,P,ye]),Zo=F(v=>{kt.current=Date.now();const L=Ze.current||Ve.current;if(qt(),Zt(),!(L||v.overlappedOutput||v.reason==="too-short")){if(v.reason==="transcribe-failed"){Xn("misunderstood","I couldn't transcribe that. Please try again, or type your question.");return}Xn("noise")}},[Zt,qt,Xn]),Qn=R({speechStart:Go,partial:Ko,turn:Yo,noise:Zo});Qn.current={speechStart:Go,partial:Ko,turn:Yo,noise:Zo};const Jo=F(()=>{navigator.mediaDevices?.enumerateDevices().then(v=>{Hn(v.filter(L=>L.kind==="audioinput").map((L,le)=>({deviceId:L.deviceId,label:L.label||`Microphone ${le+1}`})))}).catch(()=>{})},[]),$p=F(()=>{if(Gt.current){ut();return}if(Ho(),!c?.allowVoiceInput||!c.talkbackMode||c.talkbackMode==="text"||xe.current||ge||ze)return;kt.current=Date.now(),Ct.current=!1,Gt.current=!0,Ht(!1),Pt(!0),jt(!1),an(!1);let v=!1;const L=new qi({deviceId:ae.current||void 0,transcribe:async({audio:le,mimeType:Me,durationSeconds:Ne})=>{const bt=typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||void 0;return su(await Ue.current(le,Me,bt,Ne))},listener:{state:le=>{yt(le),le.mic!=="starting"&&le.mic!=="off"&&jt(!0),!v&&le.mic==="listening"&&(v=!0,Jo())},speechStart:()=>Qn.current.speechStart(),partial:({text:le})=>Qn.current.partial(le),turn:le=>Qn.current.turn(le),noise:le=>Qn.current.noise(le),level:le=>{const Me=performance.now();Me-w.current<Ku||(w.current=Me,gt(le))}}});At.current=L,L.setOutputActive(ft.current),L.start()},[ut,ge,Ho,c,Jo,ze]),Ea=F(()=>{const v=!Ct.current;Ct.current=v,Ht(v),At.current?.setMuted(v),v?(J.current="",qt(),Zt()):kt.current=Date.now()},[Zt,qt]),Xo=F(v=>{switch(kt.current=Date.now(),v){case"end":C.current=!0,zt("Okay — ending our call now. Goodbye!"),window.setTimeout(()=>{C.current&&(C.current=!1,ut())},2e3);break;case"mute":{Ct.current||Ea(),zt("Muted. Tap the mic button when you want me to listen again.");break}case"minimize":Et(),zt("Minimized — I'm still listening. Tap the call pill to bring the chat back.");break;case"expand":Qe(!0),zt("Sure — expanding the view.");break;case"shrink":it(null),Qe(!1),zt("Okay — back to the smaller view.");break}},[Et,ut,zt,Ea]);X(()=>{me.current=Xo},[Xo]);const Qo=R(!1);X(()=>{Qo.current&&!u&&C.current&&(C.current=!1,ut()),Qo.current=u},[u,ut]);const Tp=F(v=>{ae.current=v,Gn(v),At.current?.selectDevice(v||void 0)},[]),Cp=F(()=>{!Gt.current||Ct.current||(Ze.current=!1,Ve.current=!1,P(),ye(),kt.current=Date.now())},[P,ye]);X(()=>{At.current?.setOutputActive(u),kt.current=Date.now()},[u]),X(()=>{if(De!=="denied")return;const v=window.setTimeout(()=>ut(),3500);return()=>window.clearTimeout(v)},[ut,De]),X(()=>{if(!rt)return;const v=window.setInterval(()=>{const L=At.current;!L||Ct.current||xe.current||ft.current||L.snapshot.mic==="hearing"||L.snapshot.processing||Date.now()-kt.current<Gu||(At.current?.log.add("call-timeout"),an(!0),window.setTimeout(()=>ut(),2400))},5e3);return()=>window.clearInterval(v)},[ut,rt]);const Ap=rt&&!mt&&(l||u);X(()=>()=>ut(),[ut]);const[Mp,Ip]=$(""),es=R(!1);X(()=>{if(es.current&&!l){const v=[...d].reverse().find(L=>L.role==="assistant"&&!L.streaming&&!L.pending&&L.content);v&&Ip(v.content)}es.current=l},[l,d]),Sn(()=>{if(!o)return;const v=be.current,L=Ke||It?v?.querySelector(".cf-confirm__card"):Kt?v?.querySelector(".cf-history"):null;if(!L)return;const le=L.getRootNode(),Me="activeElement"in le?le.activeElement:document.activeElement;(!Me||!L.contains(Me))&&L.querySelector('button, [href], textarea, input, [tabindex]:not([tabindex="-1"])')?.focus()},[It,Ke,o,Kt]),X(()=>{if(!o)return;const v=be.current,L=Ke||It?v?.querySelector(".cf-confirm__card"):Kt?v?.querySelector(".cf-history"):null,le=v?.querySelectorAll(":scope > .cf-header, :scope > .cf-panel__video, :scope > .cf-panel__chat");le?.forEach(Ne=>{L?(Ne.setAttribute("inert",""),Ne.setAttribute("aria-hidden","true")):(Ne.removeAttribute("inert"),Ne.removeAttribute("aria-hidden"))}),L||requestAnimationFrame(()=>v?.querySelector(".cf-textarea")?.focus());const Me=Ne=>{if(Ne.key==="Escape"){Ne.preventDefault();const ta=Bo.current;if(ta.confirmEnd){Bt(!1);return}if(ta.confirmClear){on(!1);return}if(ta.showHistory){sn(!1);return}if(v?.querySelector(".cf-action-drawer"))return;Et();return}if(Ne.key!=="Tab"||!L)return;const bt=L.querySelectorAll('button, [href], textarea, input, [tabindex]:not([tabindex="-1"])'),xn=Array.from(bt).filter(ta=>!ta.hasAttribute("disabled"));if(xn.length===0)return;const Nt=xn[0],rs=xn[xn.length-1],is=L.getRootNode()instanceof ShadowRoot?L.getRootNode().activeElement:document.activeElement;Ne.shiftKey&&is===Nt?(Ne.preventDefault(),rs.focus()):!Ne.shiftKey&&is===rs&&(Ne.preventDefault(),Nt.focus())};return v?.addEventListener("keydown",Me),()=>{v?.removeEventListener("keydown",Me),le?.forEach(Ne=>{Ne.removeAttribute("inert"),Ne.removeAttribute("aria-hidden")})}},[o,Et,Ke,It,Kt]),X(()=>{const v=be.current;v&&(o?v.removeAttribute("inert"):v.setAttribute("inert",""))},[o]);const za=t.accentColor??t.themeTokens?.accent??c?.accentColor,ts=t.themeTokens?.accentText??Hu(za,t.themeTokens?.background??(he==="dark"?"#0f1c27":"#ffffff")),Ep={zIndex:t.zIndex,"--cf-h-pad":`${t.horizontalPadding}px`,"--cf-v-pad":`${t.verticalPadding}px`,...ts?{"--cf-accent-ink":ts}:{},...t.themeTokens?.accentStrong?{"--cf-accent-2":t.themeTokens.accentStrong}:{},...t.themeTokens?.background?{"--cf-bg":t.themeTokens.background}:{},...t.themeTokens?.surface?{"--cf-surface":t.themeTokens.surface}:{},...t.themeTokens?.surfaceMuted?{"--cf-surface-2":t.themeTokens.surfaceMuted}:{},...t.themeTokens?.text?{"--cf-text":t.themeTokens.text}:{},...t.themeTokens?.mutedText?{"--cf-muted":t.themeTokens.mutedText}:{},...t.themeTokens?.border?{"--cf-border":t.themeTokens.border}:{},...t.themeTokens?.shadow?{"--cf-shadow":t.themeTokens.shadow}:{},...t.themeTokens?.radius?{"--cf-radius":t.themeTokens.radius}:{},...t.themeTokens?.fontFamily?{"--cf-font":t.themeTokens.fontFamily}:{},...t.themeTokens?.success?{"--cf-success":t.themeTokens.success}:{},...t.themeTokens?.warning?{"--cf-warning":t.themeTokens.warning}:{},...t.themeTokens?.danger?{"--cf-danger":t.themeTokens.danger}:{},...za?{"--cf-accent":za,"--cf-accent-2":t.themeTokens?.accentStrong??`color-mix(in oklab, ${za} 76%, #14141f)`}:{}},zp=v=>g(v),Np=[...d].reverse().find(v=>v.role==="user"&&v.content.trim())?.content??"",Na=d.some(v=>v.role==="user"),ns=!!(c?.allowVoiceInput&&c?.talkbackMode&&c.talkbackMode!=="text"),as=ns,ea=!ze&&as&&!Na?Ca.filter((v,L)=>!(L===0&&v.role==="assistant")):Ca,Rp=f==="human"&&_?_:c?.agentName??i.chatName,Lp=f==="human"?i.liveSupport:f==="queued"?i.waitingForTeam:c?.offline?i.statusOffline:i.statusOnline,Ar=!ge&&!ze?c?.availableActions:void 0,Dp=!ge&&!ze?c?.actions:void 0,Mr=rt&&!bn&&De==="connecting"&&!ze;return r(jl,{value:i,children:r(Hl,{value:t.locale,children:r("div",{class:"cf-root",dir:t.dir,"data-theme":he,"data-align":t.alignment,"data-display":"floating",style:Ep,children:[dt&&o&&r("div",{class:"cf-theater-backdrop",onClick:Sp}),r("div",{ref:be,class:`cf-panel ${o?"is-open":""} ${rt?"cf-panel--call":""} ${Mr?"cf-panel--voice-connecting":""} ${dt&&o?"cf-panel--theater":""} ${Yn||Zn?"cf-panel--analytics-focus":""}`,role:"dialog","aria-modal":"false","aria-label":`${i.chatName}: ${c?.agentName??i.assistantName}`,"aria-hidden":!o,children:[Ye&&o&&r(hu,{state:Ye,onClose:fe}),r("div",{class:"cf-header",children:[r(uo,{persona:c,hideWhenMissing:!0}),r("div",{class:"cf-header__meta",children:[r("div",{class:"cf-header__name",children:Rp}),r("div",{class:`cf-header__status ${f==="ai"&&c?.offline?"cf-header__status--offline":""}`,children:r("span",{class:"cf-header__status-text",children:Lp})})]}),r("div",{class:"cf-header__actions",children:[We.length>0&&r("button",{type:"button",class:"cf-header__btn","aria-label":i.pastConversations,title:i.pastConversations,"aria-pressed":Kt,onClick:()=>sn(v=>!v),children:r(pd,{})}),Na&&!ge&&!ze&&r("button",{type:"button",class:"cf-header__btn","aria-label":i.endChat,title:i.endChat,onClick:bp,children:r(br,{})}),t.sound&&we&&r("button",{type:"button",class:"cf-header__btn","aria-label":Tt?i.unmuteSounds:i.muteSounds,"aria-pressed":Tt,onClick:ce,children:Tt?r(cd,{}):r(sd,{})}),r("button",{type:"button",class:"cf-header__btn cf-header__close","aria-label":i.closeChat,onClick:Et,children:r(pn,{})})]})]}),r("div",{class:"cf-panel__video",children:Yn?r("div",{class:"cf-analytics-focus",role:"region","aria-label":i.expandedAnalyticsResult,children:r(vo,{visualization:Yn,expanded:!0,onFollowUp:v=>{Ia(),g(v)},onClose:Ia})}):Zn?.visualization?r("div",{class:"cf-analytics-focus",role:"region","aria-label":i.expandedAnalyticsResult,children:r(Yd,{visualization:Zn.visualization,onClose:Ia,onFollowUp:v=>{Ia(),g(v)},onFeedback:ze?void 0:B,transport:ze?void 0:A("widget"),onOpenSource:t.onOpenAnalyticsSource})}):!ze&&as?r(Ad,{persona:c,starters:[],onPick:g,onFocusComposer:$p,speaking:u,voiceState:De,replyPending:rt&&l&&!u,pinned:!0,muted:mt,onToggleMute:Ea,onEndCall:ut,onTalkNow:Cp,showTalkNow:Ap,micLevel:Ot,theaterMode:dt,onToggleTheater:_p,onMinimize:Et,audioDevices:jn,selectedAudioDeviceId:Wn,onSelectAudioDevice:Tp,connectingOnly:Mr}):null}),!Mr&&r("div",{class:"cf-panel__chat",children:[t.preview&&r("div",{class:"cf-preview-banner",children:i.previewBanner}),ze&&r("div",{class:"cf-viewing-banner",children:i.viewingPast}),r("div",{class:"cf-body",ref:rn,role:"log",onScroll:yp,children:[ea.map((v,L)=>r(Kd,{msg:v,persona:c,isLast:!ze&&L===ea.length-1,visitor:p,hasEmail:m,lastQuestion:Np,showActions:!ze&&L===ea.length-1&&!!(v.handoffOffered||v.selectedAction),onPickReply:zp,onSubmitForm:oe,onDemoSlots:Ce,onConfirmHostedBooking:Fe,onRetry:te,ratable:!ze&&ea.slice(0,L).some(le=>le.role==="user"),onRate:U,onExplanationFeedback:ze?void 0:B,explanationTransport:ze?void 0:A("widget"),onOpenAnalyticsSource:t.onOpenAnalyticsSource,onExpandVisualization:ze?void 0:wp,onExpandExplanation:ze?void 0:kp,onOpenAttachment:pe,onReconnect:!ze&&!ge&&Oe&&v.id===et?y:void 0},v.id)),!Na&&!ze&&r(se,{children:[ea.length===0&&r(ju,{name:c?.agentName??i.assistantName,greeting:c?.greeting}),r(Hd,{items:I,onPick:g}),r(Wd,{items:x})]}),Ae&&r("button",{type:"button",class:"cf-newmsg",onClick:Yt,children:[r(bd,{}),i.newMessages]})]}),r("div",{class:"cf-sr-live","aria-live":"polite","aria-atomic":"true",children:Mp}),l&&!ge&&!ze&&r("div",{class:"cf-stopbar",children:r("button",{type:"button",class:"cf-stop",onClick:P,children:[r(ud,{}),i.stop]})}),ze?r("div",{class:"cf-ended",children:r("button",{type:"button",class:"cf-ended__btn",onClick:G,children:i.backToChat})}):ge?r("div",{class:"cf-ended",children:[r("p",{class:"cf-ended__text",children:i.conversationEnded}),t.csat&&Na?gp?r("p",{class:"cf-ended__text",children:i.feedbackThanks}):r("div",{class:"cf-csat",children:[r("span",{class:"cf-csat__q",children:i.csatPrompt}),r("button",{type:"button",class:"cf-csat__btn","aria-label":i.feedbackHelpful,onClick:()=>{ue("up"),qo(!0)},children:r(oo,{})}),r("button",{type:"button",class:"cf-csat__btn","aria-label":i.feedbackNotHelpful,onClick:()=>{ue("down"),qo(!0)},children:r(so,{})})]}):null,r("button",{type:"button",class:"cf-ended__btn",onClick:xp,children:i.startNewChat})]}):r(se,{children:[h?r("div",{class:"cf-live-typing","aria-live":"polite",children:qe(i.agentTyping,{name:h})}):null,Ar&&Ar.length>0&&r("div",{class:"cf-footer-actions",children:r(go,{actions:Ar,descriptors:Dp,visitor:p,onSubmitForm:oe,onDemoSlots:Ce,onConfirmHostedBooking:Fe,scheduler:c?.scheduler,translations:t.actionTranslations})},"footer-actions"),r(ou,{draftStore:mp,onSend:g,onSendGif:T,onTyping:V,disabled:l,allowVoice:ns,onTranscribe:_e,gifEnabled:ve,onSearchGifs:Ie,allowAttach:t.attachments,analyzeAttachments:!0,onUpload:Te,onPreviewAttachment:de},"composer")]}),!ge&&c?.disclaimerText&&r("div",{class:"cf-disclaimer",children:c.disclaimerText}),r("div",{class:"cf-footer",children:[r("button",{type:"button",class:"cf-footer__privacy","aria-label":i.clearDeviceData,onClick:()=>on(!0),children:i.privacyAndData}),r("span",{"aria-hidden":"true",children:"·"}),i.poweredBy," ",r("a",{href:"https://accurix.tech/centrinfo",target:"_blank",rel:"noopener noreferrer",children:"Centrinfo"})]})]}),Ke&&r("div",{class:"cf-confirm",onClick:()=>Bt(!1),children:r("div",{class:"cf-confirm__card",role:"alertdialog","aria-modal":"true","aria-label":i.endChatConfirm,onClick:v=>v.stopPropagation(),onKeyDownCapture:v=>Tr(v,v.currentTarget,()=>Bt(!1)),children:[r("div",{class:"cf-confirm__title",children:i.endChatConfirm}),r("div",{class:"cf-confirm__body",children:i.endChatConfirmBody}),r("div",{class:"cf-confirm__actions",children:[r("button",{ref:Uo,type:"button",class:"cf-confirm__btn cf-confirm__btn--cancel",onClick:()=>Bt(!1),children:i.cancel}),r("button",{type:"button",class:"cf-confirm__btn cf-confirm__btn--danger",onClick:vp,children:i.endConfirmCta})]})]})},"confirm-end"),Kt&&r("div",{class:"cf-confirm",onClick:()=>sn(!1),children:r("div",{class:"cf-history",role:"dialog","aria-modal":"true","aria-label":i.pastConversations,onClick:v=>v.stopPropagation(),onKeyDownCapture:v=>Tr(v,v.currentTarget,()=>sn(!1)),children:[r("div",{class:"cf-history__head",children:[r("span",{children:i.pastConversations}),r("button",{type:"button",class:"cf-header__btn","aria-label":i.closeHistory,onClick:()=>sn(!1),children:r(pn,{})})]}),r("div",{class:"cf-history__list",children:We.map(v=>r("button",{type:"button",class:`cf-history__item ${v.sessionId===k?"is-active":""}`,onClick:()=>{j(v.sessionId),sn(!1)},children:[r("span",{class:"cf-history__title",children:v.title}),r("span",{class:"cf-history__meta",children:[new Date(v.ts).toLocaleDateString(void 0,{month:"short",day:"numeric"}),v.ended?` · ${i.historyEnded}`:""]})]},v.sessionId))}),r("div",{class:"cf-history__footer",children:r("button",{type:"button",class:"cf-history__clear",onClick:()=>{sn(!1),on(!0)},children:i.clearDeviceData})})]})},"history"),It&&r("div",{class:"cf-confirm",onClick:()=>on(!1),children:r("div",{class:"cf-confirm__card",role:"alertdialog","aria-modal":"true","aria-label":i.clearDeviceData,onClick:v=>v.stopPropagation(),onKeyDownCapture:v=>Tr(v,v.currentTarget,()=>on(!1)),children:[r("div",{class:"cf-confirm__title",children:i.clearDeviceData}),r("div",{class:"cf-confirm__body",children:i.clearDeviceDataBody}),r("div",{class:"cf-confirm__actions",children:[r("button",{type:"button",class:"cf-confirm__btn cf-confirm__btn--cancel",onClick:()=>on(!1),children:i.cancel}),r("button",{type:"button",class:"cf-confirm__btn cf-confirm__btn--danger",onClick:()=>{on(!1),ne()},children:i.clearDeviceDataCta})]})]})},"confirm-clear")]}),rt&&!o?r(ru,{persona:c,voiceState:De,muted:mt,onToggleMute:Ea,onEndCall:ut,micLevel:Ot,onExpand:vn}):dt&&o?null:!t.hideDefaultLauncher&&r("button",{ref:wt,type:"button",class:"cf-launcher","aria-label":o?i.closeChat:Ge>0?`${i.openChat}. ${Ge===1?i.unreadMessage:qe(i.unreadMessages,{count:String(Ge)})}`:i.openChat,"aria-expanded":o,onClick:Jn,children:[t.launcherIcon?r("img",{class:"cf-launcher__img",src:t.launcherIcon,alt:""}):r(Jl,{}),!o&&Ge>0&&r("span",{class:"cf-launcher__badge","aria-hidden":"true",children:Ge>99?"99+":Ge})]})]})})})},np="https://api.accurixtech.com",ap=()=>typeof navigator<"u"&&(navigator.languages?.[0]||navigator.language)||"en",rp=(e,t)=>{if(!e)return;const n=t.trim().toLowerCase(),a=n.split("-")[0]??n,i=Object.entries(e);return i.find(([o])=>o.toLowerCase()===n)?.[1]??i.find(([o])=>o.toLowerCase()===a)?.[1]},ip=e=>{if(!e||typeof e.token!="string"||e.token.length===0)throw new Error("[centrinfo-widget] `token` is required — pass your pub_* token to Centrinfo.init({ token }).");const t=e.locale?.trim()||ap(),n=rp(e.translations,t);return{token:e.token,chatSurface:e.chatSurface??"floating",analyticsContextToken:e.analyticsContextToken,identityToken:e.identityToken,getIdentityToken:e.getIdentityToken,apiBaseUrl:(e.apiBaseUrl??np).replace(/\/$/,""),accentColor:e.accentColor,themeTokens:e.themeTokens,agentName:e.agentName?.trim()||void 0,agentAvatarUrl:e.agentAvatarUrl?.trim()||void 0,launcherIcon:e.launcherIcon,gifApiKey:e.gifApiKey,theme:e.theme??"auto",openByDefault:e.openByDefault??!1,sound:e.sound??!0,starters:e.starters??[],strings:Vl({...n?.labels,...e.labels,...n?.labels?.analytics||e.labels?.analytics?{analytics:{...n?.labels?.analytics,...e.labels?.analytics,explanation:{...n?.labels?.analytics?.explanation,...e.labels?.analytics?.explanation}}}:{}}),locale:t,dir:Gl(t,e.dir),actionTranslations:n?.actions??{},persistence:e.persistence??"local",attachments:e.attachments??!0,zIndex:e.zIndex??2147483e3,styleNonce:e.styleNonce?.trim()??"",demo:e.demo??!1,preview:e.preview??!1,alignment:e.alignment==="left"?"left":"right",horizontalPadding:typeof e.horizontalPadding=="number"?e.horizontalPadding:20,verticalPadding:typeof e.verticalPadding=="number"?e.verticalPadding:20,hideDefaultLauncher:e.hideDefaultLauncher??!1,customLauncherSelector:e.customLauncherSelector,sessionDurationMinutes:typeof e.sessionDurationMinutes=="number"?e.sessionDurationMinutes:0,configRefreshSeconds:typeof e.configRefreshSeconds=="number"?e.configRefreshSeconds:30,proactiveMessage:e.proactiveMessage,proactiveDelaySeconds:typeof e.proactiveDelaySeconds=="number"?e.proactiveDelaySeconds:5,proactiveOnPaths:e.proactiveOnPaths,csat:e.csat??!0,user:e.user,onOpen:e.onOpen,onClose:e.onClose,onShow:e.onShow,onHide:e.onHide,onUnreadChange:e.onUnreadChange,onMessage:e.onMessage,onOpenAnalyticsSource:e.onOpenAnalyticsSource,onAction:e.onAction,onHandoff:e.onHandoff}},Ro=`
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,7 +3393,7 @@ ${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)"})}
3396
+ ${Ml("cf",{surface:"var(--cf-surface)",subtle:"var(--cf-bg)",text:"var(--cf-text)",muted:"var(--cf-muted)",border:"var(--cf-border)",accent:"var(--cf-accent)",warning:"var(--cf-warning)",danger:"var(--cf-danger)",success:"var(--cf-success)",onAccent:"var(--cf-accent-ink)"})}
3357
3397
  ${xc("cf",{bg:"var(--cf-bg)",surface:"var(--cf-surface)",surface2:"var(--cf-surface-2)",text:"var(--cf-text)",muted:"var(--cf-muted)",border:"var(--cf-border)",accent:"var(--cf-accent)",onAccent:"var(--cf-accent-ink)",chart:bc,chartDark:vc,darkSelector:".cf-root[data-theme='dark']"})}
3358
3398
 
3359
3399
  @media (max-width: 639px) {
@@ -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
+ `,Cr="centrinfo-widget";class op extends HTMLElement{constructor(){super(...arguments);q(this,"controls",null);q(this,"composerDraftStore",{value:""})}mountWith(n){const a=ip(n),i=this.shadowRoot??this.attachShadow({mode:"open"});if(this.style.zIndex=String(a.zIndex),"adoptedStyleSheets"in Document.prototype&&typeof CSSStyleSheet<"u"&&typeof CSSStyleSheet.prototype.replaceSync=="function"){const s=new CSSStyleSheet;s.replaceSync(Ro),i.adoptedStyleSheets=[s]}else{const s=document.createElement("style");a.styleNonce&&(s.nonce=a.styleNonce),s.textContent=Ro,i.appendChild(s)}const o=Pc(a);Jr(r(tp,{transport:o,config:a,bindControls:s=>this.controls=s,composerDraftStore:this.composerDraftStore}),i)}open(){this.controls?.open()}close(){this.controls?.close()}toggle(){this.controls?.toggle()}identify(n){this.controls?.identify(n)}clear(){this.controls?.startNew()}shutdown(){this.controls?.shutdown()}unmount(){this.shadowRoot&&Jr(null,this.shadowRoot)}}typeof customElements<"u"&&!customElements.get(Cr)&&customElements.define(Cr,op);const sp=(e,t=document.body)=>{if(typeof document>"u")throw new Error("[centrinfo-widget] createWidget must run in a browser.");const n=document.createElement(Cr);return n.style.pointerEvents="none",n.style.position="fixed",n.style.inset="0",n.style.width="0",n.style.height="0",t.appendChild(n),n.mountWith(e),{open:()=>n.open(),close:()=>n.close(),toggle:()=>n.toggle(),show:()=>n.open(),hide:()=>n.close(),identify:a=>n.identify(a),update:a=>n.identify(a),clear:()=>n.clear(),shutdown:()=>n.shutdown(),logout:()=>n.shutdown(),destroy:()=>{n.unmount(),n.remove()}}},Lo=e=>sp(e);let Do=null;const Po=e=>{Do?.destroy();const t=Lo(e);return Do=t,t},cp=e=>e==="light"||e==="dark"||e==="auto"?e:void 0,qn=e=>{if(e==null||e.trim()==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0},lp=e=>{if(e)try{const t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch{return}},dp=e=>{const t=a=>e.getAttribute(a),n=t("data-token");return n?{token:n,apiBaseUrl:t("data-api-base")??void 0,accentColor:t("data-accent")??void 0,agentName:t("data-agent-name")??void 0,agentAvatarUrl:t("data-agent-avatar-url")??void 0,launcherIcon:t("data-launcher-icon")??void 0,gifApiKey:t("data-gif-api-key")??void 0,theme:cp(t("data-theme")),sound:t("data-sound")!=="false",openByDefault:t("data-open")==="true",demo:t("data-demo")==="true",preview:t("data-preview")==="true",alignment:t("data-alignment")==="left"?"left":void 0,horizontalPadding:qn(t("data-horizontal-padding")),verticalPadding:qn(t("data-vertical-padding")),hideDefaultLauncher:t("data-hide-launcher")==="true",styleNonce:(t("data-style-nonce")??e.nonce)||void 0,customLauncherSelector:t("data-custom-launcher-selector")??void 0,sessionDurationMinutes:qn(t("data-session-duration")),configRefreshSeconds:qn(t("data-config-refresh")),proactiveMessage:t("data-proactive-message")??void 0,proactiveDelaySeconds:qn(t("data-proactive-delay")),csat:t("data-csat")==="false"?!1:void 0,user:lp(t("data-user"))}:null},up=document.currentScript?.src||document.querySelector('script[src*="centrinfo-widget"]')?.src||"",Oo=e=>new URL(e,up||location.href).href;Fs(()=>import(Oo("centrinfo-widget-charts.js"))),Dc(()=>import(Oo("centrinfo-widget-dev.js")));const pp=e=>{typeof document>"u"||(document.readyState!=="loading"?e():document.addEventListener("DOMContentLoaded",e,{once:!0}))},fp=()=>{const e=document.currentScript??document.querySelector("script[data-token]");if(!e)return;const t=dp(e);t&&Po(t)};pp(()=>{try{fp()}catch(e){console.error("[centrinfo-widget]",e)}});const Fo=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));return St.createWidget=Lo,St.init=Po,Object.defineProperty(St,Symbol.toStringTag,{value:"Module"}),St})({});