@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,8 +1,8 @@
1
- import{createContext as e}from"preact";import{useCallback as t,useContext as n,useEffect as r,useLayoutEffect as i,useMemo as a,useRef as o,useState as s}from"preact/hooks";import{Fragment as c,jsx as l,jsxs as u}from"preact/jsx-runtime";var d=class extends Error{constructor(e,t,n){super(t),this.status=e,this.retryAfterSeconds=n,this.name=`ApiError`}};function f(e){"@babel/helpers - typeof";return f=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},f(e)}function p(e,t){if(f(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(f(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function m(e){var t=p(e,`string`);return f(t)==`symbol`?t:t+``}function h(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const g=()=>({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:[]}),_=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.`)},v=(e,t={})=>{let n=(e.disclaimerText?.trim())?.toLowerCase(),r=t.agentName?.trim()||e.agentName?.trim()||`Accurix`,i=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:r,agentAvatarUrl:i||void 0,disclaimerText:n===`sara is an ai assistant; answers may be imperfect.`||n?.includes(`sara is an ai assistant`)?`Accurix is an AI assistant; answers may be imperfect.`:e.disclaimerText}},y=[`/transcribe`,`/speak`,`/attachments`,`/stream`],b=e=>{let t=e.split(`?`)[0]??e;return y.some(e=>t.includes(`/public-chat${e}`))||t.endsWith(`/public-chat`)?6e4:15e3},x=e=>{let t=e.headers?.get?.(`Retry-After`),n=t?Number(t):NaN;return Number.isFinite(n)&&n>=0?n:void 0},S=e=>{try{let t=e.split(`.`)[1];if(!t)return null;let n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)),r=JSON.parse(n).exp;return typeof r==`number`&&Number.isFinite(r)?r*1e3:null}catch{return null}};var C=class{constructor(e,t,n,r,i={},a,o,s=`floating`){this.baseUrl=e,this.token=t,this.gifApiKey=n,this.analyticsContextToken=r,this.bootstrapOverrides=i,this.identityToken=a,this.identityTokenProvider=o,this.chatSurface=s,h(this,`cachedIdentity`,null),h(this,`identityFlight`,null)}async currentIdentityToken(){if(!this.identityTokenProvider)return this.identityToken;let e=this.cachedIdentity;return e&&Date.now()<e.refreshAt?e.token:(this.identityFlight??(this.identityFlight=(async()=>{try{let e=(await this.identityTokenProvider()??``).trim();this.identityToken=e||void 0;let t=e?S(e):null;return this.cachedIdentity=e&&t!==null?{token:e,refreshAt:t-6e4}:null,this.identityToken}finally{this.identityFlight=null}})()),this.identityFlight)}async fetchT(e,t={}){let n=new AbortController,r=!1,i=setTimeout(()=>{r=!0,n.abort()},b(e)),a=t.signal,o=()=>n.abort();a?.aborted?n.abort():a?.addEventListener(`abort`,o,{once:!0});try{return await fetch(e,{...t,signal:n.signal})}catch(e){throw r&&!a?.aborted?new d(408,`The request took too long. Please try again.`):e}finally{clearTimeout(i),a?.removeEventListener(`abort`,o)}}headers(e=!0){let t={Authorization:`Bearer ${this.token}`};return e&&(t[`Content-Type`]=`application/json`),t}async json(e){let t;try{t=await e.json()}catch{t=void 0}if(!e.ok){let n=T(t)??`request failed (${e.status})`;throw new d(e.status,n,x(e))}return t?.data??t}async bootstrap(){try{let e=await this.fetchT(`${this.baseUrl}/public-chat/bootstrap`,{headers:this.headers(!1)});if(!e.ok)return _(`bootstrap request failed with ${e.status}`),v(g(),this.bootstrapOverrides);let t=await this.json(e);return v({...g(),...t},this.bootstrapOverrides)}catch(e){return _(e instanceof Error?e.message:`bootstrap request failed`),v(g(),this.bootstrapOverrides)}}async history(){let e=await this.currentIdentityToken();if(!e)return{conversations:[]};let t=await this.fetchT(`${this.baseUrl}/public-chat/history`,{method:`POST`,headers:this.headers(),body:JSON.stringify({identityToken:e,surface:this.chatSurface})}),n=await this.json(t);return{activeSessionId:n.activeSessionId,conversations:Array.isArray(n.conversations)?n.conversations:[]}}async stream(e,t,n){let r=await this.currentIdentityToken(),i=await this.fetchT(`${this.baseUrl}/public-chat/stream`,{method:`POST`,headers:this.headers(),body:JSON.stringify({question:e,sessionId:t,clientMessageId:n.clientMessageId,attachmentId:n.attachmentId,attachmentIds:n.attachmentIds,voicePlaybackRequested:!!n.voicePlaybackRequested,analyticsContextToken:this.analyticsContextToken,identityToken:r,surface:this.chatSurface}),signal:n.signal});return!i.ok||!i.body?((i.status===429||i.status===401)&&await this.json(i),this.send(e,t,n)):E(i.body,n)}async liveEvents(e,t){let n=`sessionId=${encodeURIComponent(e)}&after=${encodeURIComponent(t)}`,r=await this.fetchT(`${this.baseUrl}/public-chat/live-events?${n}`,{headers:this.headers(!1)}),i=await this.json(r);return{mode:i.mode??`ai`,assignedAgentName:i.assignedAgentName,agentTyping:!!i.agentTyping,agentTypingName:i.agentTypingName,conversationEnded:!!i.conversationEnded,events:i.events??[]}}async typing(e,t){try{let n=await this.fetchT(`${this.baseUrl}/public-chat/typing`,{method:`POST`,headers:this.headers(),body:JSON.stringify({sessionId:e,isTyping:t})});if(!n.ok)try{await n.text()}catch{}}catch{}}async presence(e){try{await this.fetchT(`${this.baseUrl}/public-chat/presence`,{method:`POST`,headers:this.headers(),body:JSON.stringify({sessionId:e})})}catch{}}async send(e,t,n){let r=await this.currentIdentityToken(),i=await this.fetchT(`${this.baseUrl}/public-chat`,{method:`POST`,headers:this.headers(),body:JSON.stringify({question:e,sessionId:t,clientMessageId:n.clientMessageId,attachmentId:n.attachmentId,attachmentIds:n.attachmentIds,voicePlaybackRequested:!!n.voicePlaybackRequested,analyticsContextToken:this.analyticsContextToken,identityToken:r,surface:this.chatSurface}),signal:n.signal}),a=await this.json(i);return n.onChunk(a.answer??``),{answer:a.answer??``,sources:a.sources??[],suggestedReplies:a.suggestedReplies??[],availableActions:a.availableActions??[],actions:a.actions??[],selectedAction:a.selectedAction,handoffOffered:a.handoffOffered??!1,requestedContactFields:O(a.requestedContactFields),conversationEnded:a.conversationEnded??!1,liveMode:a.liveMode,assignedAgentName:a.assignedAgentName,audioBase64:a.audioBase64,mimeType:a.mimeType,visualization:a.visualization,artifacts:a.artifacts}}async action(e,t,n){let r=n?.trim()||(e===`contact-support`?`inquiry`:e),i=await this.fetchT(`${this.baseUrl}/public-chat/${r}`,{method:`POST`,headers:this.headers(),body:JSON.stringify(t)}),a=await this.json(i);return{ok:!0,note:a?.note,booking:a?.booking,caseReference:a?.caseReference||void 0,inquiryId:a?.inquiryId||a?.inquiry?.id||void 0}}async confirmHostedBooking(e){let t=await this.fetchT(`${this.baseUrl}/public-chat/book-demo/confirm`,{method:`POST`,headers:this.headers(),body:JSON.stringify(e)}),n=await this.json(t);if(!n?.booking)throw Error(`Calendar booking confirmation was unavailable.`);return n.booking}async speak(e){let t=await this.fetchT(`${this.baseUrl}/public-chat/speak`,{method:`POST`,headers:this.headers(),body:JSON.stringify({text:e})}),n=await this.json(t);return{providerReady:!!n.providerReady,message:n.message,audioBase64:n.audioBase64,mimeType:n.mimeType}}async identify(e,t){if(!(!e||!t))try{let n=await this.fetchT(`${this.baseUrl}/public-chat/identify`,{method:`POST`,headers:this.headers(),body:JSON.stringify(w(e,t))});if(!n.ok)try{await n.text()}catch{}}catch{}}async transcribe(e,t,n,r){let i=await this.fetchT(`${this.baseUrl}/public-chat/transcribe`,{method:`POST`,headers:this.headers(),body:JSON.stringify({audioBase64:e,mimeType:t,languageHint:n,durationSeconds:r})});return(await this.json(i)).text??``}async transcribeAudio(e,t,n,r){let i=new FormData;i.append(`audio`,e,`voice-recording`),i.append(`mimeType`,t||e.type||`audio/webm`),n&&i.append(`languageHint`,n),r!==void 0&&Number.isFinite(r)&&i.append(`durationSeconds`,String(r));let a=await this.fetchT(`${this.baseUrl}/public-chat/transcribe`,{method:`POST`,headers:this.headers(!1),body:i});return(await this.json(a)).text??``}async endConversation(e){try{let t=await this.fetchT(`${this.baseUrl}/public-chat/end`,{method:`POST`,headers:this.headers(),body:JSON.stringify({sessionId:e})});if(!t.ok)try{await t.text()}catch{}}catch{}}async sendFeedback(e){try{let t=await this.fetchT(`${this.baseUrl}/public-chat/feedback`,{method:`POST`,headers:this.headers(),body:JSON.stringify(e)});if(!t.ok)try{await t.text()}catch{}}catch{}}async sendExplanationFeedback(e){let t=await this.fetchT(`${this.baseUrl}/public-chat/explanation-feedback`,{method:`POST`,headers:this.headers(),body:JSON.stringify(e)});await this.json(t)}async fetchExplanation(e,t,n=`widget`,r){let i=await this.fetchT(`${this.baseUrl}/public-chat/analytics-explanations/${encodeURIComponent(e)}?sessionId=${encodeURIComponent(t)}&surface=${n}`,{method:`GET`,headers:this.headers(!1),signal:r});return this.explanationJob(i,e)}async retryExplanation(e,t,n=`widget`){let r=await this.fetchT(`${this.baseUrl}/public-chat/analytics-explanations/${encodeURIComponent(e)}/retry`,{method:`POST`,headers:this.headers(),body:JSON.stringify({sessionId:t,surface:n})});return this.explanationJob(r,e)}async explanationJob(e,t){return e.status===404||e.status===410?{status:`failed`,explanationId:t,retryAvailable:!1}:this.json(e)}async uploadAttachment(e,t,n,r,i){let a=await this.fetchT(`${this.baseUrl}/public-chat/attachments`,{method:`POST`,headers:this.headers(),body:JSON.stringify({fileBase64:e,mimeType:t,filename:n,sessionId:r,analyze:i})});return this.json(a)}async fetchAttachment(e,t){let n=await this.fetchT(`${this.baseUrl}/public-chat/attachments/${encodeURIComponent(e)}?sessionId=${encodeURIComponent(t)}`,{headers:this.headers(!1)});if(!n.ok)throw new d(n.status,`This file is no longer available.`);return n.blob()}async demoSlots(e,t){let n=`from=${encodeURIComponent(e)}&to=${encodeURIComponent(t)}`,r=await this.fetchT(`${this.baseUrl}/public-chat/demo-slots?${n}`,{headers:this.headers(!1)});if(!r.ok){let e=Error(`Calendar availability is temporarily unavailable.`);throw e.status=r.status,e}let i=await this.json(r);return{status:i?.status,reason:i?.reason,timezone:i?.timezone,slotDurationMinutes:i?.slotDurationMinutes,available:i?.available,taken:i?.taken??[],busy:i?.busy??[]}}async searchGifs(e){if(!this.gifApiKey)return[];let t=`https://tenor.googleapis.com/v2/search?q=${encodeURIComponent(e.trim()||`trending`)}&key=${this.gifApiKey}&limit=24&media_filter=tinygif,gif&contentfilter=high`;try{let e=await this.fetchT(t,{});return e.ok?((await e.json()).results??[]).map(e=>({id:e.id,url:e.media_formats?.gif?.url??e.media_formats?.tinygif?.url??``,preview:e.media_formats?.tinygif?.url??e.media_formats?.gif?.url??``,alt:e.content_description||`GIF`})).filter(e=>e.url):[]}catch{return[]}}};const w=(e,t)=>{let 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);let r={sessionId:e},i=t.externalId??t.userId;return i&&(r.externalId=i),t.email&&(r.email=t.email),t.firstName&&(r.firstName=t.firstName),t.lastName&&(r.lastName=t.lastName),t.name&&(r.name=t.name),t.phone&&(r.phone=t.phone),Object.keys(n).length>0&&(r.metadata=n),r},T=e=>{let t=e?.message;if(Array.isArray(t))return t.join(`, `);if(typeof t==`string`)return t},E=async(e,t)=>{let n=e.getReader(),r=new TextDecoder,i={answer:``,sources:[],suggestedReplies:[],availableActions:[],handoffOffered:!1,requestedContactFields:[],conversationEnded:!1},a=``;for(;;){let{done:e,value:o}=await n.read();if(e)break;a+=r.decode(o,{stream:!0});let s;for(;(s=a.indexOf(`
1
+ import{createContext as e}from"preact";import{useCallback as t,useContext as n,useEffect as r,useLayoutEffect as i,useMemo as a,useRef as o,useState as s}from"preact/hooks";import{Fragment as c,jsx as l,jsxs as u}from"preact/jsx-runtime";var d=class extends Error{constructor(e,t,n){super(t),this.status=e,this.retryAfterSeconds=n,this.name=`ApiError`}};function f(e){"@babel/helpers - typeof";return f=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},f(e)}function p(e,t){if(f(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(f(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function m(e){var t=p(e,`string`);return f(t)==`symbol`?t:t+``}function h(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const g=()=>({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:[]}),_=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.`)},v=(e,t={})=>{let n=(e.disclaimerText?.trim())?.toLowerCase(),r=t.agentName?.trim()||e.agentName?.trim()||`Accurix`,i=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:r,agentAvatarUrl:i||void 0,disclaimerText:n===`sara is an ai assistant; answers may be imperfect.`||n?.includes(`sara is an ai assistant`)?`Accurix is an AI assistant; answers may be imperfect.`:e.disclaimerText}},y=[`/transcribe`,`/speak`,`/attachments`,`/stream`],b=[`/book-demo`,`/schedule-callback`],x=e=>{let t=e.split(`?`)[0]??e;return b.some(e=>t.includes(`/public-chat${e}`))?12e4:y.some(e=>t.includes(`/public-chat${e}`))||t.endsWith(`/public-chat`)?6e4:15e3},S=e=>{let t=e.headers?.get?.(`Retry-After`),n=t?Number(t):NaN;return Number.isFinite(n)&&n>=0?n:void 0},C=e=>{try{let t=e.split(`.`)[1];if(!t)return null;let n=atob(t.replace(/-/g,`+`).replace(/_/g,`/`)),r=JSON.parse(n).exp;return typeof r==`number`&&Number.isFinite(r)?r*1e3:null}catch{return null}};var w=class{constructor(e,t,n,r,i={},a,o,s=`floating`){this.baseUrl=e,this.token=t,this.gifApiKey=n,this.analyticsContextToken=r,this.bootstrapOverrides=i,this.identityToken=a,this.identityTokenProvider=o,this.chatSurface=s,h(this,`cachedIdentity`,null),h(this,`identityFlight`,null)}async currentIdentityToken(){if(!this.identityTokenProvider)return this.identityToken;let e=this.cachedIdentity;return e&&Date.now()<e.refreshAt?e.token:(this.identityFlight??(this.identityFlight=(async()=>{try{let e=(await this.identityTokenProvider()??``).trim();this.identityToken=e||void 0;let t=e?C(e):null;return this.cachedIdentity=e&&t!==null?{token:e,refreshAt:t-6e4}:null,this.identityToken}finally{this.identityFlight=null}})()),this.identityFlight)}async fetchT(e,t={}){let n=new AbortController,r=!1,i=setTimeout(()=>{r=!0,n.abort()},x(e)),a=t.signal,o=()=>n.abort();a?.aborted?n.abort():a?.addEventListener(`abort`,o,{once:!0});try{return await fetch(e,{...t,signal:n.signal})}catch(e){throw r&&!a?.aborted?new d(408,`The request took too long. Please try again.`):e}finally{clearTimeout(i),a?.removeEventListener(`abort`,o)}}headers(e=!0){let t={Authorization:`Bearer ${this.token}`};return e&&(t[`Content-Type`]=`application/json`),t}async json(e){let t;try{t=await e.json()}catch{t=void 0}if(!e.ok){let n=E(t)??`request failed (${e.status})`;throw new d(e.status,n,S(e))}return t?.data??t}async bootstrap(){try{let e=await this.fetchT(`${this.baseUrl}/public-chat/bootstrap`,{headers:this.headers(!1)});if(!e.ok)return _(`bootstrap request failed with ${e.status}`),v(g(),this.bootstrapOverrides);let t=await this.json(e);return v({...g(),...t},this.bootstrapOverrides)}catch(e){return _(e instanceof Error?e.message:`bootstrap request failed`),v(g(),this.bootstrapOverrides)}}async history(){let e=await this.currentIdentityToken();if(!e)return{conversations:[]};let t=await this.fetchT(`${this.baseUrl}/public-chat/history`,{method:`POST`,headers:this.headers(),body:JSON.stringify({identityToken:e,surface:this.chatSurface})}),n=await this.json(t);return{activeSessionId:n.activeSessionId,conversations:Array.isArray(n.conversations)?n.conversations:[]}}async stream(e,t,n){let r=await this.currentIdentityToken(),i=await this.fetchT(`${this.baseUrl}/public-chat/stream`,{method:`POST`,headers:this.headers(),body:JSON.stringify({question:e,sessionId:t,clientMessageId:n.clientMessageId,attachmentId:n.attachmentId,attachmentIds:n.attachmentIds,voicePlaybackRequested:!!n.voicePlaybackRequested,analyticsContextToken:this.analyticsContextToken,identityToken:r,surface:this.chatSurface}),signal:n.signal});return!i.ok||!i.body?((i.status===429||i.status===401)&&await this.json(i),this.send(e,t,n)):D(i.body,n)}async liveEvents(e,t){let n=`sessionId=${encodeURIComponent(e)}&after=${encodeURIComponent(t)}`,r=await this.fetchT(`${this.baseUrl}/public-chat/live-events?${n}`,{headers:this.headers(!1)}),i=await this.json(r);return{mode:i.mode??`ai`,assignedAgentName:i.assignedAgentName,agentTyping:!!i.agentTyping,agentTypingName:i.agentTypingName,conversationEnded:!!i.conversationEnded,events:i.events??[]}}async typing(e,t){try{let n=await this.fetchT(`${this.baseUrl}/public-chat/typing`,{method:`POST`,headers:this.headers(),body:JSON.stringify({sessionId:e,isTyping:t})});if(!n.ok)try{await n.text()}catch{}}catch{}}async presence(e){try{await this.fetchT(`${this.baseUrl}/public-chat/presence`,{method:`POST`,headers:this.headers(),body:JSON.stringify({sessionId:e})})}catch{}}async send(e,t,n){let r=await this.currentIdentityToken(),i=await this.fetchT(`${this.baseUrl}/public-chat`,{method:`POST`,headers:this.headers(),body:JSON.stringify({question:e,sessionId:t,clientMessageId:n.clientMessageId,attachmentId:n.attachmentId,attachmentIds:n.attachmentIds,voicePlaybackRequested:!!n.voicePlaybackRequested,analyticsContextToken:this.analyticsContextToken,identityToken:r,surface:this.chatSurface}),signal:n.signal}),a=await this.json(i);return n.onChunk(a.answer??``),{answer:a.answer??``,sources:a.sources??[],suggestedReplies:a.suggestedReplies??[],availableActions:a.availableActions??[],actions:a.actions??[],selectedAction:a.selectedAction,handoffOffered:a.handoffOffered??!1,requestedContactFields:k(a.requestedContactFields),conversationEnded:a.conversationEnded??!1,liveMode:a.liveMode,assignedAgentName:a.assignedAgentName,audioBase64:a.audioBase64,mimeType:a.mimeType,visualization:a.visualization,artifacts:a.artifacts}}async action(e,t,n){let r=n?.trim()||(e===`contact-support`?`inquiry`:e),i=await this.fetchT(`${this.baseUrl}/public-chat/${r}`,{method:`POST`,headers:this.headers(),body:JSON.stringify(t)}),a=await this.json(i);return{ok:!0,note:a?.note,receipt:a?.receipt,booking:a?.booking,caseReference:a?.caseReference||void 0,inquiryId:a?.inquiryId||a?.inquiry?.id||void 0}}async confirmHostedBooking(e){let t=await this.fetchT(`${this.baseUrl}/public-chat/book-demo/confirm`,{method:`POST`,headers:this.headers(),body:JSON.stringify(e)}),n=await this.json(t);if(!n?.booking)throw Error(`Calendar booking confirmation was unavailable.`);return{...n.booking,receipt:n.receipt}}async speak(e){let t=await this.fetchT(`${this.baseUrl}/public-chat/speak`,{method:`POST`,headers:this.headers(),body:JSON.stringify({text:e})}),n=await this.json(t);return{providerReady:!!n.providerReady,message:n.message,audioBase64:n.audioBase64,mimeType:n.mimeType}}async identify(e,t){if(!(!e||!t))try{let n=await this.fetchT(`${this.baseUrl}/public-chat/identify`,{method:`POST`,headers:this.headers(),body:JSON.stringify(T(e,t))});if(!n.ok)try{await n.text()}catch{}}catch{}}async transcribe(e,t,n,r){let i=await this.fetchT(`${this.baseUrl}/public-chat/transcribe`,{method:`POST`,headers:this.headers(),body:JSON.stringify({audioBase64:e,mimeType:t,languageHint:n,durationSeconds:r})});return(await this.json(i)).text??``}async transcribeAudio(e,t,n,r){let i=new FormData;i.append(`audio`,e,`voice-recording`),i.append(`mimeType`,t||e.type||`audio/webm`),n&&i.append(`languageHint`,n),r!==void 0&&Number.isFinite(r)&&i.append(`durationSeconds`,String(r));let a=await this.fetchT(`${this.baseUrl}/public-chat/transcribe`,{method:`POST`,headers:this.headers(!1),body:i});return(await this.json(a)).text??``}async endConversation(e){try{let t=await this.fetchT(`${this.baseUrl}/public-chat/end`,{method:`POST`,headers:this.headers(),body:JSON.stringify({sessionId:e})});if(!t.ok)try{await t.text()}catch{}}catch{}}async sendFeedback(e){try{let t=await this.fetchT(`${this.baseUrl}/public-chat/feedback`,{method:`POST`,headers:this.headers(),body:JSON.stringify(e)});if(!t.ok)try{await t.text()}catch{}}catch{}}async sendExplanationFeedback(e){let t=await this.fetchT(`${this.baseUrl}/public-chat/explanation-feedback`,{method:`POST`,headers:this.headers(),body:JSON.stringify(e)});await this.json(t)}async fetchExplanation(e,t,n=`widget`,r){let i=await this.fetchT(`${this.baseUrl}/public-chat/analytics-explanations/${encodeURIComponent(e)}?sessionId=${encodeURIComponent(t)}&surface=${n}`,{method:`GET`,headers:this.headers(!1),signal:r});return this.explanationJob(i,e)}async retryExplanation(e,t,n=`widget`){let r=await this.fetchT(`${this.baseUrl}/public-chat/analytics-explanations/${encodeURIComponent(e)}/retry`,{method:`POST`,headers:this.headers(),body:JSON.stringify({sessionId:t,surface:n})});return this.explanationJob(r,e)}async explanationJob(e,t){return e.status===404||e.status===410?{status:`failed`,explanationId:t,retryAvailable:!1}:this.json(e)}async uploadAttachment(e,t,n,r,i){let a=await this.fetchT(`${this.baseUrl}/public-chat/attachments`,{method:`POST`,headers:this.headers(),body:JSON.stringify({fileBase64:e,mimeType:t,filename:n,sessionId:r,analyze:i})});return this.json(a)}async fetchAttachment(e,t){let n=await this.fetchT(`${this.baseUrl}/public-chat/attachments/${encodeURIComponent(e)}?sessionId=${encodeURIComponent(t)}`,{headers:this.headers(!1)});if(!n.ok)throw new d(n.status,`This file is no longer available.`);return n.blob()}async demoSlots(e,t){let n=`from=${encodeURIComponent(e)}&to=${encodeURIComponent(t)}`,r=await this.fetchT(`${this.baseUrl}/public-chat/demo-slots?${n}`,{headers:this.headers(!1)});if(!r.ok){let e=Error(`Calendar availability is temporarily unavailable.`);throw e.status=r.status,e}let i=await this.json(r);return{status:i?.status,reason:i?.reason,timezone:i?.timezone,slotDurationMinutes:i?.slotDurationMinutes,available:i?.available,taken:i?.taken??[],busy:i?.busy??[]}}async searchGifs(e){if(!this.gifApiKey)return[];let t=`https://tenor.googleapis.com/v2/search?q=${encodeURIComponent(e.trim()||`trending`)}&key=${this.gifApiKey}&limit=24&media_filter=tinygif,gif&contentfilter=high`;try{let e=await this.fetchT(t,{});return e.ok?((await e.json()).results??[]).map(e=>({id:e.id,url:e.media_formats?.gif?.url??e.media_formats?.tinygif?.url??``,preview:e.media_formats?.tinygif?.url??e.media_formats?.gif?.url??``,alt:e.content_description||`GIF`})).filter(e=>e.url):[]}catch{return[]}}};const T=(e,t)=>{let 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);let r={sessionId:e},i=t.externalId??t.userId;return i&&(r.externalId=i),t.email&&(r.email=t.email),t.firstName&&(r.firstName=t.firstName),t.lastName&&(r.lastName=t.lastName),t.name&&(r.name=t.name),t.phone&&(r.phone=t.phone),Object.keys(n).length>0&&(r.metadata=n),r},E=e=>{let t=e?.message;if(Array.isArray(t))return t.join(`, `);if(typeof t==`string`)return t},D=async(e,t)=>{let n=e.getReader(),r=new TextDecoder,i={answer:``,sources:[],suggestedReplies:[],availableActions:[],handoffOffered:!1,requestedContactFields:[],conversationEnded:!1},a=``;for(;;){let{done:e,value:o}=await n.read();if(e)break;a+=r.decode(o,{stream:!0});let s;for(;(s=a.indexOf(`
2
2
 
3
- `))!==-1;){let e=a.slice(0,s);a=a.slice(s+2);let n=D(e);if(n){if(n.event===`error`)throw new d(502,n.data?.message??`stream error`);if(n.event===`chunk`&&typeof n.data?.text==`string`)i.answer+=n.data.text,t.onChunk(n.data.text);else if(n.event===`reset`)i.answer=``,t.onReset?.();else if(n.event===`final`&&n.data)typeof n.data.answer==`string`&&(i.answer=n.data.answer),i.sources=n.data.sources??[],i.suggestedReplies=n.data.suggestedReplies??[],i.availableActions=n.data.availableActions??[],i.actions=n.data.actions??[],i.selectedAction=n.data.selectedAction,i.handoffOffered=!!n.data.handoffOffered,i.requestedContactFields=O(n.data.requestedContactFields),i.conversationEnded=!!n.data.conversationEnded,i.liveMode=n.data.liveMode,i.assignedAgentName=n.data.assignedAgentName,i.visualization=n.data.visualization,i.artifacts=n.data.artifacts,i.audioBase64=n.data.audioBase64,i.mimeType=n.data.mimeType,t.onTextReady?.();else if(n.event===`audio`&&n.data)typeof n.data.seq==`number`?(i.liveAudio=!0,t.onAudioSegment?.({seq:n.data.seq,audioBase64:n.data.audioBase64??``,mimeType:n.data.mimeType,text:typeof n.data.text==`string`?n.data.text:void 0})):(i.audioBase64=n.data.audioBase64,i.mimeType=n.data.mimeType);else if(n.event===`done`)return i}}}return i},D=e=>{let t=`message`,n=[];for(let r of e.split(`
3
+ `))!==-1;){let e=a.slice(0,s);a=a.slice(s+2);let n=O(e);if(n){if(n.event===`error`)throw new d(502,n.data?.message??`stream error`);if(n.event===`chunk`&&typeof n.data?.text==`string`)i.answer+=n.data.text,t.onChunk(n.data.text);else if(n.event===`reset`)i.answer=``,t.onReset?.();else if(n.event===`final`&&n.data)typeof n.data.answer==`string`&&(i.answer=n.data.answer),i.sources=n.data.sources??[],i.suggestedReplies=n.data.suggestedReplies??[],i.availableActions=n.data.availableActions??[],i.actions=n.data.actions??[],i.selectedAction=n.data.selectedAction,i.handoffOffered=!!n.data.handoffOffered,i.requestedContactFields=k(n.data.requestedContactFields),i.conversationEnded=!!n.data.conversationEnded,i.liveMode=n.data.liveMode,i.assignedAgentName=n.data.assignedAgentName,i.visualization=n.data.visualization,i.artifacts=n.data.artifacts,i.audioBase64=n.data.audioBase64,i.mimeType=n.data.mimeType,t.onTextReady?.();else if(n.event===`audio`&&n.data)typeof n.data.seq==`number`?(i.liveAudio=!0,t.onAudioSegment?.({seq:n.data.seq,audioBase64:n.data.audioBase64??``,mimeType:n.data.mimeType,text:typeof n.data.text==`string`?n.data.text:void 0})):(i.audioBase64=n.data.audioBase64,i.mimeType=n.data.mimeType);else if(n.event===`done`)return i}}}return i},O=e=>{let t=`message`,n=[];for(let r of e.split(`
4
4
  `))r.startsWith(`event:`)?t=r.slice(6).trim():r.startsWith(`data:`)&&n.push(r.slice(5).trim());if(n.length===0)return{event:t};try{return{event:t,data:JSON.parse(n.join(`
5
- `))}}catch{return{event:t}}},O=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):[];let k=()=>import(`./dev-transports-D6oaj_ri.mjs`);const A=e=>new C(e.apiBaseUrl,e.token,e.gifApiKey,e.analyticsContextToken,{agentName:e.agentName,agentAvatarUrl:e.agentAvatarUrl},e.identityToken,e.getIdentityToken,e.chatSurface),j=e=>{let t=t=>(...n)=>e().then(e=>e[t].apply(e,n));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`)}},M=e=>e.demo?j(async()=>new(await(k())).MockTransport):e.preview?j(async()=>{let{PreviewTransport:t}=await k();return new t(A(e),e.strings)}):A(e),N=(e,t=11)=>{let n=0;for(let t of e)n+=(t.codePointAt(0)??0)>11904?1:.58;return Math.ceil(n*t)},P=(e,t=12,n=20)=>Math.max(n,Math.ceil(e)+t),F=(e,t=12,n=8)=>Math.ceil(t+e+n),I=(e,t,n=11)=>e.length===0||Math.max(...e.map(e=>N(e,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},L=e=>Array.isArray(e)?e:e?[e]:[],R=(e,t)=>{let n=[];for(let r of e)if(Array.isArray(r.data))for(let e of r.data){let r=e;e&&typeof e==`object`&&!Array.isArray(e)&&(r=e.value),Array.isArray(r)&&(r=r[t?0:1]),typeof r==`number`&&Number.isFinite(r)&&n.push(r)}return n},ee=(e,t,n)=>{let r=e.axisLabel?.formatter,i=R(t,n),a=typeof e.min==`number`?e.min:Math.min(0,...i),o=typeof e.max==`number`?e.max:Math.max(0,...i)*1.1,s=i.length||e.min!==void 0?[a,o]:[];return s.length?Math.max(...s.map(e=>{let t=String(e);try{typeof r==`function`&&(t=String(r(e)))}catch{}return N(t)})):N(`00000`)},z=(e,t)=>{if(!(t>0)||Array.isArray(e.grid))return e;let n=L(e.xAxis),r=L(e.yAxis),i=r[0]?.type===`category`,a=i?r[0]:n[0],o=i?n[0]:r[0];if(!a||a.type!==`category`||!o||o.type!==`value`)return e;let s=t<420,c=L(e.series),l={...e.grid??{}},u=(a.data??[]).map(e=>String(e&&typeof e==`object`?e.value??``:e)),d={...e,grid:l},f={...a},p={...o},m=0;if(i)s&&(m=Math.min(t*.35,90),f={...f,axisLabel:{...a.axisLabel,width:Math.floor(m),overflow:`truncate`,ellipsis:`…`}},l.left=8);else{let e=ee(o,c,!1);if(m=e+8,s&&!o.name)l.left=8;else if(o.name){let t=P(e);p={...p,nameGap:Math.min(o.nameGap??t,t)},m+=18}}if(!i){let e=typeof l.left==`number`?l.left:0,n=typeof l.right==`number`?l.right:0,r=I(u,Math.max(40,t-e-n-m)/Math.max(1,u.length)),i=a.axisLabel?.fontSize??11,o=i+2;if(r.kind===`truncate`||r.kind===`rotate`){let e=r.kind===`rotate`?r.rotate:0;if(f.axisLabel={...a.axisLabel,interval:0,hideOverlap:!1,rotate:e,width:r.width,overflow:`truncate`,ellipsis:`…`},e){let t=Math.max(0,...u.map(e=>N(e,i))),n=Math.min(r.width,t);o=Math.ceil(n*Math.sin(e*Math.PI/180))+i}}a.name&&s?f.nameGap=Math.min(a.nameGap??99,F(o,6,4)):s&&l.containLabel===!0&&typeof l.bottom==`number`&&(l.bottom=Math.min(l.bottom,8))}return i?(d.yAxis=Array.isArray(e.yAxis)?[f,...r.slice(1)]:f,d.xAxis=Array.isArray(e.xAxis)?[p,...n.slice(1)]:p):(d.xAxis=Array.isArray(e.xAxis)?[f,...n.slice(1)]:f,d.yAxis=Array.isArray(e.yAxis)?[p,...r.slice(1)]:p),d},B=e=>!!(e?.headline?.trim()||e?.summary?.trim()),V=(e,t={})=>{let n=e?.explanation??void 0,r=e?.businessAnalysis?.explanation??void 0,i=[t.requested??void 0,n?.source===`ai_grounded`?n:void 0,r,n];for(let e of i)if(e&&B(e))return e;return t.fallback?.()},H={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`},te=[{id:`wrong_numbers`,label:`Wrong numbers`},{id:`missing_comparison`,label:`Missing comparison`},{id:`unclear`,label:`Unclear`},{id:`too_long`,label:`Too long`}],ne=e=>e===`ai_grounded`||e===`rag_deterministic_analysis`,U=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``}},W=e=>{switch(e){case`confirmed_zero`:return`confirmed`;case`empty_bucket`:case`unconfirmed_zero`:return`caution`;case`missing`:return`missing`;default:return`neutral`}},G=e=>!e||e===`observed`||e===`confirmed_zero`,K=e=>{let 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`},q=/^\d{4}-\d{2}-\d{2}$/,J=(e,t,n,r)=>{try{return new Intl.DateTimeFormat(t,r?{...n,timeZone:r}:n).format(e)}catch{return new Intl.DateTimeFormat(t,n).format(e)}},Y=(e,t)=>J(e,`en-CA`,{year:`numeric`,month:`2-digit`,day:`2-digit`},t),re=(e,t={})=>{let n=e?.trim();if(!n)return``;let r=new Date(n);if(Number.isNaN(r.getTime()))return``;let i={hour:`2-digit`,minute:`2-digit`,hour12:!1},a=Y(r,t.timezone)===Y(t.now??new Date,t.timezone);return J(r,t.locale,a?i:{...i,month:`short`,day:`numeric`},t.timezone)},ie=(e,t={})=>{let n=e.timezone?.trim(),r=re(e.checkedAt,{...t,timezone:n});return[n?`Times in ${n}`:``,r?`Checked ${r}`:``].filter(Boolean).join(` · `)},ae=(e,t,n)=>{let r=e?.trim();if(!r)return``;if(q.test(r)){let e=new Date(`${r}T00:00:00Z`);return Number.isNaN(e.getTime())?r:J(e,t,{day:`numeric`,month:`short`,year:`numeric`},`UTC`)}let i=new Date(r);return Number.isNaN(i.getTime())?r:J(i,t,{day:`numeric`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1},n)},oe=(e,t={})=>{if(!e)return``;let n=e.timezone?.trim()||t.timezone?.trim(),r=ae(e.start,t.locale,n),i=ae(e.end,t.locale,n);return r&&i?`${r} – ${i} (end not included)`:r?`From ${r}`:i?`Before ${i}`:``},se=(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`};let r=e=>{if(!e)return``;let t=q.test(e)?new Date(`${e}T00:00:00`):new Date(e);return Number.isNaN(t.getTime())?``:new Intl.DateTimeFormat(n,{month:`short`,day:`numeric`}).format(t)},i=r(e.dataAsOf),a=r(t);return{label:`${a?`Checked ${a} · `:``}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`}},ce=(e,t)=>{let n=typeof e.value==`number`&&Number.isFinite(e.value)?e.value:null,r=typeof t.value==`number`&&Number.isFinite(t.value)?t.value:null;return e.status===`missing`||t.status===`missing`||n===null||r===null?{kind:`not_comparable`,reason:`missing`,label:H.notComparable}:G(e.status)?G(t.status)?r===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-r)/Math.abs(r)*100}:{kind:`not_comparable`,reason:`previous_no_records`,label:H.notComparable}:{kind:`not_comparable`,reason:`current_no_records`,label:`${e.label?.trim()||`Current period`}: no records yet`}},le=e=>e&&[`day`,`week`,`month`,`quarter`,`year`].includes(e)?e:`period`,ue=e=>e===`day`?`vs yesterday at this time`:`vs same point last ${le(e)}`,de=(e,t)=>{if(!e.cutoffAt)return;let n=new Date(e.cutoffAt);if(Number.isNaN(n.getTime()))return;let r=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:r}).format(n)}catch{i=n.toISOString()}let a=e.grain===`day`?`on both days`:`in both ${le(e.grain)}s`,o=e.cutoffSource===`data_as_of`?`, the time of the latest record`:``;return`Compared up to ${i} ${a}${o}${r?` (${r})`:``}`},fe=(e,t,n,r={format:String})=>{if(!e||!e.comparisonBasis||e.comparisonBasis===`complete`)return;let i=e.comparisonBasis,a=ce(t,n);if(a.kind===`not_comparable`&&a.reason!==`previous_zero`)return{basis:i,kind:`neutral`,tone:`neutral`,label:a.label,copy:``,reason:a.reason};let o=r.format,s=e.currentPeriod?.label||t.label||`Current period`,c=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,d=e.grain===`day`?`full day`:`full ${le(e.grain)}`,f=u===void 0?void 0:`${c} ${d}: ${o(u)}`,p=u===void 0?void 0:`${d.charAt(0).toUpperCase()}${d.slice(1)}: ${o(u)}`;if(i===`like_for_like`&&typeof e.previousToDateValue==`number`&&typeof l==`number`){let n=ce({value:l,status:t.status},{value:e.previousToDateValue,status:`observed`}),a=de(e,r.locale);if(n.kind===`change`){let t=n.percent;return{basis:i,kind:`change`,percent:t,tone:t===0?`neutral`:t>0?`positive`:`negative`,label:`${t>0?`↑`:t<0?`↓`:`→`} ${Math.abs(t).toFixed(1)}%`,copy:ue(e.grain),secondary:f,compactSecondary:p,title:a}}return{basis:i,kind:`neutral`,tone:`neutral`,label:n.label,copy:ue(e.grain),secondary:f,compactSecondary:p,title:a,reason:n.reason}}if(i===`not_comparable`)return{basis:i,kind:`neutral`,tone:`neutral`,label:`Not comparable`,copy:e.reason||``,reason:e.reason};let m=[typeof l==`number`?`${s} so far: ${o(l)}`:`${s}: in progress`];return u!==void 0&&m.push(`${c}: ${o(u)} (${d})`),{basis:`current_in_progress_no_time`,kind:`neutral`,tone:`neutral`,label:m.join(` · `),copy:``,title:e.reason,reason:e.reason}},pe=e=>e?.grain===`day`?`Yesterday at this time`:`Same point last ${le(e?.grain)}`,me=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):``},he=(e,t)=>{let n=me(t);if(!(!n||!e)){if(e.previousPeriod?.start&&me(e.previousPeriod.start)===n)return`previous`;if(e.currentPeriod?.start&&me(e.currentPeriod.start)===n)return`current`}},X=(e,t,n,r={format:String})=>{if(!e||!e.series?.length||!e.comparisonBasis||e.comparisonBasis===`complete`)return;let i=he(e,t);if(!i)return;let a=String(n??``),o=e.series.find(e=>e.key===a);if(!o)return;let s=e.comparisonBasis;if(i===`previous`){let e=s===`like_for_like`&&typeof o.previousToDateValue==`number`;return{side:i,basis:s,toDate:e,plotValue:e?o.previousToDateValue:void 0,fullValue:o.previousFullValue}}return{side:i,basis:s,toDate:!1,display:fe({...e,currentValue:o.currentValue,previousToDateValue:o.previousToDateValue,previousFullValue:o.previousFullValue},{value:o.currentValue,status:o.currentValue===void 0?`missing`:`observed`},{value:o.previousFullValue,status:o.previousFullValue===void 0?`missing`:`observed`},r)}},ge=e=>!!(e&&e.seriesField&&e.series?.length&&e.comparisonBasis&&e.comparisonBasis!==`complete`&&e.comparisonBasis!==`not_comparable`),_e=e=>{if(!ge(e))return;let t=e.currentPeriod?.label||`Current period`;return e.comparisonBasis===`like_for_like`?`${t} so far, compared with ${pe(e).toLowerCase()}`:`${t} so far; the previous period is shown in full, so the bars are not like for like`},ve=(e,t,n)=>{if(!t)return[];if(t.side===`previous`)return typeof t.fullValue==`number`&&t.toDate?[`Full ${e?.grain===`day`?`day`:le(e?.grain)}: ${n(t.fullValue)}`]:[];let r=t.display;return r?r.kind===`change`&&r.percent!==void 0?[`${r.label} ${r.copy}`.trim()]:r.kind===`neutral`&&r.label&&t.basis===`like_for_like`?[r.label]:[]:[]},ye=`__previous_to_date`,be=(e,t)=>{let n=e.trim().toLowerCase(),r=t.trim().toLowerCase();return n===r||n.endsWith(`.${r}`)||r.endsWith(`.${n}`)},xe=e=>{let t=e.periodComparison,n=e.rows;if(!n?.length||!ge(t)||t.comparisonBasis!==`like_for_like`||!t.series?.some(e=>typeof e.previousToDateValue==`number`))return e;let r=e.columnMetadata??[],i=e.columns?.filter(Boolean)??(r.length?r.map(e=>String(e.key??e.name??``)).filter(Boolean):Object.keys(n[0]??{}));if(i.includes(ye))return e;let a=i.find(e=>be(t.seriesField,e));if(!a)return e;let o=e=>r.find(t=>(t.key??t.name)===e),s=i.find(e=>{let t=o(e);return t?.semanticRole===`date`||t?.role===`date`||t?.dataType===`date`||t?.dataType===`datetime`}),c=(t.measureField?i.find(e=>be(t.measureField,e)):void 0)??i.find(e=>o(e)?.semanticRole===`measure`),l=n.map(e=>{let n=s?he(t,e[s]):`current`,r=t.series?.find(t=>t.key===String(e[a]??``)),i=n&&typeof r?.previousToDateValue==`number`?r.previousToDateValue:null;return{...e,[ye]:i}}),u={...(c?o(c):void 0)??{dataType:`number`,semanticRole:`measure`},key:ye,name:void 0,label:`Previous to date`,aggregation:`none`,sourceField:void 0,priority:`secondary`,groupable:!1,filterable:!1};return{...e,rows:l,columns:e.columns?[...e.columns,ye]:e.columns,columnMetadata:r.length?[...r,u]:e.columnMetadata}},Se=e=>!!(e?.lastPeriodInProgress||e?.caveats?.some(e=>e.code===`incomplete_final_period`)||e?.periodComparison?.currentPeriod?.inProgress),Z=(e,t)=>t(String(e??``).replace(/\s+/g,` `).trim()).trim(),Ce=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e.toLocaleString(t):``,we=e=>{let 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},Te=(e,t={})=>{let{locale:n}=t,r={...H,...t.copy},i=t.cleanText??(e=>e),a=e.timezone?.trim()||void 0,o=new Map;for(let t of e.evidenceItems??[])t?.id?.trim()&&!o.has(t.id.trim())&&o.set(t.id.trim(),t);let s=[],c={},l=r=>{let l=r?.trim();if(!l)return;let u=c[l];if(u)return{id:l,index:u.index};let d=o.get(l);if(!d)return;let f=d.valueStatus,p=U(f)||(f===`observed`?`observed`:``),m=d.source?.kind,h={id:l,index:s.length+1,text:Z(d.text,i),...d.metric?.trim()?{metric:d.metric.trim()}:{},...d.period?.label?.trim()?{periodLabel:d.period.label.trim()}:{},...(()=>{let e=oe(d.period,{locale:n,timezone:a});return e?{periodRange:e}:{}})(),...d.period?.timezone?.trim()||a?{timezone:d.period?.timezone?.trim()||a}:{},...d.filters?.length?{filters:d.filters.map(e=>e.trim()).filter(Boolean)}:{},...(()=>{let e=Ce(d.value,n);return e?{valueText:e}:{}})(),...p?{statusLabel:p}:{},statusTone:W(f),...d.statusReason?.trim()?{statusReason:Z(d.statusReason,i)}:{},...m===`card`?{sourceLabel:H.sourceCard}:m===`supporting_query`?{sourceLabel:H.sourceSupportingQuery}:{},sourceTargets:we(d.source),...(()=>{let r=re(d.checkedAt??e.checkedAt,{locale:n,timezone:a,now:t.now});return r?{checkedText:r}:{}})()};return h.filters&&h.filters.length===0&&delete h.filters,s.push(h),c[l]=h,{id:l,index:h.index}},u=e=>{let t=new Set,n=[];for(let r of e??[]){let e=l(r);e&&!t.has(e.id)&&(t.add(e.id),n.push(e))}return n},d=ne(e.source)||e.level===`detailed`,f=Z(e.headline,i)||Z(e.summary,i),p={text:f,citations:u(e.headlineEvidenceIds)},m=Z(e.summary,i),h=m&&m!==f?{text:m,citations:u(e.summaryEvidenceIds)}:void 0;if(!h&&m&&e.summaryEvidenceIds?.length)for(let t of u(e.summaryEvidenceIds))p.citations.some(e=>e.id===t.id)||p.citations.push(t);let g=(e.periods??[]).filter(e=>e?.label?.trim()).map(e=>{let t=e.valueStatus,r=U(t),a=e.valueText?.trim()||Ce(e.value,n)||(t===`missing`?`—`:``),s=r?e.statusReason?.trim()||o.get(e.evidenceId?.trim()??``)?.statusReason?.trim():``,c=l(e.evidenceId);return{key:e.evidenceId||`${e.label}-${e.start??``}-${e.end??``}`,label:e.label.trim(),valueText:a,...t?{status:t}:{},statusLabel:r,statusTone:W(t),inProgress:!!e.inProgress,current:!!e.current,...s?{reason:Z(s,i)}:{},...c?{citation:c}:{}}}),_=t.maxConclusions??4,v=(e.evidenceStatements??[]).map(e=>({text:Z(e.text,i),citations:u(e.evidenceIds)})).filter(e=>e.text),y=(v.length>0?v:(e.evidence??[]).map(e=>Z(e,i)).filter(Boolean).map(e=>({text:e,citations:[]}))).filter((e,t,n)=>n.findIndex(t=>t.text===e.text)===t).filter(e=>e.text!==p.text&&e.text!==h?.text).slice(0,_),b=Z(e.businessMeaning,i),x=b?{text:b,citations:u(e.businessMeaningEvidenceIds)}:void 0,S=[],C=e=>{e.text&&!S.some(t=>t.text===e.text)&&S.push(e)},w=(e.limitations??[]).map(e=>e.toLowerCase());for(let e of g){let t=w.some(t=>t.includes(e.label.toLowerCase())&&t.includes(`in progress`));e.inProgress&&!t&&C({kind:`in_progress`,text:`${e.label} is still in progress, so its total can still change.`,...e.citation?{citation:e.citation}:{}}),(e.status===`empty_bucket`||e.status===`unconfirmed_zero`)&&C({kind:`no_records`,text:`${e.label} has no records yet. This is not a confirmed 0${e.reason?`: ${e.reason.replace(/\.$/,``)}`:``}.`,...e.citation?{citation:e.citation}:{}}),e.status===`missing`&&C({kind:`missing`,text:`${e.label} is missing${e.reason?`: ${e.reason.replace(/\.$/,``)}`:``}.`,...e.citation?{citation:e.citation}:{}})}e.currentPeriodInProgress&&!g.some(e=>e.inProgress)&&C({kind:`in_progress`,text:`The current period is still in progress, so its total can still change.`});for(let t of e.missing??[]){if(!t?.label?.trim()||!t.reason?.trim())continue;let e=l(t.evidenceId);C({kind:`missing`,text:Ee(t),...e?{citation:e}:{}})}(e.dataFreshness?.status===`delayed`||e.dataFreshness?.status===`no_data`)&&C({kind:`freshness`,text:se(e.dataFreshness,e.checkedAt,n).description});for(let t of e.limitations??[]){let e=Z(t,i);e&&C({kind:`limitation`,text:e})}let T=(e.possibleDrivers??[]).map(e=>({title:Z(e.hypothesis,i),howToCheck:Z(e.howToCheck,i),citations:u(e.evidenceIds)})).filter(e=>e.title).slice(0,t.maxCauses??3),E=(e.recommendations??[]).map(e=>({title:Z(e.action,i),why:Z(e.why,i),...e.successMetric?.trim()?{watch:Z(e.successMetric,i)}:{},citations:u(e.evidenceIds)})).filter(e=>e.title).slice(0,t.maxRecommendations??3),D=Z(e.forecast?.text,i),O=D?{badge:K(e.forecast?.qualityStatus),text:D,...e.forecast?.limitations?.trim()?{note:Z(e.forecast.limitations,i)}:{}}:void 0,k=(e.followUps??[]).map(e=>Z(e,i)).filter(Boolean).filter((e,t,n)=>n.indexOf(e)===t).slice(0,t.maxFollowUps??4);for(let e of o.keys())l(e);let A=Z(e.conversationalPreface,i);return{...e.explanationId?.trim()?{explanationId:e.explanationId.trim()}:{},ai:d,lead:{eyebrow:r.eyebrow,provenance:d?r.provenanceAI:e.level===`basic`?r.basicExplanation:r.provenanceGoverned,...A?{preface:A}:{},headline:p,...h?{summary:h}:{}},comparison:g,conclusions:y,...x?{businessMeaning:x}:{},limits:S,checkedLine:ie(e,{locale:n,now:t.now}),investigate:{causes:T,recommendations:E,...O?{outlook:O}:{},followUps:k},hasInvestigate:T.length>0||E.length>0||!!O||k.length>0||s.length>0,evidence:s,evidenceById:c,sourceNote:d?r.sourceNoteAI:r.sourceNoteGoverned}},Ee=e=>`${e.label.trim()} could not be established: ${e.reason.trim()}`,De=e=>`[${e.index}]`,Oe=(e,t)=>{let n={...H,...t},r=[];e.metric&&r.push({key:`metric`,label:n.evidenceMetric,value:e.metric});let i=[e.periodLabel,e.periodRange].filter(Boolean).join(` · `);i&&r.push({key:`period`,label:n.evidencePeriod,value:i}),e.timezone&&r.push({key:`timezone`,label:n.evidenceTimezone,value:e.timezone}),e.filters?.length&&r.push({key:`filters`,label:n.evidenceFilters,value:e.filters.join(`; `)});let a=[e.valueText,e.statusLabel].filter(Boolean).join(` · `);return a&&r.push({key:`value`,label:n.evidenceValue,value:a}),e.statusReason&&r.push({key:`reason`,label:n.evidenceStatus,value:e.statusReason}),e.sourceLabel&&r.push({key:`source`,label:n.evidenceSource,value:e.sourceLabel}),e.checkedText&&r.push({key:`checked`,label:n.evidenceChecked,value:e.checkedText}),r},ke=e=>{let t=new Set(te.map(e=>e.id)),n=Array.from(e.comment??``).map(e=>{let t=e.charCodeAt(0);return t<32||t>=127&&t<=159?` `:e}).join(``).replace(/\s+/g,` `).trim(),r=e.rating===`down`?[...new Set(e.reasons??[])].filter(e=>t.has(e)).slice(0,4):[];return{explanationId:e.explanationId,rating:e.rating,...r.length?{reasons:r}:{},...e.rating!==`clear`&&n?{comment:Array.from(n).slice(0,500).join(``)}:{},...e.modelId?{modelId:e.modelId}:{},...typeof e.modelVersion==`number`&&e.modelVersion>0?{modelVersion:e.modelVersion}:{}}},Ae=(e,t)=>{let n=`.${e}-xp`;return`
5
+ `))}}catch{return{event:t}}},k=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):[];let A=()=>import(`./dev-transports-DqSPyIEz.mjs`);const j=e=>new w(e.apiBaseUrl,e.token,e.gifApiKey,e.analyticsContextToken,{agentName:e.agentName,agentAvatarUrl:e.agentAvatarUrl},e.identityToken,e.getIdentityToken,e.chatSurface),M=e=>{let t=t=>(...n)=>e().then(e=>e[t].apply(e,n));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`)}},N=e=>e.demo?M(async()=>new(await(A())).MockTransport):e.preview?M(async()=>{let{PreviewTransport:t}=await A();return new t(j(e),e.strings)}):j(e),P=(e,t=11)=>{let n=0;for(let t of e)n+=(t.codePointAt(0)??0)>11904?1:.58;return Math.ceil(n*t)},F=(e,t=12,n=20)=>Math.max(n,Math.ceil(e)+t),I=(e,t=12,n=8)=>Math.ceil(t+e+n),L=(e,t,n=11)=>e.length===0||Math.max(...e.map(e=>P(e,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},R=e=>Array.isArray(e)?e:e?[e]:[],ee=(e,t)=>{let n=[];for(let r of e)if(Array.isArray(r.data))for(let e of r.data){let r=e;e&&typeof e==`object`&&!Array.isArray(e)&&(r=e.value),Array.isArray(r)&&(r=r[t?0:1]),typeof r==`number`&&Number.isFinite(r)&&n.push(r)}return n},z=(e,t,n)=>{let r=e.axisLabel?.formatter,i=ee(t,n),a=typeof e.min==`number`?e.min:Math.min(0,...i),o=typeof e.max==`number`?e.max:Math.max(0,...i)*1.1,s=i.length||e.min!==void 0?[a,o]:[];return s.length?Math.max(...s.map(e=>{let t=String(e);try{typeof r==`function`&&(t=String(r(e)))}catch{}return P(t)})):P(`00000`)},B=(e,t)=>{if(!(t>0)||Array.isArray(e.grid))return e;let n=R(e.xAxis),r=R(e.yAxis),i=r[0]?.type===`category`,a=i?r[0]:n[0],o=i?n[0]:r[0];if(!a||a.type!==`category`||!o||o.type!==`value`)return e;let s=t<420,c=R(e.series),l={...e.grid??{}},u=(a.data??[]).map(e=>String(e&&typeof e==`object`?e.value??``:e)),d={...e,grid:l},f={...a},p={...o},m=0;if(i)s&&(m=Math.min(t*.35,90),f={...f,axisLabel:{...a.axisLabel,width:Math.floor(m),overflow:`truncate`,ellipsis:`…`}},l.left=8);else{let e=z(o,c,!1);if(m=e+8,s&&!o.name)l.left=8;else if(o.name){let t=F(e);p={...p,nameGap:Math.min(o.nameGap??t,t)},m+=18}}if(!i){let e=typeof l.left==`number`?l.left:0,n=typeof l.right==`number`?l.right:0,r=L(u,Math.max(40,t-e-n-m)/Math.max(1,u.length)),i=a.axisLabel?.fontSize??11,o=i+2;if(r.kind===`truncate`||r.kind===`rotate`){let e=r.kind===`rotate`?r.rotate:0;if(f.axisLabel={...a.axisLabel,interval:0,hideOverlap:!1,rotate:e,width:r.width,overflow:`truncate`,ellipsis:`…`},e){let t=Math.max(0,...u.map(e=>P(e,i))),n=Math.min(r.width,t);o=Math.ceil(n*Math.sin(e*Math.PI/180))+i}}a.name&&s?f.nameGap=Math.min(a.nameGap??99,I(o,6,4)):s&&l.containLabel===!0&&typeof l.bottom==`number`&&(l.bottom=Math.min(l.bottom,8))}return i?(d.yAxis=Array.isArray(e.yAxis)?[f,...r.slice(1)]:f,d.xAxis=Array.isArray(e.xAxis)?[p,...n.slice(1)]:p):(d.xAxis=Array.isArray(e.xAxis)?[f,...n.slice(1)]:f,d.yAxis=Array.isArray(e.yAxis)?[p,...r.slice(1)]:p),d},V=e=>!!(e?.headline?.trim()||e?.summary?.trim()),H=(e,t={})=>{let n=e?.explanation??void 0,r=e?.businessAnalysis?.explanation??void 0,i=[t.requested??void 0,n?.source===`ai_grounded`?n:void 0,r,n];for(let e of i)if(e&&V(e))return e;return t.fallback?.()},U={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`},te=[{id:`wrong_numbers`,label:`Wrong numbers`},{id:`missing_comparison`,label:`Missing comparison`},{id:`unclear`,label:`Unclear`},{id:`too_long`,label:`Too long`}],W=e=>e===`ai_grounded`||e===`rag_deterministic_analysis`,G=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``}},K=e=>{switch(e){case`confirmed_zero`:return`confirmed`;case`empty_bucket`:case`unconfirmed_zero`:return`caution`;case`missing`:return`missing`;default:return`neutral`}},q=e=>!e||e===`observed`||e===`confirmed_zero`,J=e=>{let 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`},ne=/^\d{4}-\d{2}-\d{2}$/,Y=(e,t,n,r)=>{try{return new Intl.DateTimeFormat(t,r?{...n,timeZone:r}:n).format(e)}catch{return new Intl.DateTimeFormat(t,n).format(e)}},re=(e,t)=>Y(e,`en-CA`,{year:`numeric`,month:`2-digit`,day:`2-digit`},t),ie=(e,t={})=>{let n=e?.trim();if(!n)return``;let r=new Date(n);if(Number.isNaN(r.getTime()))return``;let i={hour:`2-digit`,minute:`2-digit`,hour12:!1},a=re(r,t.timezone)===re(t.now??new Date,t.timezone);return Y(r,t.locale,a?i:{...i,month:`short`,day:`numeric`},t.timezone)},ae=(e,t={})=>{let n=e.timezone?.trim(),r=ie(e.checkedAt,{...t,timezone:n});return[n?`Times in ${n}`:``,r?`Checked ${r}`:``].filter(Boolean).join(` · `)},oe=(e,t,n)=>{let r=e?.trim();if(!r)return``;if(ne.test(r)){let e=new Date(`${r}T00:00:00Z`);return Number.isNaN(e.getTime())?r:Y(e,t,{day:`numeric`,month:`short`,year:`numeric`},`UTC`)}let i=new Date(r);return Number.isNaN(i.getTime())?r:Y(i,t,{day:`numeric`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`,hour12:!1},n)},se=(e,t={})=>{if(!e)return``;let n=e.timezone?.trim()||t.timezone?.trim(),r=oe(e.start,t.locale,n),i=oe(e.end,t.locale,n);return r&&i?`${r} – ${i} (end not included)`:r?`From ${r}`:i?`Before ${i}`:``},ce=(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`};let r=e=>{if(!e)return``;let t=ne.test(e)?new Date(`${e}T00:00:00`):new Date(e);return Number.isNaN(t.getTime())?``:new Intl.DateTimeFormat(n,{month:`short`,day:`numeric`}).format(t)},i=r(e.dataAsOf),a=r(t);return{label:`${a?`Checked ${a} · `:``}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`}},le=(e,t)=>{let n=typeof e.value==`number`&&Number.isFinite(e.value)?e.value:null,r=typeof t.value==`number`&&Number.isFinite(t.value)?t.value:null;return e.status===`missing`||t.status===`missing`||n===null||r===null?{kind:`not_comparable`,reason:`missing`,label:U.notComparable}:q(e.status)?q(t.status)?r===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-r)/Math.abs(r)*100}:{kind:`not_comparable`,reason:`previous_no_records`,label:U.notComparable}:{kind:`not_comparable`,reason:`current_no_records`,label:`${e.label?.trim()||`Current period`}: no records yet`}},ue=e=>e&&[`day`,`week`,`month`,`quarter`,`year`].includes(e)?e:`period`,de=e=>e===`day`?`vs yesterday at this time`:`vs same point last ${ue(e)}`,fe=(e,t)=>{if(!e.cutoffAt)return;let n=new Date(e.cutoffAt);if(Number.isNaN(n.getTime()))return;let r=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:r}).format(n)}catch{i=n.toISOString()}let a=e.grain===`day`?`on both days`:`in both ${ue(e.grain)}s`,o=e.cutoffSource===`data_as_of`?`, the time of the latest record`:``;return`Compared up to ${i} ${a}${o}${r?` (${r})`:``}`},pe=(e,t,n,r={format:String})=>{if(!e||!e.comparisonBasis||e.comparisonBasis===`complete`)return;let i=e.comparisonBasis,a=le(t,n);if(a.kind===`not_comparable`&&a.reason!==`previous_zero`)return{basis:i,kind:`neutral`,tone:`neutral`,label:a.label,copy:``,reason:a.reason};let o=r.format,s=e.currentPeriod?.label||t.label||`Current period`,c=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,d=e.grain===`day`?`full day`:`full ${ue(e.grain)}`,f=u===void 0?void 0:`${c} ${d}: ${o(u)}`,p=u===void 0?void 0:`${d.charAt(0).toUpperCase()}${d.slice(1)}: ${o(u)}`;if(i===`like_for_like`&&typeof e.previousToDateValue==`number`&&typeof l==`number`){let n=le({value:l,status:t.status},{value:e.previousToDateValue,status:`observed`}),a=fe(e,r.locale);if(n.kind===`change`){let t=n.percent;return{basis:i,kind:`change`,percent:t,tone:t===0?`neutral`:t>0?`positive`:`negative`,label:`${t>0?`↑`:t<0?`↓`:`→`} ${Math.abs(t).toFixed(1)}%`,copy:de(e.grain),secondary:f,compactSecondary:p,title:a}}return{basis:i,kind:`neutral`,tone:`neutral`,label:n.label,copy:de(e.grain),secondary:f,compactSecondary:p,title:a,reason:n.reason}}if(i===`not_comparable`)return{basis:i,kind:`neutral`,tone:`neutral`,label:`Not comparable`,copy:e.reason||``,reason:e.reason};let m=[typeof l==`number`?`${s} so far: ${o(l)}`:`${s}: in progress`];return u!==void 0&&m.push(`${c}: ${o(u)} (${d})`),{basis:`current_in_progress_no_time`,kind:`neutral`,tone:`neutral`,label:m.join(` · `),copy:``,title:e.reason,reason:e.reason}},me=e=>e?.grain===`day`?`Yesterday at this time`:`Same point last ${ue(e?.grain)}`,he=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):``},X=(e,t)=>{let n=he(t);if(!(!n||!e)){if(e.previousPeriod?.start&&he(e.previousPeriod.start)===n)return`previous`;if(e.currentPeriod?.start&&he(e.currentPeriod.start)===n)return`current`}},ge=(e,t,n,r={format:String})=>{if(!e||!e.series?.length||!e.comparisonBasis||e.comparisonBasis===`complete`)return;let i=X(e,t);if(!i)return;let a=String(n??``),o=e.series.find(e=>e.key===a);if(!o)return;let s=e.comparisonBasis;if(i===`previous`){let e=s===`like_for_like`&&typeof o.previousToDateValue==`number`;return{side:i,basis:s,toDate:e,plotValue:e?o.previousToDateValue:void 0,fullValue:o.previousFullValue}}return{side:i,basis:s,toDate:!1,display:pe({...e,currentValue:o.currentValue,previousToDateValue:o.previousToDateValue,previousFullValue:o.previousFullValue},{value:o.currentValue,status:o.currentValue===void 0?`missing`:`observed`},{value:o.previousFullValue,status:o.previousFullValue===void 0?`missing`:`observed`},r)}},_e=e=>!!(e&&e.seriesField&&e.series?.length&&e.comparisonBasis&&e.comparisonBasis!==`complete`&&e.comparisonBasis!==`not_comparable`),ve=e=>{if(!_e(e))return;let t=e.currentPeriod?.label||`Current period`;return e.comparisonBasis===`like_for_like`?`${t} so far, compared with ${me(e).toLowerCase()}`:`${t} so far; the previous period is shown in full, so the bars are not like for like`},ye=(e,t,n)=>{if(!t)return[];if(t.side===`previous`)return typeof t.fullValue==`number`&&t.toDate?[`Full ${e?.grain===`day`?`day`:ue(e?.grain)}: ${n(t.fullValue)}`]:[];let r=t.display;return r?r.kind===`change`&&r.percent!==void 0?[`${r.label} ${r.copy}`.trim()]:r.kind===`neutral`&&r.label&&t.basis===`like_for_like`?[r.label]:[]:[]},be=`__previous_to_date`,xe=(e,t)=>{let n=e.trim().toLowerCase(),r=t.trim().toLowerCase();return n===r||n.endsWith(`.${r}`)||r.endsWith(`.${n}`)},Se=e=>{let t=e.periodComparison,n=e.rows;if(!n?.length||!_e(t)||t.comparisonBasis!==`like_for_like`||!t.series?.some(e=>typeof e.previousToDateValue==`number`))return e;let r=e.columnMetadata??[],i=e.columns?.filter(Boolean)??(r.length?r.map(e=>String(e.key??e.name??``)).filter(Boolean):Object.keys(n[0]??{}));if(i.includes(be))return e;let a=i.find(e=>xe(t.seriesField,e));if(!a)return e;let o=e=>r.find(t=>(t.key??t.name)===e),s=i.find(e=>{let t=o(e);return t?.semanticRole===`date`||t?.role===`date`||t?.dataType===`date`||t?.dataType===`datetime`}),c=(t.measureField?i.find(e=>xe(t.measureField,e)):void 0)??i.find(e=>o(e)?.semanticRole===`measure`),l=n.map(e=>{let n=s?X(t,e[s]):`current`,r=t.series?.find(t=>t.key===String(e[a]??``)),i=n&&typeof r?.previousToDateValue==`number`?r.previousToDateValue:null;return{...e,[be]:i}}),u={...(c?o(c):void 0)??{dataType:`number`,semanticRole:`measure`},key:be,name:void 0,label:`Previous to date`,aggregation:`none`,sourceField:void 0,priority:`secondary`,groupable:!1,filterable:!1};return{...e,rows:l,columns:e.columns?[...e.columns,be]:e.columns,columnMetadata:r.length?[...r,u]:e.columnMetadata}},Ce=e=>!!(e?.lastPeriodInProgress||e?.caveats?.some(e=>e.code===`incomplete_final_period`)||e?.periodComparison?.currentPeriod?.inProgress),Z=(e,t)=>t(String(e??``).replace(/\s+/g,` `).trim()).trim(),we=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e.toLocaleString(t):``,Te=e=>{let 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},Ee=(e,t={})=>{let{locale:n}=t,r={...U,...t.copy},i=t.cleanText??(e=>e),a=e.timezone?.trim()||void 0,o=new Map;for(let t of e.evidenceItems??[])t?.id?.trim()&&!o.has(t.id.trim())&&o.set(t.id.trim(),t);let s=[],c={},l=r=>{let l=r?.trim();if(!l)return;let u=c[l];if(u)return{id:l,index:u.index};let d=o.get(l);if(!d)return;let f=d.valueStatus,p=G(f)||(f===`observed`?`observed`:``),m=d.source?.kind,h={id:l,index:s.length+1,text:Z(d.text,i),...d.metric?.trim()?{metric:d.metric.trim()}:{},...d.period?.label?.trim()?{periodLabel:d.period.label.trim()}:{},...(()=>{let e=se(d.period,{locale:n,timezone:a});return e?{periodRange:e}:{}})(),...d.period?.timezone?.trim()||a?{timezone:d.period?.timezone?.trim()||a}:{},...d.filters?.length?{filters:d.filters.map(e=>e.trim()).filter(Boolean)}:{},...(()=>{let e=we(d.value,n);return e?{valueText:e}:{}})(),...p?{statusLabel:p}:{},statusTone:K(f),...d.statusReason?.trim()?{statusReason:Z(d.statusReason,i)}:{},...m===`card`?{sourceLabel:U.sourceCard}:m===`supporting_query`?{sourceLabel:U.sourceSupportingQuery}:{},sourceTargets:Te(d.source),...(()=>{let r=ie(d.checkedAt??e.checkedAt,{locale:n,timezone:a,now:t.now});return r?{checkedText:r}:{}})()};return h.filters&&h.filters.length===0&&delete h.filters,s.push(h),c[l]=h,{id:l,index:h.index}},u=e=>{let t=new Set,n=[];for(let r of e??[]){let e=l(r);e&&!t.has(e.id)&&(t.add(e.id),n.push(e))}return n},d=W(e.source)||e.level===`detailed`,f=Z(e.headline,i)||Z(e.summary,i),p={text:f,citations:u(e.headlineEvidenceIds)},m=Z(e.summary,i),h=m&&m!==f?{text:m,citations:u(e.summaryEvidenceIds)}:void 0;if(!h&&m&&e.summaryEvidenceIds?.length)for(let t of u(e.summaryEvidenceIds))p.citations.some(e=>e.id===t.id)||p.citations.push(t);let g=(e.periods??[]).filter(e=>e?.label?.trim()).map(e=>{let t=e.valueStatus,r=G(t),a=e.valueText?.trim()||we(e.value,n)||(t===`missing`?`—`:``),s=r?e.statusReason?.trim()||o.get(e.evidenceId?.trim()??``)?.statusReason?.trim():``,c=l(e.evidenceId);return{key:e.evidenceId||`${e.label}-${e.start??``}-${e.end??``}`,label:e.label.trim(),valueText:a,...t?{status:t}:{},statusLabel:r,statusTone:K(t),inProgress:!!e.inProgress,current:!!e.current,...s?{reason:Z(s,i)}:{},...c?{citation:c}:{}}}),_=t.maxConclusions??4,v=(e.evidenceStatements??[]).map(e=>({text:Z(e.text,i),citations:u(e.evidenceIds)})).filter(e=>e.text),y=(v.length>0?v:(e.evidence??[]).map(e=>Z(e,i)).filter(Boolean).map(e=>({text:e,citations:[]}))).filter((e,t,n)=>n.findIndex(t=>t.text===e.text)===t).filter(e=>e.text!==p.text&&e.text!==h?.text).slice(0,_),b=Z(e.businessMeaning,i),x=b?{text:b,citations:u(e.businessMeaningEvidenceIds)}:void 0,S=[],C=e=>{e.text&&!S.some(t=>t.text===e.text)&&S.push(e)},w=(e.limitations??[]).map(e=>e.toLowerCase());for(let e of g){let t=w.some(t=>t.includes(e.label.toLowerCase())&&t.includes(`in progress`));e.inProgress&&!t&&C({kind:`in_progress`,text:`${e.label} is still in progress, so its total can still change.`,...e.citation?{citation:e.citation}:{}}),(e.status===`empty_bucket`||e.status===`unconfirmed_zero`)&&C({kind:`no_records`,text:`${e.label} has no records yet. This is not a confirmed 0${e.reason?`: ${e.reason.replace(/\.$/,``)}`:``}.`,...e.citation?{citation:e.citation}:{}}),e.status===`missing`&&C({kind:`missing`,text:`${e.label} is missing${e.reason?`: ${e.reason.replace(/\.$/,``)}`:``}.`,...e.citation?{citation:e.citation}:{}})}e.currentPeriodInProgress&&!g.some(e=>e.inProgress)&&C({kind:`in_progress`,text:`The current period is still in progress, so its total can still change.`});for(let t of e.missing??[]){if(!t?.label?.trim()||!t.reason?.trim())continue;let e=l(t.evidenceId);C({kind:`missing`,text:De(t),...e?{citation:e}:{}})}(e.dataFreshness?.status===`delayed`||e.dataFreshness?.status===`no_data`)&&C({kind:`freshness`,text:ce(e.dataFreshness,e.checkedAt,n).description});for(let t of e.limitations??[]){let e=Z(t,i);e&&C({kind:`limitation`,text:e})}let T=(e.possibleDrivers??[]).map(e=>({title:Z(e.hypothesis,i),howToCheck:Z(e.howToCheck,i),citations:u(e.evidenceIds)})).filter(e=>e.title).slice(0,t.maxCauses??3),E=(e.recommendations??[]).map(e=>({title:Z(e.action,i),why:Z(e.why,i),...e.successMetric?.trim()?{watch:Z(e.successMetric,i)}:{},citations:u(e.evidenceIds)})).filter(e=>e.title).slice(0,t.maxRecommendations??3),D=Z(e.forecast?.text,i),O=D?{badge:J(e.forecast?.qualityStatus),text:D,...e.forecast?.limitations?.trim()?{note:Z(e.forecast.limitations,i)}:{}}:void 0,k=(e.followUps??[]).map(e=>Z(e,i)).filter(Boolean).filter((e,t,n)=>n.indexOf(e)===t).slice(0,t.maxFollowUps??4);for(let e of o.keys())l(e);let A=Z(e.conversationalPreface,i);return{...e.explanationId?.trim()?{explanationId:e.explanationId.trim()}:{},ai:d,lead:{eyebrow:r.eyebrow,provenance:d?r.provenanceAI:e.level===`basic`?r.basicExplanation:r.provenanceGoverned,...A?{preface:A}:{},headline:p,...h?{summary:h}:{}},comparison:g,conclusions:y,...x?{businessMeaning:x}:{},limits:S,checkedLine:ae(e,{locale:n,now:t.now}),investigate:{causes:T,recommendations:E,...O?{outlook:O}:{},followUps:k},hasInvestigate:T.length>0||E.length>0||!!O||k.length>0||s.length>0,evidence:s,evidenceById:c,sourceNote:d?r.sourceNoteAI:r.sourceNoteGoverned}},De=e=>`${e.label.trim()} could not be established: ${e.reason.trim()}`,Oe=e=>`[${e.index}]`,ke=(e,t)=>{let n={...U,...t},r=[];e.metric&&r.push({key:`metric`,label:n.evidenceMetric,value:e.metric});let i=[e.periodLabel,e.periodRange].filter(Boolean).join(` · `);i&&r.push({key:`period`,label:n.evidencePeriod,value:i}),e.timezone&&r.push({key:`timezone`,label:n.evidenceTimezone,value:e.timezone}),e.filters?.length&&r.push({key:`filters`,label:n.evidenceFilters,value:e.filters.join(`; `)});let a=[e.valueText,e.statusLabel].filter(Boolean).join(` · `);return a&&r.push({key:`value`,label:n.evidenceValue,value:a}),e.statusReason&&r.push({key:`reason`,label:n.evidenceStatus,value:e.statusReason}),e.sourceLabel&&r.push({key:`source`,label:n.evidenceSource,value:e.sourceLabel}),e.checkedText&&r.push({key:`checked`,label:n.evidenceChecked,value:e.checkedText}),r},Ae=e=>{let t=new Set(te.map(e=>e.id)),n=Array.from(e.comment??``).map(e=>{let t=e.charCodeAt(0);return t<32||t>=127&&t<=159?` `:e}).join(``).replace(/\s+/g,` `).trim(),r=e.rating===`down`?[...new Set(e.reasons??[])].filter(e=>t.has(e)).slice(0,4):[];return{explanationId:e.explanationId,rating:e.rating,...r.length?{reasons:r}:{},...e.rating!==`clear`&&n?{comment:Array.from(n).slice(0,500).join(``)}:{},...e.modelId?{modelId:e.modelId}:{},...typeof e.modelVersion==`number`&&e.modelVersion>0?{modelVersion:e.modelVersion}:{}}},je=(e,t)=>{let n=`.${e}-xp`;return`
6
6
  ${n}{display:grid;gap:12px;color:${t.text};font-size:13px;line-height:1.55;min-width:0}
7
7
  ${n} h3,${n} h4,${n} p,${n} ul,${n} ol,${n} dl,${n} dd{margin:0}
8
8
  ${n} ul,${n} ol{padding:0;list-style:none}
@@ -86,8 +86,8 @@ ${n}__reason[aria-pressed="true"]{border-color:${t.accent};background:color-mix(
86
86
  ${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}
87
87
  ${n}__feedback-note{color:${t.muted};font-size:12px}
88
88
  ${n}__feedback-error{color:${t.danger};font-size:12px}
89
- `};var je=class{constructor(e,t,n,r={}){this.explanationId=e,this.submit=t,this.onChange=n,this.context=r,h(this,`state`,{phase:`idle`,reasons:[],comment:``})}set(e){this.state={...this.state,...e},this.onChange(this.state)}async save(e,t){let n=this.state;this.set({phase:`saving`,error:void 0});try{await this.submit(ke({explanationId:this.explanationId,...this.context,...e})),this.set({...t,error:void 0})}catch{this.set({phase:n.phase===`details`?`details`:`error`,rating:n.rating,error:H.feedbackError})}}vote(e){return this.state.phase===`saving`?Promise.resolve():this.save({rating:e},e===`up`?{phase:`done`,rating:e,reasons:[],comment:``}:{phase:`details`,rating:e})}toggleReason(e){let t=this.state.reasons.includes(e)?this.state.reasons.filter(t=>t!==e):[...this.state.reasons,e];this.set({reasons:t})}setComment(e){this.set({comment:Array.from(e).slice(0,500).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 Me={delaysMs:[1e3,2e3,4e3],capMs:45e3},Ne=e=>e===`pending`||e===`ready`||e===`failed`?e:`not_requested`,Pe=e=>Ne(e?.aiExplanation?.status);var Fe=class{constructor(e,t,n,r={}){this.transport=t,this.onChange=n,h(this,`state`,void 0),h(this,`handle`,void 0),h(this,`disposed`,!1),h(this,`generation`,0),h(this,`attempt`,0),h(this,`startedAt`,0),h(this,`delays`,void 0),h(this,`capMs`,void 0),h(this,`now`,void 0),h(this,`schedule`,void 0),h(this,`cancelTimer`,void 0),h(this,`isVisible`,void 0),h(this,`onSettled`,void 0),h(this,`inFlight`,null),h(this,`pausedAt`,null),h(this,`onVisibilityChange`,()=>{this.disposed||this.pausedAt===null||!this.isVisible()||(this.startedAt+=this.now()-this.pausedAt,this.pausedAt=null,this.queue())}),this.delays=r.delaysMs?.length?r.delaysMs:Me.delaysMs,this.capMs=r.capMs??Me.capMs,this.now=r.now??(()=>Date.now()),this.schedule=r.schedule??((e,t)=>setTimeout(e,t)),this.cancelTimer=r.cancel??(e=>clearTimeout(e)),this.isVisible=r.isVisible??(()=>typeof document>`u`||document.visibilityState!==`hidden`),this.onSettled=r.onSettled;let i=Pe(e),a=i===`pending`&&!t?`not_requested`:i;this.state={status:a,explanation:e,retryAvailable:a===`failed`&&this.canRetry(e.aiExplanation?.retryAvailable),retrying:!1,announcement:``}}get explanationId(){return this.state.explanation.aiExplanation?.explanationId||this.state.explanation.explanationId||``}canRetry(e){return!!this.transport?.retry&&e!==!1}set(e){if(this.disposed)return;let t=this.state.status;this.state={...this.state,...e},this.onChange(this.state);let n=this.state.status;n!==t&&(n===`ready`||n===`failed`||n===`not_requested`)&&this.onSettled?.(n)}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}let e=this.now()-this.startedAt;if(e>=this.capMs){this.fail(!0);return}let t=this.delays[Math.min(this.attempt,this.delays.length-1)]??4e3;this.attempt+=1;let n=this.generation;this.handle=this.schedule(()=>{this.pollOnce(n)},Math.min(t,Math.max(0,this.capMs-e)))}async pollOnce(e){if(this.disposed||e!==this.generation||!this.transport)return;if(!this.isVisible()){this.pausedAt??(this.pausedAt=this.now());return}let t=new AbortController;this.inFlight=t;try{let n=await this.transport.poll(this.explanationId,t.signal);if(this.disposed||e!==this.generation)return;this.apply(n)}catch{if(this.disposed||e!==this.generation)return;this.queue()}finally{this.inFlight===t&&(this.inFlight=null)}}apply(e){let t=Ne(e.status);if(this.applyBasicUpdate(e,t),t===`ready`&&e.explanation&&B(e.explanation)){this.set({status:`ready`,explanation:e.explanation,retryAvailable:!1,retrying:!1,announcement:H.detailedReady});return}if(t===`pending`){this.state.status!==`pending`&&this.set({status:`pending`,retrying:!1,announcement:``}),this.queue();return}if(t===`not_requested`){this.set({status:`not_requested`,retryAvailable:!1,retrying:!1,announcement:``});return}this.fail(this.canRetry(e.retryAvailable))}applyBasicUpdate(e,t){let n=e.basic;if(!n||t===`ready`||this.state.status===`ready`||!B(n))return;let r=this.state.explanation;n.headline===r.headline&&n.summary===r.summary||this.set({explanation:{...n,explanationId:r.explanationId??n.explanationId,aiExplanation:r.aiExplanation,level:r.level}})}fail(e){this.generation+=1,this.set({status:`failed`,retryAvailable:e&&this.canRetry(!0),retrying:!1,announcement:H.detailedUnavailable})}async retry(){if(!this.transport?.retry||this.state.retrying||this.state.status===`ready`)return;let e=this.explanationId;if(!e)return;this.generation+=1;let t=this.generation;this.set({retrying:!0,announcement:``});try{let n=await this.transport.retry(e);if(this.disposed||t!==this.generation)return;if(Ne(n.status)===`pending`){this.set({status:`pending`,retrying:!1,retryAvailable:!1,announcement:H.preparingDetailed}),this.startedAt=this.now(),this.attempt=0,this.queue();return}this.apply(n)}catch{if(this.disposed||t!==this.generation)return;this.set({status:`failed`,retrying:!1,retryAvailable:!1,announcement:H.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 Ie=/^(\d{4})-(\d{2})-(\d{2})$/,Le=/^(\d{4})-(\d{2})$/,Re=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?$/,ze=/(?:Z|[+-]\d{2}:?\d{2})$/i,Be=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=Ie.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=Le.exec(t),n)return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,1)),calendar:!0,hasTime:!1};if(n=Re.exec(t),n&&!ze.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 r=new Date(t);return Number.isNaN(r.getTime())?null:{date:r,calendar:!1,hasTime:!0}},Ve=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`}},He=e=>{let t=e.map(Be).filter(e=>e!==null);if(t.length===0)return;let n=e=>e.date.getUTCHours()+e.date.getUTCMinutes();return t.some(e=>e.hasTime&&n(e)!==0)?t.every(e=>e.date.getUTCMinutes()===0)?`hour`:void 0:t.length>1&&t.every(e=>e.date.getUTCDate()===1)?`month`:`day`},Ue=(e,t)=>{try{return new Intl.DateTimeFormat(e,t)}catch{return new Intl.DateTimeFormat(e,{...t,timeZone:`UTC`})}},We=(e,t,n={})=>{let r=Be(e);if(!r)return;let i=t?.grain??Ve(t?.formatPattern)??n.grain,a=r.calendar?`UTC`:n.timezone||void 0,{date:o}=r;switch(i){case`year`:return Ue(n.locale,{year:`numeric`,timeZone:a}).format(o);case`quarter`:{let e=Number(Ue(`en-US`,{month:`numeric`,timeZone:a}).format(o)),t=Ue(n.locale,{year:`numeric`,timeZone:a}).format(o);return`Q${Math.floor((e-1)/3)+1} ${t}`}case`month`:return Ue(n.locale,{month:`short`,year:`numeric`,timeZone:a}).format(o);case`week`:case`day`:return Ue(n.locale,{day:`numeric`,month:`short`,year:`numeric`,timeZone:a}).format(o);case`hour`:return Ue(n.locale,{day:`numeric`,month:`short`,hour:`numeric`,minute:`2-digit`,timeZone:a}).format(o);default:return Ue(n.locale,{dateStyle:`medium`,...r.hasTime?{timeStyle:`short`}:{},timeZone:a}).format(o)}},Ge=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}},Ke=(e,t)=>{let n=Ge(e);return n?{minimumFractionDigits:n.min,maximumFractionDigits:n.max}:{maximumFractionDigits:t}},qe=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},Je=(e,t)=>t&&Math.abs(e)>=1e4?`compact`:`standard`,Ye=(e,t={})=>new Intl.NumberFormat(t.locale,{notation:Je(e,t.compact),...Ke(t.pattern,t.maxFractionDigits??2)}).format(e),Xe=(e,t,n={})=>{let r=t?.trim().toUpperCase();if(r&&/^[A-Z]{3}$/.test(r))try{return new Intl.NumberFormat(n.locale,{style:`currency`,currency:r,notation:Je(e,n.compact),...Ge(n.pattern)?Ke(n.pattern,2):{}}).format(e)}catch{}return Ye(e,{...n,maxFractionDigits:2})},Ze=(e,t={})=>{let n=!!(t.pattern&&/(?<!\\)%/.test(t.pattern)),r=Ke(t.pattern,2);return new Intl.NumberFormat(t.locale,{style:`percent`,...r}).format(n?e:e/100)},Qe=(e,t,n={})=>{let{locale:r,compact:i}=n;return t?.dataType===`currency`?Xe(e,t.currencyCode||n.currencyCode,{locale:r,compact:i,pattern:t.formatPattern}):t?.dataType===`percent`?Ze(e,{locale:r,pattern:t.formatPattern}):Ye(e,{locale:r,compact:i,pattern:t?.formatPattern,maxFractionDigits:n.maxFractionDigits})},$e=(e,t,n={})=>{if(e==null||e===``)return`—`;if(t?.dataType===`date`||t?.dataType===`datetime`){let r=We(e,t,n);if(r)return r}if(t?.dataType===`currency`||t?.dataType===`percent`){let r=qe(e);if(r!==null)return Qe(r,t,n)}return typeof e==`number`&&Number.isFinite(e)?Qe(e,t,{...n,maxFractionDigits:4}):typeof e==`boolean`?e?n.yes??`Yes`:n.no??`No`:String(e)},et={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`},tt=(e,t)=>e.replace(/\{(\w+)\}/g,(e,n)=>String(t[n]??``)),nt=e=>Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!=null)),rt=e=>({...et,...nt(e),explanation:{...e?.explanation}});let it=()=>import(`./echarts-runtime-Bu1uy4oO.mjs`),at=null;const ot=()=>(at||(at=it().catch(e=>{throw at=null,e})),at),st={background:`#ffffff`,border:`#dce4e9`,muted:`#5b7186`,surface:`#ffffff`,text:`#0f1e2a`,colors:[`#2f7f55`,`#2563eb`,`#b45309`,`#7c3aed`]},ct=`cf-widget-category-zoom`,lt=.68,ut=e=>({startIndex:0,endIndex:Math.max(0,e-1)}),dt=(e,t)=>{if(t<=0)return ut(0);let n=t-1,r=Math.max(0,Math.min(n,Math.floor(Math.min(e.startIndex,e.endIndex))));return{startIndex:r,endIndex:Math.max(r,Math.min(n,Math.floor(Math.max(e.startIndex,e.endIndex))))}},ft=(e,t,n)=>{let r=dt(e,n);if(n<=2)return ut(n);let i=r.endIndex-r.startIndex+1,a=t===`in`?Math.max(2,Math.floor(i*lt)):Math.min(n,Math.ceil(i/lt));if(a===i)return r;let o=(r.startIndex+r.endIndex)/2,s=n-a,c=Math.max(0,Math.min(s,Math.round(o-(a-1)/2)));return{startIndex:c,endIndex:c+a-1}},pt=(e,t,n=et)=>{let r=e.length;if(r===0)return n.zoomNone;let i=dt(t,r);return i.startIndex===0&&i.endIndex===r-1?tt(r===1?n.zoomAllOne:n.zoomAllMany,{count:r}):tt(n.zoomRange,{start:e[i.startIndex]??``,end:e[i.endIndex]??``,visible:i.endIndex-i.startIndex+1,count:r})},mt=e=>{let t=e.replaceAll(`_`,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).trim();return t?`${t.charAt(0).toUpperCase()}${t.slice(1)}`:`Value`},ht=e=>{let t=new Set,n=[];return e.forEach(e=>{let r=e?.trim();!r||t.has(r)||(t.add(r),n.push(r))}),n},gt=qe,_t=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)}`},vt=(e,t)=>t?e.columnMetadata?.find(e=>e.key===t):void 0,yt=(e,t)=>{let n=vt(e,t);if(!n||n.currencyCode||n.dataType!==`currency`)return n;let r=e.currency;return r?.code&&!r.isMixed?{...n,currencyCode:r.code}:n},bt=(e,t)=>vt(e,t)?.label?.trim()||mt(t),xt=(e,t,n,r)=>({locale:t,timezone:e.timezone||e.periodComparison?.timezone,grain:r,yes:n.yes,no:n.no}),St=e=>e?.dataType===`date`||e?.dataType===`datetime`||e?.semanticRole===`date`,Ct=(e,t,n)=>{let r=vt(e,t);if(St(r))return r?.grain??e.periodComparison?.grain??He(n.map(e=>e[t]))},wt=(e,t,n,r,i,a)=>{if(n==null||n===``)return r.notSet;let o=vt(e,t);if(o?.dataType===`boolean`){let e=String(n).trim().toLowerCase();return n===!1||n===0||[`0`,`false`,`no`].includes(e)?r.no:r.yes}if(St(o)){let t=We(n,o,xt(e,i,r,a));if(t)return t}return String(n)},Tt=(e,t,n,r=!1,i)=>Qe(e,t,{locale:i,compact:r,currencyCode:n?.currency?.code&&!n.currency.isMixed?n.currency.code:void 0}),Et=(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},Dt=e=>e.chartRecommendation?.categoryField?.trim()||e.label?.trim()||e.columnMetadata?.find(e=>[`date`,`dimension`,`geography`,`boolean`].includes(e.semanticRole))?.key||e.columns?.[0],Ot=e=>e.chartRecommendation?.seriesField?.trim()||e.seriesField?.trim()||e.series?.trim()||void 0,kt=(e,t,n)=>{let r=ht([...e.chartRecommendation?.valueFields??[],...e.valueFields??[],e.value,...e.columnMetadata?.filter(e=>e.semanticRole===`measure`).map(e=>e.key)??[]]),i=new Set([...e.columns??[],...e.columnMetadata?.map(e=>e.key)??[],...Object.keys(e.rows?.[0]??{})]);return r.filter(e=>e!==t&&e!==n&&i.has(e)).filter(t=>e.rows?.some(e=>gt(e[t])!==null))},At=(e,t,n,r,i,a,o)=>{let s=i?` ${tt(a.seriesLimited,{shown:r.length,total:r.length+i})}`:``,c=(t,n)=>Tt(t,n,e,!1,o);if(t===`line`){let e=n.length-1,t=r.map(t=>{let n=t.values[e];return n==null?null:`${t.name}: ${c(n,t.valueColumn)}`}).filter(e=>!!e);return t.length?`${tt(a.summaryLatest,{category:n[e]??``,values:t.join(`; `)})}${s}`:`${a.summaryNoTrend}${s}`}let l;return r.forEach(e=>{e.values.forEach((t,r)=>{t===null||l&&t<=l.value||(l={category:n[r]??a.notSet,series:e,value:t})})}),l?`${tt(a.summaryHighest,{category:l.category,series:l.series.name,value:c(l.value,l.series.valueColumn)})}${s}`:`${a.summaryNoComparison}${s}`},jt=(e,t,n={})=>{let r=rt(n.labels),i=n.locale,a=Et(e,t),o=Dt(e),s=e.rows??[];if(!a||!o||s.length===0)return null;let c=Ot(e),l=kt(e,o,c);if(l.length===0)return null;let u=l.length===1?c:void 0,d=Ct(e,o,s),f=l[0],p=u&&ge(e.periodComparison)&&(!e.periodComparison.measureField||!f||f===e.periodComparison.measureField||f.endsWith(`.${e.periodComparison.measureField}`)||e.periodComparison.measureField.endsWith(`.${f}`))?e.periodComparison:void 0,m=(()=>{if(!p?.seriesField||!u)return;let e=(e,t)=>e===t||e.endsWith(`.${t}`)||t.endsWith(`.${e}`);if(e(p.seriesField,o))return{group:o,time:u,timeIsSeries:!0};if(e(p.seriesField,u))return{group:u,time:o,timeIsSeries:!1}})(),h=t=>Tt(t,yt(e,f??``),e,!1,i),g=e=>p&&m?X(p,e[m.time],e[m.group],{format:h,locale:i}):void 0,_=(e,t)=>p?.comparisonBasis===`like_for_like`&&X(p,e,p.series?.[0]?.key)?.side===`previous`?pe(p):t,v=[],y=new Set;s.forEach(t=>{let n=_t(t[o]);if(y.has(n))return;y.add(n);let a=wt(e,o,t[o],r,i,d);v.push({key:n,label:m&&!m.timeIsSeries?_(t[o],a):a})});let b=v.map(e=>e.label),x=0,S;if(u){let t=[],n=new Set;s.forEach(a=>{let o=_t(a[u]);if(n.has(o))return;n.add(o);let c=wt(e,u,a[u],r,i,Ct(e,u,s));t.push({key:o,label:m?.timeIsSeries?_(a[u],c):c})});let a=t.slice(0,4);x=Math.max(0,t.length-a.length);let c=l[0];S=a.map(t=>{let n=new Map,r=new Map;return s.forEach(e=>{if(_t(e[u])!==t.key)return;let i=_t(e[o]);if(!n.has(i)){let t=g(e);r.set(i,t),n.set(i,t?.side===`previous`&&t.plotValue!==void 0?t.plotValue:gt(e[c]))}}),{field:c,name:t.label,values:v.map(e=>n.get(e.key)??null),valueColumn:yt(e,c),...m?{points:v.map(e=>r.get(e.key))}:{}}})}else x=Math.max(0,l.length-4),S=l.slice(0,4).map(t=>({field:t,name:bt(e,t),values:s.map(e=>gt(e[t])),valueColumn:yt(e,t)}));if(S.length===0)return null;let C=bt(e,o),w=r.chartValues;u?w=bt(e,l[0]):S.length===1&&(w=S[0].name);let T=e.title?.trim()||tt(r.chartTitle,{measure:w,dimension:C}),E;if(vt(e,o)?.semanticRole===`date`&&v.length>1&&Se(e)){let e=``;s.forEach(t=>{let n=String(t[o]??``);n>e&&(e=n)});let t=v.findIndex(t=>t.key===_t(e));t>=0&&(E=t)}return{type:a,title:T,xAxisTitle:C,yAxisTitle:w,categories:b,series:S,omittedSeriesCount:x,inProgressIndex:E,...m&&p?{comparison:p,comparisonNote:_e(p)}:{},locale:i,labels:r,summary:At(e,a,b,S,x,r,i)}},Mt=[{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`}],Nt={sum:`aggregationSum`,avg:`aggregationAvg`,min:`aggregationMin`,max:`aggregationMax`,count:`aggregationCount`,count_distinct:`aggregationCountDistinct`},Pt=(e,t=et)=>String(t[Nt[e]]),Ft=(e,t)=>{let n=e.columnMetadata?.find(e=>e.key===t)?.allowedAggregations;return n?.length?Mt.filter(e=>n.includes(e.value)):[...Mt]},It=(e,t,n)=>{let r=Dt(e);if(!r||!kt(e,r,Ot(e)).includes(t)||!Ft(e,t).some(e=>e.value===n))return;let i=Mt.find(e=>e.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 ${bt(e,t)} for each ${bt(e,r)}. Return a chart and show a table if this app permits it.`},Lt=(e,t=et)=>{if(e.presentation===`table`||e.presentation===`kpi`)return[];let n=jt(e);if(!n)return[];let r=[{type:`line`,label:t.chartLine,hint:t.chartLineHint},{type:`bar`,label:t.chartBar,hint:t.chartBarHint}];return n.series.length>1&&r.push({type:`stacked_bar`,label:t.chartStackedBar,hint:t.chartStackedBarHint}),r},Rt=e=>t=>{let n=e.inProgressIndex??-1,r=(Array.isArray(t)?t:[t]).filter(e=>{if(!e||typeof e!=`object`)return!1;let t=String(e.seriesId??``).startsWith(`in-progress:`),r=e.dataIndex,i=e.value;return t?r===n:!(r===n&&i==null)}),i=String(r[0]?.axisValueLabel??r[0]?.name??``),a=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`);return[i?`<strong>${a(i)}</strong>`:``,...r.map(t=>{let n=e.series[Math.floor(Number(t.seriesIndex)/2)]??e.series[0];return`${String(t.marker??``)}${a(String(t.seriesName??``))}: ${a(Tt(t.value,n?.valueColumn,void 0,!1,e.locale))}`})].filter(Boolean).join(`<br/>`)},zt=e=>t=>{let n=(Array.isArray(t)?t:[t]).filter(e=>!!e&&typeof e==`object`),r=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`),i=String(n[0]?.axisValueLabel??n[0]?.name??``),a=n.flatMap(t=>{let n=e.series[Number(t.seriesIndex)]??e.series[0],i=n?.points?.[Number(t.dataIndex)],a=t=>Tt(t,n?.valueColumn,void 0,!1,e.locale);return[`${String(t.marker??``)}${r(String(t.seriesName??``))}: ${r(a(t.value))}`,...ve(e.comparison,i,a).map(e=>`<span style="opacity:.75">${r(e)}</span>`)]});return[i?`<strong>${r(i)}</strong>`:``,...a].filter(Boolean).join(`<br/>`)},Bt=(e,{expanded:t=!1,reducedMotion:n=!1,theme:r=st,zoomWindow:i=ut(e.categories.length)}={})=>{let a=e.series.length>1||e.type===`line`&&(e.inProgressIndex??0)>0,o=e.type===`stacked_bar`,s=e.categories.length>2,c=dt(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:r.colors,textStyle:{color:r.text,fontFamily:`inherit`},grid:{top:a?t?48:42:14,right:12,bottom:t?18:10,left:10,containLabel:!0},legend:{show:a,type:`scroll`,top:0,left:`center`,itemWidth:12,itemHeight:8,textStyle:{color:r.muted,fontSize:t?11:10}},tooltip:{trigger:`axis`,...e.type===`line`&&(e.inProgressIndex??0)>0?{formatter:Rt(e)}:e.comparison?{formatter:zt(e)}:{},triggerOn:`mousemove|click`,confine:!0,backgroundColor:r.surface,borderColor:r.border,borderWidth:1,textStyle:{color:r.text,fontSize:12},axisPointer:{type:`line`,lineStyle:{color:r.muted,opacity:.5}}},dataZoom:s?[{id:ct,type:`inside`,xAxisIndex:0,startValue:c.startIndex,endValue:c.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:r.muted,fontSize:t?11:10},axisLine:{lineStyle:{color:r.border}},axisTick:{show:!1},axisLabel:{color:r.muted,fontSize:t?11:9,hideOverlap:!0,interval:`auto`,rotate:!t&&e.categories.length>5?28:0,formatter:e=>e.length>(t?18:11)?`${e.slice(0,t?16:9)}…`:e}},yAxis:{type:`value`,name:e.yAxisTitle,nameLocation:`middle`,nameGap:t?52:44,nameTextStyle:{color:r.muted,fontSize:t?11:10},axisLabel:{color:r.muted,fontSize:t?11:9,formatter:t=>Tt(t,e.series[0]?.valueColumn,void 0,!0,e.locale)},axisLine:{show:!1},axisTick:{show:!1},splitNumber:4,splitLine:{lineStyle:{color:r.border,opacity:.75}}},series:e.series.flatMap((n,i)=>{let a=e.inProgressIndex??-1,s={type:e.type===`line`?`line`:`bar`,name:n.name,data:n.values,stack:o?`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:r.background,borderWidth:2}:{borderRadius:o?0:[4,4,0,0]},emphasis:{focus:`series`},tooltip:{valueFormatter:t=>Tt(t,n.valueColumn,void 0,!1,e.locale)}};if(a<0)return[s];let c=r.colors[i%r.colors.length];return e.type===`line`?a===0?[s]:[{...s,lineStyle:{...s.lineStyle,color:c},itemStyle:{...s.itemStyle,color:c},data:n.values.map((e,t)=>t===a?null:e)},{...s,id:`in-progress:${i}`,name:e.labels.inProgressLegend||`In progress`,showSymbol:!0,symbol:`emptyCircle`,lineStyle:{width:t?3:2.5,type:`dashed`,color:c,opacity:.6},itemStyle:{color:c,opacity:.6},data:n.values.map((e,t)=>t===a||t===a-1?e:null)}]:[{...s,data:n.values.map((e,t)=>t===a?{value:e,itemStyle:{opacity:.45,borderType:`dashed`,borderWidth:1.5,borderColor:c}}:e)}]})}},Vt=e=>{let t=getComputedStyle(e),n=(e,n)=>{for(let n of e){let e=t.getPropertyValue(n).trim();if(e)return e}return n},[r,i,a,o]=st.colors;return{background:n([`--rv-bg`,`--cf-bg`],st.background),border:n([`--rv-border`,`--cf-border`],st.border),muted:n([`--rv-muted`,`--cf-muted`],st.muted),surface:n([`--rv-surface`,`--cf-surface`],st.surface),text:n([`--rv-text`,`--cf-text`],st.text),colors:[n([`--rv-chart-1`,`--rv-accent`,`--cf-accent`],r),n([`--rv-chart-2`],i),n([`--rv-chart-3`],a),n([`--rv-chart-4`],o)]}},Ht=[`data-theme`,`data-color-scheme`,`class`,`style`],Ut=(e,t)=>{let n=[];if(typeof matchMedia<`u`){let e=matchMedia(`(prefers-color-scheme: dark)`);e.addEventListener?.(`change`,t),n.push(()=>e.removeEventListener?.(`change`,t))}if(typeof MutationObserver<`u`){let r=new MutationObserver(t),i=e;for(;i;){i instanceof Element&&r.observe(i,{attributes:!0,attributeFilter:Ht});let e=i.parentNode;i=e instanceof ShadowRoot?e.host:e}n.push(()=>r.disconnect())}return()=>n.forEach(e=>e())},Wt=({model:e,expanded:t=!1,classPrefix:n=`cf`})=>{let i=o(null),a=o(null),[d,f]=s(()=>({model:e,window:ut(e.categories.length)})),[p,m]=s(!1),h=d.model===e?dt(d.window,e.categories.length):ut(e.categories.length),g=o(h);g.current=h;let _=t=>{let n=dt(t,e.categories.length);g.current=n,f({model:e,window:n}),a.current?.dispatchAction({type:`dataZoom`,dataZoomId:ct,startValue:n.startIndex,endValue:n.endIndex})},[v,y]=s(!1),[b,x]=s(0),[S,C]=s(0);r(()=>{let e=i.current;if(e)return Ut(e,()=>C(e=>e+1))},[]),r(()=>{let e=i.current;if(!e)return;let t=!1,n=null;return ot().then(({init:r})=>{if(t||!e.isConnected||typeof navigator<`u`&&navigator.userAgent.toLowerCase().includes(`jsdom`))return;let i=r(e,null,{renderer:`canvas`,devicePixelRatio:Math.min(window.devicePixelRatio||1,2)});a.current=i;let o=()=>{i.resize(),x(Math.round(e.clientWidth/40))},s=typeof ResizeObserver>`u`?null:new ResizeObserver(o);s?.observe(e),s||window.addEventListener(`resize`,o,{passive:!0}),n=()=>{s?.disconnect(),s||window.removeEventListener(`resize`,o),i.dispose(),a.current=null},y(!0)}).catch(()=>{t||m(!0)}),()=>{t=!0,n?.()}},[]),r(()=>{let n=i.current,r=a.current;if(!n||!r)return;let o=typeof matchMedia<`u`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches;r.setOption(z(Bt(e,{expanded:t,reducedMotion:o,theme:Vt(n),zoomWindow:g.current}),n.clientWidth),{lazyUpdate:!0,notMerge:!0}),r.resize()},[t,e,v,S,b]);let w=e.labels,T=!p&&e.categories.length>2,E=h.endIndex-h.startIndex+1,D=h.startIndex===0&&h.endIndex===e.categories.length-1,O=T&&E>2,k=T&&!D;return u(c,{children:[l(`div`,{ref:i,class:`${n}-analytics-echart${t?` is-expanded`:``}`,role:`img`,"aria-label":`${e.title}. ${e.summary}`,"data-chart-status":p?`fallback`:`ready`,children:p?l(`span`,{class:`${n}-analytics-echart__fallback`,children:e.summary}):null}),e.comparisonNote?l(`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?u(`div`,{class:`${n}-analytics-zoom`,children:[l(`span`,{class:`${n}-analytics-zoom__range`,"aria-live":`polite`,"aria-atomic":`true`,children:pt(e.categories,h,w)}),u(`div`,{class:`${n}-analytics-zoom__controls`,role:`group`,"aria-label":w.zoomControls,children:[l(`button`,{type:`button`,"aria-label":w.zoomOut,title:w.zoomOut,disabled:!k,onClick:()=>_(ft(g.current,`out`,e.categories.length)),children:`−`}),l(`button`,{type:`button`,class:`${n}-analytics-zoom__reset`,"aria-label":w.zoomReset,title:w.zoomReset,disabled:D,onClick:()=>_(ut(e.categories.length)),children:w.zoomResetShort}),l(`button`,{type:`button`,"aria-label":w.zoomIn,title:w.zoomIn,disabled:!O,onClick:()=>_(ft(g.current,`in`,e.categories.length)),children:`+`})]})]}):null]})},Gt=e=>{let t=e.replaceAll(`_`,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).trim();return t?`${t.charAt(0).toUpperCase()}${t.slice(1)}`:`Value`},Kt=(e,t)=>(t?.length?t:Object.keys(e[0]??{})).map(e=>typeof e==`string`?{key:e,label:Gt(e)}:{...e,label:e.label?.trim()||Gt(e.key)}),qt=(e,t,n,r={})=>$e(e,n,{...r,locale:t??r.locale}),Jt=e=>{let t=String(e??``);return/[",\r\n]/.test(t)?`"${t.replaceAll(`"`,`""`)}"`:t},Yt=(e,t)=>{let n=Kt(e,t);return[n.map(e=>Jt(e.label)).join(`,`),...e.map(e=>n.map(t=>Jt(e[t.key])).join(`,`))].join(`\r
90
- `)},Xt=({label:e,options:t,value:n,onChange:i,classPrefix:a})=>{let c=o(null),d=o(null),[f,p]=s(n),[m,h]=s(!1);r(()=>p(n),[n]);let g=e=>`${a}-${e}`,_=e=>{p(e),c.current&&(c.current.dataset.value=e,c.current.open=!1,c.current.querySelector(`summary`)?.focus()),i?.(e)};return u(`details`,{ref:c,"data-result-popover":!0,"data-result-select":!0,"data-value":f,class:g(`sdk-select`),onToggle:e=>{let t=e.currentTarget.open;h(t);let n=d.current;if(n){if(n.setAttribute(`popover`,`manual`),!t){typeof n.hidePopover==`function`&&n.matches(`:popover-open`)&&n.hidePopover();return}typeof n.showPopover==`function`&&!n.matches(`:popover-open`)&&n.showPopover(),requestAnimationFrame(()=>{if(!c.current?.open||!n.isConnected)return;let e=c.current.querySelector(`summary`).getBoundingClientRect(),t=Math.max(e.width,Math.min(220,innerWidth-24)),r=Math.min(n.scrollHeight,240);n.style.width=`${t}px`,n.style.left=`${Math.max(12,Math.min(e.left,innerWidth-t-12))}px`,n.style.top=`${e.bottom+r+6<=innerHeight-12?e.bottom+6:Math.max(12,e.top-r-6)}px`})}},children:[u(`summary`,{class:g(`sdk-select-trigger`),role:`combobox`,"aria-label":e,"aria-haspopup":`listbox`,"aria-expanded":m,children:[l(`span`,{children:t.find(([e])=>e===f)?.[1]??f}),l(`span`,{"aria-hidden":`true`,children:`⌄`})]}),l(`div`,{ref:d,class:g(`sdk-select-list`),role:`listbox`,"aria-label":e,popover:`manual`,children:t.map(([e,t])=>l(`button`,{type:`button`,role:`option`,"aria-selected":e===f,onClick:()=>_(e),children:t},e))})]})},Zt=({rows:e,columns:t,maxRows:n=6,locale:r,format:i,expanded:a=!1,classNames:o,emptyLabel:s=`No rows returned.`})=>{let d=Kt(e,t),f=a?e:e.slice(0,Math.max(1,n));return e.length===0||d.length===0?l(`div`,{class:o?.note,children:s}):u(c,{children:[l(`div`,{class:o?.wrap,role:`region`,"aria-label":`Result table with ${e.length} ${e.length===1?`row`:`rows`}`,tabIndex:0,children:u(`table`,{class:o?.table,children:[u(`caption`,{style:`position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)`,children:[`Result table with `,e.length,` `,e.length===1?`row`:`rows`]}),l(`thead`,{children:l(`tr`,{children:d.map(e=>l(`th`,{scope:`col`,children:e.label},e.key))})}),l(`tbody`,{children:f.map((e,t)=>l(`tr`,{children:d.map(t=>l(`td`,{children:qt(e[t.key],r,t,i)},t.key))},t))})]})}),!a&&e.length>f.length?u(`div`,{class:o?.note,children:[`Showing `,f.length,` of `,e.length,` rows. Expand to view all rows.`]}):null]})},Qt=(e,t,n)=>{let r=n.value.trim();if(!r)return!0;let i=String(e??``),a=typeof e==`number`?e:NaN,o=Number(r),s=!Number.isNaN(a)&&!Number.isNaN(o)?a-o:i.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`});switch(n.operator){case`equals`:return s===0;case`not_equals`:return s!==0;case`gt`:return s>0;case`gte`:return s>=0;case`lt`:return s<0;case`lte`:return s<=0;default:return i.toLocaleLowerCase().includes(r.toLocaleLowerCase())||t.toLocaleLowerCase().includes(r.toLocaleLowerCase())}},$t=({rows:e,columns:t,maxRows:n=100,locale:i,format:c,expanded:d=!1,classPrefix:f=`cr`,pageSize:p=10})=>{let m=a(()=>Kt(e,t),[t,e]),h=m.map(e=>e.key).join(`\0`),[g,_]=s(()=>m.map(e=>e.key)),[v,y]=s(``),[b,x]=s(),[S,C]=s(`asc`),[w,T]=s({}),[E,D]=s(),[O,k]=s([]),[A,j]=s({}),[M,N]=s(()=>m.map(e=>e.key)),[P,F]=s(!1),[I,L]=s([]),[R,ee]=s(`table`),[z,B]=s(1),[V,H]=s(p),te=o(null);r(()=>{let e=e=>{let t=e.composedPath();te.current?.querySelectorAll(`details[data-result-popover][open]`).forEach(e=>{t.includes(e)||(e.open=!1)})},t=e=>{let t=[...te.current?.querySelectorAll(`details[data-result-popover][open]`)??[]].at(-1);e.key!==`Escape`||!t||(t.open=!1,t.querySelector(`summary`)?.focus(),e.preventDefault())};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[]),r(()=>{_(m.map(e=>e.key)),x(void 0),T({}),D(void 0),k([]),j({}),N(m.map(e=>e.key)),L([]),B(1)},[h]);let ne=M.map(e=>m.find(t=>t.key===e)).filter(e=>!!(e&&g.includes(e.key))),U=a(()=>{let t=v.toLocaleLowerCase(i),n=e.map((e,t)=>({row:e,index:t})).filter(({row:e})=>ne.some(n=>qt(e[n.key],i,n,c).toLocaleLowerCase(i).includes(t))&&Object.entries(w).every(([t,n])=>{let r=m.find(e=>e.key===t);return Qt(e[t],qt(e[t],i,r,c),n)}));return b?n.sort((e,t)=>{let n=e.row[b],r=t.row[b],a=typeof n==`number`?n:NaN,o=typeof r==`number`?r:NaN,s=!Number.isNaN(a)&&!Number.isNaN(o)?a-o:String(n??``).localeCompare(String(r??``),i,{numeric:!0,sensitivity:`base`});return S===`asc`?s:-s}):n},[ne,w,c,i,v,m,e,S,b]),W=U.slice(0,Math.max(1,n)),G=Math.max(1,Math.ceil(W.length/V)),K=Math.min(z,G),q=d?W:W.slice((K-1)*V,K*V),J=q.length>0&&q.every(({index:e})=>I.includes(e)),Y=e=>`${f}-${e}`,re=()=>{_(m.map(e=>e.key)),N(m.map(e=>e.key)),j({}),x(void 0),C(`asc`),T({}),D(void 0),k([]),F(!1),y(``),L([]),ee(`table`),B(1)};if(e.length===0||m.length===0)return l(`div`,{class:Y(`table-note`),children:`No rows returned.`});let ie=e=>{let t=new Set(q.map(({index:e})=>e));L(n=>e?[...new Set([...n,...t])]:n.filter(e=>!t.has(e)))};return u(`section`,{ref:te,class:Y(`data-table`),children:[u(`div`,{class:Y(`table-fields`),children:[l(`strong`,{children:`Fields`}),l(`div`,{class:Y(`field-list`),children:m.map(e=>l(`span`,{class:Y(`field-chip`),children:e.label},e.key))}),u(`span`,{class:Y(`table-field-count`),children:[e.length.toLocaleString(i),` rows`]})]}),u(`div`,{class:Y(`table-controls`),children:[u(`label`,{class:Y(`table-search`),children:[l(`span`,{"aria-hidden":`true`,children:`⌕`}),l(`input`,{type:`search`,value:v,placeholder:`Search this result...`,"aria-label":`Search this result`,onInput:e=>{y(e.currentTarget.value.trim()),B(1)}})]}),l(`div`,{class:Y(`table-modes`),role:`group`,"aria-label":`Table display mode`,children:[`table`,`matrix`].map(e=>l(`button`,{type:`button`,class:`${Y(`segment`)}${R===e?` is-active`:``}`,"aria-pressed":R===e,onClick:()=>ee(e),children:e===`table`?`Table`:`Matrix`},e))})]}),u(`div`,{class:Y(`table-column-bar`),children:[u(`details`,{"data-result-popover":!0,class:Y(`column-picker`),children:[l(`summary`,{children:`Columns`}),l(`div`,{class:Y(`column-menu`),children:M.map((e,t)=>{let n=m.find(t=>t.key===e);return n?u(`div`,{class:Y(`column-picker-row`),children:[u(`label`,{children:[l(`input`,{type:`checkbox`,checked:g.includes(n.key),onChange:e=>{let t=e.currentTarget.checked;_(e=>t?[...new Set([...e,n.key])]:e.length>1?e.filter(e=>e!==n.key):e)}}),l(`span`,{children:A[n.key]||n.label})]}),l(`button`,{type:`button`,"aria-label":`Move ${n.label} left`,disabled:t===0,onClick:()=>N(e=>{let n=[...e];return[n[t-1],n[t]]=[n[t],n[t-1]],n}),children:`↑`}),l(`button`,{type:`button`,"aria-label":`Move ${n.label} right`,disabled:t===M.length-1,onClick:()=>N(e=>{let n=[...e];return[n[t+1],n[t]]=[n[t],n[t+1]],n}),children:`↓`})]},n.key):null})})]}),l(`button`,{type:`button`,class:Y(`table-view-button`),"aria-pressed":P,onClick:()=>F(e=>!e),children:P?`Comfortable rows`:`Compact rows`}),l(`button`,{type:`button`,class:Y(`table-view-button`),onClick:re,children:`Reset view`})]}),Object.keys(w).length?l(`div`,{class:Y(`table-filter-bar`),children:Object.entries(w).map(([e,t])=>{let n=m.find(t=>t.key===e);return u(`button`,{type:`button`,class:Y(`table-filter-chip`),"aria-label":`Clear ${n?.label??e} filter`,onClick:()=>T(t=>{let n={...t};return delete n[e],n}),children:[A[e]||n?.label||e,` `,t.operator.replaceAll(`_`,` `),` `,t.value,` ×`]},e)})}):null,l(`div`,{class:Y(`table-wrap`),role:`region`,"aria-label":`Scrollable result table`,tabIndex:0,children:u(`table`,{class:`${Y(`table`)}${R===`matrix`?` is-matrix`:``}${P?` is-compact`:``}`,children:[u(`caption`,{class:Y(`visually-hidden`),children:[`Result table with `,U.length,` `,U.length===1?`row`:`rows`]}),l(`thead`,{children:u(`tr`,{children:[l(`th`,{class:Y(`select-cell`),children:l(`input`,{type:`checkbox`,"aria-label":`Select all visible rows`,checked:J,onChange:e=>ie(e.currentTarget.checked)})}),ne.map(e=>u(`th`,{scope:`col`,class:E===e.key?`is-pinned`:void 0,style:E===e.key?{left:`34px`}:void 0,"aria-sort":b===e.key?S===`asc`?`ascending`:`descending`:`none`,children:[u(`button`,{type:`button`,class:Y(`table-sort`),"aria-label":`Sort by ${e.label}`,onClick:()=>{b===e.key?C(e=>e===`asc`?`desc`:`asc`):(x(e.key),C(`asc`)),B(1)},children:[l(`span`,{children:A[e.key]||e.label}),l(`span`,{class:Y(`sort-direction`),"aria-hidden":`true`,children:b===e.key?S===`asc`?`↑`:`↓`:`↕`})]}),u(`details`,{"data-result-popover":!0,class:Y(`table-column-menu`),onToggle:e=>{let t=e.currentTarget,n=t.querySelector(`.${Y(`table-column-panel`)}`);if(n?.setAttribute(`popover`,`manual`),!t.open){n&&typeof n.hidePopover==`function`&&n.matches(`:popover-open`)&&n.hidePopover(),t.querySelectorAll(`details[data-result-select][open]`).forEach(e=>{e.open=!1});return}te.current?.querySelectorAll(`details[data-result-popover][open]`).forEach(e=>{e!==t&&!t.contains(e)&&(e.open=!1)}),n&&typeof n.showPopover==`function`&&!n.matches(`:popover-open`)&&n.showPopover(),requestAnimationFrame(()=>{if(!t.open||!t.isConnected)return;let e=t.querySelector(`summary`)?.getBoundingClientRect();if(!e||!n)return;let{width:r,height:i}=n.getBoundingClientRect(),a=e.bottom+i+5<=innerHeight-12?e.bottom+5:e.top-i-5;n.style.left=`${Math.max(12,Math.min(e.right-r,innerWidth-r-12))}px`,n.style.top=`${Math.max(12,Math.min(a,innerHeight-i-12))}px`})},children:[l(`summary`,{"aria-label":`Actions for ${e.label}`,children:`⋯`}),u(`div`,{class:Y(`table-column-panel`),popover:`manual`,children:[l(`strong`,{children:A[e.key]||e.label}),l(`button`,{type:`button`,onClick:()=>{x(e.key),C(`asc`),B(1)},children:`Sort ascending`}),l(`button`,{type:`button`,onClick:()=>{x(e.key),C(`desc`),B(1)},children:`Sort descending`}),l(`span`,{children:`Filter values`}),l(Xt,{classPrefix:f,label:`Filter operator for ${e.label}`,value:w[e.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`]]}),l(`input`,{type:`text`,"aria-label":`Filter value for ${e.label}`,defaultValue:w[e.key]?.value??``,placeholder:`Enter a value`}),l(`button`,{type:`button`,onClick:t=>{let n=t.currentTarget.parentElement,r=n.querySelector(`input[aria-label^="Filter value"]`).value.trim(),i=n.querySelector(`[data-result-select]`).dataset.value;T(t=>{let n={...t};return r?n[e.key]={operator:i,value:r}:delete n[e.key],n}),B(1),t.currentTarget.closest(`details`).open=!1},children:`Apply filter`}),l(`button`,{type:`button`,onClick:t=>{D(t=>t===e.key?void 0:e.key),N(t=>[e.key,...t.filter(t=>t!==e.key)]),t.currentTarget.closest(`details`).open=!1},children:E===e.key?`Unpin column`:`Pin column`}),l(`button`,{type:`button`,onClick:t=>{k(t=>t.includes(e.key)?t.filter(t=>t!==e.key):[...t,e.key]),t.currentTarget.closest(`details`).open=!1},children:O.includes(e.key)?`Do not wrap text`:`Wrap text`}),l(`input`,{type:`text`,"aria-label":`Display name for ${e.label}`,defaultValue:A[e.key]||e.label,maxLength:80}),l(`button`,{type:`button`,onClick:t=>{let n=t.currentTarget.parentElement.querySelector(`input[aria-label^="Display name"]`).value.trim();j(t=>({...t,[e.key]:n||e.label||e.key})),t.currentTarget.closest(`details`).open=!1},children:`Apply display name`})]})]})]},e.key))]})}),l(`tbody`,{children:q.map(({row:e,index:t})=>u(`tr`,{class:I.includes(t)?`is-selected`:void 0,children:[l(`td`,{class:Y(`select-cell`),children:l(`input`,{type:`checkbox`,"aria-label":`Select row ${t+1}`,checked:I.includes(t),onChange:e=>L(n=>e.currentTarget.checked?[...new Set([...n,t])]:n.filter(e=>e!==t))})}),ne.map(t=>l(`td`,{class:`${O.includes(t.key)?`is-wrapped`:``} ${E===t.key?`is-pinned`:``}`.trim(),style:E===t.key?{left:`34px`}:void 0,children:qt(e[t.key],i,t,c)},t.key))]},t))})]})}),u(`div`,{class:Y(`table-summary`),children:[l(`span`,{children:W.length?`${((K-1)*V+1).toLocaleString(i)}-${Math.min(K*V,W.length).toLocaleString(i)} of ${U.length.toLocaleString(i)}`:`0 of ${U.length.toLocaleString(i)}`}),d?l(`span`,{children:e.length>n?`First ${n.toLocaleString(i)} rows available`:`All returned rows loaded`}):u(`div`,{class:Y(`table-pagination`),"aria-label":`Table pagination`,children:[u(`label`,{children:[l(`span`,{children:`Rows`}),l(Xt,{classPrefix:f,label:`Rows per page`,value:String(V),options:[[`10`,`10`],[`25`,`25`],[`50`,`50`]],onChange:e=>{H(Number(e)),B(1)}})]}),l(`button`,{type:`button`,"aria-label":`Previous page`,disabled:K<=1,onClick:()=>B(e=>Math.max(1,e-1)),children:`‹`}),u(`span`,{children:[K,` / `,G]}),l(`button`,{type:`button`,"aria-label":`Next page`,disabled:K>=G,onClick:()=>B(e=>Math.min(G,e+1)),children:`›`})]})]})]})},en=(e,t,n)=>{let r=rt(t),i=[],a=e.reportingPeriod?.label?.trim();a&&i.push({label:r.aboutPeriod,value:a});let o=e.rowCount??e.rows?.length;typeof o==`number`&&i.push({label:r.aboutResults,value:tt(o===1?r.rowOne:r.rowMany,{count:o})});let s=e.explanation?.checkedAt??e.freshness?.answeredAt,c=e.explanation?.timezone??e.timezone??e.reportingPeriod?.timezone;if(s){let e=new Date(s),t=s;if(!Number.isNaN(e.getTime()))try{t=new Intl.DateTimeFormat(n,{dateStyle:`medium`,timeStyle:`short`,...c?{timeZone:c}:{}}).format(e)}catch{t=e.toLocaleString(n)}i.push({label:r.aboutChecked,value:t})}c&&i.push({label:r.aboutTimezone,value:c});let l=e.explanation?.dataFreshness?.status??e.freshness?.status;return l&&l!==`unknown`&&i.push({label:r.aboutSourceData,value:l.replaceAll(`_`,` `)}),e.appliedFilters?.length&&i.push({label:r.aboutFilters,value:tt(r.filtersApplied,{count:e.appliedFilters.length})}),i},tn=e=>e.columns?.length?e.columns:Object.keys(e.rows?.[0]??{}),nn=e=>{let t=e.rows??[],n=e.currency?.code&&!e.currency.isMixed?e.currency.code:void 0;return tn(e).map(r=>{let i=e.columnMetadata?.find(e=>e.key===r);if(!i)return{key:r,label:Gt(r)};let a=i.dataType===`date`||i.dataType===`datetime`||i.semanticRole===`date`;return{key:r,label:i.label,dataType:i.dataType,currencyCode:i.currencyCode||(i.dataType===`currency`?n:void 0),formatPattern:i.formatPattern,grain:a?i.grain??e.periodComparison?.grain??He(t.map(e=>e[r])):void 0}})},rn=(e,t)=>{let n=e.rows?.[0]??{};return e.chartRecommendation?.valueFields?.[0]??e.valueFields?.[0]??e.value??e.columnMetadata?.find(e=>e.semanticRole===`measure`&&e.key in n)?.key??t.find(e=>qe(n[e])!==null)??t[1]??t[0]},an=(e,t,n=`analytics-result.csv`)=>{if(typeof document>`u`||e.length===0)return;let r=Yt(t,e),i=URL.createObjectURL(new Blob([r],{type:`text/csv;charset=utf-8`})),a=document.createElement(`a`);a.href=i,a.download=n,a.click(),URL.revokeObjectURL(i)},on=new Set,sn=e=>{let t=e.composedPath();on.forEach(e=>{e.isOpen()&&!e.contains(t)&&e.close(!1)})},cn=e=>{if(e.key===`Escape`){for(let t of on)if(t.isOpen()){t.close(!0),e.preventDefault();return}}},ln=e=>(on.size===0&&typeof document<`u`&&(document.addEventListener(`pointerdown`,sn),document.addEventListener(`keydown`,cn)),on.add(e),()=>{on.delete(e),on.size===0&&typeof document<`u`&&(document.removeEventListener(`pointerdown`,sn),document.removeEventListener(`keydown`,cn))}),un=({children:e,size:t=15})=>l(`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}),dn=()=>l(un,{children:l(`path`,{d:`M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7`})}),fn=()=>l(un,{children:l(`path`,{d:`M18 6 6 18M6 6l12 12`})}),pn=()=>l(un,{size:13,children:l(`path`,{d:`m6 9 6 6 6-6`})}),mn=()=>l(un,{size:13,children:l(`path`,{d:`m5 12 5 5L20 7`})}),hn=({type:e,className:t})=>u(`svg`,{viewBox:`0 0 32 32`,"aria-hidden":`true`,class:t,fill:`none`,children:[l(`path`,{d:`M6 26h21M6 7v19`,stroke:`var(--rv-muted)`,"stroke-width":`1.4`,"stroke-linecap":`round`}),e===`line`?l(`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`?l(c,{children:[9,15,21].map((e,t)=>u(`g`,{children:[l(`rect`,{x:e,y:18-t*2,width:`4`,height:8+t*2,fill:`var(--rv-chart-2)`,rx:`0.6`}),l(`rect`,{x:e,y:13-t,width:`4`,height:`5`,fill:`var(--rv-chart-3)`,rx:`0.6`}),l(`rect`,{x:e,y:9-t,width:`4`,height:`4`,fill:`var(--rv-chart-1)`,rx:`0.6`})]},e))}):u(c,{children:[l(`rect`,{x:`9`,y:`18`,width:`4`,height:`8`,fill:`var(--rv-chart-2)`,rx:`0.7`}),l(`rect`,{x:`15`,y:`13`,width:`4`,height:`13`,fill:`var(--rv-chart-2)`,rx:`0.7`}),l(`rect`,{x:`21`,y:`8`,width:`4`,height:`18`,fill:`var(--rv-chart-2)`,rx:`0.7`})]})]}),gn=e=>{let[t,n]=s(!1),a=o(null),c=o(null),l=o(t);return l.current=t,r(()=>ln({isOpen:()=>l.current,contains:e=>!!(a.current&&e.includes(a.current)||c.current&&e.includes(c.current)),close:e=>{n(!1),e&&a.current?.focus()}}),[]),i(()=>{if(!t)return;let n=()=>{let t=a.current,n=c.current;if(!t||!n)return;n.style.left=`0px`,n.style.top=`0px`;let r=n.getBoundingClientRect(),i=t.getBoundingClientRect(),o=document.documentElement.clientWidth||window.innerWidth,s=document.documentElement.clientHeight||window.innerHeight,l=getComputedStyle(t).direction===`rtl`,u=e===`end`===l?i.left:i.right-r.width;u=Math.max(8,Math.min(u,o-r.width-8));let d=i.bottom+7;d+r.height>s-8&&i.top-7-r.height>8&&(d=i.top-7-r.height),n.style.left=`${u-r.left}px`,n.style.top=`${d-r.top}px`};return n(),window.addEventListener(`resize`,n),window.addEventListener(`scroll`,n,!0),c.current?.querySelector(`[aria-selected="true"], button`)?.focus({preventScroll:!0}),()=>{window.removeEventListener(`resize`,n),window.removeEventListener(`scroll`,n,!0)}},[t,e]),{open:t,setOpen:n,triggerRef:a,layerRef:c}},_n=({visualization:e,field:t,prefix:n,labels:r,locale:i,headerTitle:a})=>{let o=e.rows??[],s=e.columnMetadata?.find(e=>e.key===t),d=t?o[0]?.[t]:void 0,f=qe(d),p=t=>Tt(t,s,e,!1,i),m=f===null?String(d??r.noValue):p(f),h=e.periodComparison,g=!h?.measureField||h.measureField===t,_=t?qe(o[1]?.[t]):null,v=f!==null&&h&&g?fe(h,{value:f,status:`observed`,label:h.currentPeriod?.label},{value:_??h.previousFullValue??h.previousToDateValue,status:`observed`,label:h.previousPeriod?.label},{format:p,locale:i}):void 0,y=s?.label??(t?Gt(t):r.currentValue);return u(`section`,{class:`${n}-analytics-kpi`,"aria-label":a??y,"data-testid":`analytics-kpi`,children:[l(`div`,{class:`${n}-analytics-kpi__label`,children:y}),l(`div`,{class:`${n}-analytics-kpi__value`,children:m}),v?u(c,{children:[u(`div`,{class:`${n}-analytics-kpi__change is-${v.tone}`,"data-comparison-basis":v.basis,title:v.title,children:[l(`span`,{children:v.label}),v.copy?l(`span`,{class:`${n}-analytics-kpi__copy`,children:v.copy}):null]}),v.secondary?l(`div`,{class:`${n}-analytics-kpi__secondary`,children:v.secondary}):null]}):null]})},vn=({visualization:e,classPrefix:t,labels:n,locale:i,expanded:o=!1,onExpand:d,onClose:f,expandControlId:p,onFollowUp:m,onDownload:h,headerActions:g,children:_,dataToggle:v,cardRef:y,maxTableRows:b=100})=>{let x=a(()=>rt(n),[n]),S=a(()=>jt(e,void 0,{labels:x,locale:i}),[e,x,i]),[C,w]=s(S?.type);r(()=>w(S?.type),[S]);let[T,E]=s(!1),D=a(()=>Lt(e,x),[e,x]),O=a(()=>jt(e,C,{labels:x,locale:i}),[e,C,x,i]),k=C??O?.type??S?.type,A=D.find(e=>e.type===k),j=[...new Set(O?.series.map(e=>e.field)??[])],M=gn(`end`),N=gn(`start`),P=e.rows??[],F=tn(e),I=a(()=>xe(e),[e]),L=a(()=>nn(I),[I]),R=a(()=>({locale:i,timezone:e.timezone||e.periodComparison?.timezone,yes:x.yes,no:x.no}),[i,e.timezone,e.periodComparison?.timezone,x]),ee=en(e,x,i),z=h===!1||!e.downloadAvailable?null:()=>(h??an)(F,P),B=ee.length?u(`details`,{class:`${t}-analytics-inspect`,children:[l(`summary`,{children:x.aboutResult}),l(`dl`,{children:ee.map(e=>u(`div`,{children:[l(`dt`,{children:e.label}),l(`dd`,{children:e.value})]},e.label))})]}):null,V=(()=>{let t=e.freshness?.answeredAt,n=t?new Date(t):null;return!n||Number.isNaN(n.getTime())?x.liveData:tt(x.updatedAt,{time:new Intl.DateTimeFormat(i,{hour:`numeric`,minute:`2-digit`}).format(n)})})(),H=e.rowCount??P.length,te=e.appliedFilters?.length??0,ne=u(`div`,{class:`${t}-analytics-meta`,"data-testid":`analytics-result-meta`,role:`group`,"aria-label":x.resultDetails,children:[u(`span`,{children:[l(`span`,{"aria-hidden":`true`,class:`${t}-analytics-meta__dot`}),V]}),e.reportingPeriod?.label?l(`span`,{children:e.reportingPeriod.label}):null,l(`span`,{children:tt(H===1?x.rowOne:x.rowMany,{count:H})}),te>0?l(`span`,{children:tt(te===1?x.filtersOne:x.filtersMany,{count:te})}):null]}),U=(n,r,i,a=x.expandChart)=>u(`div`,{class:`${t}-analytics-result`,children:[u(`section`,{ref:y,class:`${t}-analytics-visualization${o?` is-expanded`:``}`,"aria-label":n,children:[u(`div`,{class:`${t}-analytics-visualization__header`,children:[u(`div`,{children:[l(`div`,{class:`${t}-analytics-visualization__title`,children:n}),ne]}),u(`div`,{class:`${t}-analytics-visualization__actions`,children:[i,g,o&&f?l(`button`,{type:`button`,class:`${t}-analytics-visualization__close`,"aria-label":x.restoreView,title:x.restoreView,onClick:f,children:l(fn,{})}):d&&e.expandable!==!1?l(`button`,{type:`button`,class:`${t}-analytics-visualization__expand`,"aria-label":a,title:a,"data-visualization-message":p,onClick:d,children:l(dn,{})}):null]})]}),r,B,_]}),u(`div`,{class:`${t}-analytics-layer`,children:[m?l(`div`,{ref:N.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:`fixed`},role:`menu`,"aria-label":x.aggregate,hidden:!N.open,children:j.flatMap(n=>Ft(e,n).map(r=>{let i=e.columnMetadata?.find(e=>e.key===n)?.label??Gt(n);return l(`button`,{type:`button`,role:`menuitem`,onClick:()=>{let t=It(e,n,r.value);t&&m(t),N.setOpen(!1)},children:u(`span`,{class:`${t}-analytics-chart-picker__copy`,children:[u(`strong`,{children:[Pt(r.value,x),` · `,i]}),l(`small`,{children:x.aggregateCharge})]})},`${n}:${r.value}`)}))}):null,l(`div`,{ref:M.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:`fixed`},role:`listbox`,"aria-label":x.chartType,hidden:!M.open,children:D.map(e=>{let n=e.type===k;return u(`button`,{type:`button`,role:`option`,"aria-selected":n,class:n?`is-selected`:``,onClick:()=>{w(e.type),M.setOpen(!1),M.triggerRef.current?.focus()},children:[l(`span`,{class:`${t}-analytics-chart-picker__icon`,children:l(hn,{type:e.type,className:`${t}-chart-type-icon`})}),u(`span`,{class:`${t}-analytics-chart-picker__copy`,children:[l(`strong`,{children:e.label}),l(`small`,{children:e.hint})]}),n?l(mn,{}):null]},e.type)})})]})]}),W=l($t,{rows:I.rows??P,columns:L,maxRows:b,expanded:o,classPrefix:t,locale:i,format:R}),G=()=>e.tableAvailable===!1||F.length===0?null:U(e.title?.trim()||x.resultDetails,l(c,{children:W}),z?l(`button`,{type:`button`,class:`${t}-analytics-visualization__download`,onClick:z,children:x.download}):null,x.expandTable);if(P.length===0)return u(c,{children:[u(`section`,{class:`${t}-analytics-empty`,role:`status`,"data-testid":`analytics-empty-state`,children:[l(`p`,{children:x.noMatchTitle}),l(`p`,{children:x.noMatchBody})]}),B,_]});if(e.presentation===`table`||!e.presentation&&e.type===`table`)return G()??l(c,{children:_});let K=v&&e.tableAvailable!==!1?l(`button`,{type:`button`,class:`${t}-analytics-visualization__download`,"aria-expanded":T,onClick:()=>E(e=>{let t=!e;return v.onToggle?.(t),t}),children:T?x.hideData:x.viewData}):null,q=T?l(`div`,{class:`${t}-analytics-data`,children:W}):null;return e.presentation===`kpi`||!e.presentation&&e.type===`kpi`?U(x.liveMetric,u(c,{children:[l(_n,{visualization:e,field:rn(e,F),prefix:t,labels:x,locale:i}),K,q]})):O?U(O.title,u(c,{children:[l(Wt,{model:O,expanded:o,classPrefix:t}),z?l(`button`,{type:`button`,class:`${t}-analytics-visualization__download`,onClick:z,children:x.downloadData}):null,K,q]}),u(c,{children:[m?l(`div`,{class:`${t}-analytics-chart-picker ${t}-analytics-chart-picker--aggregation`,children:u(`button`,{type:`button`,ref:N.triggerRef,"aria-haspopup":`menu`,"aria-expanded":N.open,"aria-label":x.aggregate,title:x.aggregateTitle,onClick:()=>{M.setOpen(!1),N.setOpen(!N.open)},children:[l(`span`,{class:`${t}-analytics-chart-picker__current`,children:l(`span`,{children:x.aggregate})}),l(pn,{})]})}):null,D.length>1?l(`div`,{class:`${t}-analytics-chart-picker`,children:u(`button`,{type:`button`,ref:M.triggerRef,"aria-haspopup":`listbox`,"aria-expanded":M.open,"aria-label":x.chooseChartType,title:x.chooseChartType,onClick:()=>{N.setOpen(!1),M.setOpen(!M.open)},children:[u(`span`,{class:`${t}-analytics-chart-picker__current`,children:[l(hn,{type:k??O.type,className:`${t}-chart-type-icon`}),l(`span`,{children:A?.label??x.chartFallback})]}),l(pn,{})]})}):null]})):G()??l(c,{children:_})},yn=[`#2563eb`,`#b45309`,`#7c3aed`],bn=[`#60a5fa`,`#fbbf24`,`#a78bfa`],xn=(e,t)=>{let n=`.${e}-analytics-visualization`,r=`.${e}-analytics-result`,i=`.${e}-analytics-chart-picker`,a=`.${e}-analytics-kpi`;return`
89
+ `};var Me=class{constructor(e,t,n,r={}){this.explanationId=e,this.submit=t,this.onChange=n,this.context=r,h(this,`state`,{phase:`idle`,reasons:[],comment:``})}set(e){this.state={...this.state,...e},this.onChange(this.state)}async save(e,t){let n=this.state;this.set({phase:`saving`,error:void 0});try{await this.submit(Ae({explanationId:this.explanationId,...this.context,...e})),this.set({...t,error:void 0})}catch{this.set({phase:n.phase===`details`?`details`:`error`,rating:n.rating,error:U.feedbackError})}}vote(e){return this.state.phase===`saving`?Promise.resolve():this.save({rating:e},e===`up`?{phase:`done`,rating:e,reasons:[],comment:``}:{phase:`details`,rating:e})}toggleReason(e){let t=this.state.reasons.includes(e)?this.state.reasons.filter(t=>t!==e):[...this.state.reasons,e];this.set({reasons:t})}setComment(e){this.set({comment:Array.from(e).slice(0,500).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 Ne={delaysMs:[1e3,2e3,4e3],capMs:45e3},Pe=e=>e===`pending`||e===`ready`||e===`failed`?e:`not_requested`,Fe=e=>Pe(e?.aiExplanation?.status);var Ie=class{constructor(e,t,n,r={}){this.transport=t,this.onChange=n,h(this,`state`,void 0),h(this,`handle`,void 0),h(this,`disposed`,!1),h(this,`generation`,0),h(this,`attempt`,0),h(this,`startedAt`,0),h(this,`delays`,void 0),h(this,`capMs`,void 0),h(this,`now`,void 0),h(this,`schedule`,void 0),h(this,`cancelTimer`,void 0),h(this,`isVisible`,void 0),h(this,`onSettled`,void 0),h(this,`inFlight`,null),h(this,`pausedAt`,null),h(this,`onVisibilityChange`,()=>{this.disposed||this.pausedAt===null||!this.isVisible()||(this.startedAt+=this.now()-this.pausedAt,this.pausedAt=null,this.queue())}),this.delays=r.delaysMs?.length?r.delaysMs:Ne.delaysMs,this.capMs=r.capMs??Ne.capMs,this.now=r.now??(()=>Date.now()),this.schedule=r.schedule??((e,t)=>setTimeout(e,t)),this.cancelTimer=r.cancel??(e=>clearTimeout(e)),this.isVisible=r.isVisible??(()=>typeof document>`u`||document.visibilityState!==`hidden`),this.onSettled=r.onSettled;let i=Fe(e),a=i===`pending`&&!t?`not_requested`:i;this.state={status:a,explanation:e,retryAvailable:a===`failed`&&this.canRetry(e.aiExplanation?.retryAvailable),retrying:!1,announcement:``}}get explanationId(){return this.state.explanation.aiExplanation?.explanationId||this.state.explanation.explanationId||``}canRetry(e){return!!this.transport?.retry&&e!==!1}set(e){if(this.disposed)return;let t=this.state.status;this.state={...this.state,...e},this.onChange(this.state);let n=this.state.status;n!==t&&(n===`ready`||n===`failed`||n===`not_requested`)&&this.onSettled?.(n)}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}let e=this.now()-this.startedAt;if(e>=this.capMs){this.fail(!0);return}let t=this.delays[Math.min(this.attempt,this.delays.length-1)]??4e3;this.attempt+=1;let n=this.generation;this.handle=this.schedule(()=>{this.pollOnce(n)},Math.min(t,Math.max(0,this.capMs-e)))}async pollOnce(e){if(this.disposed||e!==this.generation||!this.transport)return;if(!this.isVisible()){this.pausedAt??(this.pausedAt=this.now());return}let t=new AbortController;this.inFlight=t;try{let n=await this.transport.poll(this.explanationId,t.signal);if(this.disposed||e!==this.generation)return;this.apply(n)}catch{if(this.disposed||e!==this.generation)return;this.queue()}finally{this.inFlight===t&&(this.inFlight=null)}}apply(e){let t=Pe(e.status);if(this.applyBasicUpdate(e,t),t===`ready`&&e.explanation&&V(e.explanation)){this.set({status:`ready`,explanation:e.explanation,retryAvailable:!1,retrying:!1,announcement:U.detailedReady});return}if(t===`pending`){this.state.status!==`pending`&&this.set({status:`pending`,retrying:!1,announcement:``}),this.queue();return}if(t===`not_requested`){this.set({status:`not_requested`,retryAvailable:!1,retrying:!1,announcement:``});return}this.fail(this.canRetry(e.retryAvailable))}applyBasicUpdate(e,t){let n=e.basic;if(!n||t===`ready`||this.state.status===`ready`||!V(n))return;let r=this.state.explanation;n.headline===r.headline&&n.summary===r.summary||this.set({explanation:{...n,explanationId:r.explanationId??n.explanationId,aiExplanation:r.aiExplanation,level:r.level}})}fail(e){this.generation+=1,this.set({status:`failed`,retryAvailable:e&&this.canRetry(!0),retrying:!1,announcement:U.detailedUnavailable})}async retry(){if(!this.transport?.retry||this.state.retrying||this.state.status===`ready`)return;let e=this.explanationId;if(!e)return;this.generation+=1;let t=this.generation;this.set({retrying:!0,announcement:``});try{let n=await this.transport.retry(e);if(this.disposed||t!==this.generation)return;if(Pe(n.status)===`pending`){this.set({status:`pending`,retrying:!1,retryAvailable:!1,announcement:U.preparingDetailed}),this.startedAt=this.now(),this.attempt=0,this.queue();return}this.apply(n)}catch{if(this.disposed||t!==this.generation)return;this.set({status:`failed`,retrying:!1,retryAvailable:!1,announcement:U.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 Le=/^(\d{4})-(\d{2})-(\d{2})$/,Re=/^(\d{4})-(\d{2})$/,ze=/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?$/,Be=/(?:Z|[+-]\d{2}:?\d{2})$/i,Ve=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=Le.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=Re.exec(t),n)return{date:new Date(Date.UTC(Number(n[1]),Number(n[2])-1,1)),calendar:!0,hasTime:!1};if(n=ze.exec(t),n&&!Be.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 r=new Date(t);return Number.isNaN(r.getTime())?null:{date:r,calendar:!1,hasTime:!0}},He=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`}},Ue=e=>{let t=e.map(Ve).filter(e=>e!==null);if(t.length===0)return;let n=e=>e.date.getUTCHours()+e.date.getUTCMinutes();return t.some(e=>e.hasTime&&n(e)!==0)?t.every(e=>e.date.getUTCMinutes()===0)?`hour`:void 0:t.length>1&&t.every(e=>e.date.getUTCDate()===1)?`month`:`day`},We=(e,t)=>{try{return new Intl.DateTimeFormat(e,t)}catch{return new Intl.DateTimeFormat(e,{...t,timeZone:`UTC`})}},Ge=(e,t,n={})=>{let r=Ve(e);if(!r)return;let i=t?.grain??He(t?.formatPattern)??n.grain,a=r.calendar?`UTC`:n.timezone||void 0,{date:o}=r;switch(i){case`year`:return We(n.locale,{year:`numeric`,timeZone:a}).format(o);case`quarter`:{let e=Number(We(`en-US`,{month:`numeric`,timeZone:a}).format(o)),t=We(n.locale,{year:`numeric`,timeZone:a}).format(o);return`Q${Math.floor((e-1)/3)+1} ${t}`}case`month`:return We(n.locale,{month:`short`,year:`numeric`,timeZone:a}).format(o);case`week`:case`day`:return We(n.locale,{day:`numeric`,month:`short`,year:`numeric`,timeZone:a}).format(o);case`hour`:return We(n.locale,{day:`numeric`,month:`short`,hour:`numeric`,minute:`2-digit`,timeZone:a}).format(o);default:return We(n.locale,{dateStyle:`medium`,...r.hasTime?{timeStyle:`short`}:{},timeZone:a}).format(o)}},Ke=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}},qe=(e,t)=>{let n=Ke(e);return n?{minimumFractionDigits:n.min,maximumFractionDigits:n.max}:{maximumFractionDigits:t}},Je=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},Ye=(e,t)=>t&&Math.abs(e)>=1e4?`compact`:`standard`,Xe=(e,t={})=>new Intl.NumberFormat(t.locale,{notation:Ye(e,t.compact),...qe(t.pattern,t.maxFractionDigits??2)}).format(e),Ze=(e,t,n={})=>{let r=t?.trim().toUpperCase();if(r&&/^[A-Z]{3}$/.test(r))try{return new Intl.NumberFormat(n.locale,{style:`currency`,currency:r,notation:Ye(e,n.compact),...Ke(n.pattern)?qe(n.pattern,2):{}}).format(e)}catch{}return Xe(e,{...n,maxFractionDigits:2})},Qe=(e,t={})=>{let n=!!(t.pattern&&/(?<!\\)%/.test(t.pattern)),r=qe(t.pattern,2);return new Intl.NumberFormat(t.locale,{style:`percent`,...r}).format(n?e:e/100)},$e=(e,t,n={})=>{let{locale:r,compact:i}=n;return t?.dataType===`currency`?Ze(e,t.currencyCode||n.currencyCode,{locale:r,compact:i,pattern:t.formatPattern}):t?.dataType===`percent`?Qe(e,{locale:r,pattern:t.formatPattern}):Xe(e,{locale:r,compact:i,pattern:t?.formatPattern,maxFractionDigits:n.maxFractionDigits})},et=(e,t,n={})=>{if(e==null||e===``)return`—`;if(t?.dataType===`date`||t?.dataType===`datetime`){let r=Ge(e,t,n);if(r)return r}if(t?.dataType===`currency`||t?.dataType===`percent`){let r=Je(e);if(r!==null)return $e(r,t,n)}return typeof e==`number`&&Number.isFinite(e)?$e(e,t,{...n,maxFractionDigits:4}):typeof e==`boolean`?e?n.yes??`Yes`:n.no??`No`:String(e)},tt={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`},nt=(e,t)=>e.replace(/\{(\w+)\}/g,(e,n)=>String(t[n]??``)),rt=e=>Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!=null)),it=e=>({...tt,...rt(e),explanation:{...e?.explanation}});let at=()=>import(`./echarts-runtime-Bu1uy4oO.mjs`),ot=null;const st=()=>(ot||(ot=at().catch(e=>{throw ot=null,e})),ot),ct={background:`#ffffff`,border:`#dce4e9`,muted:`#5b7186`,surface:`#ffffff`,text:`#0f1e2a`,colors:[`#2f7f55`,`#2563eb`,`#b45309`,`#7c3aed`]},lt=`cf-widget-category-zoom`,ut=.68,dt=e=>({startIndex:0,endIndex:Math.max(0,e-1)}),ft=(e,t)=>{if(t<=0)return dt(0);let n=t-1,r=Math.max(0,Math.min(n,Math.floor(Math.min(e.startIndex,e.endIndex))));return{startIndex:r,endIndex:Math.max(r,Math.min(n,Math.floor(Math.max(e.startIndex,e.endIndex))))}},pt=(e,t,n)=>{let r=ft(e,n);if(n<=2)return dt(n);let i=r.endIndex-r.startIndex+1,a=t===`in`?Math.max(2,Math.floor(i*ut)):Math.min(n,Math.ceil(i/ut));if(a===i)return r;let o=(r.startIndex+r.endIndex)/2,s=n-a,c=Math.max(0,Math.min(s,Math.round(o-(a-1)/2)));return{startIndex:c,endIndex:c+a-1}},mt=(e,t,n=tt)=>{let r=e.length;if(r===0)return n.zoomNone;let i=ft(t,r);return i.startIndex===0&&i.endIndex===r-1?nt(r===1?n.zoomAllOne:n.zoomAllMany,{count:r}):nt(n.zoomRange,{start:e[i.startIndex]??``,end:e[i.endIndex]??``,visible:i.endIndex-i.startIndex+1,count:r})},ht=e=>{let t=e.replaceAll(`_`,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).trim();return t?`${t.charAt(0).toUpperCase()}${t.slice(1)}`:`Value`},gt=e=>{let t=new Set,n=[];return e.forEach(e=>{let r=e?.trim();!r||t.has(r)||(t.add(r),n.push(r))}),n},_t=Je,vt=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)}`},yt=(e,t)=>t?e.columnMetadata?.find(e=>e.key===t):void 0,bt=(e,t)=>{let n=yt(e,t);if(!n||n.currencyCode||n.dataType!==`currency`)return n;let r=e.currency;return r?.code&&!r.isMixed?{...n,currencyCode:r.code}:n},xt=(e,t)=>yt(e,t)?.label?.trim()||ht(t),St=(e,t,n,r)=>({locale:t,timezone:e.timezone||e.periodComparison?.timezone,grain:r,yes:n.yes,no:n.no}),Ct=e=>e?.dataType===`date`||e?.dataType===`datetime`||e?.semanticRole===`date`,wt=(e,t,n)=>{let r=yt(e,t);if(Ct(r))return r?.grain??e.periodComparison?.grain??Ue(n.map(e=>e[t]))},Tt=(e,t,n,r,i,a)=>{if(n==null||n===``)return r.notSet;let o=yt(e,t);if(o?.dataType===`boolean`){let e=String(n).trim().toLowerCase();return n===!1||n===0||[`0`,`false`,`no`].includes(e)?r.no:r.yes}if(Ct(o)){let t=Ge(n,o,St(e,i,r,a));if(t)return t}return String(n)},Et=(e,t,n,r=!1,i)=>$e(e,t,{locale:i,compact:r,currencyCode:n?.currency?.code&&!n.currency.isMixed?n.currency.code:void 0}),Dt=(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},Ot=e=>e.chartRecommendation?.categoryField?.trim()||e.label?.trim()||e.columnMetadata?.find(e=>[`date`,`dimension`,`geography`,`boolean`].includes(e.semanticRole))?.key||e.columns?.[0],kt=e=>e.chartRecommendation?.seriesField?.trim()||e.seriesField?.trim()||e.series?.trim()||void 0,At=(e,t,n)=>{let r=gt([...e.chartRecommendation?.valueFields??[],...e.valueFields??[],e.value,...e.columnMetadata?.filter(e=>e.semanticRole===`measure`).map(e=>e.key)??[]]),i=new Set([...e.columns??[],...e.columnMetadata?.map(e=>e.key)??[],...Object.keys(e.rows?.[0]??{})]);return r.filter(e=>e!==t&&e!==n&&i.has(e)).filter(t=>e.rows?.some(e=>_t(e[t])!==null))},jt=(e,t,n,r,i,a,o)=>{let s=i?` ${nt(a.seriesLimited,{shown:r.length,total:r.length+i})}`:``,c=(t,n)=>Et(t,n,e,!1,o);if(t===`line`){let e=n.length-1,t=r.map(t=>{let n=t.values[e];return n==null?null:`${t.name}: ${c(n,t.valueColumn)}`}).filter(e=>!!e);return t.length?`${nt(a.summaryLatest,{category:n[e]??``,values:t.join(`; `)})}${s}`:`${a.summaryNoTrend}${s}`}let l;return r.forEach(e=>{e.values.forEach((t,r)=>{t===null||l&&t<=l.value||(l={category:n[r]??a.notSet,series:e,value:t})})}),l?`${nt(a.summaryHighest,{category:l.category,series:l.series.name,value:c(l.value,l.series.valueColumn)})}${s}`:`${a.summaryNoComparison}${s}`},Mt=(e,t,n={})=>{let r=it(n.labels),i=n.locale,a=Dt(e,t),o=Ot(e),s=e.rows??[];if(!a||!o||s.length===0)return null;let c=kt(e),l=At(e,o,c);if(l.length===0)return null;let u=l.length===1?c:void 0,d=wt(e,o,s),f=l[0],p=u&&_e(e.periodComparison)&&(!e.periodComparison.measureField||!f||f===e.periodComparison.measureField||f.endsWith(`.${e.periodComparison.measureField}`)||e.periodComparison.measureField.endsWith(`.${f}`))?e.periodComparison:void 0,m=(()=>{if(!p?.seriesField||!u)return;let e=(e,t)=>e===t||e.endsWith(`.${t}`)||t.endsWith(`.${e}`);if(e(p.seriesField,o))return{group:o,time:u,timeIsSeries:!0};if(e(p.seriesField,u))return{group:u,time:o,timeIsSeries:!1}})(),h=t=>Et(t,bt(e,f??``),e,!1,i),g=e=>p&&m?ge(p,e[m.time],e[m.group],{format:h,locale:i}):void 0,_=(e,t)=>p?.comparisonBasis===`like_for_like`&&ge(p,e,p.series?.[0]?.key)?.side===`previous`?me(p):t,v=[],y=new Set;s.forEach(t=>{let n=vt(t[o]);if(y.has(n))return;y.add(n);let a=Tt(e,o,t[o],r,i,d);v.push({key:n,label:m&&!m.timeIsSeries?_(t[o],a):a})});let b=v.map(e=>e.label),x=0,S;if(u){let t=[],n=new Set;s.forEach(a=>{let o=vt(a[u]);if(n.has(o))return;n.add(o);let c=Tt(e,u,a[u],r,i,wt(e,u,s));t.push({key:o,label:m?.timeIsSeries?_(a[u],c):c})});let a=t.slice(0,4);x=Math.max(0,t.length-a.length);let c=l[0];S=a.map(t=>{let n=new Map,r=new Map;return s.forEach(e=>{if(vt(e[u])!==t.key)return;let i=vt(e[o]);if(!n.has(i)){let t=g(e);r.set(i,t),n.set(i,t?.side===`previous`&&t.plotValue!==void 0?t.plotValue:_t(e[c]))}}),{field:c,name:t.label,values:v.map(e=>n.get(e.key)??null),valueColumn:bt(e,c),...m?{points:v.map(e=>r.get(e.key))}:{}}})}else x=Math.max(0,l.length-4),S=l.slice(0,4).map(t=>({field:t,name:xt(e,t),values:s.map(e=>_t(e[t])),valueColumn:bt(e,t)}));if(S.length===0)return null;let C=xt(e,o),w=r.chartValues;u?w=xt(e,l[0]):S.length===1&&(w=S[0].name);let T=e.title?.trim()||nt(r.chartTitle,{measure:w,dimension:C}),E;if(yt(e,o)?.semanticRole===`date`&&v.length>1&&Ce(e)){let e=``;s.forEach(t=>{let n=String(t[o]??``);n>e&&(e=n)});let t=v.findIndex(t=>t.key===vt(e));t>=0&&(E=t)}return{type:a,title:T,xAxisTitle:C,yAxisTitle:w,categories:b,series:S,omittedSeriesCount:x,inProgressIndex:E,...m&&p?{comparison:p,comparisonNote:ve(p)}:{},locale:i,labels:r,summary:jt(e,a,b,S,x,r,i)}},Nt=[{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`}],Pt={sum:`aggregationSum`,avg:`aggregationAvg`,min:`aggregationMin`,max:`aggregationMax`,count:`aggregationCount`,count_distinct:`aggregationCountDistinct`},Ft=(e,t=tt)=>String(t[Pt[e]]),It=(e,t)=>{let n=e.columnMetadata?.find(e=>e.key===t)?.allowedAggregations;return n?.length?Nt.filter(e=>n.includes(e.value)):[...Nt]},Lt=(e,t,n)=>{let r=Ot(e);if(!r||!At(e,r,kt(e)).includes(t)||!It(e,t).some(e=>e.value===n))return;let i=Nt.find(e=>e.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 ${xt(e,t)} for each ${xt(e,r)}. Return a chart and show a table if this app permits it.`},Rt=(e,t=tt)=>{if(e.presentation===`table`||e.presentation===`kpi`)return[];let n=Mt(e);if(!n)return[];let r=[{type:`line`,label:t.chartLine,hint:t.chartLineHint},{type:`bar`,label:t.chartBar,hint:t.chartBarHint}];return n.series.length>1&&r.push({type:`stacked_bar`,label:t.chartStackedBar,hint:t.chartStackedBarHint}),r},zt=e=>t=>{let n=e.inProgressIndex??-1,r=(Array.isArray(t)?t:[t]).filter(e=>{if(!e||typeof e!=`object`)return!1;let t=String(e.seriesId??``).startsWith(`in-progress:`),r=e.dataIndex,i=e.value;return t?r===n:!(r===n&&i==null)}),i=String(r[0]?.axisValueLabel??r[0]?.name??``),a=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`);return[i?`<strong>${a(i)}</strong>`:``,...r.map(t=>{let n=e.series[Math.floor(Number(t.seriesIndex)/2)]??e.series[0];return`${String(t.marker??``)}${a(String(t.seriesName??``))}: ${a(Et(t.value,n?.valueColumn,void 0,!1,e.locale))}`})].filter(Boolean).join(`<br/>`)},Bt=e=>t=>{let n=(Array.isArray(t)?t:[t]).filter(e=>!!e&&typeof e==`object`),r=e=>e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`),i=String(n[0]?.axisValueLabel??n[0]?.name??``),a=n.flatMap(t=>{let n=e.series[Number(t.seriesIndex)]??e.series[0],i=n?.points?.[Number(t.dataIndex)],a=t=>Et(t,n?.valueColumn,void 0,!1,e.locale);return[`${String(t.marker??``)}${r(String(t.seriesName??``))}: ${r(a(t.value))}`,...ye(e.comparison,i,a).map(e=>`<span style="opacity:.75">${r(e)}</span>`)]});return[i?`<strong>${r(i)}</strong>`:``,...a].filter(Boolean).join(`<br/>`)},Vt=(e,{expanded:t=!1,reducedMotion:n=!1,theme:r=ct,zoomWindow:i=dt(e.categories.length)}={})=>{let a=e.series.length>1||e.type===`line`&&(e.inProgressIndex??0)>0,o=e.type===`stacked_bar`,s=e.categories.length>2,c=ft(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:r.colors,textStyle:{color:r.text,fontFamily:`inherit`},grid:{top:a?t?48:42:14,right:12,bottom:t?18:10,left:10,containLabel:!0},legend:{show:a,type:`scroll`,top:0,left:`center`,itemWidth:12,itemHeight:8,textStyle:{color:r.muted,fontSize:t?11:10}},tooltip:{trigger:`axis`,...e.type===`line`&&(e.inProgressIndex??0)>0?{formatter:zt(e)}:e.comparison?{formatter:Bt(e)}:{},triggerOn:`mousemove|click`,confine:!0,backgroundColor:r.surface,borderColor:r.border,borderWidth:1,textStyle:{color:r.text,fontSize:12},axisPointer:{type:`line`,lineStyle:{color:r.muted,opacity:.5}}},dataZoom:s?[{id:lt,type:`inside`,xAxisIndex:0,startValue:c.startIndex,endValue:c.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:r.muted,fontSize:t?11:10},axisLine:{lineStyle:{color:r.border}},axisTick:{show:!1},axisLabel:{color:r.muted,fontSize:t?11:9,hideOverlap:!0,interval:`auto`,rotate:!t&&e.categories.length>5?28:0,formatter:e=>e.length>(t?18:11)?`${e.slice(0,t?16:9)}…`:e}},yAxis:{type:`value`,name:e.yAxisTitle,nameLocation:`middle`,nameGap:t?52:44,nameTextStyle:{color:r.muted,fontSize:t?11:10},axisLabel:{color:r.muted,fontSize:t?11:9,formatter:t=>Et(t,e.series[0]?.valueColumn,void 0,!0,e.locale)},axisLine:{show:!1},axisTick:{show:!1},splitNumber:4,splitLine:{lineStyle:{color:r.border,opacity:.75}}},series:e.series.flatMap((n,i)=>{let a=e.inProgressIndex??-1,s={type:e.type===`line`?`line`:`bar`,name:n.name,data:n.values,stack:o?`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:r.background,borderWidth:2}:{borderRadius:o?0:[4,4,0,0]},emphasis:{focus:`series`},tooltip:{valueFormatter:t=>Et(t,n.valueColumn,void 0,!1,e.locale)}};if(a<0)return[s];let c=r.colors[i%r.colors.length];return e.type===`line`?a===0?[s]:[{...s,lineStyle:{...s.lineStyle,color:c},itemStyle:{...s.itemStyle,color:c},data:n.values.map((e,t)=>t===a?null:e)},{...s,id:`in-progress:${i}`,name:e.labels.inProgressLegend||`In progress`,showSymbol:!0,symbol:`emptyCircle`,lineStyle:{width:t?3:2.5,type:`dashed`,color:c,opacity:.6},itemStyle:{color:c,opacity:.6},data:n.values.map((e,t)=>t===a||t===a-1?e:null)}]:[{...s,data:n.values.map((e,t)=>t===a?{value:e,itemStyle:{opacity:.45,borderType:`dashed`,borderWidth:1.5,borderColor:c}}:e)}]})}},Ht=e=>{let t=getComputedStyle(e),n=(e,n)=>{for(let n of e){let e=t.getPropertyValue(n).trim();if(e)return e}return n},[r,i,a,o]=ct.colors;return{background:n([`--rv-bg`,`--cf-bg`],ct.background),border:n([`--rv-border`,`--cf-border`],ct.border),muted:n([`--rv-muted`,`--cf-muted`],ct.muted),surface:n([`--rv-surface`,`--cf-surface`],ct.surface),text:n([`--rv-text`,`--cf-text`],ct.text),colors:[n([`--rv-chart-1`,`--rv-accent`,`--cf-accent`],r),n([`--rv-chart-2`],i),n([`--rv-chart-3`],a),n([`--rv-chart-4`],o)]}},Ut=[`data-theme`,`data-color-scheme`,`class`,`style`],Wt=(e,t)=>{let n=[];if(typeof matchMedia<`u`){let e=matchMedia(`(prefers-color-scheme: dark)`);e.addEventListener?.(`change`,t),n.push(()=>e.removeEventListener?.(`change`,t))}if(typeof MutationObserver<`u`){let r=new MutationObserver(t),i=e;for(;i;){i instanceof Element&&r.observe(i,{attributes:!0,attributeFilter:Ut});let e=i.parentNode;i=e instanceof ShadowRoot?e.host:e}n.push(()=>r.disconnect())}return()=>n.forEach(e=>e())},Gt=({model:e,expanded:t=!1,classPrefix:n=`cf`})=>{let i=o(null),a=o(null),[d,f]=s(()=>({model:e,window:dt(e.categories.length)})),[p,m]=s(!1),h=d.model===e?ft(d.window,e.categories.length):dt(e.categories.length),g=o(h);g.current=h;let _=t=>{let n=ft(t,e.categories.length);g.current=n,f({model:e,window:n}),a.current?.dispatchAction({type:`dataZoom`,dataZoomId:lt,startValue:n.startIndex,endValue:n.endIndex})},[v,y]=s(!1),[b,x]=s(0),[S,C]=s(0);r(()=>{let e=i.current;if(e)return Wt(e,()=>C(e=>e+1))},[]),r(()=>{let e=i.current;if(!e)return;let t=!1,n=null;return st().then(({init:r})=>{if(t||!e.isConnected||typeof navigator<`u`&&navigator.userAgent.toLowerCase().includes(`jsdom`))return;let i=r(e,null,{renderer:`canvas`,devicePixelRatio:Math.min(window.devicePixelRatio||1,2)});a.current=i;let o=()=>{i.resize(),x(Math.round(e.clientWidth/40))},s=typeof ResizeObserver>`u`?null:new ResizeObserver(o);s?.observe(e),s||window.addEventListener(`resize`,o,{passive:!0}),n=()=>{s?.disconnect(),s||window.removeEventListener(`resize`,o),i.dispose(),a.current=null},y(!0)}).catch(()=>{t||m(!0)}),()=>{t=!0,n?.()}},[]),r(()=>{let n=i.current,r=a.current;if(!n||!r)return;let o=typeof matchMedia<`u`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches;r.setOption(B(Vt(e,{expanded:t,reducedMotion:o,theme:Ht(n),zoomWindow:g.current}),n.clientWidth),{lazyUpdate:!0,notMerge:!0}),r.resize()},[t,e,v,S,b]);let w=e.labels,T=!p&&e.categories.length>2,E=h.endIndex-h.startIndex+1,D=h.startIndex===0&&h.endIndex===e.categories.length-1,O=T&&E>2,k=T&&!D;return u(c,{children:[l(`div`,{ref:i,class:`${n}-analytics-echart${t?` is-expanded`:``}`,role:`img`,"aria-label":`${e.title}. ${e.summary}`,"data-chart-status":p?`fallback`:`ready`,children:p?l(`span`,{class:`${n}-analytics-echart__fallback`,children:e.summary}):null}),e.comparisonNote?l(`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?u(`div`,{class:`${n}-analytics-zoom`,children:[l(`span`,{class:`${n}-analytics-zoom__range`,"aria-live":`polite`,"aria-atomic":`true`,children:mt(e.categories,h,w)}),u(`div`,{class:`${n}-analytics-zoom__controls`,role:`group`,"aria-label":w.zoomControls,children:[l(`button`,{type:`button`,"aria-label":w.zoomOut,title:w.zoomOut,disabled:!k,onClick:()=>_(pt(g.current,`out`,e.categories.length)),children:`−`}),l(`button`,{type:`button`,class:`${n}-analytics-zoom__reset`,"aria-label":w.zoomReset,title:w.zoomReset,disabled:D,onClick:()=>_(dt(e.categories.length)),children:w.zoomResetShort}),l(`button`,{type:`button`,"aria-label":w.zoomIn,title:w.zoomIn,disabled:!O,onClick:()=>_(pt(g.current,`in`,e.categories.length)),children:`+`})]})]}):null]})},Kt=e=>{let t=e.replaceAll(`_`,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).trim();return t?`${t.charAt(0).toUpperCase()}${t.slice(1)}`:`Value`},qt=(e,t)=>(t?.length?t:Object.keys(e[0]??{})).map(e=>typeof e==`string`?{key:e,label:Kt(e)}:{...e,label:e.label?.trim()||Kt(e.key)}),Jt=(e,t,n,r={})=>et(e,n,{...r,locale:t??r.locale}),Yt=e=>{let t=String(e??``);return/[",\r\n]/.test(t)?`"${t.replaceAll(`"`,`""`)}"`:t},Xt=(e,t)=>{let n=qt(e,t);return[n.map(e=>Yt(e.label)).join(`,`),...e.map(e=>n.map(t=>Yt(e[t.key])).join(`,`))].join(`\r
90
+ `)},Zt=({label:e,options:t,value:n,onChange:i,classPrefix:a})=>{let c=o(null),d=o(null),[f,p]=s(n),[m,h]=s(!1);r(()=>p(n),[n]);let g=e=>`${a}-${e}`,_=e=>{p(e),c.current&&(c.current.dataset.value=e,c.current.open=!1,c.current.querySelector(`summary`)?.focus()),i?.(e)};return u(`details`,{ref:c,"data-result-popover":!0,"data-result-select":!0,"data-value":f,class:g(`sdk-select`),onToggle:e=>{let t=e.currentTarget.open;h(t);let n=d.current;if(n){if(n.setAttribute(`popover`,`manual`),!t){typeof n.hidePopover==`function`&&n.matches(`:popover-open`)&&n.hidePopover();return}typeof n.showPopover==`function`&&!n.matches(`:popover-open`)&&n.showPopover(),requestAnimationFrame(()=>{if(!c.current?.open||!n.isConnected)return;let e=c.current.querySelector(`summary`).getBoundingClientRect(),t=Math.max(e.width,Math.min(220,innerWidth-24)),r=Math.min(n.scrollHeight,240);n.style.width=`${t}px`,n.style.left=`${Math.max(12,Math.min(e.left,innerWidth-t-12))}px`,n.style.top=`${e.bottom+r+6<=innerHeight-12?e.bottom+6:Math.max(12,e.top-r-6)}px`})}},children:[u(`summary`,{class:g(`sdk-select-trigger`),role:`combobox`,"aria-label":e,"aria-haspopup":`listbox`,"aria-expanded":m,children:[l(`span`,{children:t.find(([e])=>e===f)?.[1]??f}),l(`span`,{"aria-hidden":`true`,children:`⌄`})]}),l(`div`,{ref:d,class:g(`sdk-select-list`),role:`listbox`,"aria-label":e,popover:`manual`,children:t.map(([e,t])=>l(`button`,{type:`button`,role:`option`,"aria-selected":e===f,onClick:()=>_(e),children:t},e))})]})},Qt=({rows:e,columns:t,maxRows:n=6,locale:r,format:i,expanded:a=!1,classNames:o,emptyLabel:s=`No rows returned.`})=>{let d=qt(e,t),f=a?e:e.slice(0,Math.max(1,n));return e.length===0||d.length===0?l(`div`,{class:o?.note,children:s}):u(c,{children:[l(`div`,{class:o?.wrap,role:`region`,"aria-label":`Result table with ${e.length} ${e.length===1?`row`:`rows`}`,tabIndex:0,children:u(`table`,{class:o?.table,children:[u(`caption`,{style:`position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)`,children:[`Result table with `,e.length,` `,e.length===1?`row`:`rows`]}),l(`thead`,{children:l(`tr`,{children:d.map(e=>l(`th`,{scope:`col`,children:e.label},e.key))})}),l(`tbody`,{children:f.map((e,t)=>l(`tr`,{children:d.map(t=>l(`td`,{children:Jt(e[t.key],r,t,i)},t.key))},t))})]})}),!a&&e.length>f.length?u(`div`,{class:o?.note,children:[`Showing `,f.length,` of `,e.length,` rows. Expand to view all rows.`]}):null]})},$t=(e,t,n)=>{let r=n.value.trim();if(!r)return!0;let i=String(e??``),a=typeof e==`number`?e:NaN,o=Number(r),s=!Number.isNaN(a)&&!Number.isNaN(o)?a-o:i.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`});switch(n.operator){case`equals`:return s===0;case`not_equals`:return s!==0;case`gt`:return s>0;case`gte`:return s>=0;case`lt`:return s<0;case`lte`:return s<=0;default:return i.toLocaleLowerCase().includes(r.toLocaleLowerCase())||t.toLocaleLowerCase().includes(r.toLocaleLowerCase())}},en=({rows:e,columns:t,maxRows:n=100,locale:i,format:c,expanded:d=!1,classPrefix:f=`cr`,pageSize:p=10})=>{let m=a(()=>qt(e,t),[t,e]),h=m.map(e=>e.key).join(`\0`),[g,_]=s(()=>m.map(e=>e.key)),[v,y]=s(``),[b,x]=s(),[S,C]=s(`asc`),[w,T]=s({}),[E,D]=s(),[O,k]=s([]),[A,j]=s({}),[M,N]=s(()=>m.map(e=>e.key)),[P,F]=s(!1),[I,L]=s([]),[R,ee]=s(`table`),[z,B]=s(1),[V,H]=s(p),U=o(null);r(()=>{let e=e=>{let t=e.composedPath();U.current?.querySelectorAll(`details[data-result-popover][open]`).forEach(e=>{t.includes(e)||(e.open=!1)})},t=e=>{let t=[...U.current?.querySelectorAll(`details[data-result-popover][open]`)??[]].at(-1);e.key!==`Escape`||!t||(t.open=!1,t.querySelector(`summary`)?.focus(),e.preventDefault())};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[]),r(()=>{_(m.map(e=>e.key)),x(void 0),T({}),D(void 0),k([]),j({}),N(m.map(e=>e.key)),L([]),B(1)},[h]);let te=M.map(e=>m.find(t=>t.key===e)).filter(e=>!!(e&&g.includes(e.key))),W=a(()=>{let t=v.toLocaleLowerCase(i),n=e.map((e,t)=>({row:e,index:t})).filter(({row:e})=>te.some(n=>Jt(e[n.key],i,n,c).toLocaleLowerCase(i).includes(t))&&Object.entries(w).every(([t,n])=>{let r=m.find(e=>e.key===t);return $t(e[t],Jt(e[t],i,r,c),n)}));return b?n.sort((e,t)=>{let n=e.row[b],r=t.row[b],a=typeof n==`number`?n:NaN,o=typeof r==`number`?r:NaN,s=!Number.isNaN(a)&&!Number.isNaN(o)?a-o:String(n??``).localeCompare(String(r??``),i,{numeric:!0,sensitivity:`base`});return S===`asc`?s:-s}):n},[te,w,c,i,v,m,e,S,b]),G=W.slice(0,Math.max(1,n)),K=Math.max(1,Math.ceil(G.length/V)),q=Math.min(z,K),J=d?G:G.slice((q-1)*V,q*V),ne=J.length>0&&J.every(({index:e})=>I.includes(e)),Y=e=>`${f}-${e}`,re=()=>{_(m.map(e=>e.key)),N(m.map(e=>e.key)),j({}),x(void 0),C(`asc`),T({}),D(void 0),k([]),F(!1),y(``),L([]),ee(`table`),B(1)};if(e.length===0||m.length===0)return l(`div`,{class:Y(`table-note`),children:`No rows returned.`});let ie=e=>{let t=new Set(J.map(({index:e})=>e));L(n=>e?[...new Set([...n,...t])]:n.filter(e=>!t.has(e)))};return u(`section`,{ref:U,class:Y(`data-table`),children:[u(`div`,{class:Y(`table-fields`),children:[l(`strong`,{children:`Fields`}),l(`div`,{class:Y(`field-list`),children:m.map(e=>l(`span`,{class:Y(`field-chip`),children:e.label},e.key))}),u(`span`,{class:Y(`table-field-count`),children:[e.length.toLocaleString(i),` rows`]})]}),u(`div`,{class:Y(`table-controls`),children:[u(`label`,{class:Y(`table-search`),children:[l(`span`,{"aria-hidden":`true`,children:`⌕`}),l(`input`,{type:`search`,value:v,placeholder:`Search this result...`,"aria-label":`Search this result`,onInput:e=>{y(e.currentTarget.value.trim()),B(1)}})]}),l(`div`,{class:Y(`table-modes`),role:`group`,"aria-label":`Table display mode`,children:[`table`,`matrix`].map(e=>l(`button`,{type:`button`,class:`${Y(`segment`)}${R===e?` is-active`:``}`,"aria-pressed":R===e,onClick:()=>ee(e),children:e===`table`?`Table`:`Matrix`},e))})]}),u(`div`,{class:Y(`table-column-bar`),children:[u(`details`,{"data-result-popover":!0,class:Y(`column-picker`),children:[l(`summary`,{children:`Columns`}),l(`div`,{class:Y(`column-menu`),children:M.map((e,t)=>{let n=m.find(t=>t.key===e);return n?u(`div`,{class:Y(`column-picker-row`),children:[u(`label`,{children:[l(`input`,{type:`checkbox`,checked:g.includes(n.key),onChange:e=>{let t=e.currentTarget.checked;_(e=>t?[...new Set([...e,n.key])]:e.length>1?e.filter(e=>e!==n.key):e)}}),l(`span`,{children:A[n.key]||n.label})]}),l(`button`,{type:`button`,"aria-label":`Move ${n.label} left`,disabled:t===0,onClick:()=>N(e=>{let n=[...e];return[n[t-1],n[t]]=[n[t],n[t-1]],n}),children:`↑`}),l(`button`,{type:`button`,"aria-label":`Move ${n.label} right`,disabled:t===M.length-1,onClick:()=>N(e=>{let n=[...e];return[n[t+1],n[t]]=[n[t],n[t+1]],n}),children:`↓`})]},n.key):null})})]}),l(`button`,{type:`button`,class:Y(`table-view-button`),"aria-pressed":P,onClick:()=>F(e=>!e),children:P?`Comfortable rows`:`Compact rows`}),l(`button`,{type:`button`,class:Y(`table-view-button`),onClick:re,children:`Reset view`})]}),Object.keys(w).length?l(`div`,{class:Y(`table-filter-bar`),children:Object.entries(w).map(([e,t])=>{let n=m.find(t=>t.key===e);return u(`button`,{type:`button`,class:Y(`table-filter-chip`),"aria-label":`Clear ${n?.label??e} filter`,onClick:()=>T(t=>{let n={...t};return delete n[e],n}),children:[A[e]||n?.label||e,` `,t.operator.replaceAll(`_`,` `),` `,t.value,` ×`]},e)})}):null,l(`div`,{class:Y(`table-wrap`),role:`region`,"aria-label":`Scrollable result table`,tabIndex:0,children:u(`table`,{class:`${Y(`table`)}${R===`matrix`?` is-matrix`:``}${P?` is-compact`:``}`,children:[u(`caption`,{class:Y(`visually-hidden`),children:[`Result table with `,W.length,` `,W.length===1?`row`:`rows`]}),l(`thead`,{children:u(`tr`,{children:[l(`th`,{class:Y(`select-cell`),children:l(`input`,{type:`checkbox`,"aria-label":`Select all visible rows`,checked:ne,onChange:e=>ie(e.currentTarget.checked)})}),te.map(e=>u(`th`,{scope:`col`,class:E===e.key?`is-pinned`:void 0,style:E===e.key?{left:`34px`}:void 0,"aria-sort":b===e.key?S===`asc`?`ascending`:`descending`:`none`,children:[u(`button`,{type:`button`,class:Y(`table-sort`),"aria-label":`Sort by ${e.label}`,onClick:()=>{b===e.key?C(e=>e===`asc`?`desc`:`asc`):(x(e.key),C(`asc`)),B(1)},children:[l(`span`,{children:A[e.key]||e.label}),l(`span`,{class:Y(`sort-direction`),"aria-hidden":`true`,children:b===e.key?S===`asc`?`↑`:`↓`:`↕`})]}),u(`details`,{"data-result-popover":!0,class:Y(`table-column-menu`),onToggle:e=>{let t=e.currentTarget,n=t.querySelector(`.${Y(`table-column-panel`)}`);if(n?.setAttribute(`popover`,`manual`),!t.open){n&&typeof n.hidePopover==`function`&&n.matches(`:popover-open`)&&n.hidePopover(),t.querySelectorAll(`details[data-result-select][open]`).forEach(e=>{e.open=!1});return}U.current?.querySelectorAll(`details[data-result-popover][open]`).forEach(e=>{e!==t&&!t.contains(e)&&(e.open=!1)}),n&&typeof n.showPopover==`function`&&!n.matches(`:popover-open`)&&n.showPopover(),requestAnimationFrame(()=>{if(!t.open||!t.isConnected)return;let e=t.querySelector(`summary`)?.getBoundingClientRect();if(!e||!n)return;let{width:r,height:i}=n.getBoundingClientRect(),a=e.bottom+i+5<=innerHeight-12?e.bottom+5:e.top-i-5;n.style.left=`${Math.max(12,Math.min(e.right-r,innerWidth-r-12))}px`,n.style.top=`${Math.max(12,Math.min(a,innerHeight-i-12))}px`})},children:[l(`summary`,{"aria-label":`Actions for ${e.label}`,children:`⋯`}),u(`div`,{class:Y(`table-column-panel`),popover:`manual`,children:[l(`strong`,{children:A[e.key]||e.label}),l(`button`,{type:`button`,onClick:()=>{x(e.key),C(`asc`),B(1)},children:`Sort ascending`}),l(`button`,{type:`button`,onClick:()=>{x(e.key),C(`desc`),B(1)},children:`Sort descending`}),l(`span`,{children:`Filter values`}),l(Zt,{classPrefix:f,label:`Filter operator for ${e.label}`,value:w[e.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`]]}),l(`input`,{type:`text`,"aria-label":`Filter value for ${e.label}`,defaultValue:w[e.key]?.value??``,placeholder:`Enter a value`}),l(`button`,{type:`button`,onClick:t=>{let n=t.currentTarget.parentElement,r=n.querySelector(`input[aria-label^="Filter value"]`).value.trim(),i=n.querySelector(`[data-result-select]`).dataset.value;T(t=>{let n={...t};return r?n[e.key]={operator:i,value:r}:delete n[e.key],n}),B(1),t.currentTarget.closest(`details`).open=!1},children:`Apply filter`}),l(`button`,{type:`button`,onClick:t=>{D(t=>t===e.key?void 0:e.key),N(t=>[e.key,...t.filter(t=>t!==e.key)]),t.currentTarget.closest(`details`).open=!1},children:E===e.key?`Unpin column`:`Pin column`}),l(`button`,{type:`button`,onClick:t=>{k(t=>t.includes(e.key)?t.filter(t=>t!==e.key):[...t,e.key]),t.currentTarget.closest(`details`).open=!1},children:O.includes(e.key)?`Do not wrap text`:`Wrap text`}),l(`input`,{type:`text`,"aria-label":`Display name for ${e.label}`,defaultValue:A[e.key]||e.label,maxLength:80}),l(`button`,{type:`button`,onClick:t=>{let n=t.currentTarget.parentElement.querySelector(`input[aria-label^="Display name"]`).value.trim();j(t=>({...t,[e.key]:n||e.label||e.key})),t.currentTarget.closest(`details`).open=!1},children:`Apply display name`})]})]})]},e.key))]})}),l(`tbody`,{children:J.map(({row:e,index:t})=>u(`tr`,{class:I.includes(t)?`is-selected`:void 0,children:[l(`td`,{class:Y(`select-cell`),children:l(`input`,{type:`checkbox`,"aria-label":`Select row ${t+1}`,checked:I.includes(t),onChange:e=>L(n=>e.currentTarget.checked?[...new Set([...n,t])]:n.filter(e=>e!==t))})}),te.map(t=>l(`td`,{class:`${O.includes(t.key)?`is-wrapped`:``} ${E===t.key?`is-pinned`:``}`.trim(),style:E===t.key?{left:`34px`}:void 0,children:Jt(e[t.key],i,t,c)},t.key))]},t))})]})}),u(`div`,{class:Y(`table-summary`),children:[l(`span`,{children:G.length?`${((q-1)*V+1).toLocaleString(i)}-${Math.min(q*V,G.length).toLocaleString(i)} of ${W.length.toLocaleString(i)}`:`0 of ${W.length.toLocaleString(i)}`}),d?l(`span`,{children:e.length>n?`First ${n.toLocaleString(i)} rows available`:`All returned rows loaded`}):u(`div`,{class:Y(`table-pagination`),"aria-label":`Table pagination`,children:[u(`label`,{children:[l(`span`,{children:`Rows`}),l(Zt,{classPrefix:f,label:`Rows per page`,value:String(V),options:[[`10`,`10`],[`25`,`25`],[`50`,`50`]],onChange:e=>{H(Number(e)),B(1)}})]}),l(`button`,{type:`button`,"aria-label":`Previous page`,disabled:q<=1,onClick:()=>B(e=>Math.max(1,e-1)),children:`‹`}),u(`span`,{children:[q,` / `,K]}),l(`button`,{type:`button`,"aria-label":`Next page`,disabled:q>=K,onClick:()=>B(e=>Math.min(K,e+1)),children:`›`})]})]})]})},tn=(e,t,n)=>{let r=it(t),i=[],a=e.reportingPeriod?.label?.trim();a&&i.push({label:r.aboutPeriod,value:a});let o=e.rowCount??e.rows?.length;typeof o==`number`&&i.push({label:r.aboutResults,value:nt(o===1?r.rowOne:r.rowMany,{count:o})});let s=e.explanation?.checkedAt??e.freshness?.answeredAt,c=e.explanation?.timezone??e.timezone??e.reportingPeriod?.timezone;if(s){let e=new Date(s),t=s;if(!Number.isNaN(e.getTime()))try{t=new Intl.DateTimeFormat(n,{dateStyle:`medium`,timeStyle:`short`,...c?{timeZone:c}:{}}).format(e)}catch{t=e.toLocaleString(n)}i.push({label:r.aboutChecked,value:t})}c&&i.push({label:r.aboutTimezone,value:c});let l=e.explanation?.dataFreshness?.status??e.freshness?.status;return l&&l!==`unknown`&&i.push({label:r.aboutSourceData,value:l.replaceAll(`_`,` `)}),e.appliedFilters?.length&&i.push({label:r.aboutFilters,value:nt(r.filtersApplied,{count:e.appliedFilters.length})}),i},nn=e=>e.columns?.length?e.columns:Object.keys(e.rows?.[0]??{}),rn=e=>{let t=e.rows??[],n=e.currency?.code&&!e.currency.isMixed?e.currency.code:void 0;return nn(e).map(r=>{let i=e.columnMetadata?.find(e=>e.key===r);if(!i)return{key:r,label:Kt(r)};let a=i.dataType===`date`||i.dataType===`datetime`||i.semanticRole===`date`;return{key:r,label:i.label,dataType:i.dataType,currencyCode:i.currencyCode||(i.dataType===`currency`?n:void 0),formatPattern:i.formatPattern,grain:a?i.grain??e.periodComparison?.grain??Ue(t.map(e=>e[r])):void 0}})},an=(e,t)=>{let n=e.rows?.[0]??{};return e.chartRecommendation?.valueFields?.[0]??e.valueFields?.[0]??e.value??e.columnMetadata?.find(e=>e.semanticRole===`measure`&&e.key in n)?.key??t.find(e=>Je(n[e])!==null)??t[1]??t[0]},on=(e,t,n=`analytics-result.csv`)=>{if(typeof document>`u`||e.length===0)return;let r=Xt(t,e),i=URL.createObjectURL(new Blob([r],{type:`text/csv;charset=utf-8`})),a=document.createElement(`a`);a.href=i,a.download=n,a.click(),URL.revokeObjectURL(i)},sn=new Set,cn=e=>{let t=e.composedPath();sn.forEach(e=>{e.isOpen()&&!e.contains(t)&&e.close(!1)})},ln=e=>{if(e.key===`Escape`){for(let t of sn)if(t.isOpen()){t.close(!0),e.preventDefault();return}}},un=e=>(sn.size===0&&typeof document<`u`&&(document.addEventListener(`pointerdown`,cn),document.addEventListener(`keydown`,ln)),sn.add(e),()=>{sn.delete(e),sn.size===0&&typeof document<`u`&&(document.removeEventListener(`pointerdown`,cn),document.removeEventListener(`keydown`,ln))}),dn=({children:e,size:t=15})=>l(`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}),fn=()=>l(dn,{children:l(`path`,{d:`M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7`})}),pn=()=>l(dn,{children:l(`path`,{d:`M18 6 6 18M6 6l12 12`})}),mn=()=>l(dn,{size:13,children:l(`path`,{d:`m6 9 6 6 6-6`})}),hn=()=>l(dn,{size:13,children:l(`path`,{d:`m5 12 5 5L20 7`})}),gn=({type:e,className:t})=>u(`svg`,{viewBox:`0 0 32 32`,"aria-hidden":`true`,class:t,fill:`none`,children:[l(`path`,{d:`M6 26h21M6 7v19`,stroke:`var(--rv-muted)`,"stroke-width":`1.4`,"stroke-linecap":`round`}),e===`line`?l(`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`?l(c,{children:[9,15,21].map((e,t)=>u(`g`,{children:[l(`rect`,{x:e,y:18-t*2,width:`4`,height:8+t*2,fill:`var(--rv-chart-2)`,rx:`0.6`}),l(`rect`,{x:e,y:13-t,width:`4`,height:`5`,fill:`var(--rv-chart-3)`,rx:`0.6`}),l(`rect`,{x:e,y:9-t,width:`4`,height:`4`,fill:`var(--rv-chart-1)`,rx:`0.6`})]},e))}):u(c,{children:[l(`rect`,{x:`9`,y:`18`,width:`4`,height:`8`,fill:`var(--rv-chart-2)`,rx:`0.7`}),l(`rect`,{x:`15`,y:`13`,width:`4`,height:`13`,fill:`var(--rv-chart-2)`,rx:`0.7`}),l(`rect`,{x:`21`,y:`8`,width:`4`,height:`18`,fill:`var(--rv-chart-2)`,rx:`0.7`})]})]}),_n=e=>{let[t,n]=s(!1),a=o(null),c=o(null),l=o(t);return l.current=t,r(()=>un({isOpen:()=>l.current,contains:e=>!!(a.current&&e.includes(a.current)||c.current&&e.includes(c.current)),close:e=>{n(!1),e&&a.current?.focus()}}),[]),i(()=>{if(!t)return;let n=()=>{let t=a.current,n=c.current;if(!t||!n)return;n.style.left=`0px`,n.style.top=`0px`;let r=n.getBoundingClientRect(),i=t.getBoundingClientRect(),o=document.documentElement.clientWidth||window.innerWidth,s=document.documentElement.clientHeight||window.innerHeight,l=getComputedStyle(t).direction===`rtl`,u=e===`end`===l?i.left:i.right-r.width;u=Math.max(8,Math.min(u,o-r.width-8));let d=i.bottom+7;d+r.height>s-8&&i.top-7-r.height>8&&(d=i.top-7-r.height),n.style.left=`${u-r.left}px`,n.style.top=`${d-r.top}px`};return n(),window.addEventListener(`resize`,n),window.addEventListener(`scroll`,n,!0),c.current?.querySelector(`[aria-selected="true"], button`)?.focus({preventScroll:!0}),()=>{window.removeEventListener(`resize`,n),window.removeEventListener(`scroll`,n,!0)}},[t,e]),{open:t,setOpen:n,triggerRef:a,layerRef:c}},vn=({visualization:e,field:t,prefix:n,labels:r,locale:i,headerTitle:a})=>{let o=e.rows??[],s=e.columnMetadata?.find(e=>e.key===t),d=t?o[0]?.[t]:void 0,f=Je(d),p=t=>Et(t,s,e,!1,i),m=f===null?String(d??r.noValue):p(f),h=e.periodComparison,g=!h?.measureField||h.measureField===t,_=t?Je(o[1]?.[t]):null,v=f!==null&&h&&g?pe(h,{value:f,status:`observed`,label:h.currentPeriod?.label},{value:_??h.previousFullValue??h.previousToDateValue,status:`observed`,label:h.previousPeriod?.label},{format:p,locale:i}):void 0,y=s?.label??(t?Kt(t):r.currentValue);return u(`section`,{class:`${n}-analytics-kpi`,"aria-label":a??y,"data-testid":`analytics-kpi`,children:[l(`div`,{class:`${n}-analytics-kpi__label`,children:y}),l(`div`,{class:`${n}-analytics-kpi__value`,children:m}),v?u(c,{children:[u(`div`,{class:`${n}-analytics-kpi__change is-${v.tone}`,"data-comparison-basis":v.basis,title:v.title,children:[l(`span`,{children:v.label}),v.copy?l(`span`,{class:`${n}-analytics-kpi__copy`,children:v.copy}):null]}),v.secondary?l(`div`,{class:`${n}-analytics-kpi__secondary`,children:v.secondary}):null]}):null]})},yn=({visualization:e,classPrefix:t,labels:n,locale:i,expanded:o=!1,onExpand:d,onClose:f,expandControlId:p,onFollowUp:m,onDownload:h,headerActions:g,children:_,dataToggle:v,cardRef:y,maxTableRows:b=100})=>{let x=a(()=>it(n),[n]),S=a(()=>Mt(e,void 0,{labels:x,locale:i}),[e,x,i]),[C,w]=s(S?.type);r(()=>w(S?.type),[S]);let[T,E]=s(!1),D=a(()=>Rt(e,x),[e,x]),O=a(()=>Mt(e,C,{labels:x,locale:i}),[e,C,x,i]),k=C??O?.type??S?.type,A=D.find(e=>e.type===k),j=[...new Set(O?.series.map(e=>e.field)??[])],M=_n(`end`),N=_n(`start`),P=e.rows??[],F=nn(e),I=a(()=>Se(e),[e]),L=a(()=>rn(I),[I]),R=a(()=>({locale:i,timezone:e.timezone||e.periodComparison?.timezone,yes:x.yes,no:x.no}),[i,e.timezone,e.periodComparison?.timezone,x]),ee=tn(e,x,i),z=h===!1||!e.downloadAvailable?null:()=>(h??on)(F,P),B=ee.length?u(`details`,{class:`${t}-analytics-inspect`,children:[l(`summary`,{children:x.aboutResult}),l(`dl`,{children:ee.map(e=>u(`div`,{children:[l(`dt`,{children:e.label}),l(`dd`,{children:e.value})]},e.label))})]}):null,V=(()=>{let t=e.freshness?.answeredAt,n=t?new Date(t):null;return!n||Number.isNaN(n.getTime())?x.liveData:nt(x.updatedAt,{time:new Intl.DateTimeFormat(i,{hour:`numeric`,minute:`2-digit`}).format(n)})})(),H=e.rowCount??P.length,U=e.appliedFilters?.length??0,te=u(`div`,{class:`${t}-analytics-meta`,"data-testid":`analytics-result-meta`,role:`group`,"aria-label":x.resultDetails,children:[u(`span`,{children:[l(`span`,{"aria-hidden":`true`,class:`${t}-analytics-meta__dot`}),V]}),e.reportingPeriod?.label?l(`span`,{children:e.reportingPeriod.label}):null,l(`span`,{children:nt(H===1?x.rowOne:x.rowMany,{count:H})}),U>0?l(`span`,{children:nt(U===1?x.filtersOne:x.filtersMany,{count:U})}):null]}),W=(n,r,i,a=x.expandChart)=>u(`div`,{class:`${t}-analytics-result`,children:[u(`section`,{ref:y,class:`${t}-analytics-visualization${o?` is-expanded`:``}`,"aria-label":n,children:[u(`div`,{class:`${t}-analytics-visualization__header`,children:[u(`div`,{children:[l(`div`,{class:`${t}-analytics-visualization__title`,children:n}),te]}),u(`div`,{class:`${t}-analytics-visualization__actions`,children:[i,g,o&&f?l(`button`,{type:`button`,class:`${t}-analytics-visualization__close`,"aria-label":x.restoreView,title:x.restoreView,onClick:f,children:l(pn,{})}):d&&e.expandable!==!1?l(`button`,{type:`button`,class:`${t}-analytics-visualization__expand`,"aria-label":a,title:a,"data-visualization-message":p,onClick:d,children:l(fn,{})}):null]})]}),r,B,_]}),u(`div`,{class:`${t}-analytics-layer`,children:[m?l(`div`,{ref:N.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:`fixed`},role:`menu`,"aria-label":x.aggregate,hidden:!N.open,children:j.flatMap(n=>It(e,n).map(r=>{let i=e.columnMetadata?.find(e=>e.key===n)?.label??Kt(n);return l(`button`,{type:`button`,role:`menuitem`,onClick:()=>{let t=Lt(e,n,r.value);t&&m(t),N.setOpen(!1)},children:u(`span`,{class:`${t}-analytics-chart-picker__copy`,children:[u(`strong`,{children:[Ft(r.value,x),` · `,i]}),l(`small`,{children:x.aggregateCharge})]})},`${n}:${r.value}`)}))}):null,l(`div`,{ref:M.layerRef,class:`${t}-analytics-chart-picker__menu`,style:{position:`fixed`},role:`listbox`,"aria-label":x.chartType,hidden:!M.open,children:D.map(e=>{let n=e.type===k;return u(`button`,{type:`button`,role:`option`,"aria-selected":n,class:n?`is-selected`:``,onClick:()=>{w(e.type),M.setOpen(!1),M.triggerRef.current?.focus()},children:[l(`span`,{class:`${t}-analytics-chart-picker__icon`,children:l(gn,{type:e.type,className:`${t}-chart-type-icon`})}),u(`span`,{class:`${t}-analytics-chart-picker__copy`,children:[l(`strong`,{children:e.label}),l(`small`,{children:e.hint})]}),n?l(hn,{}):null]},e.type)})})]})]}),G=l(en,{rows:I.rows??P,columns:L,maxRows:b,expanded:o,classPrefix:t,locale:i,format:R}),K=()=>e.tableAvailable===!1||F.length===0?null:W(e.title?.trim()||x.resultDetails,l(c,{children:G}),z?l(`button`,{type:`button`,class:`${t}-analytics-visualization__download`,onClick:z,children:x.download}):null,x.expandTable);if(P.length===0)return u(c,{children:[u(`section`,{class:`${t}-analytics-empty`,role:`status`,"data-testid":`analytics-empty-state`,children:[l(`p`,{children:x.noMatchTitle}),l(`p`,{children:x.noMatchBody})]}),B,_]});if(e.presentation===`table`||!e.presentation&&e.type===`table`)return K()??l(c,{children:_});let q=v&&e.tableAvailable!==!1?l(`button`,{type:`button`,class:`${t}-analytics-visualization__download`,"aria-expanded":T,onClick:()=>E(e=>{let t=!e;return v.onToggle?.(t),t}),children:T?x.hideData:x.viewData}):null,J=T?l(`div`,{class:`${t}-analytics-data`,children:G}):null;return e.presentation===`kpi`||!e.presentation&&e.type===`kpi`?W(x.liveMetric,u(c,{children:[l(vn,{visualization:e,field:an(e,F),prefix:t,labels:x,locale:i}),q,J]})):O?W(O.title,u(c,{children:[l(Gt,{model:O,expanded:o,classPrefix:t}),z?l(`button`,{type:`button`,class:`${t}-analytics-visualization__download`,onClick:z,children:x.downloadData}):null,q,J]}),u(c,{children:[m?l(`div`,{class:`${t}-analytics-chart-picker ${t}-analytics-chart-picker--aggregation`,children:u(`button`,{type:`button`,ref:N.triggerRef,"aria-haspopup":`menu`,"aria-expanded":N.open,"aria-label":x.aggregate,title:x.aggregateTitle,onClick:()=>{M.setOpen(!1),N.setOpen(!N.open)},children:[l(`span`,{class:`${t}-analytics-chart-picker__current`,children:l(`span`,{children:x.aggregate})}),l(mn,{})]})}):null,D.length>1?l(`div`,{class:`${t}-analytics-chart-picker`,children:u(`button`,{type:`button`,ref:M.triggerRef,"aria-haspopup":`listbox`,"aria-expanded":M.open,"aria-label":x.chooseChartType,title:x.chooseChartType,onClick:()=>{N.setOpen(!1),M.setOpen(!M.open)},children:[u(`span`,{class:`${t}-analytics-chart-picker__current`,children:[l(gn,{type:k??O.type,className:`${t}-chart-type-icon`}),l(`span`,{children:A?.label??x.chartFallback})]}),l(mn,{})]})}):null]})):K()??l(c,{children:_})},bn=[`#2563eb`,`#b45309`,`#7c3aed`],xn=[`#60a5fa`,`#fbbf24`,`#a78bfa`],Sn=(e,t)=>{let n=`.${e}-analytics-visualization`,r=`.${e}-analytics-result`,i=`.${e}-analytics-chart-picker`,a=`.${e}-analytics-kpi`;return`
91
91
  ${r}{
92
92
  display:contents;
93
93
  --rv-bg:${t.bg};--rv-surface:${t.surface};--rv-surface-2:${t.surface2};--rv-text:${t.text};
@@ -157,17 +157,17 @@ ${n}.is-expanded .${e}-analytics-echart{height:auto;min-height:310px;flex:1}
157
157
  .${e}-analytics-zoom__controls button:focus-visible{position:relative;z-index:1;outline:2px solid var(--rv-accent);outline-offset:-2px}
158
158
  .${e}-analytics-zoom__controls button:disabled{cursor:not-allowed;opacity:.38}
159
159
  .${e}-analytics-zoom__controls .${e}-analytics-zoom__reset{min-width:56px;padding:0 10px;font-size:10px;font-weight:700}
160
- `},Sn=16e3;var Cn=class{constructor(e){h(this,`ratio`,void 0),h(this,`position`,0),h(this,`carry`,[]),this.ratio=e/Sn}process(e){if(this.ratio===1)return e.slice();let t=this.carry.length?Float32Array.from([...this.carry,...e]):e,n=[],r=this.position;for(;r+this.ratio<=t.length;){let e=Math.floor(r),i=Math.min(t.length,Math.floor(r+this.ratio)),a=0;for(let n=e;n<i;n+=1)a+=t[n]??0;n.push(i>e?a/(i-e):0),r+=this.ratio}let i=Math.floor(r);return this.carry=Array.from(t.subarray(i)),this.position=r-i,Float32Array.from(n)}};const wn=(e,t=Sn)=>{let n=e.reduce((e,t)=>e+t.length,0),r=new ArrayBuffer(44+n*2),i=new DataView(r),a=(e,t)=>{for(let n=0;n<t.length;n+=1)i.setUint8(e+n,t.charCodeAt(n))};a(0,`RIFF`),i.setUint32(4,36+n*2,!0),a(8,`WAVE`),a(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),a(36,`data`),i.setUint32(40,n*2,!0);let o=44;for(let t of e)for(let e=0;e<t.length;e+=1){let n=Math.max(-1,Math.min(1,t[e]??0));i.setInt16(o,n<0?n*32768:n*32767,!0),o+=2}return new Blob([r],{type:`audio/wav`})},Tn=e=>e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,` `).split(/\s+/).filter(e=>e.length>1),En=(e,t)=>{let n=Tn(e);if(n.length===0||!t.trim())return!1;let r=new Set(Tn(t));return n.filter(e=>r.has(e)).length/n.length>=.7},Dn=e=>{let t=e.replace(/```[\s\S]*?```/g,``).split(`
160
+ `},Cn=16e3;var wn=class{constructor(e){h(this,`ratio`,void 0),h(this,`position`,0),h(this,`carry`,[]),this.ratio=e/Cn}process(e){if(this.ratio===1)return e.slice();let t=this.carry.length?Float32Array.from([...this.carry,...e]):e,n=[],r=this.position;for(;r+this.ratio<=t.length;){let e=Math.floor(r),i=Math.min(t.length,Math.floor(r+this.ratio)),a=0;for(let n=e;n<i;n+=1)a+=t[n]??0;n.push(i>e?a/(i-e):0),r+=this.ratio}let i=Math.floor(r);return this.carry=Array.from(t.subarray(i)),this.position=r-i,Float32Array.from(n)}};const Tn=(e,t=Cn)=>{let n=e.reduce((e,t)=>e+t.length,0),r=new ArrayBuffer(44+n*2),i=new DataView(r),a=(e,t)=>{for(let n=0;n<t.length;n+=1)i.setUint8(e+n,t.charCodeAt(n))};a(0,`RIFF`),i.setUint32(4,36+n*2,!0),a(8,`WAVE`),a(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),a(36,`data`),i.setUint32(40,n*2,!0);let o=44;for(let t of e)for(let e=0;e<t.length;e+=1){let n=Math.max(-1,Math.min(1,t[e]??0));i.setInt16(o,n<0?n*32768:n*32767,!0),o+=2}return new Blob([r],{type:`audio/wav`})},En=e=>e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,` `).split(/\s+/).filter(e=>e.length>1),Dn=(e,t)=>{let n=En(e);if(n.length===0||!t.trim())return!1;let r=new Set(En(t));return n.filter(e=>r.has(e)).length/n.length>=.7},On=e=>{let t=e.replace(/```[\s\S]*?```/g,``).split(`
161
161
  `),n=new Set;for(let e=1;e<t.length;e+=1){let r=t[e]?.trim().replace(/^\|/,``).replace(/\|$/,``);if(!(!t[e-1]?.includes(`|`)||!r||!r.split(`|`).every(e=>/^\s*:?-{3,}:?\s*$/.test(e)))){n.add(e-1),n.add(e);for(let r=e+1;r<t.length&&t[r]?.includes(`|`);r+=1)n.add(r)}}return t.filter((e,t)=>!n.has(t)).join(`
162
- `).trim()},On=(e,t)=>{let n=t?.explanation,r=[n?.summary?.trim()||n?.headline?.trim(),n?.businessMeaning?.trim(),...n?.limitations??[]].filter(e=>!!e?.trim()),i=r.length?[...new Set(r)].join(`
163
- `):e;return Dn(i)||(i.trim()?`The detailed results are available in the chat.`:``)},kn=()=>{let e=globalThis;if(e.__voiceDebug)return!0;try{return e.localStorage?.getItem(`accurix.voiceDebug`)===`1`}catch{return!1}};var An=class{constructor(e=()=>Date.now()){this.now=e,h(this,`entries`,[]),h(this,`startedAt`,void 0),this.startedAt=e(),globalThis.__accurixVoiceLog=()=>this.list()}add(e,t){let n={at:Math.round(this.now()-this.startedAt),event:e,detail:t};this.entries.push(n),this.entries.length>300&&this.entries.splice(0,this.entries.length-300),kn()&&console.debug(`VOICEDBG ${e} ${t?JSON.stringify(t):``}`)}list(){return this.entries.slice()}};Sn/50;const jn=8e-4;var Mn=class{constructor(e){this.options=e,h(this,`endSilenceMs`,void 0),h(this,`pending`,new Float32Array),h(this,`levels`,[]),h(this,`framesSinceFloor`,0),h(this,`floor`,jn*4),h(this,`recentSpeech`,[]),h(this,`preroll`,[]),h(this,`silentMs`,0),h(this,`inputSilent`,!1),h(this,`outputActive`,!1),h(this,`turns`,[]),h(this,`nextTurnId`,1),this.endSilenceMs=e.endSilenceMs??2e3}get hearing(){return this.current()?.capturing??!1}get processing(){return this.turns.some(e=>!e.capturing&&!e.cancelled)}feed(e){let t=e;this.pending.length&&(t=new Float32Array(this.pending.length+e.length),t.set(this.pending),t.set(e,this.pending.length));let n=0;for(;n+320<=t.length;)this.frame(t.slice(n,n+320)),n+=320;this.pending=t.slice(n)}setOutputActive(e){this.outputActive!==e&&(this.outputActive=e,this.options.log.add(`output`,{active:e}))}finishTurn(){let e=this.current();e&&(e.capturing?this.endTurn(e,`done`):e.closed||(e.closed=!0,e.endedBy=`done`,this.options.log.add(`turn-done`,{turn:e.id})))}reset(e){for(let e of this.turns)e.cancelled=!0;this.turns.length&&this.options.log.add(`turns-dropped`,{reason:e,count:this.turns.length}),this.turns=[],this.preroll=[],this.recentSpeech=[],this.pending=new Float32Array,this.options.onChange()}current(){return this.turns[this.turns.length-1]}frame(e){let t=0,n=0;for(let r=0;r<e.length;r+=1){let i=e[r]??0;t+=i*i,n=Math.max(n,Math.abs(i))}let r=Math.sqrt(t/e.length);this.trackInputSilence(n);let i=this.current();!i?.capturing&&!this.outputActive&&this.trackFloor(r);let a=this.outputActive,o=Math.max(.006,this.floor*2.8)*(a?1.8:1),s=Math.max(.004,this.floor*1.8)*(a?1.4:1),c=r>=o,l=r>=s;if(!i?.capturing){for(this.preroll.push(e);this.preroll.length*20>500;)this.preroll.shift();this.recentSpeech.push(c);let t=(a?600:300)/20;for(;this.recentSpeech.length>t;)this.recentSpeech.shift();let n=this.recentSpeech.filter(Boolean).length*20;n>=(a?280:120)&&this.beginCapture(n);return}i.chunk.push(e),i.chunkMs+=20,i.durationMs+=20,c&&(i.voicedMs+=20,i.chunkVoicedMs+=20),i.quietMs=l?0:i.quietMs+20,a&&(i.overlappedOutput=!0),i.quietMs>=this.endSilenceMs?this.endTurn(i,`silence`):(i.chunkMs>=25e3||i.chunkMs>=12e3&&i.quietMs>=300||i.chunkMs>=2e4&&i.quietMs>=60)&&this.cutChunk(i)}trackFloor(e){if(this.levels.push(e),this.levels.length>250&&this.levels.shift(),this.framesSinceFloor+=1,this.framesSinceFloor<10&&this.levels.length>10)return;this.framesSinceFloor=0;let t=this.levels.slice().sort((e,t)=>e-t);this.floor=Math.max(jn,t[Math.floor(t.length*.1)]??jn)}trackInputSilence(e){this.silentMs=e===0?this.silentMs+20:0;let t=this.silentMs>=2e3;t!==this.inputSilent&&(this.inputSilent=t,this.options.log.add(`input-silent`,{silent:t}),this.options.onInputSilent?.(t))}beginCapture(e){let t=this.current(),n;t&&!t.capturing&&!t.closed?(n=t,n.capturing=!0,this.options.log.add(`turn-resumed`,{turn:n.id})):(n={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(n),this.options.log.add(`turn-start`,{turn:n.id,overOutput:this.outputActive}),this.options.listener.speechStart?.({turnId:n.id,overlappedOutput:this.outputActive})),n.chunk.push(...this.preroll),n.chunkMs+=this.preroll.length*20,n.durationMs+=this.preroll.length*20,n.voicedMs+=e,n.chunkVoicedMs+=e,n.quietMs=0,this.preroll=[],this.recentSpeech=[],this.options.onChange()}endTurn(e,t){let n=Math.max(0,Math.floor((e.quietMs-400)/20));if(n>0&&(e.chunk.splice(e.chunk.length-Math.min(n,e.chunk.length)),e.chunkMs=e.chunk.length*20),e.capturing=!1,e.endedBy=t,t===`done`&&(e.closed=!0),this.options.log.add(`turn-end`,{turn:e.id,by:t,ms:e.durationMs,voicedMs:e.voicedMs}),e.chunkCount===0&&e.voicedMs<300){this.turns=this.turns.filter(t=>t!==e),this.options.log.add(`turn-noise`,{turn:e.id,reason:`too-short`}),this.options.listener.noise?.({id:e.id,reason:`too-short`,overlappedOutput:e.overlappedOutput}),this.options.onChange();return}this.cutChunk(e),this.options.onChange(),this.settle()}cutChunk(e){if(e.chunk.length===0)return;let t=e.chunk,n=e.chunkCount;e.chunkCount+=1,e.results[n]=void 0,e.chunk=[];let r=t.length*20,i=e.chunkVoicedMs;if(e.chunkMs=0,e.chunkVoicedMs=0,i===0&&n>0){e.results[n]=``;return}this.options.log.add(`chunk`,{turn:e.id,index:n,ms:r}),this.options.transcribe({audio:wn(t),mimeType:`audio/wav`,durationSeconds:r/1e3,turnId:e.id,chunkIndex:n}).then(e=>(e??``).trim(),()=>null).then(t=>{if(e.cancelled)return;e.results[n]=t,this.options.log.add(`chunk-text`,{turn:e.id,index:n,chars:t===null?-1:t.length});let r=[];for(let t of e.results){if(t===void 0)break;t&&r.push(t)}r.length&&this.options.listener.partial?.({turnId:e.id,text:r.join(` `)}),this.settle()})}settle(){for(;this.turns.length;){let e=this.turns[0];if(!e||e.capturing||e.results.some(e=>e===void 0))return;this.turns.shift();let t=e.results.filter(e=>typeof e==`string`&&e!==``),n=e.results.every(e=>e===null),r=t.join(` `).replace(/\s+/g,` `).trim();if(r)this.options.log.add(`turn`,{turn:e.id,chars:r.length,by:e.endedBy}),this.options.listener.turn?.({id:e.id,text:r,durationMs:e.durationMs,endedBy:e.endedBy,overlappedOutput:e.overlappedOutput});else{let t=n?`transcribe-failed`:`empty-transcript`;this.options.log.add(`turn-noise`,{turn:e.id,reason:t}),this.options.listener.noise?.({id:e.id,reason:t,overlappedOutput:e.overlappedOutput})}this.options.onChange()}}};const Nn=[300,1e3,2500],Pn=()=>typeof navigator<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`&&typeof globalThis.AudioContext==`function`,Fn=e=>{let t=e?.name;return t===`NotAllowedError`||t===`SecurityError`?`permission-denied`:t===`NotFoundError`||t===`OverconstrainedError`?`no-device`:`error`};var In=class{constructor(e){this.options=e,h(this,`log`,new An),h(this,`turns`,void 0),h(this,`mic`,`off`),h(this,`reason`,void 0),h(this,`muted`,!1),h(this,`inputSilent`,!1),h(this,`stream`,null),h(this,`context`,null),h(this,`source`,null),h(this,`processor`,null),h(this,`sink`,null),h(this,`downsampler`,null),h(this,`deviceId`,void 0),h(this,`generation`,0),h(this,`recoveryAttempt`,0),h(this,`recoveryTimer`,null),h(this,`lastSnapshot`,``),h(this,`groupId`,void 0),h(this,`onTrackEnded`,()=>{this.log.add(`track-ended`),this.recover(`track-ended`)}),h(this,`onTrackMuteChange`,()=>{let e=this.stream?.getAudioTracks()[0];this.log.add(`track-mute-change`,{muted:!!e?.muted}),this.refreshMic()}),h(this,`onContextState`,()=>{let e=this.context?.state;this.log.add(`audio-state`,{state:e}),(e===`suspended`||e===`interrupted`)&&this.context?.resume().catch(()=>void 0),this.refreshMic()}),h(this,`onDeviceChange`,()=>{this.checkDevices()}),this.deviceId=e.deviceId,this.turns=new Mn({transcribe:e.transcribe,listener:e.listener,log:this.log,endSilenceMs:e.endSilenceMs,onChange:()=>this.publish(),onInputSilent:e=>{this.inputSilent=e,this.publish()}})}get snapshot(){let e=this.mic,t=this.reason;return e===`listening`&&this.inputSilent&&(e=`unavailable`,t=`input-silent`),e===`listening`&&this.turns.hearing&&(e=`hearing`),{mic:e,processing:this.turns.processing,reason:e===`unavailable`?t: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(e=`stopped`){this.mic!==`off`&&(this.log.add(`stop`,{reason:e}),this.generation+=1,this.clearRecovery(),this.mediaDevices()?.removeEventListener(`devicechange`,this.onDeviceChange),this.turns.reset(e),this.close(),this.context?.close().catch(()=>void 0),this.context=null,this.setMic(`off`))}setMuted(e){if(!(this.muted===e||this.mic===`off`)){this.muted=e,this.log.add(e?`mute`:`unmute`);for(let t of this.stream?.getAudioTracks()??[])t.enabled=!e;e?(this.turns.reset(`muted`),this.setMic(`muted`)):this.refreshMic()}}finishTurn(){this.log.add(`done-pressed`),this.turns.finishTurn()}setOutputActive(e){this.turns.setOutputActive(e)}async selectDevice(e){e!==this.deviceId&&(this.deviceId=e,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(e){let t=++this.generation;this.setMic(`starting`);let n=this.options.media?.getUserMedia??(Pn()?e=>navigator.mediaDevices.getUserMedia(e):null);if(!n){this.unavailable(`unsupported`);return}let r;try{r=await n({audio:{...this.deviceId?{deviceId:{exact:this.deviceId}}:{},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1}})}catch(n){if(t!==this.generation)return;let r=Fn(n);if(this.log.add(`mic-open-failed`,{why:e,reason:r}),r===`no-device`&&this.deviceId){this.deviceId=void 0,await this.open(`default-device`);return}this.unavailable(r);return}if(t!==this.generation){r.getTracks().forEach(e=>e.stop());return}try{this.connect(r)}catch(e){this.log.add(`audio-setup-failed`,{message:String(e?.name??`error`)}),r.getTracks().forEach(e=>e.stop()),this.unavailable(`error`);return}this.recoveryAttempt=0,this.groupId=r.getAudioTracks()[0]?.getSettings?.().groupId,this.log.add(`mic-open`,{why:e}),this.refreshMic()}connect(e){this.stream=e;for(let t of e.getAudioTracks())t.enabled=!this.muted,t.addEventListener(`ended`,this.onTrackEnded),t.addEventListener(`mute`,this.onTrackMuteChange),t.addEventListener(`unmute`,this.onTrackMuteChange);let t=this.context??this.options.media?.createAudioContext?.()??new globalThis.AudioContext;this.context||(this.context=t,t.addEventListener(`statechange`,this.onContextState)),t.state===`suspended`&&t.resume().catch(()=>void 0),this.downsampler=new Cn(t.sampleRate),this.source=t.createMediaStreamSource(e),this.processor=t.createScriptProcessor(2048,1,1),this.sink=t.createGain(),this.sink.gain.value=0,this.processor.onaudioprocess=e=>{if(this.muted||!this.downsampler)return;let t=this.downsampler.process(e.inputBuffer.getChannelData(0));if(this.turns.feed(t),this.options.listener.level&&t.length){let e=0;for(let n of t)e+=n*n;this.options.listener.level(Math.sqrt(e/t.length))}},this.source.connect(this.processor),this.processor.connect(this.sink),this.sink.connect(t.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(let e of this.stream?.getTracks()??[])e.removeEventListener(`ended`,this.onTrackEnded),e.removeEventListener(`mute`,this.onTrackMuteChange),e.removeEventListener(`unmute`,this.onTrackMuteChange),e.stop();this.stream=null,this.inputSilent=!1}refreshMic(){if(this.mic===`off`)return;if(this.muted)return this.setMic(`muted`);let e=this.stream?.getAudioTracks()[0];if(!e||e.readyState!==`live`)return this.unavailable(`device-lost`);if(e.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(e){this.reason=e,this.setMic(`unavailable`)}setMic(e){this.mic!==e&&this.log.add(`mic`,{state:e,reason:e===`unavailable`?this.reason:void 0}),this.mic=e,this.publish()}publish(){let e=this.snapshot,t=JSON.stringify(e);t!==this.lastSnapshot&&(this.lastSnapshot=t,this.options.listener.state?.(e))}recover(e){if(this.mic===`off`||this.recoveryTimer)return;let t=Nn[this.recoveryAttempt];if(this.turns.reset(e),this.close(),t===void 0){this.log.add(`mic-recovery-gave-up`,{why:e}),this.unavailable(`device-lost`);return}this.recoveryAttempt+=1,this.unavailable(`device-lost`),this.log.add(`mic-recovering`,{why:e,attempt:this.recoveryAttempt}),this.recoveryTimer=setTimeout(()=>{this.recoveryTimer=null,this.mic!==`off`&&this.open(e)},t)}clearRecovery(){this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,this.recoveryAttempt=0}async checkDevices(){let e=this.stream?.getAudioTracks()[0];if(!e||e.readyState!==`live`){this.log.add(`device-change`,{live:!1}),this.recover(`device-change`);return}let t=[];try{t=(await this.mediaDevices()?.enumerateDevices()??[]).filter(e=>e.kind===`audioinput`)}catch{return}let n=t.some(e=>!this.groupId||e.groupId===this.groupId),r=t.find(e=>e.deviceId===`default`),i=!this.deviceId&&r!==void 0&&this.groupId!==void 0&&r.groupId!==this.groupId;this.log.add(`device-change`,{live:!0,ours:n,defaultMoved:i}),(!n||i)&&this.recover(`device-change`)}};const Ln=e(H),Rn=()=>n(Ln),zn=(e,t)=>{let n=o(t);n.current=t;let i=o(()=>void 0),c=e.aiExplanation?.explanationId??e.explanationId??``,l=a(()=>{let t=n.current;return new Fe(e,t?{poll:(e,t)=>n.current.poll(e,t),...t.retry?{retry:(e,t)=>n.current.retry(e,t)}:{}}:void 0,e=>i.current(e),{onSettled:e=>n.current?.settled?.(c,e)})},[c,e.aiExplanation?.status===`pending`?`pending`:`settled`,!!t]),[u,d]=s(l.state);return r(()=>(i.current=d,d(l.state),l.start(),()=>l.dispose()),[l]),[u.status===`ready`?u:{...u,explanation:e},l]},Bn=({prefix:e,state:t,onRetry:n})=>{let r=Rn();return u(`div`,{class:`${e}-xp__ai`,"data-ai-status":t.status,children:[t.status===`pending`?l(`p`,{class:`${e}-xp__ai-note`,children:r.preparingDetailed}):null,t.status===`failed`?u(`p`,{class:`${e}-xp__ai-note`,children:[r.detailedUnavailable,t.retryAvailable?l(`button`,{type:`button`,class:`${e}-xp__ai-retry`,disabled:t.retrying,onClick:n,children:r.detailedRetry}):null]}):null,l(`span`,{class:`${e}-xp__sr`,role:`status`,"aria-live":`polite`,children:t.announcement})]})},Vn=({citations:e,step:t,prefix:n,active:r,onToggle:i,evidenceById:a})=>{let o=Rn();return e.length===0?null:l(c,{children:e.map(e=>{let s=r?.id===e.id&&r.step===t;return l(`button`,{type:`button`,class:`${n}-xp__cite`,"data-evidence-id":e.id,"aria-expanded":s,"aria-label":`${o.citationLabel} ${e.index}: ${a[e.id]?.text??``}`.trim(),onClick:n=>i(e.id,t,n.currentTarget),children:De(e).slice(1,-1)},e.id)})})},Hn=(e,t)=>e.sourceTargets.find(e=>t?t(e):!0),Un=({evidence:e,prefix:t,onClose:n,onOpenSource:i,canOpenSource:a})=>{let s=Rn(),c=o(null);r(()=>{c.current?.focus()},[e.id]);let d=i?Hn(e,a):void 0;return u(`div`,{ref:c,class:`${t}-xp__evidence-panel`,role:`region`,tabIndex:-1,"aria-label":`${s.evidence} ${e.index}`,"data-testid":`analytics-explanation-evidence`,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),n())},children:[u(`div`,{class:`${t}-xp__evidence-head`,children:[u(`p`,{class:`${t}-xp__evidence-text`,children:[`[`,e.index,`] `,e.text]}),l(`button`,{type:`button`,class:`${t}-xp__close`,"aria-label":s.closeEvidence,onClick:n,children:`×`})]}),l(`dl`,{class:`${t}-xp__evidence-rows`,children:Oe(e,s).map(e=>u(`div`,{style:{display:`contents`},"data-row":e.key,children:[l(`dt`,{children:e.label}),l(`dd`,{children:e.value})]},e.key))}),d&&i?l(`div`,{class:`${t}-xp__evidence-actions`,children:l(`button`,{type:`button`,class:`${t}-xp__button`,onClick:()=>i(d,e),children:s.openSource})}):null]})},Wn=({down:e})=>l(`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:l(`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`})}),Gn=(e,t,n)=>t===`wrong_numbers`?e.reasonWrongNumbers:t===`missing_comparison`?e.reasonMissingComparison:t===`unclear`?e.reasonUnclear:t===`too_long`?e.reasonTooLong:n,Kn=({prefix:e,explanationId:t,submit:n,context:r})=>{let i=Rn(),[o,c]=s({phase:`idle`,reasons:[],comment:``}),d=a(()=>new je(t,n,c,r),[t]),f=o.phase===`saving`;return u(`div`,{class:`${e}-xp__feedback`,"data-testid":`analytics-explanation-feedback`,children:[o.phase===`done`?u(`div`,{class:`${e}-xp__feedback-row`,role:`status`,children:[l(`span`,{class:`${e}-xp__feedback-note`,children:i.feedbackThanks}),l(`button`,{type:`button`,class:`${e}-xp__button`,onClick:()=>void d.undo(),children:i.feedbackUndo})]}):u(`div`,{class:`${e}-xp__feedback-row`,children:[l(`span`,{class:`${e}-xp__feedback-label`,children:i.feedbackPrompt}),l(`button`,{type:`button`,class:`${e}-xp__vote`,"aria-label":i.feedbackHelpful,"aria-pressed":o.rating===`up`,disabled:f,onClick:()=>void d.vote(`up`),children:l(Wn,{down:!1})}),l(`button`,{type:`button`,class:`${e}-xp__vote`,"aria-label":i.feedbackNotHelpful,"aria-pressed":o.rating===`down`,disabled:f,onClick:()=>void d.vote(`down`),children:l(Wn,{down:!0})})]}),o.phase===`details`||f&&o.rating===`down`?u(`form`,{class:`${e}-xp__feedback-form`,onSubmit:e=>{e.preventDefault(),d.send()},children:[u(`fieldset`,{class:`${e}-xp__reasons`,children:[l(`legend`,{children:i.feedbackReasonsPrompt}),te.map(t=>l(`button`,{type:`button`,class:`${e}-xp__reason`,"aria-pressed":o.reasons.includes(t.id),onClick:()=>d.toggleReason(t.id),children:Gn(i,t.id,t.label)},t.id))]}),l(`textarea`,{class:`${e}-xp__comment`,"aria-label":i.feedbackCommentPlaceholder,placeholder:i.feedbackCommentPlaceholder,maxLength:500,value:o.comment,onInput:e=>d.setComment(e.currentTarget.value)}),l(`div`,{class:`${e}-xp__feedback-row`,children:l(`button`,{type:`submit`,class:`${e}-xp__button is-primary`,disabled:f,children:i.feedbackSubmit})})]}):null,o.error?l(`p`,{class:`${e}-xp__feedback-error`,role:`alert`,children:o.error}):null]})},qn=({aiTransport:e,...t})=>{let[n,r]=zn(t.explanation,e),i=Jn(t.explanation),o=a(()=>({...H,...t.copy}),[t.copy]);return l(Ln.Provider,{value:o,children:l(Yn,{...t,explanation:n.explanation,aiStatus:i?l(Bn,{prefix:t.classPrefix,state:n,onRetry:()=>void r.retry()}):null})})},Jn=e=>!!(e.aiExplanation&&e.aiExplanation.status!==`not_requested`),Yn=({explanation:e,aiStatus:t,classPrefix:n,showLead:r=!0,investigateOpen:d=!1,onFollowUp:f,onOpenSource:p,canOpenSource:m,onFeedback:h,feedbackContext:g,onExpand:_,onCollapse:v,expanded:y=!1,...b})=>{let x=Rn(),S=o(null),C=o(null),w=o(!1),T=()=>{let e=S.current,t=e?.getRootNode(),n=t&&`activeElement`in t?t.activeElement:null;return!!(e&&n&&e.contains(n))},E=a(()=>(w.current=T(),Te(e,{...b,copy:x})),[e,b.locale,b.cleanText,x]),[D,O]=s(),k=o(null);i(()=>{D&&(E.evidenceById[D.id]&&S.current?.querySelector(`[data-testid="analytics-explanation-evidence"]`)||(O(void 0),w.current&&!T()&&(C.current??S.current)?.focus()))},[E]);let A=(e,t,n)=>{k.current=n,O(n=>n?.id===e&&n.step===t?void 0:{id:e,step:t})},j=()=>{O(void 0);let e=k.current;e?.isConnected?e.focus():(C.current??S.current)?.focus()},M=(e,t)=>l(Vn,{citations:e,step:t,prefix:n,active:D,onToggle:A,evidenceById:E.evidenceById}),N=e=>{if(!D||D.step!==e)return null;let t=E.evidenceById[D.id];return t?l(Un,{evidence:t,prefix:n,onClose:j,onOpenSource:p,canOpenSource:m}):null},P=(e,t)=>u(c,{children:[e.text,M(e.citations,t)]}),{investigate:F}=E;return u(`section`,{ref:S,class:`${n}-xp${y?` is-expanded`:``}${_||v?` has-expand`:``}`,"data-testid":`analytics-explanation`,"aria-label":x.region,tabIndex:-1,children:[y&&v?l(`button`,{type:`button`,class:`${n}-xp__expand`,"aria-label":x.collapse,title:x.collapse,onClick:v,children:`×`}):_?l(`button`,{type:`button`,class:`${n}-xp__expand`,"aria-label":x.expand,title:x.expand,"data-testid":`analytics-explanation-expand`,onClick:_,children:`⤢`}):null,r?u(`div`,{class:`${n}-xp__lead`,"data-step":`lead`,children:[E.lead.preface?l(`p`,{class:`${n}-xp__preface`,children:E.lead.preface}):null,u(`div`,{class:`${n}-xp__meta`,children:[l(`span`,{class:`${n}-xp__eyebrow`,children:E.lead.eyebrow}),l(`span`,{class:`${n}-xp__provenance`,children:E.lead.provenance})]}),l(`h3`,{class:`${n}-xp__headline`,ref:C,tabIndex:-1,children:P(E.lead.headline,`lead`)}),E.lead.summary?l(`p`,{class:`${n}-xp__summary`,children:P(E.lead.summary,`lead`)}):null,N(`lead`)]}):null,t,E.comparison.length>0?u(`section`,{class:`${n}-xp__step`,"data-step":`comparison`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.comparison}),l(`ul`,{class:`${n}-xp__periods`,children:E.comparison.map(e=>u(`li`,{class:`${n}-xp__period`,"data-status":e.status??`observed`,children:[l(`span`,{class:`${n}-xp__period-label`,children:e.label}),e.valueText?l(`span`,{class:`${n}-xp__period-value`,children:e.valueText}):null,e.statusLabel?l(`span`,{class:`${n}-xp__chip is-${e.statusTone}`,children:e.statusLabel}):null,e.inProgress?l(`span`,{class:`${n}-xp__chip is-progress`,children:x.inProgress}):null,e.citation?M([e.citation],`comparison`):null,e.reason?l(`small`,{class:`${n}-xp__period-reason`,children:e.reason}):null]},e.key))}),N(`comparison`)]}):null,E.conclusions.length>0||E.businessMeaning?u(`section`,{class:`${n}-xp__step`,"data-step":`conclusions`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.conclusions}),E.conclusions.length>0?l(`ul`,{class:`${n}-xp__list`,children:E.conclusions.map(e=>l(`li`,{children:P(e,`conclusions`)},e.text))}):null,E.businessMeaning?u(`p`,{class:`${n}-xp__meaning`,children:[u(`strong`,{children:[x.whyItMatters,`: `]}),P(E.businessMeaning,`conclusions`)]}):null,N(`conclusions`)]}):null,E.limits.length>0?u(`section`,{class:`${n}-xp__step`,"data-step":`limits`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.limits}),l(`ul`,{class:`${n}-xp__list ${n}-xp__limits`,children:E.limits.map(e=>u(`li`,{"data-kind":e.kind,children:[e.text,e.citation?M([e.citation],`limits`):null]},e.text))}),N(`limits`)]}):null,E.checkedLine?l(`p`,{class:`${n}-xp__checked`,"data-step":`checked`,children:E.checkedLine}):null,E.hasInvestigate?u(`details`,{class:`${n}-xp__investigate`,"data-step":`investigate`,open:d,children:[l(`summary`,{children:x.investigate}),u(`div`,{class:`${n}-xp__investigate-body`,children:[F.causes.length>0?u(`div`,{class:`${n}-xp__group`,children:[u(`div`,{class:`${n}-xp__group-head`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.causes}),l(`span`,{class:`${n}-xp__hint`,children:x.causesHint})]}),F.causes.map(e=>u(`article`,{class:`${n}-xp__card`,children:[u(`p`,{class:`${n}-xp__card-title`,children:[e.title,M(e.citations,`investigate`)]}),e.howToCheck?u(`p`,{class:`${n}-xp__card-body`,children:[x.howToCheck,` `,e.howToCheck]}):null]},e.title))]}):null,F.recommendations.length>0?u(`div`,{class:`${n}-xp__group`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.recommendations}),F.recommendations.map(e=>u(`article`,{class:`${n}-xp__card`,children:[u(`p`,{class:`${n}-xp__card-title`,children:[e.title,M(e.citations,`investigate`)]}),e.why?l(`p`,{class:`${n}-xp__card-body`,children:e.why}):null,e.watch?u(`p`,{class:`${n}-xp__card-body`,children:[x.watch,` `,e.watch]}):null]},e.title))]}):null,F.outlook?u(`div`,{class:`${n}-xp__group`,children:[u(`div`,{class:`${n}-xp__group-head`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.outlook}),l(`span`,{class:`${n}-xp__hint`,children:F.outlook.badge})]}),l(`p`,{class:`${n}-xp__card-body`,children:F.outlook.text}),F.outlook.note?l(`p`,{class:`${n}-xp__card-body`,children:F.outlook.note}):null]}):null,f&&F.followUps.length>0?u(`div`,{class:`${n}-xp__group`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.followUps}),l(`div`,{class:`${n}-xp__questions`,children:F.followUps.map(e=>l(`button`,{type:`button`,class:`${n}-xp__question`,onClick:()=>f(e),children:e},e))})]}):null,E.evidence.length>0?u(`div`,{class:`${n}-xp__group`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.evidenceList}),l(`ul`,{class:`${n}-xp__list`,children:E.evidence.map(e=>u(`li`,{children:[e.text,M([{id:e.id,index:e.index}],`investigate`)]},e.id))})]}):null,N(`investigate`)]})]}):null,l(`p`,{class:`${n}-xp__source`,children:E.sourceNote}),h&&E.explanationId?l(Kn,{prefix:n,explanationId:E.explanationId,submit:h,context:g}):null]})},Xn=[{name:`Smileys`,emojis:`😀.😃.😄.😁.😅.😂.🤣.😊.😇.🙂.🙃.😉.😌.😍.🥰.😘.😋.😛.😜.🤪.🤗.🤭.🤔.🤐.😐.😶.😏.🙄.😴.🥳.😎.🤓.🥺.😢.😭.😤.😠.🤯.😬.😱.🤩.🥱`.split(`.`)},{name:`Gestures`,emojis:[`👍`,`👎`,`👌`,`🤌`,`✌️`,`🤞`,`🤟`,`🤘`,`🤙`,`👈`,`👉`,`👆`,`👇`,`✋`,`🖐️`,`👋`,`🤝`,`🙏`,`💪`,`👏`,`🙌`,`👐`,`🤲`,`🫶`]},{name:`Hearts & symbols`,emojis:`❤️.🧡.💛.💚.💙.💜.🖤.🤍.💔.❣️.💕.💖.💘.💝.✨.⭐.🌟.💫.🔥.🎉.🎊.✅.❌.⚡.💯.🚀`.split(`.`)},{name:`Animals & nature`,emojis:[`🐶`,`🐱`,`🦊`,`🐻`,`🐼`,`🐨`,`🦁`,`🐮`,`🐸`,`🐵`,`🐧`,`🦄`,`🐝`,`🦋`,`🐢`,`🐬`,`🌷`,`🌸`,`🌹`,`🌻`,`🌳`,`🍀`]},{name:`Food & drink`,emojis:[`🍎`,`🍌`,`🍉`,`🍓`,`🍒`,`🥑`,`🍔`,`🍟`,`🍕`,`🌮`,`🍿`,`🍩`,`🍪`,`🎂`,`☕`,`🍵`,`🍺`,`🥂`,`🍷`]},{name:`Objects & travel`,emojis:`🚀.✈️.🚗.🏠.📦.📱.💻.⌚.📷.💡.🔑.🎁.📌.✏️.📝.📞.📧.💰.📈.⏰.🔔.🎯.🏆.🎮.🎵.💬.👀`.split(`.`)}],Zn={"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`}]}},Qn={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`},Q=(e,t)=>e.replace(/\{(\w+)\}/g,(e,n)=>t[n]??``),$n=(e,t,n)=>!t||e.includes(t)?e:`${e} ${Q(n.caseReference,{reference:t})}`,er=e=>e?{...Qn,...e}:Qn,tr=e(Qn),nr=tr.Provider,rr=e(void 0),ir=rr.Provider,ar=()=>n(rr),or=new Set([`ar`,`he`,`iw`,`fa`,`ur`,`ps`,`sd`,`ug`,`yi`,`dv`,`ckb`]),sr=(e,t)=>{if(t===`ltr`||t===`rtl`)return t;let n=(e??``).trim().toLowerCase().split(/[-_]/)[0]??``;return or.has(n)?`rtl`:`ltr`},cr=()=>n(tr),lr=[[`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})),ur=e=>[...e.toUpperCase()].map(e=>String.fromCodePoint(127397+e.charCodeAt(0))).join(``),dr=()=>{let e=``;try{if(Intl.DateTimeFormat().resolvedOptions().timeZone===`Africa/Lagos`&&(e=`NG`),!e){let t=navigator.languages?.[0]||navigator.language;e=new Intl.Locale(t).region||``}}catch{e=``}return lr.find(t=>t.iso===e)??lr.find(e=>e.iso===`US`)},fr=e=>{let t=dr(),n=e?.trim()??``;if(!n.startsWith(`+`))return{country:t,national:n.replace(/\D/g,``)};let r=n.replace(/\D/g,``),i=[...lr].sort((e,t)=>t.dial.length-e.dial.length).find(e=>r.startsWith(e.dial))??t;return{country:i,national:r.slice(i.dial.length)}},pr=(e,t)=>{let n=t.replace(/\D/g,``).replace(/^0+/,``);return n?`+${e.dial}${n}`:``},mr=e=>{let t=e.replace(/\D/g,``);return e.startsWith(`+`)&&t.length>=8&&t.length<=15},$=(e,t)=>l(`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}),hr=e=>l(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,"aria-hidden":`true`,...e,children:l(`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`})}),gr=e=>$(l(`path`,{d:`m6 9 6 6 6-6`}),e),_r=e=>$(u(c,{children:[l(`path`,{d:`m22 2-7 20-4-9-9-4Z`}),l(`path`,{d:`M22 2 11 13`})]}),e),vr=e=>$(u(c,{children:[l(`path`,{d:`M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z`}),l(`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2`}),l(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`22`})]}),e),yr=e=>$(u(c,{children:[l(`path`,{d:`M9 9v1a3 3 0 0 0 4.24 2.73`}),l(`path`,{d:`M15 5.5V5a3 3 0 0 0-5.94-.6`}),l(`path`,{d:`M19 10v2a7 7 0 0 1-9.9 6.36`}),l(`path`,{d:`M5 10v2a6.98 6.98 0 0 0 1.11 3.79`}),l(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`22`}),l(`line`,{x1:`2`,y1:`2`,x2:`22`,y2:`22`})]}),e),br=e=>$(u(c,{children:[l(`path`,{d:`M15 3h6v6`}),l(`path`,{d:`M10 14 21 3`}),l(`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`})]}),e),xr=e=>$(u(c,{children:[l(`rect`,{x:`3`,y:`4`,width:`18`,height:`18`,rx:`2`}),l(`line`,{x1:`16`,y1:`2`,x2:`16`,y2:`6`}),l(`line`,{x1:`8`,y1:`2`,x2:`8`,y2:`6`}),l(`line`,{x1:`3`,y1:`10`,x2:`21`,y2:`10`})]}),e),Sr=e=>$(u(c,{children:[l(`rect`,{x:`2`,y:`4`,width:`20`,height:`16`,rx:`2`}),l(`path`,{d:`m22 7-10 5L2 7`})]}),e),Cr=e=>$(l(`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),wr=e=>$(u(c,{children:[l(`path`,{d:`M4 14v-2a8 8 0 0 1 16 0v2`}),l(`path`,{d:`M18 19h-2`}),l(`rect`,{x:`3`,y:`13`,width:`4`,height:`6`,rx:`2`}),l(`rect`,{x:`17`,y:`13`,width:`4`,height:`6`,rx:`2`})]}),e),Tr=e=>$(u(c,{children:[l(`path`,{d:`M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4Z`}),l(`path`,{d:`M8 9h8M8 13h5`})]}),e),Er=e=>$(u(c,{children:[l(`path`,{d:`M3 4h18M4 4v12h16V4M12 16v5M8 21h8`}),l(`path`,{d:`m8 12 2.5-2.5 2 2L16 8`})]}),e),Dr=e=>$(u(c,{children:[l(`path`,{d:`M15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6`}),l(`path`,{d:`M3 9h12M7 2v4M12 2v4`}),l(`circle`,{cx:`17`,cy:`17`,r:`4`}),l(`path`,{d:`M17 15v2l1.5 1`})]}),e),Or=e=>$(u(c,{children:[l(`path`,{d:`M4 4h16v16H5a3 3 0 0 1-3-3V6`}),l(`path`,{d:`M8 8h8M8 12h8M8 16h5`})]}),e),kr=e=>$(u(c,{children:[l(`circle`,{cx:`12`,cy:`12`,r:`9`}),l(`path`,{d:`M8.5 14.5a4 4 0 0 0 7 0`}),l(`line`,{x1:`9`,y1:`9.5`,x2:`9.01`,y2:`9.5`}),l(`line`,{x1:`15`,y1:`9.5`,x2:`15.01`,y2:`9.5`})]}),e),Ar=e=>$(u(c,{children:[l(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),l(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),e),jr=e=>$(u(c,{children:[l(`path`,{d:`M11 5 6 9H2v6h4l5 4z`}),l(`path`,{d:`M15.5 8.5a5 5 0 0 1 0 7`}),l(`path`,{d:`M19 5a9 9 0 0 1 0 14`})]}),e),Mr=e=>$(u(c,{children:[l(`path`,{d:`M11 5 6 9H2v6h4l5 4z`}),l(`line`,{x1:`22`,y1:`9`,x2:`16`,y2:`15`}),l(`line`,{x1:`16`,y1:`9`,x2:`22`,y2:`15`})]}),e),Nr=e=>$(l(`path`,{d:`M20 6 9 17l-5-5`}),e),Pr=e=>$(u(c,{children:[l(`rect`,{x:`9`,y:`9`,width:`13`,height:`13`,rx:`2`}),l(`path`,{d:`M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1`})]}),e),Fr=e=>$(u(c,{children:[l(`path`,{d:`M1 4v6h6`}),l(`path`,{d:`M3.51 15a9 9 0 1 0 2.13-9.36L1 10`})]}),e),Ir=e=>$(l(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`}),e),Lr=e=>$(l(`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),Rr=e=>$(u(c,{children:[l(`path`,{d:`M18.36 6.64a9 9 0 1 1-12.73 0`}),l(`line`,{x1:`12`,y1:`2`,x2:`12`,y2:`12`})]}),e),zr=e=>$(u(c,{children:[l(`circle`,{cx:`12`,cy:`12`,r:`9`}),l(`path`,{d:`M12 7v5l3 2`})]}),e),Br=e=>$(u(c,{children:[l(`path`,{d:`M7 10v12`}),l(`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),Vr=e=>$(u(c,{children:[l(`path`,{d:`M17 14V2`}),l(`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),Hr=e=>$(u(c,{children:[l(`path`,{d:`M15 3h6v6`}),l(`path`,{d:`M9 21H3v-6`}),l(`path`,{d:`M21 3l-7 7`}),l(`path`,{d:`M3 21l7-7`})]}),e),Ur=e=>$(u(c,{children:[l(`path`,{d:`M9 3v6H3`}),l(`path`,{d:`M15 21v-6h6`}),l(`path`,{d:`M9 9 2 2`}),l(`path`,{d:`M15 15l7 7`})]}),e),Wr=e=>$(u(c,{children:[l(`rect`,{x:`3`,y:`4`,width:`18`,height:`14`,rx:`2`}),l(`rect`,{x:`11`,y:`11`,width:`8`,height:`6`,rx:`1`,fill:`currentColor`,stroke:`none`})]}),e),Gr=e=>$(u(c,{children:[l(`rect`,{x:`4`,y:`5`,width:`16`,height:`14`,rx:`2`}),l(`path`,{d:`M12 15V9`}),l(`path`,{d:`m8.5 12.5 3.5-3.5 3.5 3.5`})]}),e),Kr=e=>$(u(c,{children:[l(`line`,{x1:`12`,y1:`5`,x2:`12`,y2:`19`}),l(`path`,{d:`m19 12-7 7-7-7`})]}),e),qr=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\(https?:\/\/[^\s)]+\))|(\[[^\]]+\]\([^\s)]+\))|(https?:\/\/[^\s)]+)/g,Jr=e=>e.replace(/([^\n])\s+((?:[-*•]|\d+\.)\s+)(?=(?:\*\*[^*\n]{1,80}\*\*|[A-Z][A-Za-z0-9/& -]{1,50}:))/g,`$1
164
- $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.index>n&&t.push(e.slice(n,i.index));let a=i[0];if(a.startsWith("`"))t.push(l(`code`,{class:`cf-md-code`,children:a.slice(1,-1)},r++));else if(a.startsWith(`**`))t.push(l(`strong`,{children:a.slice(2,-2)},r++));else if(a.startsWith(`[`)&&!/\]\(https?:\/\//.test(a))t.push(/^\[([^\]]+)\]/.exec(a)?.[1]??a);else if(a.startsWith(`[`)){let e=/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/.exec(a),n=e?e[1]:a,i=e?e[2]:`#`;t.push(l(`a`,{href:i,target:`_blank`,rel:`noopener noreferrer nofollow`,children:n},r++))}else t.push(l(`a`,{href:a,target:`_blank`,rel:`noopener noreferrer nofollow`,children:a},r++));n=i.index+a.length}return n<e.length&&t.push(e.slice(n)),t},Xr=/^(```|#{1,6}\s|\s*[-*•]\s|\s*\d+\.\s)/,Zr=(e,t,n)=>{let r=`cf-md-h cf-md-h--${Math.min(e,6)}`;return l(e<=2?`h3`:e===3?`h4`:`h5`,{class:r,children:t},n)},Qr=e=>{let t=Jr(e.replace(/\r\n/g,`
162
+ `).trim()},kn=(e,t)=>{let n=t?.explanation,r=[n?.summary?.trim()||n?.headline?.trim(),n?.businessMeaning?.trim(),...n?.limitations??[]].filter(e=>!!e?.trim()),i=r.length?[...new Set(r)].join(`
163
+ `):e;return On(i)||(i.trim()?`The detailed results are available in the chat.`:``)},An=()=>{let e=globalThis;if(e.__voiceDebug)return!0;try{return e.localStorage?.getItem(`accurix.voiceDebug`)===`1`}catch{return!1}};var jn=class{constructor(e=()=>Date.now()){this.now=e,h(this,`entries`,[]),h(this,`startedAt`,void 0),this.startedAt=e(),globalThis.__accurixVoiceLog=()=>this.list()}add(e,t){let n={at:Math.round(this.now()-this.startedAt),event:e,detail:t};this.entries.push(n),this.entries.length>300&&this.entries.splice(0,this.entries.length-300),An()&&console.debug(`VOICEDBG ${e} ${t?JSON.stringify(t):``}`)}list(){return this.entries.slice()}};Cn/50;const Mn=8e-4;var Nn=class{constructor(e){this.options=e,h(this,`endSilenceMs`,void 0),h(this,`pending`,new Float32Array),h(this,`levels`,[]),h(this,`framesSinceFloor`,0),h(this,`floor`,Mn*4),h(this,`recentSpeech`,[]),h(this,`preroll`,[]),h(this,`silentMs`,0),h(this,`inputSilent`,!1),h(this,`outputActive`,!1),h(this,`turns`,[]),h(this,`nextTurnId`,1),this.endSilenceMs=e.endSilenceMs??2e3}get hearing(){return this.current()?.capturing??!1}get processing(){return this.turns.some(e=>!e.capturing&&!e.cancelled)}feed(e){let t=e;this.pending.length&&(t=new Float32Array(this.pending.length+e.length),t.set(this.pending),t.set(e,this.pending.length));let n=0;for(;n+320<=t.length;)this.frame(t.slice(n,n+320)),n+=320;this.pending=t.slice(n)}setOutputActive(e){this.outputActive!==e&&(this.outputActive=e,this.options.log.add(`output`,{active:e}))}finishTurn(){let e=this.current();e&&(e.capturing?this.endTurn(e,`done`):e.closed||(e.closed=!0,e.endedBy=`done`,this.options.log.add(`turn-done`,{turn:e.id})))}reset(e){for(let e of this.turns)e.cancelled=!0;this.turns.length&&this.options.log.add(`turns-dropped`,{reason:e,count:this.turns.length}),this.turns=[],this.preroll=[],this.recentSpeech=[],this.pending=new Float32Array,this.options.onChange()}current(){return this.turns[this.turns.length-1]}frame(e){let t=0,n=0;for(let r=0;r<e.length;r+=1){let i=e[r]??0;t+=i*i,n=Math.max(n,Math.abs(i))}let r=Math.sqrt(t/e.length);this.trackInputSilence(n);let i=this.current();!i?.capturing&&!this.outputActive&&this.trackFloor(r);let a=this.outputActive,o=Math.max(.006,this.floor*2.8)*(a?1.8:1),s=Math.max(.004,this.floor*1.8)*(a?1.4:1),c=r>=o,l=r>=s;if(!i?.capturing){for(this.preroll.push(e);this.preroll.length*20>500;)this.preroll.shift();this.recentSpeech.push(c);let t=(a?600:300)/20;for(;this.recentSpeech.length>t;)this.recentSpeech.shift();let n=this.recentSpeech.filter(Boolean).length*20;n>=(a?280:120)&&this.beginCapture(n);return}i.chunk.push(e),i.chunkMs+=20,i.durationMs+=20,c&&(i.voicedMs+=20,i.chunkVoicedMs+=20),i.quietMs=l?0:i.quietMs+20,a&&(i.overlappedOutput=!0),i.quietMs>=this.endSilenceMs?this.endTurn(i,`silence`):(i.chunkMs>=25e3||i.chunkMs>=12e3&&i.quietMs>=300||i.chunkMs>=2e4&&i.quietMs>=60)&&this.cutChunk(i)}trackFloor(e){if(this.levels.push(e),this.levels.length>250&&this.levels.shift(),this.framesSinceFloor+=1,this.framesSinceFloor<10&&this.levels.length>10)return;this.framesSinceFloor=0;let t=this.levels.slice().sort((e,t)=>e-t);this.floor=Math.max(Mn,t[Math.floor(t.length*.1)]??Mn)}trackInputSilence(e){this.silentMs=e===0?this.silentMs+20:0;let t=this.silentMs>=2e3;t!==this.inputSilent&&(this.inputSilent=t,this.options.log.add(`input-silent`,{silent:t}),this.options.onInputSilent?.(t))}beginCapture(e){let t=this.current(),n;t&&!t.capturing&&!t.closed?(n=t,n.capturing=!0,this.options.log.add(`turn-resumed`,{turn:n.id})):(n={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(n),this.options.log.add(`turn-start`,{turn:n.id,overOutput:this.outputActive}),this.options.listener.speechStart?.({turnId:n.id,overlappedOutput:this.outputActive})),n.chunk.push(...this.preroll),n.chunkMs+=this.preroll.length*20,n.durationMs+=this.preroll.length*20,n.voicedMs+=e,n.chunkVoicedMs+=e,n.quietMs=0,this.preroll=[],this.recentSpeech=[],this.options.onChange()}endTurn(e,t){let n=Math.max(0,Math.floor((e.quietMs-400)/20));if(n>0&&(e.chunk.splice(e.chunk.length-Math.min(n,e.chunk.length)),e.chunkMs=e.chunk.length*20),e.capturing=!1,e.endedBy=t,t===`done`&&(e.closed=!0),this.options.log.add(`turn-end`,{turn:e.id,by:t,ms:e.durationMs,voicedMs:e.voicedMs}),e.chunkCount===0&&e.voicedMs<300){this.turns=this.turns.filter(t=>t!==e),this.options.log.add(`turn-noise`,{turn:e.id,reason:`too-short`}),this.options.listener.noise?.({id:e.id,reason:`too-short`,overlappedOutput:e.overlappedOutput}),this.options.onChange();return}this.cutChunk(e),this.options.onChange(),this.settle()}cutChunk(e){if(e.chunk.length===0)return;let t=e.chunk,n=e.chunkCount;e.chunkCount+=1,e.results[n]=void 0,e.chunk=[];let r=t.length*20,i=e.chunkVoicedMs;if(e.chunkMs=0,e.chunkVoicedMs=0,i===0&&n>0){e.results[n]=``;return}this.options.log.add(`chunk`,{turn:e.id,index:n,ms:r}),this.options.transcribe({audio:Tn(t),mimeType:`audio/wav`,durationSeconds:r/1e3,turnId:e.id,chunkIndex:n}).then(e=>(e??``).trim(),()=>null).then(t=>{if(e.cancelled)return;e.results[n]=t,this.options.log.add(`chunk-text`,{turn:e.id,index:n,chars:t===null?-1:t.length});let r=[];for(let t of e.results){if(t===void 0)break;t&&r.push(t)}r.length&&this.options.listener.partial?.({turnId:e.id,text:r.join(` `)}),this.settle()})}settle(){for(;this.turns.length;){let e=this.turns[0];if(!e||e.capturing||e.results.some(e=>e===void 0))return;this.turns.shift();let t=e.results.filter(e=>typeof e==`string`&&e!==``),n=e.results.every(e=>e===null),r=t.join(` `).replace(/\s+/g,` `).trim();if(r)this.options.log.add(`turn`,{turn:e.id,chars:r.length,by:e.endedBy}),this.options.listener.turn?.({id:e.id,text:r,durationMs:e.durationMs,endedBy:e.endedBy,overlappedOutput:e.overlappedOutput});else{let t=n?`transcribe-failed`:`empty-transcript`;this.options.log.add(`turn-noise`,{turn:e.id,reason:t}),this.options.listener.noise?.({id:e.id,reason:t,overlappedOutput:e.overlappedOutput})}this.options.onChange()}}};const Pn=[300,1e3,2500],Fn=()=>typeof navigator<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`&&typeof globalThis.AudioContext==`function`,In=e=>{let t=e?.name;return t===`NotAllowedError`||t===`SecurityError`?`permission-denied`:t===`NotFoundError`||t===`OverconstrainedError`?`no-device`:`error`};var Ln=class{constructor(e){this.options=e,h(this,`log`,new jn),h(this,`turns`,void 0),h(this,`mic`,`off`),h(this,`reason`,void 0),h(this,`muted`,!1),h(this,`inputSilent`,!1),h(this,`stream`,null),h(this,`context`,null),h(this,`source`,null),h(this,`processor`,null),h(this,`sink`,null),h(this,`downsampler`,null),h(this,`deviceId`,void 0),h(this,`generation`,0),h(this,`recoveryAttempt`,0),h(this,`recoveryTimer`,null),h(this,`lastSnapshot`,``),h(this,`groupId`,void 0),h(this,`onTrackEnded`,()=>{this.log.add(`track-ended`),this.recover(`track-ended`)}),h(this,`onTrackMuteChange`,()=>{let e=this.stream?.getAudioTracks()[0];this.log.add(`track-mute-change`,{muted:!!e?.muted}),this.refreshMic()}),h(this,`onContextState`,()=>{let e=this.context?.state;this.log.add(`audio-state`,{state:e}),(e===`suspended`||e===`interrupted`)&&this.context?.resume().catch(()=>void 0),this.refreshMic()}),h(this,`onDeviceChange`,()=>{this.checkDevices()}),this.deviceId=e.deviceId,this.turns=new Nn({transcribe:e.transcribe,listener:e.listener,log:this.log,endSilenceMs:e.endSilenceMs,onChange:()=>this.publish(),onInputSilent:e=>{this.inputSilent=e,this.publish()}})}get snapshot(){let e=this.mic,t=this.reason;return e===`listening`&&this.inputSilent&&(e=`unavailable`,t=`input-silent`),e===`listening`&&this.turns.hearing&&(e=`hearing`),{mic:e,processing:this.turns.processing,reason:e===`unavailable`?t: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(e=`stopped`){this.mic!==`off`&&(this.log.add(`stop`,{reason:e}),this.generation+=1,this.clearRecovery(),this.mediaDevices()?.removeEventListener(`devicechange`,this.onDeviceChange),this.turns.reset(e),this.close(),this.context?.close().catch(()=>void 0),this.context=null,this.setMic(`off`))}setMuted(e){if(!(this.muted===e||this.mic===`off`)){this.muted=e,this.log.add(e?`mute`:`unmute`);for(let t of this.stream?.getAudioTracks()??[])t.enabled=!e;e?(this.turns.reset(`muted`),this.setMic(`muted`)):this.refreshMic()}}finishTurn(){this.log.add(`done-pressed`),this.turns.finishTurn()}setOutputActive(e){this.turns.setOutputActive(e)}async selectDevice(e){e!==this.deviceId&&(this.deviceId=e,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(e){let t=++this.generation;this.setMic(`starting`);let n=this.options.media?.getUserMedia??(Fn()?e=>navigator.mediaDevices.getUserMedia(e):null);if(!n){this.unavailable(`unsupported`);return}let r;try{r=await n({audio:{...this.deviceId?{deviceId:{exact:this.deviceId}}:{},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1}})}catch(n){if(t!==this.generation)return;let r=In(n);if(this.log.add(`mic-open-failed`,{why:e,reason:r}),r===`no-device`&&this.deviceId){this.deviceId=void 0,await this.open(`default-device`);return}this.unavailable(r);return}if(t!==this.generation){r.getTracks().forEach(e=>e.stop());return}try{this.connect(r)}catch(e){this.log.add(`audio-setup-failed`,{message:String(e?.name??`error`)}),r.getTracks().forEach(e=>e.stop()),this.unavailable(`error`);return}this.recoveryAttempt=0,this.groupId=r.getAudioTracks()[0]?.getSettings?.().groupId,this.log.add(`mic-open`,{why:e}),this.refreshMic()}connect(e){this.stream=e;for(let t of e.getAudioTracks())t.enabled=!this.muted,t.addEventListener(`ended`,this.onTrackEnded),t.addEventListener(`mute`,this.onTrackMuteChange),t.addEventListener(`unmute`,this.onTrackMuteChange);let t=this.context??this.options.media?.createAudioContext?.()??new globalThis.AudioContext;this.context||(this.context=t,t.addEventListener(`statechange`,this.onContextState)),t.state===`suspended`&&t.resume().catch(()=>void 0),this.downsampler=new wn(t.sampleRate),this.source=t.createMediaStreamSource(e),this.processor=t.createScriptProcessor(2048,1,1),this.sink=t.createGain(),this.sink.gain.value=0,this.processor.onaudioprocess=e=>{if(this.muted||!this.downsampler)return;let t=this.downsampler.process(e.inputBuffer.getChannelData(0));if(this.turns.feed(t),this.options.listener.level&&t.length){let e=0;for(let n of t)e+=n*n;this.options.listener.level(Math.sqrt(e/t.length))}},this.source.connect(this.processor),this.processor.connect(this.sink),this.sink.connect(t.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(let e of this.stream?.getTracks()??[])e.removeEventListener(`ended`,this.onTrackEnded),e.removeEventListener(`mute`,this.onTrackMuteChange),e.removeEventListener(`unmute`,this.onTrackMuteChange),e.stop();this.stream=null,this.inputSilent=!1}refreshMic(){if(this.mic===`off`)return;if(this.muted)return this.setMic(`muted`);let e=this.stream?.getAudioTracks()[0];if(!e||e.readyState!==`live`)return this.unavailable(`device-lost`);if(e.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(e){this.reason=e,this.setMic(`unavailable`)}setMic(e){this.mic!==e&&this.log.add(`mic`,{state:e,reason:e===`unavailable`?this.reason:void 0}),this.mic=e,this.publish()}publish(){let e=this.snapshot,t=JSON.stringify(e);t!==this.lastSnapshot&&(this.lastSnapshot=t,this.options.listener.state?.(e))}recover(e){if(this.mic===`off`||this.recoveryTimer)return;let t=Pn[this.recoveryAttempt];if(this.turns.reset(e),this.close(),t===void 0){this.log.add(`mic-recovery-gave-up`,{why:e}),this.unavailable(`device-lost`);return}this.recoveryAttempt+=1,this.unavailable(`device-lost`),this.log.add(`mic-recovering`,{why:e,attempt:this.recoveryAttempt}),this.recoveryTimer=setTimeout(()=>{this.recoveryTimer=null,this.mic!==`off`&&this.open(e)},t)}clearRecovery(){this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,this.recoveryAttempt=0}async checkDevices(){let e=this.stream?.getAudioTracks()[0];if(!e||e.readyState!==`live`){this.log.add(`device-change`,{live:!1}),this.recover(`device-change`);return}let t=[];try{t=(await this.mediaDevices()?.enumerateDevices()??[]).filter(e=>e.kind===`audioinput`)}catch{return}let n=t.some(e=>!this.groupId||e.groupId===this.groupId),r=t.find(e=>e.deviceId===`default`),i=!this.deviceId&&r!==void 0&&this.groupId!==void 0&&r.groupId!==this.groupId;this.log.add(`device-change`,{live:!0,ours:n,defaultMoved:i}),(!n||i)&&this.recover(`device-change`)}};const Rn=e(U),zn=()=>n(Rn),Bn=(e,t)=>{let n=o(t);n.current=t;let i=o(()=>void 0),c=e.aiExplanation?.explanationId??e.explanationId??``,l=a(()=>{let t=n.current;return new Ie(e,t?{poll:(e,t)=>n.current.poll(e,t),...t.retry?{retry:(e,t)=>n.current.retry(e,t)}:{}}:void 0,e=>i.current(e),{onSettled:e=>n.current?.settled?.(c,e)})},[c,e.aiExplanation?.status===`pending`?`pending`:`settled`,!!t]),[u,d]=s(l.state);return r(()=>(i.current=d,d(l.state),l.start(),()=>l.dispose()),[l]),[u.status===`ready`?u:{...u,explanation:e},l]},Vn=({prefix:e,state:t,onRetry:n})=>{let r=zn();return u(`div`,{class:`${e}-xp__ai`,"data-ai-status":t.status,children:[t.status===`pending`?l(`p`,{class:`${e}-xp__ai-note`,children:r.preparingDetailed}):null,t.status===`failed`?u(`p`,{class:`${e}-xp__ai-note`,children:[r.detailedUnavailable,t.retryAvailable?l(`button`,{type:`button`,class:`${e}-xp__ai-retry`,disabled:t.retrying,onClick:n,children:r.detailedRetry}):null]}):null,l(`span`,{class:`${e}-xp__sr`,role:`status`,"aria-live":`polite`,children:t.announcement})]})},Hn=({citations:e,step:t,prefix:n,active:r,onToggle:i,evidenceById:a})=>{let o=zn();return e.length===0?null:l(c,{children:e.map(e=>{let s=r?.id===e.id&&r.step===t;return l(`button`,{type:`button`,class:`${n}-xp__cite`,"data-evidence-id":e.id,"aria-expanded":s,"aria-label":`${o.citationLabel} ${e.index}: ${a[e.id]?.text??``}`.trim(),onClick:n=>i(e.id,t,n.currentTarget),children:Oe(e).slice(1,-1)},e.id)})})},Un=(e,t)=>e.sourceTargets.find(e=>t?t(e):!0),Wn=({evidence:e,prefix:t,onClose:n,onOpenSource:i,canOpenSource:a})=>{let s=zn(),c=o(null);r(()=>{c.current?.focus()},[e.id]);let d=i?Un(e,a):void 0;return u(`div`,{ref:c,class:`${t}-xp__evidence-panel`,role:`region`,tabIndex:-1,"aria-label":`${s.evidence} ${e.index}`,"data-testid":`analytics-explanation-evidence`,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),n())},children:[u(`div`,{class:`${t}-xp__evidence-head`,children:[u(`p`,{class:`${t}-xp__evidence-text`,children:[`[`,e.index,`] `,e.text]}),l(`button`,{type:`button`,class:`${t}-xp__close`,"aria-label":s.closeEvidence,onClick:n,children:`×`})]}),l(`dl`,{class:`${t}-xp__evidence-rows`,children:ke(e,s).map(e=>u(`div`,{style:{display:`contents`},"data-row":e.key,children:[l(`dt`,{children:e.label}),l(`dd`,{children:e.value})]},e.key))}),d&&i?l(`div`,{class:`${t}-xp__evidence-actions`,children:l(`button`,{type:`button`,class:`${t}-xp__button`,onClick:()=>i(d,e),children:s.openSource})}):null]})},Gn=({down:e})=>l(`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:l(`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`})}),Kn=(e,t,n)=>t===`wrong_numbers`?e.reasonWrongNumbers:t===`missing_comparison`?e.reasonMissingComparison:t===`unclear`?e.reasonUnclear:t===`too_long`?e.reasonTooLong:n,qn=({prefix:e,explanationId:t,submit:n,context:r})=>{let i=zn(),[o,c]=s({phase:`idle`,reasons:[],comment:``}),d=a(()=>new Me(t,n,c,r),[t]),f=o.phase===`saving`;return u(`div`,{class:`${e}-xp__feedback`,"data-testid":`analytics-explanation-feedback`,children:[o.phase===`done`?u(`div`,{class:`${e}-xp__feedback-row`,role:`status`,children:[l(`span`,{class:`${e}-xp__feedback-note`,children:i.feedbackThanks}),l(`button`,{type:`button`,class:`${e}-xp__button`,onClick:()=>void d.undo(),children:i.feedbackUndo})]}):u(`div`,{class:`${e}-xp__feedback-row`,children:[l(`span`,{class:`${e}-xp__feedback-label`,children:i.feedbackPrompt}),l(`button`,{type:`button`,class:`${e}-xp__vote`,"aria-label":i.feedbackHelpful,"aria-pressed":o.rating===`up`,disabled:f,onClick:()=>void d.vote(`up`),children:l(Gn,{down:!1})}),l(`button`,{type:`button`,class:`${e}-xp__vote`,"aria-label":i.feedbackNotHelpful,"aria-pressed":o.rating===`down`,disabled:f,onClick:()=>void d.vote(`down`),children:l(Gn,{down:!0})})]}),o.phase===`details`||f&&o.rating===`down`?u(`form`,{class:`${e}-xp__feedback-form`,onSubmit:e=>{e.preventDefault(),d.send()},children:[u(`fieldset`,{class:`${e}-xp__reasons`,children:[l(`legend`,{children:i.feedbackReasonsPrompt}),te.map(t=>l(`button`,{type:`button`,class:`${e}-xp__reason`,"aria-pressed":o.reasons.includes(t.id),onClick:()=>d.toggleReason(t.id),children:Kn(i,t.id,t.label)},t.id))]}),l(`textarea`,{class:`${e}-xp__comment`,"aria-label":i.feedbackCommentPlaceholder,placeholder:i.feedbackCommentPlaceholder,maxLength:500,value:o.comment,onInput:e=>d.setComment(e.currentTarget.value)}),l(`div`,{class:`${e}-xp__feedback-row`,children:l(`button`,{type:`submit`,class:`${e}-xp__button is-primary`,disabled:f,children:i.feedbackSubmit})})]}):null,o.error?l(`p`,{class:`${e}-xp__feedback-error`,role:`alert`,children:o.error}):null]})},Jn=({aiTransport:e,...t})=>{let[n,r]=Bn(t.explanation,e),i=Yn(t.explanation),o=a(()=>({...U,...t.copy}),[t.copy]);return l(Rn.Provider,{value:o,children:l(Xn,{...t,explanation:n.explanation,aiStatus:i?l(Vn,{prefix:t.classPrefix,state:n,onRetry:()=>void r.retry()}):null})})},Yn=e=>!!(e.aiExplanation&&e.aiExplanation.status!==`not_requested`),Xn=({explanation:e,aiStatus:t,classPrefix:n,showLead:r=!0,investigateOpen:d=!1,onFollowUp:f,onOpenSource:p,canOpenSource:m,onFeedback:h,feedbackContext:g,onExpand:_,onCollapse:v,expanded:y=!1,...b})=>{let x=zn(),S=o(null),C=o(null),w=o(!1),T=()=>{let e=S.current,t=e?.getRootNode(),n=t&&`activeElement`in t?t.activeElement:null;return!!(e&&n&&e.contains(n))},E=a(()=>(w.current=T(),Ee(e,{...b,copy:x})),[e,b.locale,b.cleanText,x]),[D,O]=s(),k=o(null);i(()=>{D&&(E.evidenceById[D.id]&&S.current?.querySelector(`[data-testid="analytics-explanation-evidence"]`)||(O(void 0),w.current&&!T()&&(C.current??S.current)?.focus()))},[E]);let A=(e,t,n)=>{k.current=n,O(n=>n?.id===e&&n.step===t?void 0:{id:e,step:t})},j=()=>{O(void 0);let e=k.current;e?.isConnected?e.focus():(C.current??S.current)?.focus()},M=(e,t)=>l(Hn,{citations:e,step:t,prefix:n,active:D,onToggle:A,evidenceById:E.evidenceById}),N=e=>{if(!D||D.step!==e)return null;let t=E.evidenceById[D.id];return t?l(Wn,{evidence:t,prefix:n,onClose:j,onOpenSource:p,canOpenSource:m}):null},P=(e,t)=>u(c,{children:[e.text,M(e.citations,t)]}),{investigate:F}=E;return u(`section`,{ref:S,class:`${n}-xp${y?` is-expanded`:``}${_||v?` has-expand`:``}`,"data-testid":`analytics-explanation`,"aria-label":x.region,tabIndex:-1,children:[y&&v?l(`button`,{type:`button`,class:`${n}-xp__expand`,"aria-label":x.collapse,title:x.collapse,onClick:v,children:`×`}):_?l(`button`,{type:`button`,class:`${n}-xp__expand`,"aria-label":x.expand,title:x.expand,"data-testid":`analytics-explanation-expand`,onClick:_,children:`⤢`}):null,r?u(`div`,{class:`${n}-xp__lead`,"data-step":`lead`,children:[E.lead.preface?l(`p`,{class:`${n}-xp__preface`,children:E.lead.preface}):null,u(`div`,{class:`${n}-xp__meta`,children:[l(`span`,{class:`${n}-xp__eyebrow`,children:E.lead.eyebrow}),l(`span`,{class:`${n}-xp__provenance`,children:E.lead.provenance})]}),l(`h3`,{class:`${n}-xp__headline`,ref:C,tabIndex:-1,children:P(E.lead.headline,`lead`)}),E.lead.summary?l(`p`,{class:`${n}-xp__summary`,children:P(E.lead.summary,`lead`)}):null,N(`lead`)]}):null,t,E.comparison.length>0?u(`section`,{class:`${n}-xp__step`,"data-step":`comparison`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.comparison}),l(`ul`,{class:`${n}-xp__periods`,children:E.comparison.map(e=>u(`li`,{class:`${n}-xp__period`,"data-status":e.status??`observed`,children:[l(`span`,{class:`${n}-xp__period-label`,children:e.label}),e.valueText?l(`span`,{class:`${n}-xp__period-value`,children:e.valueText}):null,e.statusLabel?l(`span`,{class:`${n}-xp__chip is-${e.statusTone}`,children:e.statusLabel}):null,e.inProgress?l(`span`,{class:`${n}-xp__chip is-progress`,children:x.inProgress}):null,e.citation?M([e.citation],`comparison`):null,e.reason?l(`small`,{class:`${n}-xp__period-reason`,children:e.reason}):null]},e.key))}),N(`comparison`)]}):null,E.conclusions.length>0||E.businessMeaning?u(`section`,{class:`${n}-xp__step`,"data-step":`conclusions`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.conclusions}),E.conclusions.length>0?l(`ul`,{class:`${n}-xp__list`,children:E.conclusions.map(e=>l(`li`,{children:P(e,`conclusions`)},e.text))}):null,E.businessMeaning?u(`p`,{class:`${n}-xp__meaning`,children:[u(`strong`,{children:[x.whyItMatters,`: `]}),P(E.businessMeaning,`conclusions`)]}):null,N(`conclusions`)]}):null,E.limits.length>0?u(`section`,{class:`${n}-xp__step`,"data-step":`limits`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.limits}),l(`ul`,{class:`${n}-xp__list ${n}-xp__limits`,children:E.limits.map(e=>u(`li`,{"data-kind":e.kind,children:[e.text,e.citation?M([e.citation],`limits`):null]},e.text))}),N(`limits`)]}):null,E.checkedLine?l(`p`,{class:`${n}-xp__checked`,"data-step":`checked`,children:E.checkedLine}):null,E.hasInvestigate?u(`details`,{class:`${n}-xp__investigate`,"data-step":`investigate`,open:d,children:[l(`summary`,{children:x.investigate}),u(`div`,{class:`${n}-xp__investigate-body`,children:[F.causes.length>0?u(`div`,{class:`${n}-xp__group`,children:[u(`div`,{class:`${n}-xp__group-head`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.causes}),l(`span`,{class:`${n}-xp__hint`,children:x.causesHint})]}),F.causes.map(e=>u(`article`,{class:`${n}-xp__card`,children:[u(`p`,{class:`${n}-xp__card-title`,children:[e.title,M(e.citations,`investigate`)]}),e.howToCheck?u(`p`,{class:`${n}-xp__card-body`,children:[x.howToCheck,` `,e.howToCheck]}):null]},e.title))]}):null,F.recommendations.length>0?u(`div`,{class:`${n}-xp__group`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.recommendations}),F.recommendations.map(e=>u(`article`,{class:`${n}-xp__card`,children:[u(`p`,{class:`${n}-xp__card-title`,children:[e.title,M(e.citations,`investigate`)]}),e.why?l(`p`,{class:`${n}-xp__card-body`,children:e.why}):null,e.watch?u(`p`,{class:`${n}-xp__card-body`,children:[x.watch,` `,e.watch]}):null]},e.title))]}):null,F.outlook?u(`div`,{class:`${n}-xp__group`,children:[u(`div`,{class:`${n}-xp__group-head`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.outlook}),l(`span`,{class:`${n}-xp__hint`,children:F.outlook.badge})]}),l(`p`,{class:`${n}-xp__card-body`,children:F.outlook.text}),F.outlook.note?l(`p`,{class:`${n}-xp__card-body`,children:F.outlook.note}):null]}):null,f&&F.followUps.length>0?u(`div`,{class:`${n}-xp__group`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.followUps}),l(`div`,{class:`${n}-xp__questions`,children:F.followUps.map(e=>l(`button`,{type:`button`,class:`${n}-xp__question`,onClick:()=>f(e),children:e},e))})]}):null,E.evidence.length>0?u(`div`,{class:`${n}-xp__group`,children:[l(`h4`,{class:`${n}-xp__title`,children:x.evidenceList}),l(`ul`,{class:`${n}-xp__list`,children:E.evidence.map(e=>u(`li`,{children:[e.text,M([{id:e.id,index:e.index}],`investigate`)]},e.id))})]}):null,N(`investigate`)]})]}):null,l(`p`,{class:`${n}-xp__source`,children:E.sourceNote}),h&&E.explanationId?l(qn,{prefix:n,explanationId:E.explanationId,submit:h,context:g}):null]})},Zn=[{name:`Smileys`,emojis:`😀.😃.😄.😁.😅.😂.🤣.😊.😇.🙂.🙃.😉.😌.😍.🥰.😘.😋.😛.😜.🤪.🤗.🤭.🤔.🤐.😐.😶.😏.🙄.😴.🥳.😎.🤓.🥺.😢.😭.😤.😠.🤯.😬.😱.🤩.🥱`.split(`.`)},{name:`Gestures`,emojis:[`👍`,`👎`,`👌`,`🤌`,`✌️`,`🤞`,`🤟`,`🤘`,`🤙`,`👈`,`👉`,`👆`,`👇`,`✋`,`🖐️`,`👋`,`🤝`,`🙏`,`💪`,`👏`,`🙌`,`👐`,`🤲`,`🫶`]},{name:`Hearts & symbols`,emojis:`❤️.🧡.💛.💚.💙.💜.🖤.🤍.💔.❣️.💕.💖.💘.💝.✨.⭐.🌟.💫.🔥.🎉.🎊.✅.❌.⚡.💯.🚀`.split(`.`)},{name:`Animals & nature`,emojis:[`🐶`,`🐱`,`🦊`,`🐻`,`🐼`,`🐨`,`🦁`,`🐮`,`🐸`,`🐵`,`🐧`,`🦄`,`🐝`,`🦋`,`🐢`,`🐬`,`🌷`,`🌸`,`🌹`,`🌻`,`🌳`,`🍀`]},{name:`Food & drink`,emojis:[`🍎`,`🍌`,`🍉`,`🍓`,`🍒`,`🥑`,`🍔`,`🍟`,`🍕`,`🌮`,`🍿`,`🍩`,`🍪`,`🎂`,`☕`,`🍵`,`🍺`,`🥂`,`🍷`]},{name:`Objects & travel`,emojis:`🚀.✈️.🚗.🏠.📦.📱.💻.⌚.📷.💡.🔑.🎁.📌.✏️.📝.📞.📧.💰.📈.⏰.🔔.🎯.🏆.🎮.🎵.💬.👀`.split(`.`)}],Qn={"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`}]}},$n={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`},Q=(e,t)=>e.replace(/\{(\w+)\}/g,(e,n)=>t[n]??``),er=(e,t,n)=>!t||e.includes(t)?e:`${e} ${Q(n.caseReference,{reference:t})}`,tr=e=>e?{...$n,...e}:$n,nr=e($n),rr=nr.Provider,ir=e(void 0),ar=ir.Provider,or=()=>n(ir),sr=new Set([`ar`,`he`,`iw`,`fa`,`ur`,`ps`,`sd`,`ug`,`yi`,`dv`,`ckb`]),cr=(e,t)=>{if(t===`ltr`||t===`rtl`)return t;let n=(e??``).trim().toLowerCase().split(/[-_]/)[0]??``;return sr.has(n)?`rtl`:`ltr`},lr=()=>n(nr),ur=[[`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})),dr=e=>[...e.toUpperCase()].map(e=>String.fromCodePoint(127397+e.charCodeAt(0))).join(``),fr=()=>{let e=``;try{if(Intl.DateTimeFormat().resolvedOptions().timeZone===`Africa/Lagos`&&(e=`NG`),!e){let t=navigator.languages?.[0]||navigator.language;e=new Intl.Locale(t).region||``}}catch{e=``}return ur.find(t=>t.iso===e)??ur.find(e=>e.iso===`US`)},pr=e=>{let t=fr(),n=e?.trim()??``;if(!n.startsWith(`+`))return{country:t,national:n.replace(/\D/g,``)};let r=n.replace(/\D/g,``),i=[...ur].sort((e,t)=>t.dial.length-e.dial.length).find(e=>r.startsWith(e.dial))??t;return{country:i,national:r.slice(i.dial.length)}},mr=(e,t)=>{let n=t.replace(/\D/g,``).replace(/^0+/,``);return n?`+${e.dial}${n}`:``},hr=e=>{let t=e.replace(/\D/g,``);return e.startsWith(`+`)&&t.length>=8&&t.length<=15},$=(e,t)=>l(`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}),gr=e=>l(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,"aria-hidden":`true`,...e,children:l(`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`})}),_r=e=>$(l(`path`,{d:`m6 9 6 6 6-6`}),e),vr=e=>$(u(c,{children:[l(`path`,{d:`m22 2-7 20-4-9-9-4Z`}),l(`path`,{d:`M22 2 11 13`})]}),e),yr=e=>$(u(c,{children:[l(`path`,{d:`M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z`}),l(`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2`}),l(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`22`})]}),e),br=e=>$(u(c,{children:[l(`path`,{d:`M9 9v1a3 3 0 0 0 4.24 2.73`}),l(`path`,{d:`M15 5.5V5a3 3 0 0 0-5.94-.6`}),l(`path`,{d:`M19 10v2a7 7 0 0 1-9.9 6.36`}),l(`path`,{d:`M5 10v2a6.98 6.98 0 0 0 1.11 3.79`}),l(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`22`}),l(`line`,{x1:`2`,y1:`2`,x2:`22`,y2:`22`})]}),e),xr=e=>$(u(c,{children:[l(`path`,{d:`M15 3h6v6`}),l(`path`,{d:`M10 14 21 3`}),l(`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`})]}),e),Sr=e=>$(u(c,{children:[l(`rect`,{x:`3`,y:`4`,width:`18`,height:`18`,rx:`2`}),l(`line`,{x1:`16`,y1:`2`,x2:`16`,y2:`6`}),l(`line`,{x1:`8`,y1:`2`,x2:`8`,y2:`6`}),l(`line`,{x1:`3`,y1:`10`,x2:`21`,y2:`10`})]}),e),Cr=e=>$(u(c,{children:[l(`rect`,{x:`2`,y:`4`,width:`20`,height:`16`,rx:`2`}),l(`path`,{d:`m22 7-10 5L2 7`})]}),e),wr=e=>$(l(`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),Tr=e=>$(u(c,{children:[l(`path`,{d:`M4 14v-2a8 8 0 0 1 16 0v2`}),l(`path`,{d:`M18 19h-2`}),l(`rect`,{x:`3`,y:`13`,width:`4`,height:`6`,rx:`2`}),l(`rect`,{x:`17`,y:`13`,width:`4`,height:`6`,rx:`2`})]}),e),Er=e=>$(u(c,{children:[l(`path`,{d:`M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4Z`}),l(`path`,{d:`M8 9h8M8 13h5`})]}),e),Dr=e=>$(u(c,{children:[l(`path`,{d:`M3 4h18M4 4v12h16V4M12 16v5M8 21h8`}),l(`path`,{d:`m8 12 2.5-2.5 2 2L16 8`})]}),e),Or=e=>$(u(c,{children:[l(`path`,{d:`M15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6`}),l(`path`,{d:`M3 9h12M7 2v4M12 2v4`}),l(`circle`,{cx:`17`,cy:`17`,r:`4`}),l(`path`,{d:`M17 15v2l1.5 1`})]}),e),kr=e=>$(u(c,{children:[l(`path`,{d:`M4 4h16v16H5a3 3 0 0 1-3-3V6`}),l(`path`,{d:`M8 8h8M8 12h8M8 16h5`})]}),e),Ar=e=>$(u(c,{children:[l(`circle`,{cx:`12`,cy:`12`,r:`9`}),l(`path`,{d:`M8.5 14.5a4 4 0 0 0 7 0`}),l(`line`,{x1:`9`,y1:`9.5`,x2:`9.01`,y2:`9.5`}),l(`line`,{x1:`15`,y1:`9.5`,x2:`15.01`,y2:`9.5`})]}),e),jr=e=>$(u(c,{children:[l(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),l(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),e),Mr=e=>$(u(c,{children:[l(`path`,{d:`M11 5 6 9H2v6h4l5 4z`}),l(`path`,{d:`M15.5 8.5a5 5 0 0 1 0 7`}),l(`path`,{d:`M19 5a9 9 0 0 1 0 14`})]}),e),Nr=e=>$(u(c,{children:[l(`path`,{d:`M11 5 6 9H2v6h4l5 4z`}),l(`line`,{x1:`22`,y1:`9`,x2:`16`,y2:`15`}),l(`line`,{x1:`16`,y1:`9`,x2:`22`,y2:`15`})]}),e),Pr=e=>$(l(`path`,{d:`M20 6 9 17l-5-5`}),e),Fr=e=>$(u(c,{children:[l(`rect`,{x:`9`,y:`9`,width:`13`,height:`13`,rx:`2`}),l(`path`,{d:`M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1`})]}),e),Ir=e=>$(u(c,{children:[l(`path`,{d:`M1 4v6h6`}),l(`path`,{d:`M3.51 15a9 9 0 1 0 2.13-9.36L1 10`})]}),e),Lr=e=>$(l(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`2`}),e),Rr=e=>$(l(`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),zr=e=>$(u(c,{children:[l(`path`,{d:`M18.36 6.64a9 9 0 1 1-12.73 0`}),l(`line`,{x1:`12`,y1:`2`,x2:`12`,y2:`12`})]}),e),Br=e=>$(u(c,{children:[l(`circle`,{cx:`12`,cy:`12`,r:`9`}),l(`path`,{d:`M12 7v5l3 2`})]}),e),Vr=e=>$(u(c,{children:[l(`path`,{d:`M7 10v12`}),l(`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),Hr=e=>$(u(c,{children:[l(`path`,{d:`M17 14V2`}),l(`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),Ur=e=>$(u(c,{children:[l(`path`,{d:`M15 3h6v6`}),l(`path`,{d:`M9 21H3v-6`}),l(`path`,{d:`M21 3l-7 7`}),l(`path`,{d:`M3 21l7-7`})]}),e),Wr=e=>$(u(c,{children:[l(`path`,{d:`M9 3v6H3`}),l(`path`,{d:`M15 21v-6h6`}),l(`path`,{d:`M9 9 2 2`}),l(`path`,{d:`M15 15l7 7`})]}),e),Gr=e=>$(u(c,{children:[l(`rect`,{x:`3`,y:`4`,width:`18`,height:`14`,rx:`2`}),l(`rect`,{x:`11`,y:`11`,width:`8`,height:`6`,rx:`1`,fill:`currentColor`,stroke:`none`})]}),e),Kr=e=>$(u(c,{children:[l(`rect`,{x:`4`,y:`5`,width:`16`,height:`14`,rx:`2`}),l(`path`,{d:`M12 15V9`}),l(`path`,{d:`m8.5 12.5 3.5-3.5 3.5 3.5`})]}),e),qr=e=>$(u(c,{children:[l(`line`,{x1:`12`,y1:`5`,x2:`12`,y2:`19`}),l(`path`,{d:`m19 12-7 7-7-7`})]}),e),Jr=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\(https?:\/\/[^\s)]+\))|(\[[^\]]+\]\([^\s)]+\))|(https?:\/\/[^\s)]+)/g,Yr=e=>e.replace(/([^\n])\s+((?:[-*•]|\d+\.)\s+)(?=(?:\*\*[^*\n]{1,80}\*\*|[A-Z][A-Za-z0-9/& -]{1,50}:))/g,`$1
164
+ $2`),Xr=e=>{let t=[],n=0,r=0,i;for(Jr.lastIndex=0;(i=Jr.exec(e))!==null;){i.index>n&&t.push(e.slice(n,i.index));let a=i[0];if(a.startsWith("`"))t.push(l(`code`,{class:`cf-md-code`,children:a.slice(1,-1)},r++));else if(a.startsWith(`**`))t.push(l(`strong`,{children:a.slice(2,-2)},r++));else if(a.startsWith(`[`)&&!/\]\(https?:\/\//.test(a))t.push(/^\[([^\]]+)\]/.exec(a)?.[1]??a);else if(a.startsWith(`[`)){let e=/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/.exec(a),n=e?e[1]:a,i=e?e[2]:`#`;t.push(l(`a`,{href:i,target:`_blank`,rel:`noopener noreferrer nofollow`,children:n},r++))}else t.push(l(`a`,{href:a,target:`_blank`,rel:`noopener noreferrer nofollow`,children:a},r++));n=i.index+a.length}return n<e.length&&t.push(e.slice(n)),t},Zr=/^(```|#{1,6}\s|\s*[-*•]\s|\s*\d+\.\s)/,Qr=(e,t,n)=>{let r=`cf-md-h cf-md-h--${Math.min(e,6)}`;return l(e<=2?`h3`:e===3?`h4`:`h5`,{class:r,children:t},n)},$r=e=>{let t=Yr(e.replace(/\r\n/g,`
165
165
  `)).split(`
166
166
  `),n=[],r=0,i=0;for(;i<t.length;){let e=t[i];if(e.trim().startsWith("```")){let e=[];for(i++;i<t.length&&!t[i].trim().startsWith("```");)e.push(t[i]),i++;i++,n.push(l(`pre`,{class:`cf-md-pre`,children:l(`code`,{children:e.join(`
167
- `)})},r++));continue}if(e.trim()===``){i++;continue}let a=/^(#{1,6})\s+(.*)$/.exec(e);if(a){n.push(Zr(a[1].length,Yr(a[2]),r++)),i++;continue}if(/^\s*[-*•]\s+/.test(e)){let e=[];for(;i<t.length&&/^\s*[-*•]\s+/.test(t[i]);)e.push(l(`li`,{children:Yr(t[i].replace(/^\s*[-*•]\s+/,``))},e.length)),i++;n.push(l(`ul`,{class:`cf-md-list`,children:e},r++));continue}if(/^\s*\d+\.\s+/.test(e)){let e=[];for(;i<t.length&&/^\s*\d+\.\s+/.test(t[i]);)e.push(l(`li`,{children:Yr(t[i].replace(/^\s*\d+\.\s+/,``))},e.length)),i++;n.push(l(`ol`,{class:`cf-md-list`,children:e},r++));continue}let o=[e];for(i++;i<t.length&&t[i].trim()!==``&&!Xr.test(t[i]);)o.push(t[i]),i++;let s=o.join(` `);if(/:\s*$/.test(s)&&i<t.length&&/^(?:\s*[-*•]\s+|\s*\d+\.\s+)/.test(t[i])){let e=/^(.*[.!?])\s+([^.!?]{2,120}:)$/.exec(s);e&&n.push(l(`p`,{children:Yr(e[1])},r++)),n.push(l(`p`,{class:`cf-md-list-intro`,children:Yr(e?.[2]??s)},r++))}else n.push(l(`p`,{children:Yr(s)},r++))}return n},$r=e=>V(e),ei=()=>{let e=o(null);return r(()=>{let t=requestAnimationFrame(()=>e.current?.scrollIntoView?.({block:`end`}));return()=>cancelAnimationFrame(t)},[]),e},ti=e=>e.trim().split(/\s+/).slice(0,2).map(e=>e[0]?.toUpperCase()??``).join(``)||`🤖`,ni=e=>{let t=e?.avatarId?.trim().toLowerCase().replace(/[^a-z0-9-]/g,`-`);return t?` cf-avatar-preset--${t}`:``},ri={"support-guide":`SG`,"sales-host":`SH`,"calm-advisor":`CA`,"technical-guide":`TG`,"school-desk":`SD`,"front-office":`FO`},ii=e=>{let t=e?.avatarId?.trim().toLowerCase();return t&&ri[t]||(e?ti(e.agentName):`·`)},ai=({persona:e,small:t,hideWhenMissing:n})=>{let r=t?`cf-msg__avatar`:`cf-header__avatar`,i=e?.agentAvatarUrl?.trim();return i?l(`span`,{class:r,children:l(`img`,{src:i,alt:``})}):n?null:l(`span`,{class:`${r}${ni(e)}`,children:ii(e)})},oi=()=>{let e=cr(),[t,n]=s(0),i=[`Understanding your question`,`Checking approved information`,`Preparing your answer`];return r(()=>{let e=[window.setTimeout(()=>n(1),1800),window.setTimeout(()=>n(2),5e3)];return()=>e.forEach(e=>window.clearTimeout(e))},[]),u(`div`,{class:`cf-msg__bubble cf-typing`,"aria-label":e.assistantTyping,children:[l(`span`,{class:`cf-typing__label`,"aria-live":`polite`,children:i[t]}),l(`span`,{class:`cf-typing__dot`}),l(`span`,{class:`cf-typing__dot`}),l(`span`,{class:`cf-typing__dot`})]})},si=({msg:e})=>{if(!e.sources||e.sources.length===0)return null;let t=new Set,n=[];for(let r of e.sources){let i=(r.url||r.title||``).toLowerCase();!i||t.has(i)||r.url&&e.content.includes(r.url)||(t.add(i),n.push(r))}if(n.length===0)return null;let r=n.slice(0,3),i=n.length-r.length;return u(`div`,{class:`cf-sources`,children:[r.map((e,t)=>e.url?u(`a`,{class:`cf-source`,href:e.url,target:`_blank`,rel:`noopener noreferrer nofollow`,title:e.title||e.url,children:[l(br,{}),l(`span`,{children:e.title||e.url})]},t):u(`span`,{class:`cf-source`,title:e.title,children:[l(br,{}),l(`span`,{children:e.title})]},t)),i>0&&u(`span`,{class:`cf-source cf-source--more`,children:[`+`,i,` more`]})]})},ci=({replies:e,onPick:t})=>e&&e.length>0?l(`div`,{class:`cf-chips`,children:e.map((e,n)=>l(`button`,{type:`button`,class:`cf-chip`,onClick:()=>t(e),children:e},n))}):null,li=({persona:e,starters:t,onPick:n,onFocusComposer:r,speaking:i,voiceState:a=`idle`,replyPending:o=!1,pinned:s=!1,muted:d=!1,onToggleMute:f,onEndCall:p,onTalkNow:m,showTalkNow:h=!1,micLevel:g=0,theaterMode:_=!1,onToggleTheater:v,onMinimize:y,audioDevices:b=[],selectedAudioDeviceId:x=``,onSelectAudioDevice:S,connectingOnly:C=!1})=>{if(!e)return null;let w=!!(e.allowVoiceInput&&e.talkbackMode&&e.talkbackMode!==`text`);if(!(w||e.widgetModule===`assistant`))return null;let T=e.agentAvatarUrl?.trim()||``,E=e.assistantMediaUrl?.trim()||T,D=e.assistantMediaKind===`video`&&!!E,O=t.slice(0,3),k=a!==`idle`,A=a===`idle`?`Speak with ${e.agentName}`:`End voice chat`,j=s&&w&&!k&&!i,M=a===`connecting`||a===`processing`||k&&o,N=[`cf-assistant-card__stage`,`cf-assistant-card__stage--local`,k?`is-live`:``,M?`is-thinking`:``,Ui(a)&&!d?`is-listening`:``,i||a===`speaking`?`is-speaking`:``,d?`is-muted`:``].filter(Boolean).join(` `),P=Ui(a)&&!d?{"--cf-listen":String(Math.max(.18,Math.min(1,g*8)))}:void 0,F=M&&u(`span`,{class:`cf-call-ripple`,"aria-hidden":`true`,children:[l(`span`,{}),l(`span`,{}),l(`span`,{})]});if(C)return u(`div`,{class:`cf-assistant-card cf-assistant-card--connecting`,"aria-live":`polite`,children:[u(`div`,{class:`cf-assistant-card__connecting-avatar`,children:[T?l(`img`,{src:T,alt:``}):l(`span`,{class:`cf-assistant-card__connecting-face${ni(e)}`,children:ii(e)}),F]}),u(`div`,{class:`cf-assistant-card__connecting-copy`,children:[l(`span`,{class:`cf-assistant-card__connecting-eyebrow`,children:e.agentName}),l(`strong`,{children:`Connecting with the AI…`})]})]});let I=k&&p&&l(qi,{voiceState:a,muted:d,onToggleMute:f??(()=>{}),onEndCall:p,onTalkNow:m??(()=>{}),showTalkNow:h,micLevel:g,theaterMode:_,onToggleTheater:v??(()=>{}),onMinimize:y??(()=>{}),audioDevices:b,selectedAudioDeviceId:x,onSelectAudioDevice:S??(()=>{})});return j?l(`div`,{class:`cf-assistant-card cf-assistant-card--pinned cf-assistant-card--compact`,children:u(`button`,{type:`button`,class:`cf-assistant-card__compact-speak`,onClick:r,children:[T?l(`span`,{class:`cf-assistant-card__compact-avatar`,children:l(`img`,{src:T,alt:``})}):null,l(`span`,{class:`cf-assistant-card__compact-mic`,"aria-hidden":`true`,children:l(vr,{})}),l(`span`,{class:`cf-assistant-card__compact-label`,children:A})]})}):u(`div`,{class:`cf-assistant-card ${s?`cf-assistant-card--pinned`:``} ${i?`is-speaking`:``}`,children:[(E||w)&&u(`div`,{class:N,style:P,children:[u(`div`,{class:`cf-assistant-card__media ${E?`cf-assistant-card__media--uploaded`:`cf-assistant-card__media--generated`}${ni(e)}`,children:[D?l(`video`,{src:E,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):E?l(`img`,{src:E,alt:``}):l(`div`,{class:`cf-assistant-card__avatar-stage${ni(e)}`,children:u(`div`,{class:`cf-assistant-card__face`,children:[l(`span`,{class:`cf-assistant-card__initials`,children:ii(e)}),l(`span`,{class:`cf-assistant-card__eye cf-assistant-card__eye--left`}),l(`span`,{class:`cf-assistant-card__eye cf-assistant-card__eye--right`}),l(`span`,{class:`cf-assistant-card__mouth`})]})}),E&&!D&&l(`span`,{class:`cf-assistant-card__mouth cf-assistant-card__mouth--overlay`}),l(`span`,{class:`cf-avatar-aura cf-avatar-aura--one`,"aria-hidden":`true`}),l(`span`,{class:`cf-avatar-aura cf-avatar-aura--two`,"aria-hidden":`true`}),l(`span`,{class:`cf-avatar-listen-ring`,"aria-hidden":`true`}),u(`span`,{class:`cf-avatar-wave`,"aria-hidden":`true`,children:[l(`span`,{}),l(`span`,{}),l(`span`,{}),l(`span`,{})]})]}),F,k&&l(`span`,{class:`cf-call-status`,role:`status`,"aria-live":`polite`,children:Wi(a)}),w&&(I||u(`button`,{type:`button`,class:`cf-assistant-card__speak`,onClick:r,children:[l(vr,{}),A]}))]}),!s&&u(c,{children:[e.agentDescription?l(`p`,{class:`cf-assistant-card__copy`,children:e.agentDescription}):l(`p`,{class:`cf-assistant-card__copy`,children:e.greeting}),O.length>0&&l(`div`,{class:`cf-assistant-card__chips`,children:O.map(e=>l(`button`,{type:`button`,class:`cf-assistant-card__chip`,onClick:()=>n(e),children:e},e))}),e.disclaimerText||e.assistantPrivacyUrl?u(`p`,{class:`cf-assistant-card__privacy`,children:[e.disclaimerText||`This chat may be recorded for quality and support.`,e.assistantPrivacyUrl?u(c,{children:[` `,l(`a`,{href:e.assistantPrivacyUrl,target:`_blank`,rel:`noopener noreferrer nofollow`,children:`Privacy Policy`})]}):null]}):null]})]})},ui={calendar:xr,"calendar-clock":Dr,headset:wr,mail:Sr,message:Tr,newsletter:Or,phone:Cr,presentation:Er,lifebuoy:wr},di=e=>ui[e]??Sr,fi=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`}},pi={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`}},mi=(e,t,n={})=>Array.isArray(e)?e.filter(e=>e.readiness!==`unavailable`).map(e=>hi(e,n[e.id])):(t??[]).flatMap(e=>{let t=pi[e];if(!t)return[];let n=fi({...t,id:e}),r=Zn[n];return[{...t,id:e,presentation:n===`book-demo`||n===`schedule-callback`?`booking`:`form`,formTitle:r.title,submitLabel:r.submit,fields:r.fields,delivery:``,prompt:``,shortLabel:t.label.toLowerCase(),enabled:!0,readiness:`available`,legacyFallback:!0}]}).map(e=>hi(e,n[e.id])),hi=(e,t)=>{if(!t)return e;let n=t.fields??{};return{...e,...Object.fromEntries(Object.entries(t).filter(([e,t])=>e!==`fields`&&t!==void 0)),fields:e.fields.map(e=>({...e,...n[e.key]}))}},gi=(e,t)=>{let n=e.map(e=>e.label);return n.length===0?t.actionGetInTouch:n.length<=3?n.join(`, `):`${n.slice(0,2).join(`, `)} ${Q(t.actionMore,{count:String(n.length-2)})}`},_i=({label:e,required:t,value:n,onInput:i})=>{let c=a(()=>fr(n),[]),[d,f]=s(c.country.iso),[p,m]=s(c.national),[h,g]=s(!1),[_,v]=s(``),y=o(null),b=lr.find(e=>e.iso===d)??c.country,x=a(()=>{let e=_.trim().toLowerCase().replace(/^\+/,``);return e?lr.filter(t=>t.name.toLowerCase().includes(e)||t.iso.toLowerCase().includes(e)||t.dial.includes(e)):lr},[_]);r(()=>{if(!h)return;let e=e=>{y.current&&!e.composedPath().includes(y.current)&&g(!1)},t=e=>{e.key===`Escape`&&g(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[h]);let S=e=>{let t=lr.find(t=>t.iso===e)??b;f(t.iso),g(!1),v(``),i(pr(t,p))};return u(`div`,{class:`cf-phone`,role:`group`,"aria-label":`${e}${t?` *`:``}`,ref:y,children:[u(`span`,{class:`cf-phone__label`,children:[e,t?` *`:``]}),u(`div`,{class:`cf-phone__control`,children:[u(`button`,{type:`button`,class:`cf-phone__country`,"aria-label":`${b.name}, +${b.dial}. Choose country and calling code`,"aria-haspopup":`listbox`,"aria-expanded":h,onClick:()=>g(e=>!e),children:[l(`span`,{"aria-hidden":`true`,children:ur(b.iso)}),u(`span`,{class:`cf-phone__country-code`,children:[`+`,b.dial]}),l(gr,{})]}),l(`input`,{class:`cf-phone__input`,type:`tel`,inputMode:`numeric`,pattern:`[0-9]*`,autoComplete:`tel-national`,maxLength:15,placeholder:`8028509941`,value:p,"aria-label":e,onInput:e=>{let t=e.target,n=t.value.replace(/\D/g,``);t.value=n,m(n),i(pr(b,n))}})]}),h?u(`div`,{class:`cf-phone__menu`,children:[l(`input`,{class:`cf-phone__search`,type:`search`,placeholder:`Search country or code`,"aria-label":`Search countries`,value:_,autoFocus:!0,onInput:e=>v(e.target.value)}),l(`div`,{class:`cf-phone__options`,role:`listbox`,"aria-label":`Countries`,children:x.length>0?x.map(e=>u(`button`,{type:`button`,class:`cf-phone__option ${e.iso===b.iso?`is-selected`:``}`,role:`option`,"aria-selected":e.iso===b.iso,onClick:()=>S(e.iso),children:[l(`span`,{"aria-hidden":`true`,children:ur(e.iso)}),l(`span`,{class:`cf-phone__option-name`,children:e.name}),u(`span`,{class:`cf-phone__option-code`,children:[`+`,e.dial]})]},e.iso)):l(`div`,{class:`cf-phone__empty`,children:`No countries found`})})]}):null]})},vi=({field:e,value:t,onInput:n})=>{if(e.kind===`tel`)return l(_i,{label:e.label,required:e.required,value:t,onInput:n});let r=e.placeholder??e.label,i={class:`cf-form__input`,placeholder:e.required?`${r} *`:r,value:t,"aria-label":e.label,onInput:e=>n(e.target.value)};return e.kind===`textarea`?l(`textarea`,{rows:2,...i}):l(`input`,{type:e.kind,...i})},yi=({spec:e,visitor:t,onSubmit:n,onCancel:r})=>{let i=cr(),a=ei(),[o,c]=s(()=>{let n={};for(let r of e.fields)r.identity&&t[r.identity]&&(n[r.key]=t[r.identity]);return n}),[d,f]=s(`idle`),[p,m]=s(``),h=e=>!!(e.identity&&t[e.identity]?.trim()),g=e.fields.filter(e=>!h(e)),_=g.every(e=>!e.required||(o[e.key]?.trim()??``)!==``),v=t.email||t.name||``;return d===`done`?u(`div`,{class:`cf-form cf-form--done`,children:[l(Nr,{}),l(`span`,{children:p})]}):u(`div`,{class:`cf-form`,ref:a,children:[g.length===0&&v&&l(`div`,{class:`cf-form__as`,children:Q(i.actionAs,{identity:v})}),g.map(e=>l(vi,{field:e,value:o[e.key]??``,onInput:t=>c(n=>({...n,[e.key]:t}))},e.key)),d===`error`&&l(`div`,{class:`cf-form__err`,children:i.formError}),u(`div`,{class:`cf-form__actions`,children:[r&&l(`button`,{type:`button`,class:`cf-form__cancel`,onClick:r,children:i.cancel}),l(`button`,{type:`button`,class:`cf-form__submit`,disabled:!_||d===`submitting`,onClick:async()=>{if(!_||d===`submitting`)return;f(`submitting`);let t={},r={};for(let n of e.fields){let e=o[n.key]?.trim();e&&(t[n.key]=e,n.identity&&(r[n.identity]=e))}try{let e=await n(t,r);m($n(e.note||i.formThanks,e.caseReference,i)),f(`done`)}catch{f(`error`)}},children:d===`submitting`?i.sending:e.submit})]})]})},bi=e=>String(e).padStart(2,`0`),xi=()=>{let e=[];for(let t=9;t<=17;t++)e.push(`${bi(t)}:00`),e.push(`${bi(t)}:30`);return e},Si=e=>{let t=new Date;return t.setHours(0,0,0,0),Array.from({length:e},(e,n)=>{let r=new Date(t);return r.setDate(t.getDate()+n),r})},Ci=(e,t)=>{let[n,r]=t.split(`:`).map(Number),i=new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,r??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}`}},wi=(e,t)=>{let[n,r]=t.split(`:`).map(Number);return new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,r??0)},Ti=(e,t)=>{let n=wi(e,t);try{return new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}).format(n)}catch{return t}},Ei=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||``}catch{return``}},Di=(e,t)=>{try{let 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}},Oi=(e,t)=>{if(!t?.contentWindow||e.source!==t.contentWindow)return!1;try{let t=new URL(e.origin).hostname;if(t!==`calendly.com`&&!t.endsWith(`.calendly.com`))return!1}catch{return!1}return!!(e.data&&typeof e.data==`object`&&typeof e.data.event==`string`)},ki=({actionId:e,fields:t=Zn[`book-demo`].fields,visitor:n,onSubmit:i,onCancel:d,onDemoSlots:f,onConfirmHostedBooking:p,scheduler:m,title:h,submitLabel:g})=>{let _=e===`public_schedule_callback`,v=_?Zn[`schedule-callback`]:Zn[`book-demo`],y=h?.trim()||v.title,b=cr(),x=ei(),S=!!(!_&&m?.connected&&m.provider===`calendly`),C=S?b.bookingOpenScheduler:g?.trim()||v.submit,w=!!(m?.connected&&m.mode===`event`&&!S&&(m.availability===void 0||m.availability.calendarIds.length>0)),T=Math.min(60,Math.max(1,m?.availability?.bookingWindowDays??14)),E=a(()=>Si(T),[T]),[D,O]=s(null),[k,A]=s(w?`loading`:`request_only`),[j,M]=s(m?.availability?.slotDurationMinutes??30),[N,P]=s(Ei()||m?.availability?.timezone||``),F=a(()=>w?k!==`available`||D===null?[]:[...new Set([...D].map(e=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}))].sort():xi(),[D,k,w]),[I,L]=s(a(()=>{let e=Date.now();for(let t=0;t<E.length;t++)if(F.some(n=>wi(E[t],n).getTime()>e))return t;return 0},[E,F])),[R,ee]=s(null),[z,B]=s(n.name??``),[V,H]=s(n.email??``),[te,ne]=s(n.phone??``),[U,W]=s(``),[G,K]=s(`idle`),[q,J]=s(``),[Y,re]=s(!1),[ie,ae]=s(``),[oe,se]=s(`scheduler`),[ce,le]=s(null),[ue,de]=s(`idle`),[fe,pe]=s(``),[me,he]=s(``),[X,ge]=s(``),_e=o(null),ve=async(e,t,n)=>{de(`loading`);try{let r=await p?.(e,t,n),i=r?.meetingUrl||r?.eventLink||``,a=r?.rescheduleUrl||r?.cancelUrl||``;ae(i||a),se(i?`meeting`:`manage`),de(i||a?`idle`:`error`)}catch{de(`error`)}};r(()=>{if(!fe)return;let e=e=>{if(!Oi(e,_e.current)||e.data.event!==`calendly.event_scheduled`)return;let t=e.data.payload,n=t?.event?.uri?.trim()||``,r=t?.invitee?.uri?.trim()||``;X&&n&&r?(le({eventUri:n,inviteeUri:r}),ve(X,n,r)):de(`error`),pe(``),J($n(b.bookingScheduled,me,b)),K(`done`)};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[p,me,X,fe,b]),r(()=>{if(!w||k!==`available`||D===null)return;let e=E.findIndex(e=>F.some(t=>D.has(wi(e,t).getTime())));e>=0&&L(e)},[D,k,E,w,F]);let ye=!!(!_&&m?.connected&&(m.mode===`link`||m.provider===`calendly`)),be=async()=>{if(G===`submitting`||G===`scheduling`||!n.name?.trim()&&!z.trim()||!n.email?.trim()&&!V.trim())return;K(`submitting`);let e={};V.trim()&&(e.email=V.trim()),z.trim()&&(e.name=z.trim());try{let t=await i({...V.trim()?{visitorEmail:V.trim()}:{},...z.trim()?{visitorName:z.trim()}:{}},e),r=t.booking?.schedulingLink||m?.bookingLink||``;if(!r){K(`error`);return}ae(r),se(`scheduler`),he(t.caseReference||``),ge(t.inquiryId||``),pe(Di(r,{name:z.trim()||n.name,email:V.trim()||n.email})),K(`scheduling`)}catch{K(`error`)}},[xe,Se]=s(new Set),[Z,Ce]=s([]),[we,Te]=s(0),[Ee,De]=s(!1);r(()=>{if(!f)return;let e=!0,t=new Date,n=new Date;return n.setDate(n.getDate()+T+1),f(t.toISOString(),n.toISOString()).then(t=>{if(e)if(Se(new Set(t.taken.map(e=>Date.parse(e)).filter(e=>!Number.isNaN(e)))),Ce(t.busy.map(e=>[Date.parse(e.start),Date.parse(e.end)]).filter(([e,t])=>!Number.isNaN(e)&&!Number.isNaN(t))),M(t.slotDurationMinutes??30),P(Ei()||t.timezone||``),w){if(t.status!==`available`||!Array.isArray(t.available)){O(null),A(`unavailable`);return}O(new Set(t.available.map(e=>Date.parse(e)).filter(e=>!Number.isNaN(e)))),A(`available`)}else A(t.status??`request_only`)}).catch(()=>{!e||!w||(O(null),A(`unavailable`))}),()=>{e=!1}},[T,w,f,we]);let Oe=!!n.email?.trim(),ke=!!n.name?.trim(),Ae=!!n.phone?.trim(),je=te,Me=!!R&&(!w||k===`available`)&&(ke||z.trim()!==``)&&(_?Ae||mr(je):Oe||V.trim()!==``),Ne=(_?n.phone||n.name:n.email||n.name)||``,Pe=e=>t.find(t=>t.key===e),Fe=Pe(`visitorPhone`),Ie=Pe(`topic`),Le=e=>xe.has(wi(E[I],e).getTime()),Re=e=>wi(E[I],e).getTime()<=Date.now(),ze=j*60*1e3,Be=e=>{let t=wi(E[I],e).getTime(),n=t+ze;return Z.some(([e,r])=>t<r&&n>e)},Ve=e=>!w||D?.has(wi(E[I],e).getTime())===!0,He=async()=>{if(!Me||G===`submitting`||!R)return;K(`submitting`),De(!1);let e=wi(E[I],R),t=Ci(E[I],R),r={};z.trim()&&(r.name=z.trim()),_?je&&(r.phone=je):V.trim()&&(r.email=V.trim());try{let a=await i(_?{bestTime:t,slotAt:e.toISOString(),visitorTimezone:Ei()||`UTC`,...je?{visitorPhone:je}:{},...z.trim()?{visitorName:z.trim()}:{},...U.trim()?{topic:U.trim()}:{}}:{preferredAt:t,slotAt:e.toISOString(),visitorTimezone:Ei()||`UTC`,...V.trim()?{visitorEmail:V.trim()}:{},...z.trim()?{visitorName:z.trim()}:{}},r);if(!_&&a.booking?.mode===`link`&&a.booking.schedulingLink?.trim()){let e=a.booking.schedulingLink.trim();ae(e),he(a.caseReference||``),ge(a.inquiryId||``),pe(Di(e,{name:z.trim()||n.name,email:V.trim()||n.email})),K(`scheduling`);return}a.booking?.confirmed?(J($n(a.note||Q(_?b.bookingCallbackConfirmed:b.bookingConfirmed,{when:t}),a.caseReference,b)),ae(a.booking.meetingUrl||a.booking.rescheduleUrl||a.booking.cancelUrl||a.booking.eventLink||``),se(a.booking.meetingUrl||a.booking.eventLink?`meeting`:`manage`)):a.booking?.verificationPending?(re(!0),J($n(a.note||Q(b.bookingVerificationPending,{when:t}),a.caseReference,b))):J($n(a.note||Q(_?b.bookingCallbackRequested:b.bookingRequested,{when:t}),a.caseReference,b)),K(`done`)}catch(t){t?.status===409?(Se(t=>new Set(t).add(e.getTime())),ee(null),De(!0),Te(e=>e+1),K(`idle`)):K(`error`)}},Ue=()=>{pe(``),K(`idle`),d?.()};return G===`scheduling`&&fe?u(`div`,{class:`cf-scheduler-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":y,children:[u(`header`,{class:`cf-scheduler-overlay__head`,children:[l(`button`,{type:`button`,class:`cf-scheduler-overlay__back`,onClick:Ue,children:b.bookingBackToChat}),l(`strong`,{children:y}),u(`div`,{class:`cf-scheduler-overlay__tools`,children:[u(`a`,{href:ie,target:`_blank`,rel:`noopener noreferrer`,children:[b.bookingOpenNewTab,` `,l(br,{})]}),l(`button`,{type:`button`,"aria-label":b.bookingCloseScheduler,onClick:Ue,children:l(Ar,{})})]})]}),u(`div`,{class:`cf-scheduler-overlay__body`,children:[l(`div`,{class:`cf-scheduler-overlay__loading`,children:b.bookingLoadingScheduler}),l(`iframe`,{ref:_e,class:`cf-scheduler-overlay__frame`,src:fe,title:y,allow:`camera; microphone; fullscreen; payment`})]})]}):G===`done`?u(`div`,{class:`cf-form cf-form--done${Y?` cf-form--pending`:``}`,role:Y?`alert`:`status`,children:[!Y&&l(Nr,{}),l(`span`,{children:q}),ue===`loading`&&l(`span`,{role:`status`,children:b.bookingCheckingDetails}),ue===`error`&&u(`div`,{class:`cf-booking__receipt-error`,role:`alert`,children:[l(`span`,{children:b.bookingDetailsUnavailable}),ce&&X&&p&&l(`button`,{type:`button`,class:`cf-booking__back`,onClick:()=>void ve(X,ce.eventUri,ce.inviteeUri),children:b.bookingRetryDetails})]}),ie&&u(`a`,{class:`cf-booking__link`,href:ie,target:`_blank`,rel:`noopener noreferrer`,children:[oe===`meeting`?b.bookingMeetingLink:oe===`manage`?b.bookingManageLink:b.bookingOpenScheduler,` `,l(br,{}),l(`span`,{class:`cf-booking__url`,children:ie})]}),d&&l(`button`,{type:`button`,class:`cf-booking__back`,onClick:d,children:b.bookingBackToChat})]}):ye?u(`div`,{class:`cf-form cf-booking`,ref:x,children:[l(`div`,{class:`cf-booking__hint`,children:Q(b.bookingViaProvider,{provider:m?.label??b.bookingSchedulerFallback})}),Oe?Ne?l(`div`,{class:`cf-form__as`,children:Q(b.actionAs,{identity:Ne})}):null:u(c,{children:[!n.name?.trim()&&l(`input`,{class:`cf-form__input`,type:`text`,placeholder:`${b.handoffName} *`,value:z,"aria-label":b.handoffName,onInput:e=>B(e.target.value)}),l(`input`,{class:`cf-form__input`,type:`email`,placeholder:`${b.handoffEmail} *`,value:V,"aria-label":b.handoffEmail,onInput:e=>H(e.target.value)})]}),G===`error`&&l(`div`,{class:`cf-form__err`,children:b.formError}),u(`div`,{class:`cf-form__actions`,children:[d&&l(`button`,{type:`button`,class:`cf-form__cancel`,onClick:d,children:b.cancel}),l(`button`,{type:`button`,class:`cf-form__submit`,disabled:G===`submitting`||!n.name?.trim()&&z.trim()===``||!Oe&&V.trim()===``,onClick:be,children:G===`submitting`?b.sending:b.bookingOpenScheduler})]})]}):u(`div`,{class:`cf-form cf-booking`,ref:x,children:[u(`div`,{class:`cf-booking__hint`,children:[b.bookingPickTime,` ·`,` `,l(`span`,{class:`cf-booking__dur`,children:Q(_?b.bookingCallbackDuration:b.bookingDuration,{count:String(j)})}),N?` · ${Q(b.bookingTimezone,{timezone:N})}`:``]}),w&&k===`loading`?l(`div`,{class:`cf-booking__state`,role:`status`,children:b.bookingCheckingAvailability}):null,w&&k===`unavailable`?l(`div`,{class:`cf-form__err`,role:`alert`,children:b.bookingAvailabilityUnavailable}):null,w&&k===`available`&&F.length===0?l(`div`,{class:`cf-booking__state`,role:`status`,children:b.bookingNoSlots}):null,F.length>0?l(`div`,{class:`cf-booking__dates`,role:`tablist`,"aria-label":b.bookingPickDay,children:E.map((e,t)=>u(`button`,{type:`button`,role:`tab`,"aria-selected":t===I,disabled:w&&k===`available`&&!F.some(t=>D?.has(wi(e,t).getTime())),class:`cf-booking__date ${t===I?`is-selected`:``}`,onClick:()=>{L(t),ee(null)},children:[l(`span`,{class:`cf-booking__dow`,children:e.toLocaleDateString(void 0,{weekday:`short`})}),l(`span`,{class:`cf-booking__dom`,children:e.getDate()})]},t))}):null,F.length>0?l(`div`,{class:`cf-booking__slots`,role:`listbox`,"aria-label":b.bookingPickTimeLabel,children:F.map(e=>{let t=Re(e),n=Be(e),r=Le(e),i=Ve(e),a=r||t||n||!i;return l(`button`,{type:`button`,role:`option`,"aria-selected":R===e,disabled:a,title:t?b.bookingEarlierToday:n?b.bookingCalendarBusy:r?b.bookingAlreadyBooked:i?void 0:b.bookingNotOffered,class:`cf-booking__slot ${R===e?`is-selected`:``} ${a?`is-taken`:``}`,onClick:()=>ee(e),children:Ti(E[I],e)},e)})}):null,Ee&&l(`div`,{class:`cf-form__err`,children:b.bookingSlotTaken}),Ne?l(`div`,{class:`cf-form__as`,children:Q(b.actionAs,{identity:Ne})}):null,!ke&&l(`input`,{class:`cf-form__input`,type:`text`,placeholder:`${b.handoffName} *`,value:z,"aria-label":b.handoffName,onInput:e=>B(e.target.value)}),_&&!Ae&&l(_i,{label:Fe?.label??`Phone number`,required:!0,value:te,onInput:ne}),_&&Ie?l(`input`,{class:`cf-form__input`,type:`text`,placeholder:Ie.placeholder||Ie.label,value:U,"aria-label":Ie.label,onInput:e=>W(e.target.value)}):null,!_&&!Oe&&l(c,{children:l(`input`,{class:`cf-form__input`,type:`email`,placeholder:`${b.handoffEmail} *`,value:V,"aria-label":b.handoffEmail,onInput:e=>H(e.target.value)})}),G===`error`&&l(`div`,{class:`cf-form__err`,children:b.formError}),u(`div`,{class:`cf-form__actions`,children:[d&&l(`button`,{type:`button`,class:`cf-form__cancel`,onClick:d,children:b.cancel}),l(`button`,{type:`button`,class:`cf-form__submit`,disabled:!Me||G===`submitting`,onClick:He,children:G===`submitting`?b.sending:C})]})]})},Ai=({actions:e,descriptors:n,visitor:c,onSubmitForm:d,onDemoSlots:f,onConfirmHostedBooking:p,scheduler:m,exclude:h=[],openAction:g,translations:_={},onClose:v})=>{let y=cr(),[b,x]=s(null),[S,C]=s(!1),w=o(null),T=o(null),E=o(!1),D=a(()=>`cf-actions-${Math.random().toString(36).slice(2,9)}`,[]),O=a(()=>mi(n,e,_).filter(e=>!h.includes(e.id)&&!h.includes(e.endpoint)),[n,e,h,_]);r(()=>{g&&O.some(e=>e.id===g)&&(x(g),C(!0))},[g,O]);let k=b?O.find(e=>e.id===b):void 0,A=t(()=>{if(v){v();return}E.current=!0,x(null),C(!1)},[v]),j=t(()=>{v?v():x(null)},[v]);i(()=>{S||!E.current||(E.current=!1,w.current?.focus())},[S]);let M=o({drawerOpen:S,activeId:b});if(M.current={drawerOpen:S,activeId:b},r(()=>{let e=e=>{if(e.key!==`Escape`)return;let{drawerOpen:t,activeId:n}=M.current;!t&&!n||(e.stopPropagation(),n?j():A())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[j,A]),r(()=>{S&&T.current?.querySelector(`button, input, textarea, select`)?.focus()},[S,b]),O.length===0)return null;let N=S?k?u(`div`,{ref:T,id:D,class:`cf-action-drawer is-open`,role:`dialog`,"aria-modal":`false`,"aria-label":k.formTitle||k.label,children:[l(`div`,{class:`cf-action-drawer__handle`,"aria-hidden":`true`}),u(`div`,{class:`cf-action-drawer__head`,children:[u(`div`,{children:[l(`strong`,{children:k.formTitle||k.label}),k.legacyFallback?l(`small`,{class:`cf-action-test-mode`,children:y.actionTestMode}):null]}),l(`button`,{type:`button`,class:`cf-action-drawer__close`,"aria-label":y.actionClose,onClick:j,children:l(Ar,{})})]}),k.readiness===`degraded`&&k.readinessNote?l(`p`,{class:`cf-action-drawer__note cf-action-drawer__note--warn`,role:`status`,children:k.readinessNote}):null,k.presentation===`booking`||k.endpoint===`book-demo`||k.endpoint===`schedule-callback`?l(ki,{actionId:k.id,fields:k.fields,visitor:c,title:k.formTitle,submitLabel:k.submitLabel,onCancel:j,onSubmit:(e,t)=>d(k.id,e,t,k.endpoint),onDemoSlots:f,onConfirmHostedBooking:p,scheduler:m}):l(yi,{spec:{title:k.formTitle||k.label,submit:k.submitLabel,fields:k.endpoint===`request-callback`?k.fields.filter(e=>e.key!==`bestTime`):k.fields},visitor:c,onCancel:j,onSubmit:(e,t)=>d(k.id,e,t,k.endpoint)})]}):u(`div`,{ref:T,id:D,class:`cf-action-drawer cf-action-drawer--menu`,role:`dialog`,"aria-modal":`false`,"aria-label":y.actionChoose,children:[l(`div`,{class:`cf-action-drawer__handle`,"aria-hidden":`true`}),u(`div`,{class:`cf-action-drawer__head`,children:[u(`div`,{children:[l(`span`,{class:`cf-action-drawer__eyebrow`,children:y.actionNeedHelp}),l(`strong`,{children:y.actionChoose})]}),l(`button`,{type:`button`,class:`cf-action-drawer__close`,"aria-label":y.actionClose,onClick:A,children:l(Ar,{})})]}),l(`div`,{class:`cf-action-drawer__grid`,children:O.map(e=>{let t=di(e.icon);return u(`button`,{type:`button`,class:`cf-action-card`,onClick:()=>x(e.id),children:[l(`span`,{class:`cf-action-card__icon cf-action-card__icon--${e.category}`,children:l(t,{})}),u(`span`,{class:`cf-action-card__copy`,children:[l(`strong`,{children:e.label}),e.legacyFallback?l(`small`,{class:`cf-action-test-mode`,children:y.actionTestMode}):null,l(`small`,{children:e.description}),e.readiness===`degraded`&&e.readinessNote?l(`small`,{class:`cf-action-card__warn`,children:e.readinessNote}):null]}),l(gr,{})]},e.id)})}),l(`p`,{class:`cf-action-drawer__note`,children:y.actionFooter})]}):null;return u(`div`,{class:`cf-action-shell`,children:[u(`button`,{ref:w,type:`button`,class:`cf-action-trigger`,hidden:S,"aria-expanded":S,"aria-controls":D,onClick:()=>S?A():C(!0),children:[l(`span`,{class:`cf-action-trigger__icon`,children:l(Sr,{})}),u(`span`,{class:`cf-action-trigger__copy`,children:[l(`strong`,{children:y.actionContactOptions}),l(`small`,{children:gi(O,y)})]}),l(gr,{})]}),N]})},ji=({hasEmail:e,visitor:t,question:n,onSubmitForm:r})=>{let i=cr(),[a,o]=s(!1),[c,d]=s(!1),[f,p]=s(t.name??``),[m,h]=s(t.email??``);if(e)return u(`div`,{class:`cf-handoff cf-handoff--done`,children:[l(Nr,{}),l(`span`,{children:`We’ve alerted the team. If someone is available, they can continue here.`})]});if(a){let e=t.email||m;return u(`div`,{class:`cf-handoff cf-handoff--done`,children:[l(Nr,{}),l(`span`,{children:Q(i.handoffShared,{email:e})})]})}let g=async()=>{if(!(!m.trim()||c)){d(!0);try{await r(`inquiry`,{visitorEmail:m.trim(),...f.trim()?{visitorName:f.trim()}:{},message:n||`I had a question the assistant couldn’t answer.`,subject:`Help request from chat`},{email:m.trim(),name:f.trim()||void 0}),o(!0)}catch{d(!1)}}};return u(`div`,{class:`cf-handoff`,children:[l(`div`,{class:`cf-handoff__title`,children:i.handoffTitle}),l(`input`,{class:`cf-form__input`,type:`text`,placeholder:i.handoffName,value:f,"aria-label":i.handoffName,onInput:e=>p(e.target.value)}),l(`input`,{class:`cf-form__input`,type:`email`,placeholder:`${i.handoffEmail} *`,value:m,"aria-label":i.handoffEmail,onInput:e=>h(e.target.value)}),l(`button`,{type:`button`,class:`cf-form__submit`,disabled:!m.trim()||c,onClick:g,children:c?i.sending:i.handoffNotify})]})},Mi=({text:e})=>{let t=cr(),[n,r]=s(!1);return u(`button`,{type:`button`,class:`cf-tool`,onClick:async()=>{try{await navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),1500)}catch{}},"aria-label":t.copy,children:[l(n?Nr:Pr,{}),n?t.copied:t.copy]})},Ni=({items:e,onPick:t})=>e.length===0?null:l(`div`,{class:`cf-starters`,children:e.map((e,n)=>l(`button`,{type:`button`,class:`cf-starter`,onClick:()=>t(e),children:e},n))}),Pi=({items:e})=>{let t=e.filter(e=>e.label.trim()&&e.url.trim()).slice(0,4);return t.length===0?null:l(`div`,{class:`cf-featured-links`,children:t.map((e,t)=>u(`a`,{class:`cf-featured-link`,href:e.url,target:`_blank`,rel:`noopener noreferrer nofollow`,title:e.label,children:[l(br,{}),l(`span`,{children:e.label})]},`${e.url}-${t}`))})},Fi=({msg:e,onRate:t})=>{let n=cr(),[r,i]=s(!1),[a,o]=s(``),c=e.feedback,d=()=>{t(e.id,`up`),i(!1)},f=()=>{t(e.id,`down`),i(!0)},p=()=>{t(e.id,`down`,a.trim()),i(!1)};return u(`div`,{class:`cf-feedback`,children:[u(`div`,{class:`cf-feedback__row`,children:[l(`span`,{class:`cf-feedback__label`,children:n.feedbackAnswerPrompt}),l(`button`,{type:`button`,class:`cf-feedback__btn ${c===`up`?`is-active`:``}`,"aria-label":`${n.feedbackHelpful} answer`,"aria-pressed":c===`up`,onClick:d,children:l(Br,{})}),l(`button`,{type:`button`,class:`cf-feedback__btn ${c===`down`?`is-active`:``}`,"aria-label":`${n.feedbackNotHelpful} answer`,"aria-pressed":c===`down`,onClick:f,children:l(Vr,{})}),c&&!r&&l(`span`,{class:`cf-feedback__thanks`,children:n.feedbackThanks})]}),r&&c===`down`&&u(`div`,{class:`cf-feedback__comment`,children:[l(`textarea`,{class:`cf-feedback__input`,rows:2,placeholder:n.feedbackCommentPlaceholder,value:a,onInput:e=>o(e.target.value)}),l(`button`,{type:`button`,class:`cf-feedback__send`,onClick:p,children:n.feedbackSend})]})]})},Ii=e=>e.attachments??(e.attachmentName?[{id:e.attachmentId,name:e.attachmentName}]:[]),Li=({msg:e,persona:t,isLast:n,visitor:r,hasEmail:i,lastQuestion:a,showActions:o,onPickReply:s,onSubmitForm:d,onDemoSlots:f,onConfirmHostedBooking:p,onRetry:m,ratable:h,onRate:g,onExpandVisualization:_,onExpandExplanation:v,onReconnect:y,onOpenAttachment:b,onExplanationFeedback:x,explanationTransport:S,onOpenAnalyticsSource:C})=>{let w=cr(),T=ar(),E=e.role===`user`,D=e.liveEventType??``,O=e.content.trim().toLowerCase(),k=D===`handoff_queued`||D===`agent_joined`||D===`agent_left`||D===`ai_handback`||D===`conversation_ended`||O.includes(`joined the chat`)||O.includes(`left the chat`)||O.includes(`support agents will be with you`),A=e.role===`system`||k,j=e.requestedContactFields?.includes(`email`)===!0,M=n&&!E&&!A&&!e.reconnectOffer&&!!(e.handoffOffered||j),N=M&&!i?[`inquiry`]:[],P=!e.pending&&!e.streaming,F=[...e.artifacts??[],...e.visualization&&!(e.artifacts??[]).some(e=>e.type===`visualization`)?[{type:`visualization`,visualization:e.visualization}]:[]];return A?l(`div`,{class:`cf-msg cf-msg--system`,children:u(`div`,{class:`cf-system-event`,children:[l(`div`,{class:`cf-system-event__mark`,"aria-hidden":`true`}),l(`div`,{class:`cf-system-event__text`,children:e.content}),y&&l(`button`,{type:`button`,class:`cf-system-event__action`,onClick:y,children:w.reconnectSupport}),e.createdAt&&l(`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`})})]})}):u(`div`,{class:`cf-msg cf-msg--${E?`user`:`agent`}`,children:[!E&&l(ai,{persona:t,small:!0}),u(`div`,{class:`cf-msg__col`,children:[e.pending&&e.content===``?l(oi,{}):e.imageUrl?u(`div`,{class:`cf-msg__bubble cf-msg__bubble--media`,children:[l(`img`,{class:`cf-msg__media`,src:e.imageUrl,alt:`GIF`}),e.content&&l(`span`,{class:`cf-msg__caption`,children:e.content})]}):u(`div`,{class:`cf-msg__bubble`,children:[E?e.content:Qr(e.content),e.streaming&&l(`span`,{class:`cf-caret`,"aria-hidden":`true`})]}),E?null:F.map((t,n)=>t.type===`visualization`&&t.visualization?l(zi,{visualization:t.visualization,onFollowUp:s,onExpand:_?()=>_(e.id):void 0,expandControlId:e.id},`visualization-${n}`):t.type===`image`&&(t.data||t.uri?.startsWith(`https://`))&&[`image/png`,`image/jpeg`,`image/webp`].includes(t.mimeType??``)?u(`figure`,{class:`cf-artifact`,children:[t.title?l(`figcaption`,{children:t.title}):null,l(`img`,{src:t.uri||`data:${t.mimeType};base64,${t.data}`,alt:t.altText||t.caption||t.title||`Tool result`}),t.caption&&t.caption!==t.title?l(`p`,{children:t.caption}):null]},`image-${n}`):t.type===`video`&&t.uri?.startsWith(`https://`)&&(t.mimeType??``).startsWith(`video/`)?u(`figure`,{class:`cf-artifact`,children:[t.title?l(`figcaption`,{children:t.title}):null,l(`video`,{controls:!0,preload:`metadata`,playsInline:!0,src:t.uri}),t.caption&&t.caption!==t.title?l(`p`,{children:t.caption}):null]},`video-${n}`):t.type===`resource_link`&&t.uri?.startsWith(`https://`)?u(`a`,{class:`cf-artifact-link`,href:t.uri,target:`_blank`,rel:`noopener noreferrer nofollow`,children:[l(`strong`,{children:t.title||t.name||`Open result`}),t.caption?l(`span`,{children:t.caption}):null]},`link-${n}`):null),!E&&e.resultExpired&&!e.visualization?u(`p`,{class:`cf-analytics-expired`,"data-testid":`analytics-result-expired`,children:[e.resultExpired.title?u(`strong`,{children:[e.resultExpired.title,`. `]}):null,w.resultExpired]}):null,!E&&e.visualization&&$r(e.visualization)?l(`div`,{class:`cf-analytics-explanation`,"data-testid":`inline-analytics-explanation`,"data-explanation-message":e.id,children:l(qn,{classPrefix:`cf`,copy:w.analytics?.explanation,locale:T,onExpand:v?()=>v(e.id):void 0,explanation:$r(e.visualization),onFollowUp:s,onFeedback:x,aiTransport:S,canOpenSource:e=>!!C&&(e.kind===`liveboard_tile`||e.kind===`insight`),onOpenSource:C?t=>{(t.kind===`liveboard_tile`||t.kind===`insight`)&&C({kind:t.kind,id:t.id,...e.visualization?.appliedFilters?.length?{appliedFilters:e.visualization.appliedFilters}:{}})}:void 0,maxFollowUps:3,showLead:(()=>{let t=$r(e.visualization).headline?.trim().toLocaleLowerCase();return!t||!e.content.toLocaleLowerCase().includes(t)})()})}):null,E&&Ii(e).length>0&&l(`div`,{class:`cf-attach-row cf-attach-row--sent`,children:Ii(e).map((t,n)=>b?u(`button`,{type:`button`,class:`cf-attach-chip cf-attach-chip--open`,title:Q(w.attachOpen,{name:t.name}),"aria-label":Q(w.attachOpen,{name:t.name}),onClick:()=>b(e,t,n),children:[l(Lr,{}),l(`span`,{children:t.name})]},`${t.id??t.name}-${n}`):u(`div`,{class:`cf-attach-chip`,title:t.name,children:[l(Lr,{}),l(`span`,{children:t.name})]},`${t.id??t.name}-${n}`))}),!E&&u(c,{children:[P&&(e.error||e.content)&&u(`div`,{class:`cf-msg__actions`,children:[l(`div`,{class:`cf-msg__tools`,children:e.error?u(`button`,{type:`button`,class:`cf-tool`,onClick:()=>m(e.id,e.retryText??``),children:[l(Fr,{}),w.retry]}):l(Mi,{text:e.content})}),h&&!e.error&&e.content?l(Fi,{msg:e,onRate:g}):null]}),l(si,{msg:e}),n&&l(ci,{replies:e.suggestedReplies,onPick:s}),M&&l(ji,{hasEmail:i,visitor:r,question:a,onSubmitForm:d}),o&&l(Ai,{actions:e.availableActions,descriptors:e.actions,openAction:e.selectedAction,visitor:r,onSubmitForm:d,onDemoSlots:f,onConfirmHostedBooking:p,scheduler:t?.scheduler,exclude:N})]})]})]})},Ri=({visualization:e,onClose:t,onFollowUp:n,onFeedback:r,transport:i,onOpenSource:a})=>{let o=cr(),s=ar(),c=$r(e);return c?l(`div`,{class:`cf-analytics-explanation is-expanded`,"data-testid":`expanded-analytics-explanation`,children:l(qn,{classPrefix:`cf`,explanation:c,copy:o.analytics?.explanation,locale:s,expanded:!0,onCollapse:t,onFollowUp:n,onFeedback:r,aiTransport:i,canOpenSource:e=>!!a&&(e.kind===`liveboard_tile`||e.kind===`insight`),onOpenSource:a?t=>{(t.kind===`liveboard_tile`||t.kind===`insight`)&&a({kind:t.kind,id:t.id,...e.appliedFilters?.length?{appliedFilters:e.appliedFilters}:{}})}:void 0})}):null},zi=({visualization:e,expanded:t=!1,onExpand:n,onClose:r,onFollowUp:i,expandControlId:a})=>{let o=cr(),s=ar();return l(vn,{visualization:e,classPrefix:`cf`,labels:o.analytics,locale:s,expanded:t,onExpand:n,onClose:r,onFollowUp:i,expandControlId:a})},Bi=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result).split(`,`)[1]??``),r.onerror=n,r.readAsDataURL(e)}),Vi=({onPick:e})=>l(`div`,{class:`cf-picker cf-emoji`,children:Xn.map(t=>u(`div`,{class:`cf-emoji__group`,children:[l(`div`,{class:`cf-emoji__label`,children:t.name}),l(`div`,{class:`cf-emoji__grid`,children:t.emojis.map((t,n)=>l(`button`,{type:`button`,class:`cf-emoji__btn`,onClick:()=>e(t),"aria-label":t,children:t},n))})]},t.name))}),Hi=({onSearch:e,onPick:t})=>{let n=cr(),[i,a]=s(``),[o,c]=s([]),[d,f]=s(!0);return r(()=>{let t=!0;f(!0);let n=setTimeout(()=>{e(i).then(e=>t&&(c(e),f(!1))).catch(()=>t&&(c([]),f(!1)))},300);return()=>{t=!1,clearTimeout(n)}},[i,e]),u(`div`,{class:`cf-picker cf-gif`,children:[l(`input`,{class:`cf-gif__search`,placeholder:n.searchGifs,value:i,"aria-label":n.searchGifs,onInput:e=>a(e.target.value)}),l(`div`,{class:`cf-gif__grid`,children:d?l(`div`,{class:`cf-gif__hint`,children:n.searchingGifs}):o.length===0?l(`div`,{class:`cf-gif__hint`,children:n.noGifs}):o.map(e=>l(`button`,{type:`button`,class:`cf-gif__item`,onClick:()=>t(e.url),"aria-label":e.alt,children:l(`img`,{src:e.preview,alt:e.alt,loading:`lazy`})},e.id))}),l(`div`,{class:`cf-gif__powered`,children:`via Tenor`})]})},Ui=e=>e===`listening`||e===`hearing`,Wi=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``}},Gi=({muted:e,listening:t,micLevel:n,onToggleMute:r})=>l(`button`,{type:`button`,class:`cf-call-btn ${e?`is-muted`:``} ${t?`is-listening`:``} ${t&&n>=.004?`is-hot`:``}`,"aria-label":e?`Unmute microphone`:`Mute microphone`,"aria-pressed":e,onClick:r,style:t?{"--cf-wave":String(Math.max(.2,Math.min(1,n*6)))}:void 0,children:l(e?yr:vr,{})}),Ki=({audioDevices:e,selectedAudioDeviceId:t,onSelectAudioDevice:n})=>{let[a,c]=s(!1),[d,f]=s(null),p=o(null);r(()=>{if(!a)return;let e=e=>{p.current&&!e.composedPath().includes(p.current)&&c(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[a]),i(()=>{if(!a){f(null);return}let e=p.current;if(!e)return;let t=new DOMRect(0,0,window.innerWidth,window.innerHeight);for(let n=e.parentElement;n;n=n.parentElement){let e=getComputedStyle(n);if(e.overflow!==`visible`||e.overflowY!==`visible`){t=n.getBoundingClientRect();break}}let n=e.getBoundingClientRect(),r=t.bottom-n.bottom-16,i=n.top-t.top-16,o=i>r;f({up:o,maxHeight:Math.max(72,Math.floor(o?i:r))})},[a]);let m=[{deviceId:``,label:`Default microphone`},...e];return u(`div`,{class:`cf-call-more`,ref:p,children:[l(`button`,{type:`button`,class:`cf-call-btn cf-call-btn--microphones`,"aria-label":`Choose microphone`,"aria-expanded":a,onClick:()=>c(e=>!e),children:l(gr,{})}),a&&u(`div`,{class:`cf-call-menu${d?.up?` cf-call-menu--up`:``}`,role:`menu`,style:d?{maxHeight:`${d.maxHeight}px`}:{visibility:`hidden`},children:[l(`div`,{class:`cf-call-menu__label`,children:`Microphone`}),m.map(e=>u(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":e.deviceId===t,class:`cf-call-menu__item ${e.deviceId===t?`is-active`:``}`,onClick:()=>{n(e.deviceId),c(!1)},children:[e.deviceId===t?l(Nr,{}):l(`span`,{class:`cf-call-menu__spacer`}),l(`span`,{children:e.label})]},e.deviceId))]})]})},qi=({voiceState:e,muted:t,onToggleMute:n,onEndCall:r,onTalkNow:i,showTalkNow:a,micLevel:o,theaterMode:s,onToggleTheater:c,onMinimize:d,audioDevices:f,selectedAudioDeviceId:p,onSelectAudioDevice:m})=>u(`div`,{class:`cf-call-controls`,children:[l(Gi,{muted:t,listening:Ui(e)&&!t,micLevel:o,onToggleMute:n}),l(Ki,{audioDevices:f,selectedAudioDeviceId:p,onSelectAudioDevice:m}),a&&l(`button`,{type:`button`,class:`cf-call-btn cf-call-btn--talk`,"aria-label":`Talk now`,onClick:i,children:l(vr,{})}),l(`button`,{type:`button`,class:`cf-call-btn`,"aria-label":s?`Exit expanded view`:`Expand view`,"aria-pressed":s,onClick:c,children:l(s?Ur:Hr,{})}),l(`button`,{type:`button`,class:`cf-call-btn`,"aria-label":`Minimize voice chat`,onClick:d,children:l(Wr,{})}),l(`button`,{type:`button`,class:`cf-call-btn cf-call-btn--end`,"aria-label":`End voice chat`,onClick:r,children:l(Rr,{})})]}),Ji=({persona:e,voiceState:t,muted:n,onToggleMute:r,onEndCall:i,micLevel:a,onExpand:o})=>{let s=e=>e.stopPropagation(),c=e?.assistantMediaUrl?.trim()||e?.agentAvatarUrl?.trim()||``,d=e?.assistantMediaKind===`video`&&!!c,f=e?.agentName||`Assistant`;return u(`div`,{class:[`cf-floating-call-card`,Ui(t)&&!n?`is-listening`:``,t===`speaking`?`is-speaking`:``,t===`processing`||t===`connecting`?`is-thinking`:``,n?`is-muted`:``].filter(Boolean).join(` `),style:Ui(t)&&!n?{"--cf-listen":String(Math.max(.18,Math.min(1,a*8)))}:void 0,role:`button`,tabIndex:0,"aria-label":`Reopen voice chat with ${f}`,onClick:o,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())},children:[l(`div`,{class:`cf-floating-call-card__media`,"aria-hidden":`true`,children:c?d?l(`video`,{src:c,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):l(`img`,{src:c,alt:``}):u(`div`,{class:`cf-floating-call-card__avatar${ni(e)}`,children:[l(`span`,{children:ii(e)}),l(`span`,{class:`cf-floating-call-card__eye cf-floating-call-card__eye--left`}),l(`span`,{class:`cf-floating-call-card__eye cf-floating-call-card__eye--right`}),l(`span`,{class:`cf-floating-call-card__mouth`})]})}),l(`div`,{class:`cf-floating-call-card__shade`,"aria-hidden":`true`}),l(`span`,{class:`cf-floating-call-card__status`,role:`status`,"aria-live":`polite`,children:Wi(t)}),u(`div`,{class:`cf-floating-call-card__controls`,onClick:s,onKeyDown:s,role:`presentation`,children:[l(Gi,{muted:n,listening:Ui(t)&&!n,micLevel:a,onToggleMute:r}),l(`button`,{type:`button`,class:`cf-call-btn cf-call-btn--restore`,"aria-label":`Restore voice chat`,onClick:e=>{s(e),o()},children:l(Gr,{})}),l(`button`,{type:`button`,class:`cf-call-btn cf-call-btn--end`,"aria-label":`End voice chat`,onClick:e=>{s(e),i()},children:l(Rr,{})})]})]})},Yi=(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 Wi(e)}},Xi=({draftStore:e,onSend:t,onSendGif:n,onTyping:i,disabled:a,allowVoice:f,onTranscribe:p,gifEnabled:m,onSearchGifs:h,allowAttach:g,analyzeAttachments:_=!0,onUpload:v,voiceStartSignal:y=0,onVoiceStateChange:b,onPreviewAttachment:x})=>{let S=cr(),[C,w]=s(()=>e.value),T=t=>{let n=typeof t==`function`?t(C):t;e.value=n,w(n)},[E,D]=s(!1),[O,k]=s(!1),[A,j]=s(`idle`),[M,N]=s(`none`),[P,F]=s([]),I=o([]);I.current=P;let L=o(0),[R,ee]=s(!1),[z,B]=s(!1),[V,H]=s(``),te=o(null),ne=o(null),U=o(null),W=o(0),G=o(null),K=o(void 0),q=e=>{j(e),b?.(e)},J=()=>{K.current&&window.clearTimeout(K.current),K.current=void 0};r(()=>{let e=te.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,110)}px`)},[C]),r(()=>()=>{for(let e of I.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl)},[]);let Y=e=>{F(t=>{let n=t.find(t=>t.key===e);return n?.previewUrl&&URL.revokeObjectURL(n.previewUrl),t.filter(t=>t.key!==e)})},re=()=>F([]);r(()=>{if(M===`none`)return;let e=e=>{ne.current&&!e.composedPath().includes(ne.current)&&N(`none`)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[M]);let ie=e=>N(t=>t===e?`none`:e),ae=e=>{let t=te.current;if(!t){T(t=>t+e);return}let n=t.selectionStart??C.length,r=t.selectionEnd??C.length;T(C.slice(0,n)+e+C.slice(r)),requestAnimationFrame(()=>{t.focus();let r=n+e.length;t.setSelectionRange(r,r)})},oe=e=>{N(`none`),n(e)},se=async e=>{if(e.length===0)return;H(``);let t=W.current,n=5-I.current.length-L.current;if(n<=0){H(Q(S.attachLimit,{count:`5`}));return}let r=e.slice(0,n);L.current+=r.length,ee(!0);for(let e of r){if(t!==W.current)break;try{await ce(e,t)}finally{t===W.current&&(--L.current,ee(L.current>0))}}t===W.current&&e.length>r.length&&H(Q(S.attachLimit,{count:`5`}))},ce=async(e,t)=>{if(e.size>5242880){H(S.attachTooLarge);return}if(!v){H(S.attachFailed);return}try{let n=await Bi(e);if(t!==W.current)return;let r=await v(n,e.type||`application/octet-stream`,e.name,_);if(t!==W.current)return;let i={key:`${r.id||e.name}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,id:r.id,analysisFailed:r.analysisFailed,name:e.name,text:r.text,mimeType:e.type||`application/octet-stream`,size:e.size,previewUrl:e.type.startsWith(`image/`)?URL.createObjectURL(e):void 0,file:e};F(e=>[...e,i])}catch(e){if(t!==W.current)return;e instanceof d&&e.status===413?H(S.attachTooLarge):e instanceof d&&[400,415,503].includes(e.status)?H(e.message):H(S.attachFailed)}},le=async e=>{let t=e.target,n=Array.from(t.files??[]);t.value=``,await se(n)},ue=()=>{W.current+=1,L.current=0,ee(!1),H(``)},de=(!!C.trim()||P.length>0)&&!a&&!R&&!O,fe=()=>{de&&(t(C,P.length>0?{attachments:P.map(e=>({id:e.id,name:e.name,text:e.text,file:e.file}))}:void 0),i?.(!1),T(``),re(),H(``))},pe=e=>{let n=e.trim();if(!n||a){q(`misunderstood`);return}let r=C.trim();t(r?`${r} ${n}`:n),i?.(!1),T(``),re(),H(``),q(`idle`)},me=e=>{if(e.key===`Enter`&&!e.shiftKey){if(a)return;e.preventDefault(),fe()}else e.key===`Escape`&&M!==`none`&&(e.preventDefault(),e.stopPropagation(),N(`none`))},he=()=>{J(),G.current?.stop(`dictation-ended`),G.current=null,D(!1),k(!1)},X=async()=>{let e=G.current;if(e){let{mic:t,processing:n}=e.snapshot;t===`hearing`||n?e.finishTurn():(he(),q(`idle`));return}let t=typeof navigator<`u`&&(navigator.languages?.[0]||navigator.language)||void 0;q(`connecting`);let n=new In({transcribe:async({audio:e,mimeType:n,durationSeconds:r})=>p(await Bi(e),n,t,r),listener:{state:({mic:e,processing:t,reason:r})=>{if(G.current===n){if(e===`unavailable`){if(r===`permission-denied`||r===`unsupported`||r===`no-device`||r===`error`){he(),q(`denied`);return}q(`unavailable`);return}D(e===`listening`||e===`hearing`),k(t),e===`starting`?q(`connecting`):t&&e!==`hearing`?q(`processing`):e===`hearing`?q(`hearing`):e===`listening`&&q(`listening`)}},speechStart:()=>J(),turn:e=>{G.current===n&&(he(),pe(e.text))},noise:e=>{G.current===n&&(he(),q(e.reason===`transcribe-failed`?`misunderstood`:`noise`))}}});G.current=n,K.current=window.setTimeout(()=>{G.current===n&&(he(),q(`noise`))},15e3),await n.start()};return r(()=>{!y||!f||a||E||O||X()},[y]),r(()=>()=>{J(),G.current?.stop(`unmounted`),G.current=null},[]),u(`div`,{class:`cf-composer ${z?`is-dragging`:``}`,ref:ne,onDragEnter:e=>{g&&(e.preventDefault(),B(!0))},onDragOver:e=>{g&&e.preventDefault()},onDragLeave:e=>{e.currentTarget===e.target&&B(!1)},onDrop:e=>{g&&(e.preventDefault(),B(!1),se(Array.from(e.dataTransfer?.files??[])))},children:[M===`emoji`&&l(Vi,{onPick:ae}),M===`gif`&&l(Hi,{onSearch:h,onPick:oe}),(P.length>0||R||V)&&u(`div`,{class:`cf-attach-row`,role:`list`,"aria-label":S.attachedFiles,children:[P.map(e=>u(`span`,{class:`cf-attach-chip`,role:`listitem`,title:e.name,children:[u(`button`,{type:`button`,class:`cf-attach-open`,"aria-label":Q(S.attachOpen,{name:e.name}),disabled:!x,onClick:()=>x?.(e.file,e.name),children:[e.previewUrl?l(`img`,{class:`cf-attach-preview`,src:e.previewUrl,alt:``}):l(Lr,{}),u(`span`,{class:`cf-attach-copy`,children:[l(`span`,{children:e.name}),l(`small`,{children:e.analysisFailed?S.attachAnalysisFailed:`${Math.max(1,Math.ceil(e.size/1024))} KB`})]})]}),l(`button`,{type:`button`,class:`cf-attach-x`,"aria-label":Q(S.removeAttachmentNamed,{name:e.name}),onClick:()=>Y(e.key),children:l(Ar,{})})]},e.key)),R&&u(`span`,{class:`cf-attach-status`,children:[l(`span`,{children:S.attaching}),l(`button`,{type:`button`,onClick:ue,children:S.cancel})]}),V&&!R&&l(`span`,{class:`cf-attach-status cf-attach-status--err`,children:V})]}),A!==`idle`&&u(`div`,{class:`cf-voice-state`,"aria-live":`polite`,children:[l(`span`,{class:`cf-voice-state__dot ${E?`is-live`:``}`}),Yi(A,S)]}),u(`div`,{class:`cf-composer__field`,children:[l(`button`,{type:`button`,class:`cf-iconbtn ${M===`emoji`?`is-active`:``}`,"aria-label":S.emoji,"aria-pressed":M===`emoji`,onClick:()=>ie(`emoji`),children:l(M===`emoji`?Ar:kr,{})}),m&&l(`button`,{type:`button`,class:`cf-iconbtn cf-gifbtn ${M===`gif`?`is-active`:``}`,"aria-label":S.gifs,"aria-pressed":M===`gif`,onClick:()=>ie(`gif`),children:l(`span`,{class:`cf-gif-label`,children:`GIF`})}),g&&u(c,{children:[l(`input`,{ref:U,type:`file`,class:`cf-file-input`,accept:`image/png,image/jpeg,image/webp,image/gif,application/pdf`,multiple:!0,onChange:le,tabIndex:-1,"aria-hidden":`true`}),l(`button`,{type:`button`,class:`cf-iconbtn`,"aria-label":S.attachFile,disabled:R,onClick:()=>U.current?.click(),children:l(Lr,{})})]}),l(`textarea`,{ref:te,class:`cf-textarea`,rows:1,placeholder:S.composerPlaceholder,value:C,"aria-label":S.composerPlaceholder,"aria-busy":a,onInput:e=>{let t=e.target.value;T(t),i?.(!!t.trim())},onPaste:e=>{let t=Array.from(e.clipboardData?.files??[]);!g||t.length===0||(e.preventDefault(),se(t))},onKeyDown:me}),f&&l(`button`,{type:`button`,class:`cf-iconbtn cf-mic ${E?`is-recording`:``}`,"aria-label":E?S.stopRecording:S.recordVoice,"aria-pressed":E,disabled:O||a,onClick:X,children:l(vr,{})}),l(`button`,{type:`button`,class:`cf-send`,"aria-label":S.send,disabled:!de,onClick:fe,children:l(_r,{})})]})]})},Zi=e=>e.replace(/\[[^\]]{0,60}\]/g,` `).replace(/\(([^)]{0,60})\)/g,(e,t)=>Qi.has(t.trim().toLowerCase().replace(/[.!?,…]+$/,``).replace(/\s+/g,` `))?` `:e).replace(/\*[^*]{0,60}\*/g,` `).replace(/\s+/g,` `).trim(),Qi=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`.split(`.`)),$i=/^\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?(?:\s*(?:-|–|—|to|-->)\s*\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?)?$/,ea=e=>{let t=e.trim().toLowerCase().replace(/[()[\]*]/g,` `).replace(/[.!?,…]+$/,``).replace(/\s+/g,` `).trim();return!t||/^(?:sh+\s*)+$/.test(t)||$i.test(t)?!0:Qi.has(t)},ta=e=>{let 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},na=e=>{let t=Zi(e);return ea(t)||ta(t)?``:t},ra=(e,t)=>En(e,t);let ia=!0,aa=null;const oa=e=>{ia=e},sa=()=>{let e=typeof window<`u`?window.AudioContext??window.webkitAudioContext:void 0;if(!e)return null;if(!aa)try{aa=new e}catch{return null}return aa.state===`suspended`&&aa.resume(),aa},ca=(e,t,n,r,i,a)=>{let o=e.createOscillator(),s=e.createGain();o.type=i,o.frequency.setValueAtTime(t,n),o.connect(s),s.connect(e.destination),s.gain.setValueAtTime(1e-4,n),s.gain.exponentialRampToValueAtTime(a,n+.012),s.gain.exponentialRampToValueAtTime(1e-4,n+r),o.start(n),o.stop(n+r+.03)},la=e=>{if(!ia)return;let t=sa();if(!t)return;let n=t.currentTime;try{e===`open`?(ca(t,523,n,.12,`sine`,.05),ca(t,784,n+.08,.16,`sine`,.05)):e===`send`?ca(t,660,n,.08,`triangle`,.04):e===`receive`&&(ca(t,880,n,.1,`sine`,.045),ca(t,1175,n+.09,.14,`sine`,.045))}catch{}},ua=[`audio/webm;codecs=opus`,`audio/webm`,`audio/ogg;codecs=opus`,`audio/ogg`],da=()=>{if(typeof navigator>`u`||!navigator.mediaDevices?.getSupportedConstraints)return{};try{return navigator.mediaDevices.getSupportedConstraints()}catch{return{}}},fa=(e=``,t=da())=>{let n={...e?{deviceId:{exact:e}}:{}};return t.echoCancellation&&(n.echoCancellation={ideal:!0}),t.noiseSuppression&&(n.noiseSuppression={ideal:!0}),t.autoGainControl&&(n.autoGainControl={ideal:!0}),t.channelCount&&(n.channelCount={ideal:1}),t.voiceIsolation&&(n.voiceIsolation={ideal:!0}),n},pa=(e={})=>{let t=Math.max(2,e.calibrationSamples??6),n=Math.max(t,e.ambientWindowSamples??72),r=Math.min(.5,Math.max(0,e.ambientPercentile??.2)),i=Math.min(1,Math.max(.01,e.smoothing??.22)),a=Math.max(2**-52,e.minimumNoiseFloor??5e-4),o=Math.max(1.1,e.speechToNoiseRatio??2.7),s=Math.min(o,Math.max(1,e.quietToNoiseRatio??1.55)),c=Math.max(250,e.minimumEndSilenceMs??650),l=Math.max(c,e.maximumEndSilenceMs??1100),u=[],d=a,f=d*o,p=0;return{observe:e=>{let m=Number.isFinite(e)?Math.max(0,e):0;if(u.length<t||m<=f){u.push(m),u.length>n&&u.shift();let e=[...u].sort((e,t)=>e-t),t=Math.min(e.length-1,Math.floor((e.length-1)*r)),o=Math.max(a,e[t]??a);d+=(o-d)*i}f=d*o;let h=d*s,g=u.length>=t,_=g&&m>=f;_&&(p=Math.max(p,m/Math.max(d,a)));let v=Math.min(1,Math.max(0,(p-o)/o)),y=Math.round(l-(l-c)*v);return{speech:_,quiet:g&&m<=h,calibrated:g,noiseFloor:d,speechThreshold:f,quietThreshold:h,endOfSpeechDelayMs:y}},reset:()=>{u=[],d=a,f=d*o,p=0}}},ma=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result??``).split(`,`)[1]??``),r.onerror=()=>n(r.error),r.readAsDataURL(e)}),ha=e=>{let t=globalThis.MediaRecorder;if(typeof t?.isTypeSupported==`function`){for(let n of ua)if(t.isTypeSupported(n))try{return new t(e,{mimeType:n})}catch{}}return new t(e)},ga=e=>{if(!(!e||e.state!==`recording`)){try{e.requestData()}catch{}e.stop()}},_a=(e,t)=>e?.status===429?t.errorRateLimit:t.errorGeneric,va=()=>typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),ya=(e,t)=>{let n=va(),r={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:r})),r},ba=/!?\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,xa=/https?:\/\/[^\s)]+/g,Sa=e=>Dn(e).replace(ba,`$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(xa,e=>e.replace(/^https?:\/\//,``).replace(/^www\./,``).replace(/\/$/,``)).replace(/[ \t]+\n/g,`
167
+ `)})},r++));continue}if(e.trim()===``){i++;continue}let a=/^(#{1,6})\s+(.*)$/.exec(e);if(a){n.push(Qr(a[1].length,Xr(a[2]),r++)),i++;continue}if(/^\s*[-*•]\s+/.test(e)){let e=[];for(;i<t.length&&/^\s*[-*•]\s+/.test(t[i]);)e.push(l(`li`,{children:Xr(t[i].replace(/^\s*[-*•]\s+/,``))},e.length)),i++;n.push(l(`ul`,{class:`cf-md-list`,children:e},r++));continue}if(/^\s*\d+\.\s+/.test(e)){let e=[];for(;i<t.length&&/^\s*\d+\.\s+/.test(t[i]);)e.push(l(`li`,{children:Xr(t[i].replace(/^\s*\d+\.\s+/,``))},e.length)),i++;n.push(l(`ol`,{class:`cf-md-list`,children:e},r++));continue}let o=[e];for(i++;i<t.length&&t[i].trim()!==``&&!Zr.test(t[i]);)o.push(t[i]),i++;let s=o.join(` `);if(/:\s*$/.test(s)&&i<t.length&&/^(?:\s*[-*•]\s+|\s*\d+\.\s+)/.test(t[i])){let e=/^(.*[.!?])\s+([^.!?]{2,120}:)$/.exec(s);e&&n.push(l(`p`,{children:Xr(e[1])},r++)),n.push(l(`p`,{class:`cf-md-list-intro`,children:Xr(e?.[2]??s)},r++))}else n.push(l(`p`,{children:Xr(s)},r++))}return n},ei=e=>H(e),ti=()=>{let e=o(null);return r(()=>{let t=requestAnimationFrame(()=>e.current?.scrollIntoView?.({block:`end`}));return()=>cancelAnimationFrame(t)},[]),e},ni=e=>e.trim().split(/\s+/).slice(0,2).map(e=>e[0]?.toUpperCase()??``).join(``)||`🤖`,ri=e=>{let t=e?.avatarId?.trim().toLowerCase().replace(/[^a-z0-9-]/g,`-`);return t?` cf-avatar-preset--${t}`:``},ii={"support-guide":`SG`,"sales-host":`SH`,"calm-advisor":`CA`,"technical-guide":`TG`,"school-desk":`SD`,"front-office":`FO`},ai=e=>{let t=e?.avatarId?.trim().toLowerCase();return t&&ii[t]||(e?ni(e.agentName):`·`)},oi=({persona:e,small:t,hideWhenMissing:n})=>{let r=t?`cf-msg__avatar`:`cf-header__avatar`,i=e?.agentAvatarUrl?.trim();return i?l(`span`,{class:r,children:l(`img`,{src:i,alt:``})}):n?null:l(`span`,{class:`${r}${ri(e)}`,children:ai(e)})},si=()=>{let e=lr(),[t,n]=s(0),i=[`Understanding your question`,`Checking approved information`,`Preparing your answer`];return r(()=>{let e=[window.setTimeout(()=>n(1),1800),window.setTimeout(()=>n(2),5e3)];return()=>e.forEach(e=>window.clearTimeout(e))},[]),u(`div`,{class:`cf-msg__bubble cf-typing`,"aria-label":e.assistantTyping,children:[l(`span`,{class:`cf-typing__label`,"aria-live":`polite`,children:i[t]}),l(`span`,{class:`cf-typing__dot`}),l(`span`,{class:`cf-typing__dot`}),l(`span`,{class:`cf-typing__dot`})]})},ci=({msg:e})=>{if(!e.sources||e.sources.length===0)return null;let t=new Set,n=[];for(let r of e.sources){let i=(r.url||r.title||``).toLowerCase();!i||t.has(i)||r.url&&e.content.includes(r.url)||(t.add(i),n.push(r))}if(n.length===0)return null;let r=n.slice(0,3),i=n.length-r.length;return u(`div`,{class:`cf-sources`,children:[r.map((e,t)=>e.url?u(`a`,{class:`cf-source`,href:e.url,target:`_blank`,rel:`noopener noreferrer nofollow`,title:e.title||e.url,children:[l(xr,{}),l(`span`,{children:e.title||e.url})]},t):u(`span`,{class:`cf-source`,title:e.title,children:[l(xr,{}),l(`span`,{children:e.title})]},t)),i>0&&u(`span`,{class:`cf-source cf-source--more`,children:[`+`,i,` more`]})]})},li=({replies:e,onPick:t})=>e&&e.length>0?l(`div`,{class:`cf-chips`,children:e.map((e,n)=>l(`button`,{type:`button`,class:`cf-chip`,onClick:()=>t(e),children:e},n))}):null,ui=({persona:e,starters:t,onPick:n,onFocusComposer:r,speaking:i,voiceState:a=`idle`,replyPending:o=!1,pinned:s=!1,muted:d=!1,onToggleMute:f,onEndCall:p,onTalkNow:m,showTalkNow:h=!1,micLevel:g=0,theaterMode:_=!1,onToggleTheater:v,onMinimize:y,audioDevices:b=[],selectedAudioDeviceId:x=``,onSelectAudioDevice:S,connectingOnly:C=!1})=>{if(!e)return null;let w=!!(e.allowVoiceInput&&e.talkbackMode&&e.talkbackMode!==`text`);if(!(w||e.widgetModule===`assistant`))return null;let T=e.agentAvatarUrl?.trim()||``,E=e.assistantMediaUrl?.trim()||T,D=e.assistantMediaKind===`video`&&!!E,O=t.slice(0,3),k=a!==`idle`,A=a===`idle`?`Speak with ${e.agentName}`:`End voice chat`,j=s&&w&&!k&&!i,M=a===`connecting`||a===`processing`||k&&o,N=[`cf-assistant-card__stage`,`cf-assistant-card__stage--local`,k?`is-live`:``,M?`is-thinking`:``,Wi(a)&&!d?`is-listening`:``,i||a===`speaking`?`is-speaking`:``,d?`is-muted`:``].filter(Boolean).join(` `),P=Wi(a)&&!d?{"--cf-listen":String(Math.max(.18,Math.min(1,g*8)))}:void 0,F=M&&u(`span`,{class:`cf-call-ripple`,"aria-hidden":`true`,children:[l(`span`,{}),l(`span`,{}),l(`span`,{})]});if(C)return u(`div`,{class:`cf-assistant-card cf-assistant-card--connecting`,"aria-live":`polite`,children:[u(`div`,{class:`cf-assistant-card__connecting-avatar`,children:[T?l(`img`,{src:T,alt:``}):l(`span`,{class:`cf-assistant-card__connecting-face${ri(e)}`,children:ai(e)}),F]}),u(`div`,{class:`cf-assistant-card__connecting-copy`,children:[l(`span`,{class:`cf-assistant-card__connecting-eyebrow`,children:e.agentName}),l(`strong`,{children:`Connecting with the AI…`})]})]});let I=k&&p&&l(Ji,{voiceState:a,muted:d,onToggleMute:f??(()=>{}),onEndCall:p,onTalkNow:m??(()=>{}),showTalkNow:h,micLevel:g,theaterMode:_,onToggleTheater:v??(()=>{}),onMinimize:y??(()=>{}),audioDevices:b,selectedAudioDeviceId:x,onSelectAudioDevice:S??(()=>{})});return j?l(`div`,{class:`cf-assistant-card cf-assistant-card--pinned cf-assistant-card--compact`,children:u(`button`,{type:`button`,class:`cf-assistant-card__compact-speak`,onClick:r,children:[T?l(`span`,{class:`cf-assistant-card__compact-avatar`,children:l(`img`,{src:T,alt:``})}):null,l(`span`,{class:`cf-assistant-card__compact-mic`,"aria-hidden":`true`,children:l(yr,{})}),l(`span`,{class:`cf-assistant-card__compact-label`,children:A})]})}):u(`div`,{class:`cf-assistant-card ${s?`cf-assistant-card--pinned`:``} ${i?`is-speaking`:``}`,children:[(E||w)&&u(`div`,{class:N,style:P,children:[u(`div`,{class:`cf-assistant-card__media ${E?`cf-assistant-card__media--uploaded`:`cf-assistant-card__media--generated`}${ri(e)}`,children:[D?l(`video`,{src:E,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):E?l(`img`,{src:E,alt:``}):l(`div`,{class:`cf-assistant-card__avatar-stage${ri(e)}`,children:u(`div`,{class:`cf-assistant-card__face`,children:[l(`span`,{class:`cf-assistant-card__initials`,children:ai(e)}),l(`span`,{class:`cf-assistant-card__eye cf-assistant-card__eye--left`}),l(`span`,{class:`cf-assistant-card__eye cf-assistant-card__eye--right`}),l(`span`,{class:`cf-assistant-card__mouth`})]})}),E&&!D&&l(`span`,{class:`cf-assistant-card__mouth cf-assistant-card__mouth--overlay`}),l(`span`,{class:`cf-avatar-aura cf-avatar-aura--one`,"aria-hidden":`true`}),l(`span`,{class:`cf-avatar-aura cf-avatar-aura--two`,"aria-hidden":`true`}),l(`span`,{class:`cf-avatar-listen-ring`,"aria-hidden":`true`}),u(`span`,{class:`cf-avatar-wave`,"aria-hidden":`true`,children:[l(`span`,{}),l(`span`,{}),l(`span`,{}),l(`span`,{})]})]}),F,k&&l(`span`,{class:`cf-call-status`,role:`status`,"aria-live":`polite`,children:Gi(a)}),w&&(I||u(`button`,{type:`button`,class:`cf-assistant-card__speak`,onClick:r,children:[l(yr,{}),A]}))]}),!s&&u(c,{children:[e.agentDescription?l(`p`,{class:`cf-assistant-card__copy`,children:e.agentDescription}):l(`p`,{class:`cf-assistant-card__copy`,children:e.greeting}),O.length>0&&l(`div`,{class:`cf-assistant-card__chips`,children:O.map(e=>l(`button`,{type:`button`,class:`cf-assistant-card__chip`,onClick:()=>n(e),children:e},e))}),e.disclaimerText||e.assistantPrivacyUrl?u(`p`,{class:`cf-assistant-card__privacy`,children:[e.disclaimerText||`This chat may be recorded for quality and support.`,e.assistantPrivacyUrl?u(c,{children:[` `,l(`a`,{href:e.assistantPrivacyUrl,target:`_blank`,rel:`noopener noreferrer nofollow`,children:`Privacy Policy`})]}):null]}):null]})]})},di={calendar:Sr,"calendar-clock":Or,headset:Tr,mail:Cr,message:Er,newsletter:kr,phone:wr,presentation:Dr,lifebuoy:Tr},fi=e=>di[e]??Cr,pi=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`}},mi={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`}},hi=(e,t,n={})=>Array.isArray(e)?e.filter(e=>e.readiness!==`unavailable`).map(e=>gi(e,n[e.id])):(t??[]).flatMap(e=>{let t=mi[e];if(!t)return[];let n=pi({...t,id:e}),r=Qn[n];return[{...t,id:e,presentation:n===`book-demo`||n===`schedule-callback`?`booking`:`form`,formTitle:r.title,submitLabel:r.submit,fields:r.fields,delivery:``,prompt:``,shortLabel:t.label.toLowerCase(),enabled:!0,readiness:`available`,legacyFallback:!0}]}).map(e=>gi(e,n[e.id])),gi=(e,t)=>{if(!t)return e;let n=t.fields??{};return{...e,...Object.fromEntries(Object.entries(t).filter(([e,t])=>e!==`fields`&&t!==void 0)),fields:e.fields.map(e=>({...e,...n[e.key]}))}},_i=(e,t)=>{let n=e.map(e=>e.label);return n.length===0?t.actionGetInTouch:n.length<=3?n.join(`, `):`${n.slice(0,2).join(`, `)} ${Q(t.actionMore,{count:String(n.length-2)})}`},vi=({label:e,required:t,value:n,onInput:i})=>{let c=a(()=>pr(n),[]),[d,f]=s(c.country.iso),[p,m]=s(c.national),[h,g]=s(!1),[_,v]=s(``),y=o(null),b=ur.find(e=>e.iso===d)??c.country,x=a(()=>{let e=_.trim().toLowerCase().replace(/^\+/,``);return e?ur.filter(t=>t.name.toLowerCase().includes(e)||t.iso.toLowerCase().includes(e)||t.dial.includes(e)):ur},[_]);r(()=>{if(!h)return;let e=e=>{y.current&&!e.composedPath().includes(y.current)&&g(!1)},t=e=>{e.key===`Escape`&&g(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[h]);let S=e=>{let t=ur.find(t=>t.iso===e)??b;f(t.iso),g(!1),v(``),i(mr(t,p))};return u(`div`,{class:`cf-phone`,role:`group`,"aria-label":`${e}${t?` *`:``}`,ref:y,children:[u(`span`,{class:`cf-phone__label`,children:[e,t?` *`:``]}),u(`div`,{class:`cf-phone__control`,children:[u(`button`,{type:`button`,class:`cf-phone__country`,"aria-label":`${b.name}, +${b.dial}. Choose country and calling code`,"aria-haspopup":`listbox`,"aria-expanded":h,onClick:()=>g(e=>!e),children:[l(`span`,{"aria-hidden":`true`,children:dr(b.iso)}),u(`span`,{class:`cf-phone__country-code`,children:[`+`,b.dial]}),l(_r,{})]}),l(`input`,{class:`cf-phone__input`,type:`tel`,inputMode:`numeric`,pattern:`[0-9]*`,autoComplete:`tel-national`,maxLength:15,placeholder:`8028509941`,value:p,"aria-label":e,onInput:e=>{let t=e.target,n=t.value.replace(/\D/g,``);t.value=n,m(n),i(mr(b,n))}})]}),h?u(`div`,{class:`cf-phone__menu`,children:[l(`input`,{class:`cf-phone__search`,type:`search`,placeholder:`Search country or code`,"aria-label":`Search countries`,value:_,autoFocus:!0,onInput:e=>v(e.target.value)}),l(`div`,{class:`cf-phone__options`,role:`listbox`,"aria-label":`Countries`,children:x.length>0?x.map(e=>u(`button`,{type:`button`,class:`cf-phone__option ${e.iso===b.iso?`is-selected`:``}`,role:`option`,"aria-selected":e.iso===b.iso,onClick:()=>S(e.iso),children:[l(`span`,{"aria-hidden":`true`,children:dr(e.iso)}),l(`span`,{class:`cf-phone__option-name`,children:e.name}),u(`span`,{class:`cf-phone__option-code`,children:[`+`,e.dial]})]},e.iso)):l(`div`,{class:`cf-phone__empty`,children:`No countries found`})})]}):null]})},yi=({field:e,value:t,onInput:n})=>{if(e.kind===`tel`)return l(vi,{label:e.label,required:e.required,value:t,onInput:n});let r=e.placeholder??e.label,i={class:`cf-form__input`,placeholder:e.required?`${r} *`:r,value:t,"aria-label":e.label,onInput:e=>n(e.target.value)};return e.kind===`textarea`?l(`textarea`,{rows:2,...i}):l(`input`,{type:e.kind,...i})},bi=({spec:e,visitor:t,onSubmit:n,onCancel:r})=>{let i=lr(),a=ti(),[o,c]=s(()=>{let n={};for(let r of e.fields)r.identity&&t[r.identity]&&(n[r.key]=t[r.identity]);return n}),[d,f]=s(`idle`),[p,m]=s(``),h=e=>!!(e.identity&&t[e.identity]?.trim()),g=e.fields.filter(e=>!h(e)),_=g.every(e=>!e.required||(o[e.key]?.trim()??``)!==``),v=t.email||t.name||``;return d===`done`?u(`div`,{class:`cf-form cf-form--done`,children:[l(Pr,{}),l(`span`,{children:p})]}):u(`div`,{class:`cf-form`,ref:a,children:[g.length===0&&v&&l(`div`,{class:`cf-form__as`,children:Q(i.actionAs,{identity:v})}),g.map(e=>l(yi,{field:e,value:o[e.key]??``,onInput:t=>c(n=>({...n,[e.key]:t}))},e.key)),d===`error`&&l(`div`,{class:`cf-form__err`,children:i.formError}),u(`div`,{class:`cf-form__actions`,children:[r&&l(`button`,{type:`button`,class:`cf-form__cancel`,onClick:r,children:i.cancel}),l(`button`,{type:`button`,class:`cf-form__submit`,disabled:!_||d===`submitting`,onClick:async()=>{if(!_||d===`submitting`)return;f(`submitting`);let t={},r={};for(let n of e.fields){let e=o[n.key]?.trim();e&&(t[n.key]=e,n.identity&&(r[n.identity]=e))}try{let e=await n(t,r);m(er(e.note||i.formThanks,e.caseReference,i)),f(`done`)}catch{f(`error`)}},children:d===`submitting`?i.sending:e.submit})]})]})},xi=e=>String(e).padStart(2,`0`),Si=()=>{let e=[];for(let t=9;t<=17;t++)e.push(`${xi(t)}:00`),e.push(`${xi(t)}:30`);return e},Ci=e=>{let t=new Date;return t.setHours(0,0,0,0),Array.from({length:e},(e,n)=>{let r=new Date(t);return r.setDate(t.getDate()+n),r})},wi=(e,t)=>{let[n,r]=t.split(`:`).map(Number),i=new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,r??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}`}},Ti=(e,t)=>{let[n,r]=t.split(`:`).map(Number);return new Date(e.getFullYear(),e.getMonth(),e.getDate(),n??0,r??0)},Ei=(e,t)=>{let n=Ti(e,t);try{return new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}).format(n)}catch{return t}},Di=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||``}catch{return``}},Oi=(e,t)=>{try{let 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}},ki=(e,t)=>{if(!t?.contentWindow||e.source!==t.contentWindow)return!1;try{let t=new URL(e.origin).hostname;if(t!==`calendly.com`&&!t.endsWith(`.calendly.com`))return!1}catch{return!1}return!!(e.data&&typeof e.data==`object`&&typeof e.data.event==`string`)},Ai=({actionId:e,fields:t=Qn[`book-demo`].fields,visitor:n,onSubmit:i,onCancel:d,onDemoSlots:f,onConfirmHostedBooking:p,scheduler:m,title:h,submitLabel:g})=>{let _=e===`public_schedule_callback`,v=_?Qn[`schedule-callback`]:Qn[`book-demo`],y=h?.trim()||v.title,b=lr(),x=ti(),S=!!(!_&&m?.connected&&m.provider===`calendly`),C=S?b.bookingOpenScheduler:g?.trim()||v.submit,w=!!(m?.connected&&m.mode===`event`&&!S&&(m.availability===void 0||m.availability.calendarIds.length>0)),T=Math.min(60,Math.max(1,m?.availability?.bookingWindowDays??14)),E=a(()=>Ci(T),[T]),[D,O]=s(null),[k,A]=s(w?`loading`:`request_only`),[j,M]=s(m?.availability?.slotDurationMinutes??30),[N,P]=s(Di()||m?.availability?.timezone||``),F=a(()=>w?k!==`available`||D===null?[]:[...new Set([...D].map(e=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}))].sort():Si(),[D,k,w]),[I,L]=s(a(()=>{let e=Date.now();for(let t=0;t<E.length;t++)if(F.some(n=>Ti(E[t],n).getTime()>e))return t;return 0},[E,F])),[R,ee]=s(null),[z,B]=s(n.name??``),[V,H]=s(n.email??``),[U,te]=s(n.phone??``),[W,G]=s(``),[K,q]=s(`idle`),[J,ne]=s(``),[Y,re]=s(!1),[ie,ae]=s(``),[oe,se]=s(`scheduler`),[ce,le]=s(null),[ue,de]=s(`idle`),[fe,pe]=s(``),[me,he]=s(``),[X,ge]=s(``),_e=o(null),ve=async(e,t,n)=>{de(`loading`);try{let r=await p?.(e,t,n);if(!r?.confirmed)throw Error(`booking confirmation unavailable`);let i=r?.meetingUrl||r?.eventLink||``,a=r?.rescheduleUrl||r?.cancelUrl||``;ae(i||a),se(i?`meeting`:`manage`),de(`idle`),re(!1),ne(er(b.bookingScheduled,me,b))}catch{de(`error`),re(!0),ne(b.bookingDetailsUnavailable)}};r(()=>{if(!fe)return;let e=e=>{if(!ki(e,_e.current)||e.data.event!==`calendly.event_scheduled`)return;let t=e.data.payload,n=t?.event?.uri?.trim()||``,r=t?.invitee?.uri?.trim()||``;X&&n&&r?(le({eventUri:n,inviteeUri:r}),ve(X,n,r),ne(b.bookingCheckingDetails)):(de(`error`),re(!0),ne(b.bookingDetailsUnavailable)),pe(``),q(`done`)};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[p,me,X,fe,b]),r(()=>{if(!w||k!==`available`||D===null)return;let e=E.findIndex(e=>F.some(t=>D.has(Ti(e,t).getTime())));e>=0&&L(e)},[D,k,E,w,F]);let ye=!!(!_&&m?.connected&&(m.mode===`link`||m.provider===`calendly`)),be=async()=>{if(K===`submitting`||K===`scheduling`||!n.name?.trim()&&!z.trim()||!n.email?.trim()&&!V.trim())return;q(`submitting`);let e={};V.trim()&&(e.email=V.trim()),z.trim()&&(e.name=z.trim());try{let t=await i({...V.trim()?{visitorEmail:V.trim()}:{},...z.trim()?{visitorName:z.trim()}:{}},e),r=t.booking?.schedulingLink||m?.bookingLink||``;if(!r){q(`error`);return}ae(r),se(`scheduler`),he(t.caseReference||``),ge(t.inquiryId||``),pe(Oi(r,{name:z.trim()||n.name,email:V.trim()||n.email})),q(`scheduling`)}catch{q(`error`)}},[xe,Se]=s(new Set),[Ce,Z]=s([]),[we,Te]=s(0),[Ee,De]=s(!1);r(()=>{if(!f)return;let e=!0,t=new Date,n=new Date;return n.setDate(n.getDate()+T+1),f(t.toISOString(),n.toISOString()).then(t=>{if(e)if(Se(new Set(t.taken.map(e=>Date.parse(e)).filter(e=>!Number.isNaN(e)))),Z(t.busy.map(e=>[Date.parse(e.start),Date.parse(e.end)]).filter(([e,t])=>!Number.isNaN(e)&&!Number.isNaN(t))),M(t.slotDurationMinutes??30),P(Di()||t.timezone||``),w){if(t.status!==`available`||!Array.isArray(t.available)){O(null),A(`unavailable`);return}O(new Set(t.available.map(e=>Date.parse(e)).filter(e=>!Number.isNaN(e)))),A(`available`)}else A(t.status??`request_only`)}).catch(()=>{!e||!w||(O(null),A(`unavailable`))}),()=>{e=!1}},[T,w,f,we]);let Oe=!!n.email?.trim(),ke=!!n.name?.trim(),Ae=!!n.phone?.trim(),je=U,Me=!!R&&(!w||k===`available`)&&(ke||z.trim()!==``)&&(_?Ae||hr(je):Oe||V.trim()!==``),Ne=(_?n.phone||n.name:n.email||n.name)||``,Pe=e=>t.find(t=>t.key===e),Fe=Pe(`visitorName`)?.label||v.fields.find(e=>e.key===`visitorName`).label,Ie=Pe(`visitorEmail`)?.label||b.handoffEmail,Le=Pe(`visitorPhone`),Re=Pe(`topic`),ze=e=>xe.has(Ti(E[I],e).getTime()),Be=e=>Ti(E[I],e).getTime()<=Date.now(),Ve=j*60*1e3,He=e=>{let t=Ti(E[I],e).getTime(),n=t+Ve;return Ce.some(([e,r])=>t<r&&n>e)},Ue=e=>!w||D?.has(Ti(E[I],e).getTime())===!0,We=async()=>{if(!Me||K===`submitting`||!R)return;q(`submitting`),De(!1);let e=Ti(E[I],R),t=wi(E[I],R),r={};z.trim()&&(r.name=z.trim()),_?je&&(r.phone=je):V.trim()&&(r.email=V.trim());try{let a=await i(_?{bestTime:t,slotAt:e.toISOString(),visitorTimezone:Di()||`UTC`,...je?{visitorPhone:je}:{},...z.trim()?{visitorName:z.trim()}:{},...W.trim()?{topic:W.trim()}:{}}:{preferredAt:t,slotAt:e.toISOString(),visitorTimezone:Di()||`UTC`,...V.trim()?{visitorEmail:V.trim()}:{},...z.trim()?{visitorName:z.trim()}:{}},r);if(!_&&a.booking?.mode===`link`&&a.booking.schedulingLink?.trim()){let e=a.booking.schedulingLink.trim();ae(e),he(a.caseReference||``),ge(a.inquiryId||``),pe(Oi(e,{name:z.trim()||n.name,email:V.trim()||n.email})),q(`scheduling`);return}if(a.booking?.confirmed)ne(er(a.note||Q(_?b.bookingCallbackConfirmed:b.bookingConfirmed,{when:t}),a.caseReference,b)),ae(a.booking.meetingUrl||a.booking.rescheduleUrl||a.booking.cancelUrl||a.booking.eventLink||``),se(a.booking.meetingUrl||a.booking.eventLink?`meeting`:`manage`);else if(a.booking?.verificationPending){re(!0);let e=a.booking.eventLink||a.booking.meetingUrl||``;/^https?:\/\//i.test(e)&&(ae(e),se(`unverified`)),ne(er(a.note||Q(b.bookingVerificationPending,{when:t}),a.caseReference,b))}else ne(er(a.note||Q(_?b.bookingCallbackRequested:b.bookingRequested,{when:t}),a.caseReference,b));q(`done`)}catch(t){t?.status===409?(Se(t=>new Set(t).add(e.getTime())),ee(null),De(!0),Te(e=>e+1),q(`idle`)):q(`error`)}},Ge=()=>{pe(``),q(`idle`),d?.()};return K===`scheduling`&&fe?u(`div`,{class:`cf-scheduler-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":y,children:[u(`header`,{class:`cf-scheduler-overlay__head`,children:[l(`button`,{type:`button`,class:`cf-scheduler-overlay__back`,onClick:Ge,children:b.bookingBackToChat}),l(`strong`,{children:y}),u(`div`,{class:`cf-scheduler-overlay__tools`,children:[u(`a`,{href:ie,target:`_blank`,rel:`noopener noreferrer`,children:[b.bookingOpenNewTab,` `,l(xr,{})]}),l(`button`,{type:`button`,"aria-label":b.bookingCloseScheduler,onClick:Ge,children:l(jr,{})})]})]}),u(`div`,{class:`cf-scheduler-overlay__body`,children:[l(`div`,{class:`cf-scheduler-overlay__loading`,children:b.bookingLoadingScheduler}),l(`iframe`,{ref:_e,class:`cf-scheduler-overlay__frame`,src:fe,title:y,allow:`camera; microphone; fullscreen; payment`})]})]}):K===`done`?u(`div`,{class:`cf-form cf-form--done${Y?` cf-form--pending`:``}`,role:Y?`alert`:`status`,children:[!Y&&l(Pr,{}),l(`span`,{children:J}),ue===`loading`&&l(`span`,{role:`status`,children:b.bookingCheckingDetails}),ue===`error`&&u(`div`,{class:`cf-booking__receipt-error`,role:`alert`,children:[l(`span`,{children:b.bookingDetailsUnavailable}),ce&&X&&p&&l(`button`,{type:`button`,class:`cf-booking__back`,onClick:()=>void ve(X,ce.eventUri,ce.inviteeUri),children:b.bookingRetryDetails})]}),ie&&u(`a`,{class:`cf-booking__link`,href:ie,target:`_blank`,rel:`noopener noreferrer`,children:[oe===`meeting`?b.bookingMeetingLink:oe===`manage`?b.bookingManageLink:oe===`unverified`?b.bookingUnverifiedLink:b.bookingOpenScheduler,` `,l(xr,{}),l(`span`,{class:`cf-booking__url`,children:ie})]}),d&&l(`button`,{type:`button`,class:`cf-booking__back`,onClick:d,children:b.bookingBackToChat})]}):ye?u(`div`,{class:`cf-form cf-booking`,ref:x,children:[l(`div`,{class:`cf-booking__hint`,children:Q(b.bookingViaProvider,{provider:m?.label??b.bookingSchedulerFallback})}),Oe?Ne?l(`div`,{class:`cf-form__as`,children:Q(b.actionAs,{identity:Ne})}):null:u(c,{children:[!n.name?.trim()&&l(`input`,{class:`cf-form__input`,type:`text`,placeholder:`${Fe} *`,value:z,"aria-label":Fe,onInput:e=>B(e.target.value)}),l(`input`,{class:`cf-form__input`,type:`email`,placeholder:`${Ie} *`,value:V,"aria-label":Ie,onInput:e=>H(e.target.value)})]}),K===`error`&&l(`div`,{class:`cf-form__err`,children:b.formError}),u(`div`,{class:`cf-form__actions`,children:[d&&l(`button`,{type:`button`,class:`cf-form__cancel`,onClick:d,children:b.cancel}),l(`button`,{type:`button`,class:`cf-form__submit`,disabled:K===`submitting`||!n.name?.trim()&&z.trim()===``||!Oe&&V.trim()===``,onClick:be,children:K===`submitting`?b.sending:b.bookingOpenScheduler})]})]}):u(`div`,{class:`cf-form cf-booking`,ref:x,children:[u(`div`,{class:`cf-booking__hint`,children:[b.bookingPickTime,` ·`,` `,l(`span`,{class:`cf-booking__dur`,children:Q(_?b.bookingCallbackDuration:b.bookingDuration,{count:String(j)})}),N?l(`span`,{class:`cf-booking__timezone`,children:Q(b.bookingTimezone,{timezone:N})}):null]}),w&&k===`loading`?l(`div`,{class:`cf-booking__state`,role:`status`,children:b.bookingCheckingAvailability}):null,w&&k===`unavailable`?l(`div`,{class:`cf-form__err`,role:`alert`,children:b.bookingAvailabilityUnavailable}):null,w&&k===`available`&&F.length===0?l(`div`,{class:`cf-booking__state`,role:`status`,children:b.bookingNoSlots}):null,F.length>0?l(`div`,{class:`cf-booking__dates`,role:`tablist`,"aria-label":b.bookingPickDay,children:E.map((e,t)=>u(`button`,{type:`button`,role:`tab`,"aria-selected":t===I,disabled:w&&k===`available`&&!F.some(t=>D?.has(Ti(e,t).getTime())),class:`cf-booking__date ${t===I?`is-selected`:``}`,onClick:()=>{L(t),ee(null)},children:[l(`span`,{class:`cf-booking__dow`,children:e.toLocaleDateString(void 0,{weekday:`short`})}),l(`span`,{class:`cf-booking__dom`,children:e.getDate()})]},t))}):null,F.length>0?l(`div`,{class:`cf-booking__slots`,role:`listbox`,"aria-label":b.bookingPickTimeLabel,children:F.map(e=>{let t=Be(e),n=He(e),r=ze(e),i=Ue(e),a=r||t||n||!i;return l(`button`,{type:`button`,role:`option`,"aria-selected":R===e,disabled:a,title:t?b.bookingEarlierToday:n?b.bookingCalendarBusy:r?b.bookingAlreadyBooked:i?void 0:b.bookingNotOffered,class:`cf-booking__slot ${R===e?`is-selected`:``} ${a?`is-taken`:``}`,onClick:()=>ee(e),children:Ei(E[I],e)},e)})}):null,Ee&&l(`div`,{class:`cf-form__err`,children:b.bookingSlotTaken}),Ne?l(`div`,{class:`cf-form__as`,children:Q(b.actionAs,{identity:Ne})}):null,!ke&&l(`input`,{class:`cf-form__input`,type:`text`,placeholder:`${Fe} *`,value:z,"aria-label":Fe,onInput:e=>B(e.target.value)}),_&&!Ae&&l(vi,{label:Le?.label??`Phone number`,required:!0,value:U,onInput:te}),_&&Re?l(`input`,{class:`cf-form__input`,type:`text`,placeholder:Re.placeholder||Re.label,value:W,"aria-label":Re.label,onInput:e=>G(e.target.value)}):null,!_&&!Oe&&l(c,{children:l(`input`,{class:`cf-form__input`,type:`email`,placeholder:`${Ie} *`,value:V,"aria-label":Ie,onInput:e=>H(e.target.value)})}),K===`error`&&l(`div`,{class:`cf-form__err`,children:b.formError}),u(`div`,{class:`cf-form__actions`,children:[d&&l(`button`,{type:`button`,class:`cf-form__cancel`,onClick:d,children:b.cancel}),l(`button`,{type:`button`,class:`cf-form__submit`,disabled:!Me||K===`submitting`,onClick:We,children:K===`submitting`?b.sending:C})]})]})},ji=({actions:e,descriptors:n,visitor:c,onSubmitForm:d,onDemoSlots:f,onConfirmHostedBooking:p,scheduler:m,exclude:h=[],openAction:g,showTrigger:_=!0,translations:v={},onClose:y})=>{let b=lr(),[x,S]=s(null),[C,w]=s(!1),T=o(null),E=o(null),D=o(!1),O=o(null),k=o(void 0),A=o(!1),j=a(()=>`cf-actions-${Math.random().toString(36).slice(2,9)}`,[]),M=a(()=>hi(n,e,v).filter(e=>!h.includes(e.id)&&!h.includes(e.endpoint)),[n,e,h,v]);r(()=>{if(!g){k.current=void 0;return}k.current!==g&&M.some(e=>e.id===g)&&(k.current=g,A.current=!0,S(g),w(!0))},[g,M]);let N=x?M.find(e=>e.id===x):void 0,P=t(()=>{if(y){y();return}D.current=!0,O.current=T.current||E.current?.closest(`.cf-panel`)?.querySelector(`.cf-footer-actions .cf-action-trigger, .cf-textarea`)||null,A.current=!1,S(null),w(!1)},[y]),F=t(()=>{A.current?P():y?y():S(null)},[y,P]);i(()=>{C||!D.current||(D.current=!1,O.current?.focus(),O.current=null)},[C]);let I=o({drawerOpen:C,activeId:x});if(I.current={drawerOpen:C,activeId:x},r(()=>{let e=e=>{if(e.key!==`Escape`)return;let{drawerOpen:t,activeId:n}=I.current;!t&&!n||(e.stopPropagation(),n?F():P())};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[F,P]),r(()=>{if(!C)return;let e=E.current;if(!e)return;e.querySelector(`button, input, textarea, select`)?.focus({preventScroll:!0});let t,n=()=>{cancelAnimationFrame(t),t=requestAnimationFrame(()=>e.scrollIntoView?.({block:`nearest`}))};n();let r=e.closest(`.cf-body`)&&typeof ResizeObserver==`function`?new ResizeObserver(n):null;return r?.observe(e),()=>{cancelAnimationFrame(t),r?.disconnect()}},[C,x]),M.length===0||!_&&!C)return null;let L=C?N?u(`div`,{ref:E,id:j,class:`cf-action-drawer is-open`,role:`dialog`,"aria-modal":`false`,"aria-label":N.formTitle||N.label,children:[l(`div`,{class:`cf-action-drawer__handle`,"aria-hidden":`true`}),u(`div`,{class:`cf-action-drawer__head`,children:[u(`div`,{children:[l(`strong`,{children:N.formTitle||N.label}),N.legacyFallback?l(`small`,{class:`cf-action-test-mode`,children:b.actionTestMode}):null]}),l(`button`,{type:`button`,class:`cf-action-drawer__close`,"aria-label":b.actionClose,onClick:F,children:l(jr,{})})]}),N.readiness===`degraded`&&N.readinessNote?l(`p`,{class:`cf-action-drawer__note cf-action-drawer__note--warn`,role:`status`,children:N.readinessNote}):null,N.presentation===`booking`||N.endpoint===`book-demo`||N.endpoint===`schedule-callback`?l(Ai,{actionId:N.id,fields:N.fields,visitor:c,title:N.formTitle,submitLabel:N.submitLabel,onCancel:F,onSubmit:(e,t)=>d(N.id,e,t,N.endpoint),onDemoSlots:f,onConfirmHostedBooking:p,scheduler:m}):l(bi,{spec:{title:N.formTitle||N.label,submit:N.submitLabel,fields:N.endpoint===`request-callback`?N.fields.filter(e=>e.key!==`bestTime`):N.fields},visitor:c,onCancel:F,onSubmit:(e,t)=>d(N.id,e,t,N.endpoint)})]}):u(`div`,{ref:E,id:j,class:`cf-action-drawer cf-action-drawer--menu`,role:`dialog`,"aria-modal":`false`,"aria-label":b.actionChoose,children:[l(`div`,{class:`cf-action-drawer__handle`,"aria-hidden":`true`}),u(`div`,{class:`cf-action-drawer__head`,children:[u(`div`,{children:[l(`span`,{class:`cf-action-drawer__eyebrow`,children:b.actionNeedHelp}),l(`strong`,{children:b.actionChoose})]}),l(`button`,{type:`button`,class:`cf-action-drawer__close`,"aria-label":b.actionClose,onClick:P,children:l(jr,{})})]}),l(`div`,{class:`cf-action-drawer__grid`,children:M.map(e=>{let t=fi(e.icon);return u(`button`,{type:`button`,class:`cf-action-card`,onClick:()=>{A.current=!1,S(e.id)},children:[l(`span`,{class:`cf-action-card__icon cf-action-card__icon--${e.category}`,children:l(t,{})}),u(`span`,{class:`cf-action-card__copy`,children:[l(`strong`,{children:e.label}),e.legacyFallback?l(`small`,{class:`cf-action-test-mode`,children:b.actionTestMode}):null,l(`small`,{children:e.description}),e.readiness===`degraded`&&e.readinessNote?l(`small`,{class:`cf-action-card__warn`,children:e.readinessNote}):null]}),l(_r,{})]},e.id)})}),l(`p`,{class:`cf-action-drawer__note`,children:b.actionFooter})]}):null;return u(`div`,{class:`cf-action-shell`,children:[_&&u(`button`,{ref:T,type:`button`,class:`cf-action-trigger`,hidden:C,"aria-expanded":C,"aria-controls":j,onClick:()=>C?P():w(!0),children:[l(`span`,{class:`cf-action-trigger__icon`,children:l(Cr,{})}),u(`span`,{class:`cf-action-trigger__copy`,children:[l(`strong`,{children:b.actionContactOptions}),l(`small`,{children:_i(M,b)})]}),l(_r,{})]}),L]})},Mi=({hasEmail:e,visitor:t,question:n,onSubmitForm:r})=>{let i=lr(),[a,o]=s(!1),[c,d]=s(!1),[f,p]=s(t.name??``),[m,h]=s(t.email??``);if(e)return u(`div`,{class:`cf-handoff cf-handoff--done`,children:[l(Pr,{}),l(`span`,{children:`We’ve alerted the team. If someone is available, they can continue here.`})]});if(a){let e=t.email||m;return u(`div`,{class:`cf-handoff cf-handoff--done`,children:[l(Pr,{}),l(`span`,{children:Q(i.handoffShared,{email:e})})]})}let g=async()=>{if(!(!m.trim()||c)){d(!0);try{await r(`inquiry`,{visitorEmail:m.trim(),...f.trim()?{visitorName:f.trim()}:{},message:n||`I had a question the assistant couldn’t answer.`,subject:`Help request from chat`},{email:m.trim(),name:f.trim()||void 0}),o(!0)}catch{d(!1)}}};return u(`div`,{class:`cf-handoff`,children:[l(`div`,{class:`cf-handoff__title`,children:i.handoffTitle}),l(`input`,{class:`cf-form__input`,type:`text`,placeholder:i.handoffName,value:f,"aria-label":i.handoffName,onInput:e=>p(e.target.value)}),l(`input`,{class:`cf-form__input`,type:`email`,placeholder:`${i.handoffEmail} *`,value:m,"aria-label":i.handoffEmail,onInput:e=>h(e.target.value)}),l(`button`,{type:`button`,class:`cf-form__submit`,disabled:!m.trim()||c,onClick:g,children:c?i.sending:i.handoffNotify})]})},Ni=({text:e})=>{let t=lr(),[n,r]=s(!1);return u(`button`,{type:`button`,class:`cf-tool`,onClick:async()=>{try{await navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),1500)}catch{}},"aria-label":t.copy,children:[l(n?Pr:Fr,{}),n?t.copied:t.copy]})},Pi=({items:e,onPick:t})=>e.length===0?null:l(`div`,{class:`cf-starters`,children:e.map((e,n)=>l(`button`,{type:`button`,class:`cf-starter`,onClick:()=>t(e),children:e},n))}),Fi=({items:e})=>{let t=e.filter(e=>e.label.trim()&&e.url.trim()).slice(0,4);return t.length===0?null:l(`div`,{class:`cf-featured-links`,children:t.map((e,t)=>u(`a`,{class:`cf-featured-link`,href:e.url,target:`_blank`,rel:`noopener noreferrer nofollow`,title:e.label,children:[l(xr,{}),l(`span`,{children:e.label})]},`${e.url}-${t}`))})},Ii=({msg:e,onRate:t})=>{let n=lr(),[r,i]=s(!1),[a,o]=s(``),c=e.feedback,d=()=>{t(e.id,`up`),i(!1)},f=()=>{t(e.id,`down`),i(!0)},p=()=>{t(e.id,`down`,a.trim()),i(!1)};return u(`div`,{class:`cf-feedback`,children:[u(`div`,{class:`cf-feedback__row`,children:[l(`span`,{class:`cf-feedback__label`,children:n.feedbackAnswerPrompt}),l(`button`,{type:`button`,class:`cf-feedback__btn ${c===`up`?`is-active`:``}`,"aria-label":`${n.feedbackHelpful} answer`,"aria-pressed":c===`up`,onClick:d,children:l(Vr,{})}),l(`button`,{type:`button`,class:`cf-feedback__btn ${c===`down`?`is-active`:``}`,"aria-label":`${n.feedbackNotHelpful} answer`,"aria-pressed":c===`down`,onClick:f,children:l(Hr,{})}),c&&!r&&l(`span`,{class:`cf-feedback__thanks`,children:n.feedbackThanks})]}),r&&c===`down`&&u(`div`,{class:`cf-feedback__comment`,children:[l(`textarea`,{class:`cf-feedback__input`,rows:2,placeholder:n.feedbackCommentPlaceholder,value:a,onInput:e=>o(e.target.value)}),l(`button`,{type:`button`,class:`cf-feedback__send`,onClick:p,children:n.feedbackSend})]})]})},Li=e=>e.attachments??(e.attachmentName?[{id:e.attachmentId,name:e.attachmentName}]:[]),Ri=({msg:e,persona:t,isLast:n,visitor:r,hasEmail:i,lastQuestion:a,showActions:o,onPickReply:s,onSubmitForm:d,onDemoSlots:f,onConfirmHostedBooking:p,onRetry:m,ratable:h,onRate:g,onExpandVisualization:_,onExpandExplanation:v,onReconnect:y,onOpenAttachment:b,onExplanationFeedback:x,explanationTransport:S,onOpenAnalyticsSource:C})=>{let w=lr(),T=or(),E=e.role===`user`,D=e.liveEventType??``,O=e.content.trim().toLowerCase(),k=D===`handoff_queued`||D===`agent_joined`||D===`agent_left`||D===`ai_handback`||D===`conversation_ended`||O.includes(`joined the chat`)||O.includes(`left the chat`)||O.includes(`support agents will be with you`),A=e.role===`system`||k,j=e.requestedContactFields?.includes(`email`)===!0,M=n&&!E&&!A&&!e.reconnectOffer&&!!(e.handoffOffered||j),N=M&&!i?[`inquiry`]:[],P=!e.pending&&!e.streaming,F=[...e.artifacts??[],...e.visualization&&!(e.artifacts??[]).some(e=>e.type===`visualization`)?[{type:`visualization`,visualization:e.visualization}]:[]];return A?l(`div`,{class:`cf-msg cf-msg--system`,children:u(`div`,{class:`cf-system-event`,children:[l(`div`,{class:`cf-system-event__mark`,"aria-hidden":`true`}),l(`div`,{class:`cf-system-event__text`,children:e.content}),y&&l(`button`,{type:`button`,class:`cf-system-event__action`,onClick:y,children:w.reconnectSupport}),e.createdAt&&l(`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`})})]})}):u(`div`,{class:`cf-msg cf-msg--${E?`user`:`agent`}`,children:[!E&&l(oi,{persona:t,small:!0}),u(`div`,{class:`cf-msg__col${!E&&o?` cf-msg__col--actions`:``}`,children:[e.pending&&e.content===``?l(si,{}):e.imageUrl?u(`div`,{class:`cf-msg__bubble cf-msg__bubble--media`,children:[l(`img`,{class:`cf-msg__media`,src:e.imageUrl,alt:`GIF`}),e.content&&l(`span`,{class:`cf-msg__caption`,children:e.content})]}):u(`div`,{class:`cf-msg__bubble`,children:[E?e.content:$r(e.content),e.streaming&&l(`span`,{class:`cf-caret`,"aria-hidden":`true`})]}),E?null:F.map((t,n)=>t.type===`visualization`&&t.visualization?l(Bi,{visualization:t.visualization,onFollowUp:s,onExpand:_?()=>_(e.id):void 0,expandControlId:e.id},`visualization-${n}`):t.type===`image`&&(t.data||t.uri?.startsWith(`https://`))&&[`image/png`,`image/jpeg`,`image/webp`].includes(t.mimeType??``)?u(`figure`,{class:`cf-artifact`,children:[t.title?l(`figcaption`,{children:t.title}):null,l(`img`,{src:t.uri||`data:${t.mimeType};base64,${t.data}`,alt:t.altText||t.caption||t.title||`Tool result`}),t.caption&&t.caption!==t.title?l(`p`,{children:t.caption}):null]},`image-${n}`):t.type===`video`&&t.uri?.startsWith(`https://`)&&(t.mimeType??``).startsWith(`video/`)?u(`figure`,{class:`cf-artifact`,children:[t.title?l(`figcaption`,{children:t.title}):null,l(`video`,{controls:!0,preload:`metadata`,playsInline:!0,src:t.uri}),t.caption&&t.caption!==t.title?l(`p`,{children:t.caption}):null]},`video-${n}`):t.type===`resource_link`&&t.uri?.startsWith(`https://`)?u(`a`,{class:`cf-artifact-link`,href:t.uri,target:`_blank`,rel:`noopener noreferrer nofollow`,children:[l(`strong`,{children:t.title||t.name||`Open result`}),t.caption?l(`span`,{children:t.caption}):null]},`link-${n}`):null),!E&&e.resultExpired&&!e.visualization?u(`p`,{class:`cf-analytics-expired`,"data-testid":`analytics-result-expired`,children:[e.resultExpired.title?u(`strong`,{children:[e.resultExpired.title,`. `]}):null,w.resultExpired]}):null,!E&&e.visualization&&ei(e.visualization)?l(`div`,{class:`cf-analytics-explanation`,"data-testid":`inline-analytics-explanation`,"data-explanation-message":e.id,children:l(Jn,{classPrefix:`cf`,copy:w.analytics?.explanation,locale:T,onExpand:v?()=>v(e.id):void 0,explanation:ei(e.visualization),onFollowUp:s,onFeedback:x,aiTransport:S,canOpenSource:e=>!!C&&(e.kind===`liveboard_tile`||e.kind===`insight`),onOpenSource:C?t=>{(t.kind===`liveboard_tile`||t.kind===`insight`)&&C({kind:t.kind,id:t.id,...e.visualization?.appliedFilters?.length?{appliedFilters:e.visualization.appliedFilters}:{}})}:void 0,maxFollowUps:3,showLead:(()=>{let t=ei(e.visualization).headline?.trim().toLocaleLowerCase();return!t||!e.content.toLocaleLowerCase().includes(t)})()})}):null,E&&Li(e).length>0&&l(`div`,{class:`cf-attach-row cf-attach-row--sent`,children:Li(e).map((t,n)=>b?u(`button`,{type:`button`,class:`cf-attach-chip cf-attach-chip--open`,title:Q(w.attachOpen,{name:t.name}),"aria-label":Q(w.attachOpen,{name:t.name}),onClick:()=>b(e,t,n),children:[l(Rr,{}),l(`span`,{children:t.name})]},`${t.id??t.name}-${n}`):u(`div`,{class:`cf-attach-chip`,title:t.name,children:[l(Rr,{}),l(`span`,{children:t.name})]},`${t.id??t.name}-${n}`))}),!E&&u(c,{children:[P&&(e.error||e.content)&&u(`div`,{class:`cf-msg__actions`,children:[l(`div`,{class:`cf-msg__tools`,children:e.error?u(`button`,{type:`button`,class:`cf-tool`,onClick:()=>m(e.id,e.retryText??``),children:[l(Ir,{}),w.retry]}):l(Ni,{text:e.content})}),h&&!e.error&&e.content?l(Ii,{msg:e,onRate:g}):null]}),l(ci,{msg:e}),n&&l(li,{replies:e.suggestedReplies,onPick:s}),M&&l(Mi,{hasEmail:i,visitor:r,question:a,onSubmitForm:d}),o&&l(ji,{showTrigger:!1,actions:e.availableActions,descriptors:e.actions,openAction:e.selectedAction,visitor:r,onSubmitForm:d,onDemoSlots:f,onConfirmHostedBooking:p,scheduler:t?.scheduler,exclude:N})]})]})]})},zi=({visualization:e,onClose:t,onFollowUp:n,onFeedback:r,transport:i,onOpenSource:a})=>{let o=lr(),s=or(),c=ei(e);return c?l(`div`,{class:`cf-analytics-explanation is-expanded`,"data-testid":`expanded-analytics-explanation`,children:l(Jn,{classPrefix:`cf`,explanation:c,copy:o.analytics?.explanation,locale:s,expanded:!0,onCollapse:t,onFollowUp:n,onFeedback:r,aiTransport:i,canOpenSource:e=>!!a&&(e.kind===`liveboard_tile`||e.kind===`insight`),onOpenSource:a?t=>{(t.kind===`liveboard_tile`||t.kind===`insight`)&&a({kind:t.kind,id:t.id,...e.appliedFilters?.length?{appliedFilters:e.appliedFilters}:{}})}:void 0})}):null},Bi=({visualization:e,expanded:t=!1,onExpand:n,onClose:r,onFollowUp:i,expandControlId:a})=>{let o=lr(),s=or();return l(yn,{visualization:e,classPrefix:`cf`,labels:o.analytics,locale:s,expanded:t,onExpand:n,onClose:r,onFollowUp:i,expandControlId:a})},Vi=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result).split(`,`)[1]??``),r.onerror=n,r.readAsDataURL(e)}),Hi=({onPick:e})=>l(`div`,{class:`cf-picker cf-emoji`,children:Zn.map(t=>u(`div`,{class:`cf-emoji__group`,children:[l(`div`,{class:`cf-emoji__label`,children:t.name}),l(`div`,{class:`cf-emoji__grid`,children:t.emojis.map((t,n)=>l(`button`,{type:`button`,class:`cf-emoji__btn`,onClick:()=>e(t),"aria-label":t,children:t},n))})]},t.name))}),Ui=({onSearch:e,onPick:t})=>{let n=lr(),[i,a]=s(``),[o,c]=s([]),[d,f]=s(!0);return r(()=>{let t=!0;f(!0);let n=setTimeout(()=>{e(i).then(e=>t&&(c(e),f(!1))).catch(()=>t&&(c([]),f(!1)))},300);return()=>{t=!1,clearTimeout(n)}},[i,e]),u(`div`,{class:`cf-picker cf-gif`,children:[l(`input`,{class:`cf-gif__search`,placeholder:n.searchGifs,value:i,"aria-label":n.searchGifs,onInput:e=>a(e.target.value)}),l(`div`,{class:`cf-gif__grid`,children:d?l(`div`,{class:`cf-gif__hint`,children:n.searchingGifs}):o.length===0?l(`div`,{class:`cf-gif__hint`,children:n.noGifs}):o.map(e=>l(`button`,{type:`button`,class:`cf-gif__item`,onClick:()=>t(e.url),"aria-label":e.alt,children:l(`img`,{src:e.preview,alt:e.alt,loading:`lazy`})},e.id))}),l(`div`,{class:`cf-gif__powered`,children:`via Tenor`})]})},Wi=e=>e===`listening`||e===`hearing`,Gi=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``}},Ki=({muted:e,listening:t,micLevel:n,onToggleMute:r})=>l(`button`,{type:`button`,class:`cf-call-btn ${e?`is-muted`:``} ${t?`is-listening`:``} ${t&&n>=.004?`is-hot`:``}`,"aria-label":e?`Unmute microphone`:`Mute microphone`,"aria-pressed":e,onClick:r,style:t?{"--cf-wave":String(Math.max(.2,Math.min(1,n*6)))}:void 0,children:l(e?br:yr,{})}),qi=({audioDevices:e,selectedAudioDeviceId:t,onSelectAudioDevice:n})=>{let[a,c]=s(!1),[d,f]=s(null),p=o(null);r(()=>{if(!a)return;let e=e=>{p.current&&!e.composedPath().includes(p.current)&&c(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[a]),i(()=>{if(!a){f(null);return}let e=p.current;if(!e)return;let t=new DOMRect(0,0,window.innerWidth,window.innerHeight);for(let n=e.parentElement;n;n=n.parentElement){let e=getComputedStyle(n);if(e.overflow!==`visible`||e.overflowY!==`visible`){t=n.getBoundingClientRect();break}}let n=e.getBoundingClientRect(),r=t.bottom-n.bottom-16,i=n.top-t.top-16,o=i>r;f({up:o,maxHeight:Math.max(72,Math.floor(o?i:r))})},[a]);let m=[{deviceId:``,label:`Default microphone`},...e];return u(`div`,{class:`cf-call-more`,ref:p,children:[l(`button`,{type:`button`,class:`cf-call-btn cf-call-btn--microphones`,"aria-label":`Choose microphone`,"aria-expanded":a,onClick:()=>c(e=>!e),children:l(_r,{})}),a&&u(`div`,{class:`cf-call-menu${d?.up?` cf-call-menu--up`:``}`,role:`menu`,style:d?{maxHeight:`${d.maxHeight}px`}:{visibility:`hidden`},children:[l(`div`,{class:`cf-call-menu__label`,children:`Microphone`}),m.map(e=>u(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":e.deviceId===t,class:`cf-call-menu__item ${e.deviceId===t?`is-active`:``}`,onClick:()=>{n(e.deviceId),c(!1)},children:[e.deviceId===t?l(Pr,{}):l(`span`,{class:`cf-call-menu__spacer`}),l(`span`,{children:e.label})]},e.deviceId))]})]})},Ji=({voiceState:e,muted:t,onToggleMute:n,onEndCall:r,onTalkNow:i,showTalkNow:a,micLevel:o,theaterMode:s,onToggleTheater:c,onMinimize:d,audioDevices:f,selectedAudioDeviceId:p,onSelectAudioDevice:m})=>u(`div`,{class:`cf-call-controls`,children:[l(Ki,{muted:t,listening:Wi(e)&&!t,micLevel:o,onToggleMute:n}),l(qi,{audioDevices:f,selectedAudioDeviceId:p,onSelectAudioDevice:m}),a&&l(`button`,{type:`button`,class:`cf-call-btn cf-call-btn--talk`,"aria-label":`Talk now`,onClick:i,children:l(yr,{})}),l(`button`,{type:`button`,class:`cf-call-btn`,"aria-label":s?`Exit expanded view`:`Expand view`,"aria-pressed":s,onClick:c,children:l(s?Wr:Ur,{})}),l(`button`,{type:`button`,class:`cf-call-btn`,"aria-label":`Minimize voice chat`,onClick:d,children:l(Gr,{})}),l(`button`,{type:`button`,class:`cf-call-btn cf-call-btn--end`,"aria-label":`End voice chat`,onClick:r,children:l(zr,{})})]}),Yi=({persona:e,voiceState:t,muted:n,onToggleMute:r,onEndCall:i,micLevel:a,onExpand:o})=>{let s=e=>e.stopPropagation(),c=e?.assistantMediaUrl?.trim()||e?.agentAvatarUrl?.trim()||``,d=e?.assistantMediaKind===`video`&&!!c,f=e?.agentName||`Assistant`;return u(`div`,{class:[`cf-floating-call-card`,Wi(t)&&!n?`is-listening`:``,t===`speaking`?`is-speaking`:``,t===`processing`||t===`connecting`?`is-thinking`:``,n?`is-muted`:``].filter(Boolean).join(` `),style:Wi(t)&&!n?{"--cf-listen":String(Math.max(.18,Math.min(1,a*8)))}:void 0,role:`button`,tabIndex:0,"aria-label":`Reopen voice chat with ${f}`,onClick:o,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())},children:[l(`div`,{class:`cf-floating-call-card__media`,"aria-hidden":`true`,children:c?d?l(`video`,{src:c,muted:!0,loop:!0,playsInline:!0,autoPlay:!0}):l(`img`,{src:c,alt:``}):u(`div`,{class:`cf-floating-call-card__avatar${ri(e)}`,children:[l(`span`,{children:ai(e)}),l(`span`,{class:`cf-floating-call-card__eye cf-floating-call-card__eye--left`}),l(`span`,{class:`cf-floating-call-card__eye cf-floating-call-card__eye--right`}),l(`span`,{class:`cf-floating-call-card__mouth`})]})}),l(`div`,{class:`cf-floating-call-card__shade`,"aria-hidden":`true`}),l(`span`,{class:`cf-floating-call-card__status`,role:`status`,"aria-live":`polite`,children:Gi(t)}),u(`div`,{class:`cf-floating-call-card__controls`,onClick:s,onKeyDown:s,role:`presentation`,children:[l(Ki,{muted:n,listening:Wi(t)&&!n,micLevel:a,onToggleMute:r}),l(`button`,{type:`button`,class:`cf-call-btn cf-call-btn--restore`,"aria-label":`Restore voice chat`,onClick:e=>{s(e),o()},children:l(Kr,{})}),l(`button`,{type:`button`,class:`cf-call-btn cf-call-btn--end`,"aria-label":`End voice chat`,onClick:e=>{s(e),i()},children:l(zr,{})})]})]})},Xi=(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 Gi(e)}},Zi=({draftStore:e,onSend:t,onSendGif:n,onTyping:i,disabled:a,allowVoice:f,onTranscribe:p,gifEnabled:m,onSearchGifs:h,allowAttach:g,analyzeAttachments:_=!0,onUpload:v,voiceStartSignal:y=0,onVoiceStateChange:b,onPreviewAttachment:x})=>{let S=lr(),[C,w]=s(()=>e.value),T=t=>{let n=typeof t==`function`?t(C):t;e.value=n,w(n)},[E,D]=s(!1),[O,k]=s(!1),[A,j]=s(`idle`),[M,N]=s(`none`),[P,F]=s([]),I=o([]);I.current=P;let L=o(0),[R,ee]=s(!1),[z,B]=s(!1),[V,H]=s(``),U=o(null),te=o(null),W=o(null),G=o(0),K=o(null),q=o(void 0),J=e=>{j(e),b?.(e)},ne=()=>{q.current&&window.clearTimeout(q.current),q.current=void 0};r(()=>{let e=U.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,110)}px`)},[C]),r(()=>()=>{for(let e of I.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl)},[]);let Y=e=>{F(t=>{let n=t.find(t=>t.key===e);return n?.previewUrl&&URL.revokeObjectURL(n.previewUrl),t.filter(t=>t.key!==e)})},re=()=>F([]);r(()=>{if(M===`none`)return;let e=e=>{te.current&&!e.composedPath().includes(te.current)&&N(`none`)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[M]);let ie=e=>N(t=>t===e?`none`:e),ae=e=>{let t=U.current;if(!t){T(t=>t+e);return}let n=t.selectionStart??C.length,r=t.selectionEnd??C.length;T(C.slice(0,n)+e+C.slice(r)),requestAnimationFrame(()=>{t.focus();let r=n+e.length;t.setSelectionRange(r,r)})},oe=e=>{N(`none`),n(e)},se=async e=>{if(e.length===0)return;H(``);let t=G.current,n=5-I.current.length-L.current;if(n<=0){H(Q(S.attachLimit,{count:`5`}));return}let r=e.slice(0,n);L.current+=r.length,ee(!0);for(let e of r){if(t!==G.current)break;try{await ce(e,t)}finally{t===G.current&&(--L.current,ee(L.current>0))}}t===G.current&&e.length>r.length&&H(Q(S.attachLimit,{count:`5`}))},ce=async(e,t)=>{if(e.size>5242880){H(S.attachTooLarge);return}if(!v){H(S.attachFailed);return}try{let n=await Vi(e);if(t!==G.current)return;let r=await v(n,e.type||`application/octet-stream`,e.name,_);if(t!==G.current)return;let i={key:`${r.id||e.name}-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,id:r.id,analysisFailed:r.analysisFailed,name:e.name,text:r.text,mimeType:e.type||`application/octet-stream`,size:e.size,previewUrl:e.type.startsWith(`image/`)?URL.createObjectURL(e):void 0,file:e};F(e=>[...e,i])}catch(e){if(t!==G.current)return;e instanceof d&&e.status===413?H(S.attachTooLarge):e instanceof d&&[400,415,503].includes(e.status)?H(e.message):H(S.attachFailed)}},le=async e=>{let t=e.target,n=Array.from(t.files??[]);t.value=``,await se(n)},ue=()=>{G.current+=1,L.current=0,ee(!1),H(``)},de=(!!C.trim()||P.length>0)&&!a&&!R&&!O,fe=()=>{de&&(t(C,P.length>0?{attachments:P.map(e=>({id:e.id,name:e.name,text:e.text,file:e.file}))}:void 0),i?.(!1),T(``),re(),H(``))},pe=e=>{let n=e.trim();if(!n||a){J(`misunderstood`);return}let r=C.trim();t(r?`${r} ${n}`:n),i?.(!1),T(``),re(),H(``),J(`idle`)},me=e=>{if(e.key===`Enter`&&!e.shiftKey){if(a)return;e.preventDefault(),fe()}else e.key===`Escape`&&M!==`none`&&(e.preventDefault(),e.stopPropagation(),N(`none`))},he=()=>{ne(),K.current?.stop(`dictation-ended`),K.current=null,D(!1),k(!1)},X=async()=>{let e=K.current;if(e){let{mic:t,processing:n}=e.snapshot;t===`hearing`||n?e.finishTurn():(he(),J(`idle`));return}let t=typeof navigator<`u`&&(navigator.languages?.[0]||navigator.language)||void 0;J(`connecting`);let n=new Ln({transcribe:async({audio:e,mimeType:n,durationSeconds:r})=>p(await Vi(e),n,t,r),listener:{state:({mic:e,processing:t,reason:r})=>{if(K.current===n){if(e===`unavailable`){if(r===`permission-denied`||r===`unsupported`||r===`no-device`||r===`error`){he(),J(`denied`);return}J(`unavailable`);return}D(e===`listening`||e===`hearing`),k(t),e===`starting`?J(`connecting`):t&&e!==`hearing`?J(`processing`):e===`hearing`?J(`hearing`):e===`listening`&&J(`listening`)}},speechStart:()=>ne(),turn:e=>{K.current===n&&(he(),pe(e.text))},noise:e=>{K.current===n&&(he(),J(e.reason===`transcribe-failed`?`misunderstood`:`noise`))}}});K.current=n,q.current=window.setTimeout(()=>{K.current===n&&(he(),J(`noise`))},15e3),await n.start()};return r(()=>{!y||!f||a||E||O||X()},[y]),r(()=>()=>{ne(),K.current?.stop(`unmounted`),K.current=null},[]),u(`div`,{class:`cf-composer ${z?`is-dragging`:``}`,ref:te,onDragEnter:e=>{g&&(e.preventDefault(),B(!0))},onDragOver:e=>{g&&e.preventDefault()},onDragLeave:e=>{e.currentTarget===e.target&&B(!1)},onDrop:e=>{g&&(e.preventDefault(),B(!1),se(Array.from(e.dataTransfer?.files??[])))},children:[M===`emoji`&&l(Hi,{onPick:ae}),M===`gif`&&l(Ui,{onSearch:h,onPick:oe}),(P.length>0||R||V)&&u(`div`,{class:`cf-attach-row`,role:`list`,"aria-label":S.attachedFiles,children:[P.map(e=>u(`span`,{class:`cf-attach-chip`,role:`listitem`,title:e.name,children:[u(`button`,{type:`button`,class:`cf-attach-open`,"aria-label":Q(S.attachOpen,{name:e.name}),disabled:!x,onClick:()=>x?.(e.file,e.name),children:[e.previewUrl?l(`img`,{class:`cf-attach-preview`,src:e.previewUrl,alt:``}):l(Rr,{}),u(`span`,{class:`cf-attach-copy`,children:[l(`span`,{children:e.name}),l(`small`,{children:e.analysisFailed?S.attachAnalysisFailed:`${Math.max(1,Math.ceil(e.size/1024))} KB`})]})]}),l(`button`,{type:`button`,class:`cf-attach-x`,"aria-label":Q(S.removeAttachmentNamed,{name:e.name}),onClick:()=>Y(e.key),children:l(jr,{})})]},e.key)),R&&u(`span`,{class:`cf-attach-status`,children:[l(`span`,{children:S.attaching}),l(`button`,{type:`button`,onClick:ue,children:S.cancel})]}),V&&!R&&l(`span`,{class:`cf-attach-status cf-attach-status--err`,children:V})]}),A!==`idle`&&u(`div`,{class:`cf-voice-state`,"aria-live":`polite`,children:[l(`span`,{class:`cf-voice-state__dot ${E?`is-live`:``}`}),Xi(A,S)]}),u(`div`,{class:`cf-composer__field`,children:[l(`button`,{type:`button`,class:`cf-iconbtn ${M===`emoji`?`is-active`:``}`,"aria-label":S.emoji,"aria-pressed":M===`emoji`,onClick:()=>ie(`emoji`),children:l(M===`emoji`?jr:Ar,{})}),m&&l(`button`,{type:`button`,class:`cf-iconbtn cf-gifbtn ${M===`gif`?`is-active`:``}`,"aria-label":S.gifs,"aria-pressed":M===`gif`,onClick:()=>ie(`gif`),children:l(`span`,{class:`cf-gif-label`,children:`GIF`})}),g&&u(c,{children:[l(`input`,{ref:W,type:`file`,class:`cf-file-input`,accept:`image/png,image/jpeg,image/webp,image/gif,application/pdf`,multiple:!0,onChange:le,tabIndex:-1,"aria-hidden":`true`}),l(`button`,{type:`button`,class:`cf-iconbtn`,"aria-label":S.attachFile,disabled:R,onClick:()=>W.current?.click(),children:l(Rr,{})})]}),l(`textarea`,{ref:U,class:`cf-textarea`,rows:1,placeholder:S.composerPlaceholder,value:C,"aria-label":S.composerPlaceholder,"aria-busy":a,onInput:e=>{let t=e.target.value;T(t),i?.(!!t.trim())},onPaste:e=>{let t=Array.from(e.clipboardData?.files??[]);!g||t.length===0||(e.preventDefault(),se(t))},onKeyDown:me}),f&&l(`button`,{type:`button`,class:`cf-iconbtn cf-mic ${E?`is-recording`:``}`,"aria-label":E?S.stopRecording:S.recordVoice,"aria-pressed":E,disabled:O||a,onClick:X,children:l(yr,{})}),l(`button`,{type:`button`,class:`cf-send`,"aria-label":S.send,disabled:!de,onClick:fe,children:l(vr,{})})]})]})},Qi=e=>e.replace(/\[[^\]]{0,60}\]/g,` `).replace(/\(([^)]{0,60})\)/g,(e,t)=>$i.has(t.trim().toLowerCase().replace(/[.!?,…]+$/,``).replace(/\s+/g,` `))?` `:e).replace(/\*[^*]{0,60}\*/g,` `).replace(/\s+/g,` `).trim(),$i=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`.split(`.`)),ea=/^\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?(?:\s*(?:-|–|—|to|-->)\s*\d{1,2}:\d{2}(?::\d{2})?(?:[.,]\d+)?)?$/,ta=e=>{let t=e.trim().toLowerCase().replace(/[()[\]*]/g,` `).replace(/[.!?,…]+$/,``).replace(/\s+/g,` `).trim();return!t||/^(?:sh+\s*)+$/.test(t)||ea.test(t)?!0:$i.has(t)},na=e=>{let 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},ra=e=>{let t=Qi(e);return ta(t)||na(t)?``:t},ia=(e,t)=>Dn(e,t);let aa=!0,oa=null;const sa=e=>{aa=e},ca=()=>{let e=typeof window<`u`?window.AudioContext??window.webkitAudioContext:void 0;if(!e)return null;if(!oa)try{oa=new e}catch{return null}return oa.state===`suspended`&&oa.resume(),oa},la=(e,t,n,r,i,a)=>{let o=e.createOscillator(),s=e.createGain();o.type=i,o.frequency.setValueAtTime(t,n),o.connect(s),s.connect(e.destination),s.gain.setValueAtTime(1e-4,n),s.gain.exponentialRampToValueAtTime(a,n+.012),s.gain.exponentialRampToValueAtTime(1e-4,n+r),o.start(n),o.stop(n+r+.03)},ua=e=>{if(!aa)return;let t=ca();if(!t)return;let n=t.currentTime;try{e===`open`?(la(t,523,n,.12,`sine`,.05),la(t,784,n+.08,.16,`sine`,.05)):e===`send`?la(t,660,n,.08,`triangle`,.04):e===`receive`&&(la(t,880,n,.1,`sine`,.045),la(t,1175,n+.09,.14,`sine`,.045))}catch{}},da=[`audio/webm;codecs=opus`,`audio/webm`,`audio/ogg;codecs=opus`,`audio/ogg`],fa=()=>{if(typeof navigator>`u`||!navigator.mediaDevices?.getSupportedConstraints)return{};try{return navigator.mediaDevices.getSupportedConstraints()}catch{return{}}},pa=(e=``,t=fa())=>{let n={...e?{deviceId:{exact:e}}:{}};return t.echoCancellation&&(n.echoCancellation={ideal:!0}),t.noiseSuppression&&(n.noiseSuppression={ideal:!0}),t.autoGainControl&&(n.autoGainControl={ideal:!0}),t.channelCount&&(n.channelCount={ideal:1}),t.voiceIsolation&&(n.voiceIsolation={ideal:!0}),n},ma=(e={})=>{let t=Math.max(2,e.calibrationSamples??6),n=Math.max(t,e.ambientWindowSamples??72),r=Math.min(.5,Math.max(0,e.ambientPercentile??.2)),i=Math.min(1,Math.max(.01,e.smoothing??.22)),a=Math.max(2**-52,e.minimumNoiseFloor??5e-4),o=Math.max(1.1,e.speechToNoiseRatio??2.7),s=Math.min(o,Math.max(1,e.quietToNoiseRatio??1.55)),c=Math.max(250,e.minimumEndSilenceMs??650),l=Math.max(c,e.maximumEndSilenceMs??1100),u=[],d=a,f=d*o,p=0;return{observe:e=>{let m=Number.isFinite(e)?Math.max(0,e):0;if(u.length<t||m<=f){u.push(m),u.length>n&&u.shift();let e=[...u].sort((e,t)=>e-t),t=Math.min(e.length-1,Math.floor((e.length-1)*r)),o=Math.max(a,e[t]??a);d+=(o-d)*i}f=d*o;let h=d*s,g=u.length>=t,_=g&&m>=f;_&&(p=Math.max(p,m/Math.max(d,a)));let v=Math.min(1,Math.max(0,(p-o)/o)),y=Math.round(l-(l-c)*v);return{speech:_,quiet:g&&m<=h,calibrated:g,noiseFloor:d,speechThreshold:f,quietThreshold:h,endOfSpeechDelayMs:y}},reset:()=>{u=[],d=a,f=d*o,p=0}}},ha=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result??``).split(`,`)[1]??``),r.onerror=()=>n(r.error),r.readAsDataURL(e)}),ga=e=>{let t=globalThis.MediaRecorder;if(typeof t?.isTypeSupported==`function`){for(let n of da)if(t.isTypeSupported(n))try{return new t(e,{mimeType:n})}catch{}}return new t(e)},_a=e=>{if(!(!e||e.state!==`recording`)){try{e.requestData()}catch{}e.stop()}},va=(e,t)=>e?.status===429?t.errorRateLimit:t.errorGeneric,ya=()=>typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now(),ba=(e,t)=>{let n=ya(),r={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:r})),r},xa=/!?\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,Sa=/https?:\/\/[^\s)]+/g,Ca=e=>On(e).replace(xa,`$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(Sa,e=>e.replace(/^https?:\/\//,``).replace(/^www\./,``).replace(/\/$/,``)).replace(/[ \t]+\n/g,`
168
168
  `).replace(/\n{3,}/g,`
169
169
 
170
- `).replace(/[ \t]{2,}/g,` `).trim(),Ca=(e,t)=>Sa(On(e,t)),wa=e=>e.type===`visualization`,Ta=e=>{let t=!!e.visualization,n=(e.artifacts??[]).some(wa);if(!t&&!n)return e;let{visualization:r,artifacts:i,...a}=e,o=(i??[]).filter(e=>!wa(e)),s=r?.title??(i??[]).find(wa)?.visualization?.title??e.resultExpired?.title;return{...a,...o.length>0?{artifacts:o}:{},resultExpired:s?{title:s}:{}}},Ea=e=>e.map(Ta),Da=(e,t=Date.now())=>{let n=e.visualization?.explanation?.aiExplanation;if(!e.visualization?.explanation||!n||n.status!==`pending`)return e;let r=e.createdAt?Date.parse(e.createdAt):NaN;return Number.isFinite(r)&&t-r<45e3?e:{...e,visualization:{...e.visualization,explanation:{...e.visualization.explanation,aiExplanation:{...n,status:`failed`,retryAvailable:!1}}}}},Oa=e=>e instanceof DOMException&&(e.name===`QuotaExceededError`||e.name===`NS_ERROR_DOM_QUOTA_REACHED`),ka=(e,t,n,r)=>{let i=r;for(let r=0;r<4&&i.length>0;r+=1)try{return e.setItem(t,n(i)),!0}catch(e){if(!Oa(e))return!1;i=i.slice(Math.ceil(i.length/2))}try{e.removeItem(t)}catch{}return!1},Aa=(e,t)=>{if(e)try{let n=[];for(let r=0;r<e.length;r+=1){let i=e.key(r);i?.startsWith(t)&&n.push(i)}for(let t of n){let n=e.getItem(t);if(!n)continue;let r=JSON.parse(n);if(!Array.isArray(r.messages))continue;let i=Ea(r.messages);i.some((e,t)=>e!==r.messages[t])&&e.setItem(t,JSON.stringify({...r,messages:i}))}}catch{}},ja=(e,t=()=>Date.now())=>{let n=null,r=null,i=-1/0,a=()=>{r!==null&&(clearTimeout(r),r=null);let e=n;n=null,e&&(i=t(),e())};return{schedule:o=>{if(n=o,r!==null)return;let s=e-(t()-i);s<=0?a():r=setTimeout(a,s)},flush:a,cancel:()=>{r!==null&&clearTimeout(r),r=null,n=null}}},Ma=()=>typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.round(Math.random()*1e9)}`,Na=(e,t)=>{typeof console>`u`||console.warn(`[centrinfo-widget] ${e}`,t??{})},Pa=(e,t,n,r,i=1,a,o=!1,s,c)=>{e.current?.pause(),e.current=null,typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel(),t.current=null;let l=()=>{let e=a?.trim();if(!o||!e||typeof window>`u`||!(`speechSynthesis`in window)||typeof SpeechSynthesisUtterance>`u`)return!1;let n=new SpeechSynthesisUtterance(e),r=!1,l=()=>{r||(r=!0,t.current===n&&(t.current=null,c?.()))};return n.rate=i,n.lang=typeof navigator<`u`&&(navigator.languages?.[0]||navigator.language)||`en-US`,n.onend=l,n.onerror=l,t.current=n,s?.(),window.speechSynthesis.cancel(),window.speechSynthesis.speak(n),!0};if(!n||typeof Audio>`u`)return l();let u=new Audio(`data:${r||`audio/mpeg`};base64,${n}`),d=!1,f=!1,p=()=>{d||(d=!0,e.current===u&&(e.current=null,c?.()))},m=()=>{if(!d){if(f||e.current!==u){p();return}d=!0,e.current=null,l()||c?.()}};return u.playbackRate=i,u.onended=p,u.onerror=m,e.current=u,u.play().then(()=>{if(!d){if(e.current!==u){p();return}f=!0,s?.(Number.isFinite(u.duration)?u.duration*1e3:void 0)}}).catch(m),!0},Fa=e=>{try{return e===`none`?null:e===`session`?sessionStorage:localStorage}catch{return null}},Ia=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)},La=e=>{try{let t=e?.split(`.`)[1];if(!t)return;let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=JSON.parse(atob(n.padEnd(Math.ceil(n.length/4)*4,`=`)));for(let e of[`sub`,`external_user_id`,`user_id`]){let t=r[e];if(typeof t==`string`&&t.trim())return t.trim()}}catch{}},Ra=e=>{let t=e.user?.externalId?.trim()||e.user?.userId?.trim()||e.user?.email?.trim().toLowerCase()||La(e.identityToken)||(e.identityToken||e.getIdentityToken?`authenticated`:`anonymous`);return`${e.token.slice(0,12)}:${e.chatSurface}:${Ia(t)}`},za=e=>`${e.chatSurface}:${Ma()}`,Ba=e=>e.slice(0,12),Va=e=>`centrinfo:session:${e}`,Ha=e=>`centrinfo:visitor:${e}`,Ua=(e,t)=>`centrinfo:chat:${e}:${t}`,Wa=e=>`centrinfo:history:${e}`,Ga=720*60*60*1e3,Ka=(e,t)=>{try{return JSON.parse(e?.getItem(Ha(t))||`{}`)}catch{return{}}},qa=(e,t,n)=>{if(!e)return za(n);try{let r=Va(t),i=e.getItem(r);if(i)return i;let a=za(n);return e.setItem(r,a),a}catch{return za(n)}},Ja=(e,t,n)=>{if(!e)return{};try{let r=e.getItem(Ua(t,n));return r?JSON.parse(r):{}}catch{return{}}},Ya=(e,t,n)=>{let{ts:r,expiresAt:i,messages:a}=Ja(e,t,n);return!Array.isArray(a)||typeof i==`number`&&Date.now()>i||typeof r==`number`&&Date.now()-r>Ga?[]:Ea(a)},Xa=(e,t,n)=>{let{ts:r,expiresAt:i,messages:a,ended:o}=Ja(e,t,n);return!Array.isArray(a)||a.length===0||typeof i==`number`&&Date.now()>i||typeof r==`number`&&Date.now()-r>Ga?!1:o===!0||typeof r==`number`&&Date.now()-r>864e5},Za=e=>Number.isFinite(e??NaN)?Math.max(5,Math.min(200,Math.round(e))):50,Qa=e=>Number.isFinite(e??NaN)?Math.max(1,Math.min(365,Math.round(e)))*24*60*60*1e3:Ga,$a=(e,t,n,r,i,a,o,s)=>{if(e)try{if(!a){e.removeItem(Ua(t,n));return}let c=r.filter(e=>!e.pending).slice(-o);if(c.length===0)return;let l=Date.now();ka(e,Ua(t,n),e=>JSON.stringify({ts:l,expiresAt:l+s,messages:Ea(e),ended:i}),c)}catch{}},eo=(e,t)=>{if(!e)return[];try{let n=e.getItem(Wa(t)),r=n?JSON.parse(n):[];return Array.isArray(r)?r:[]}catch{return[]}},to=(e,t,n)=>{if(e)try{e.setItem(Wa(t),JSON.stringify(n.slice(0,20)))}catch{}},no=(e,t)=>{if(e)try{let n=`centrinfo:chat:${t}:`,r=new Set([Va(t),Ha(t),Wa(t)]),i=[];for(let t=0;t<e.length;t++){let a=e.key(t);a&&(r.has(a)||a.startsWith(n))&&i.push(a)}i.forEach(t=>e.removeItem(t))}catch{}},ro=e=>{let t=(e.find(e=>e.role===`user`&&e.content.trim())?.content||e.find(e=>e.content.trim())?.content||``).trim().replace(/\s+/g,` `);return t.length>60?t.slice(0,60)+`…`:t||`Conversation`},io=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}),ao=e=>(e??[]).find(e=>e.category===`support`&&e.enabled&&e.readiness!==`unavailable`&&(e.liveHandoff??e.id===`public_contact_support`)),oo=(e,t)=>{if(t===`ai`)for(let t=e.length-1;t>=0;t--){let n=e[t];if(n){if(n.reconnectOffer)return;if(n.liveEventType===`ai_handback`)return n.offerReconnect?n.id:void 0}}},so=(e,n,i=!0)=>{let a=o(Fa(n.persistence)).current,c=Ra(n),l=o(qa(a,c,n)),u=o(null),d=o(null),f=o(null),p=o(null),m=o(null),h=o(null),g=o(new Map),_=o(!1),v=o(void 0),y=o(null),b=o({}),x=o({}),[S,C]=s(null),[w,T]=s(()=>Ya(a,c,l.current)),E=o(null);E.current||(E.current=ja(1e3));let D=o(w.length>0),O=o(w.some(e=>e.role===`user`)),[k,A]=s(!1),[j,M]=s(!1),[N,P]=s({status:`idle`}),F=o({}),[I,L]=s(()=>Xa(a,c,l.current)),[R,ee]=s(()=>Ka(a,c)),[z,B]=s(()=>eo(a,c)),[V,H]=s(null),[te,ne]=s([]),[U,W]=s(`ai`),[G,K]=s(void 0),[q,J]=s(void 0),Y=o(new Date().toISOString()),re=o(void 0),ie=o(!1),ae=o(0),oe=o(R);r(()=>{oe.current=R},[R]);let se=S?.memoryEnabled!==!1,ce=Za(S?.memoryMessageCap),le=Qa(S?.memoryRetentionDays),ue=t(()=>{u.current?.abort(),E.current?.cancel(),no(a,c),no(a,Ba(n.token));let e=za(n);l.current=e;try{a?.setItem(Va(c),e)}catch{}H(null),ne([]),L(!1),B([]),ee({}),W(`ai`),K(void 0),J(void 0),Y.current=new Date().toISOString(),T(S?[{id:Ma(),role:`assistant`,content:S.greeting,availableActions:S.availableActions,actions:S.actions}]:[])},[a,c,n.token,S]),de=t(e=>{try{a?.setItem(Ha(c),JSON.stringify(e))}catch{}},[a,c]),fe=t(t=>{let n=(t.email??``).trim().toLowerCase(),r=(oe.current.email??``).trim().toLowerCase();n&&r&&n!==r&&ue();let i={};t.email?.trim()&&(i.email=t.email.trim()),t.phone?.trim()&&(i.phone=t.phone.trim());let a=[t.firstName,t.lastName].filter(e=>!!e?.trim()).join(` `).trim()||t.name?.trim()||``;a&&(i.name=a),Object.keys(i).length>0&&ee(e=>{let t={...i,...e};return de(t),t}),e.identify(l.current,t).catch(()=>{})},[e,de,ue]),pe=o(0),me=t(e=>{pe.current=Date.now(),C(e),T(t=>{if(t.length===0)return[{id:Ma(),role:`assistant`,content:e.greeting,availableActions:e.availableActions,actions:e.actions}];let n=t.some(e=>e.role===`user`),r=t[0];return!n&&r?.role===`assistant`?[{...r,content:e.greeting,availableActions:e.availableActions,actions:e.actions},...t.slice(1)]:t})},[]);r(()=>{if(S?.memoryEnabled===!1){E.current?.cancel();try{a?.removeItem(Ua(c,l.current))}catch{}to(a,c,[]),B([]),H(null),ne([]),T(e=>D.current?(D.current=!1,S?[{id:Ma(),role:`assistant`,content:S.greeting,availableActions:S.availableActions,actions:S.actions}]:[]):e)}},[S,a,c]);let he=t(async()=>{me(await e.bootstrap())},[me,e]);r(()=>{let t=!0,n=e=>e.messages.map(e=>Da({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(e=>{if(!t||e.conversations.length===0)return;let r=e.conversations.map(e=>({sessionId:e.sessionId,ts:Date.parse(e.lastSeenAt)||Date.now(),title:e.title,ended:e.ended}));for(let t of e.conversations)$a(a,c,t.sessionId,n(t),t.ended,!0,ce,le);to(a,c,r),B(r);let i=e.conversations.find(t=>t.sessionId===e.activeSessionId);if(!i||O.current)return;let o=n(i);l.current=i.sessionId,D.current=o.length>0;try{a?.setItem(Va(c),i.sessionId)}catch{}let s=o[o.length-1]?.createdAt;s&&(Y.current=s),L(i.ended),T(o)}).catch(()=>{}),()=>{t=!1}},[ce,le,c,a,e]),r(()=>{let t=!0;return pe.current=Date.now(),e.bootstrap().then(e=>{t&&me(e)}),n.user&&fe(n.user),()=>{t=!1}},[me,e]),r(()=>{let e=n.configRefreshSeconds;if(!i||e<=0||typeof window>`u`)return;let t=!0,r=!1,a=Math.max(10,e)*1e3,o=()=>typeof document>`u`||document.visibilityState!==`hidden`,s=async()=>{if(!(!t||r||!o())){r=!0;try{await he()}catch{}finally{r=!1}}};Date.now()-pe.current>=a&&s();let c=window.setInterval(s,a),l=()=>void s(),u=()=>void s();return window.addEventListener(`focus`,l),document?.addEventListener?.(`visibilitychange`,u),()=>{t=!1,window.clearInterval(c),window.removeEventListener(`focus`,l),document?.removeEventListener?.(`visibilitychange`,u)}},[i,n.configRefreshSeconds,he]),r(()=>{let e=l.current;E.current.schedule(()=>$a(a,c,e,w,I,se,ce,le))},[w,I,a,c,se,ce,le]),r(()=>{let e=E.current,t=()=>{document.visibilityState===`hidden`&&e.flush()};return document.addEventListener(`visibilitychange`,t),window.addEventListener(`pagehide`,e.flush),()=>{document.removeEventListener(`visibilitychange`,t),window.removeEventListener(`pagehide`,e.flush),e.flush()}},[]),r(()=>{Aa(a,`centrinfo:chat:`)},[a]),r(()=>{if(!i||I||V)return;let t=()=>{document.visibilityState===`visible`&&e.presence(l.current)};t();let n=window.setInterval(t,1e4);return document.addEventListener(`visibilitychange`,t),()=>{window.clearInterval(n),document.removeEventListener(`visibilitychange`,t)}},[i,I,e,V]),r(()=>{if(!i||I||V)return;let t=!0,r=!1,a=0,o,s=()=>{o!==void 0&&window.clearTimeout(o),!(!t||document.hidden)&&(o=window.setTimeout(()=>{c()},Math.min(3e4,2200*2**a)))},c=async()=>{if(!(r||document.hidden||!t)){r=!0;try{let r=await e.liveEvents(l.current,Y.current);if(!t)return;if(a=0,W(r.mode),K(r.assignedAgentName||void 0),J(r.agentTyping?r.agentTypingName||r.assignedAgentName||`Agent`:void 0),r.conversationEnded){L(!0),W(`ai`),K(void 0),J(void 0),T(e=>e.some(e=>e.id===`live:conversation-ended`)?e:[...e,{id:`live:conversation-ended`,role:`system`,content:n.strings.conversationEnded,liveEventType:`conversation_ended`,createdAt:new Date().toISOString()}]);return}if(r.events.length>0){let e=Y.current,t=Date.parse(e),n=r.events.map(n=>{let r=Date.parse(n.createdAt);return Number.isFinite(r)&&r>t&&(t=r,e=n.createdAt),io(n)});Y.current=e,T(e=>{let t=new Set(e.map(e=>e.id)),r=n.filter(e=>!t.has(e.id));return r.length>0?[...e,...r]:e}),n.some(e=>e.role===`assistant`)&&la(`receive`)}}catch{a=Math.min(a+1,4)}finally{r=!1,s()}}},u=()=>{document.hidden?o!==void 0&&window.clearTimeout(o):c()};return document.addEventListener(`visibilitychange`,u),document.hidden||c(),()=>{t=!1,o!==void 0&&window.clearTimeout(o),document.removeEventListener(`visibilitychange`,u)}},[i,n.strings.conversationEnded,e,I,V]),r(()=>{if(!se){to(a,c,[]),B(e=>e.length>0?[]:e);return}w.some(e=>e.role===`user`)&&B(e=>{let t=l.current,n=[{sessionId:t,ts:Date.now(),title:ro(w),ended:I},...e.filter(e=>e.sessionId!==t)];return to(a,c,n),n.slice(0,20)})},[w,I,a,c,se]);let X=t((e,t)=>{T(n=>n.map(n=>n.id===e?{...n,...t}:n))},[]),ge=t(()=>{v.current!==void 0&&typeof window<`u`&&window.clearInterval(v.current),v.current=void 0},[]),_e=t((e,t)=>{ge(),delete b.current[e],y.current===e&&(y.current=null),X(e,{content:t,pending:!1,streaming:!1})},[ge,X]),ve=t((e,t,n)=>{let r=t.trim();if(!r||typeof window>`u`){_e(e,r);return}ge(),y.current=e;let i=r.match(/\S+\s*/g)??[r],a=n&&n>0?n:i.length*95,o=Math.max(28,Math.min(150,a/Math.max(i.length,1))),s=0;X(e,{content:``,pending:!1,streaming:!0}),v.current=window.setInterval(()=>{s+=1,X(e,{content:i.slice(0,s).join(``),pending:!1,streaming:s<i.length}),s>=i.length&&(ge(),delete b.current[e],y.current===e&&(y.current=null),X(e,{content:r,pending:!1,streaming:!1}))},o)},[ge,_e,X]),ye=t(()=>{let e=y.current;ge(),y.current=null;let t=b.current;b.current={};for(let[e,n]of Object.entries(t))X(e,{content:n,pending:!1,streaming:!1});e&&!(e in t)&&X(e,{pending:!1,streaming:!1})},[ge,X]),be=t(t=>{if(I||V||U===`ai`||typeof window>`u`)return;if(re.current!==void 0&&window.clearTimeout(re.current),!t){if(!ie.current)return;ie.current=!1,ae.current=0,e.typing(l.current,!1).catch(()=>{});return}let n=Date.now();(!ie.current||n-ae.current>2500)&&(ie.current=!0,ae.current=n,e.typing(l.current,!0).catch(()=>{})),re.current=window.setTimeout(()=>{ie.current&&(ie.current=!1,ae.current=0,e.typing(l.current,!1).catch(()=>{}))},1600)},[e,I,V,U]);r(()=>()=>{re.current!==void 0&&typeof window<`u`&&window.clearTimeout(re.current)},[]),r(()=>()=>ge(),[ge]);let xe=t((t,r,a={})=>{ye(),A(!0);let o=va(),s=!1,c=new AbortController;u.current=c;let f=!!(S?.allowVoiceInput&&S?.voiceOutputEnabled&&S.talkbackMode!==`text`),g=!!a.forceVoicePlayback,v=e=>{g&&P(t=>t.agentId===r?{status:e,agentId:r}:t)};g&&P({status:`answering`,agentId:r});let y={pending:new Map,nextSeq:0,highestSeq:-1,playing:!1,ended:!1,started:!1,stopped:!1,utterance:null},C=()=>{h.current===N&&(h.current=null),y.started&&(y.started=!1,M(!1),v(`done`))},w=()=>{y.stopped||y.started||(y.started=!0,ya(`voice-first-audio`,o),M(!0),v(`speaking`))},E=()=>typeof window<`u`&&`speechSynthesis`in window&&typeof SpeechSynthesisUtterance<`u`,D=()=>{p.current&&y.playing&&(p.current.pause(),p.current=null),y.utterance&&(m.current===y.utterance&&(m.current=null),y.utterance=null,E()&&window.speechSynthesis.cancel()),y.playing=!1},O=(e,t)=>{let n=e?.trim();if(!n||!E())return!1;let r=new SpeechSynthesisUtterance(n);return r.rate=S?.voiceSpeed??1,r.lang=typeof navigator<`u`&&(navigator.languages?.[0]||navigator.language)||`en-US`,r.onstart=w,r.onend=t,r.onerror=t,y.utterance=r,m.current=r,window.speechSynthesis.speak(r),_.current&&window.speechSynthesis.pause(),!0},k=()=>{for(;!y.stopped&&!y.playing;){let e=y.pending.get(y.nextSeq);if(!e&&y.ended&&y.pending.size>0&&(y.nextSeq=Math.min(...y.pending.keys()),e=y.pending.get(y.nextSeq)),!e){y.ended&&C();return}if(y.pending.delete(y.nextSeq),y.nextSeq+=1,j(e))return}},j=e=>{let t=!1,n=()=>{t||(t=!0,m.current===y.utterance&&(m.current=null),y.utterance=null,y.playing=!1,k())};if(!e.audioBase64||typeof Audio>`u`)return y.playing=O(e.text,n),y.playing;let r=new Audio(`data:${e.mimeType||`audio/mpeg`};base64,${e.audioBase64}`);r.playbackRate=S?.voiceSpeed??1,r.volume=_.current?.2:1,y.playing=!0,p.current=r;let i=!1,a=!1,o=()=>{t||a||(a=!0,p.current===r&&(p.current=null),!(!i&&!y.stopped&&O(e.text,n))&&n())};return r.onended=()=>{p.current===r&&(p.current=null),n()},r.onerror=o,r.play().then(()=>{i=!0,w()}).catch(o),!0},N=()=>{y.stopped=!0,y.pending.clear(),D(),C()};e.stream(t,l.current,{voicePlaybackRequested:!!a.forceVoicePlayback,clientMessageId:a.clientMessageId,attachmentId:a.attachmentId,attachmentIds:a.attachmentIds,signal:c.signal,onChunk:e=>{e&&!s&&(s=!0,ya(`data-first-chunk`,o)),a.forceVoicePlayback&&e&&(x.current[r]=!0),T(t=>t.map(t=>t.id===r?{...t,content:t.content+e,pending:!1,streaming:!0}:t))},onTextReady:()=>{T(e=>e.map(e=>e.id===r?{...e,pending:!1,streaming:!1}:e))},onReset:()=>{T(e=>e.map(e=>e.id===r?{...e,content:``,pending:!0,streaming:!1}:e)),y.pending.clear(),y.nextSeq=y.highestSeq+1,D()},onAudioSegment:e=>{!g||y.stopped||e.seq<y.nextSeq||y.pending.has(e.seq)||(h.current=N,y.highestSeq=Math.max(y.highestSeq,e.seq),y.pending.set(e.seq,e),k())}}).then(t=>{if(i&&!t.conversationEnded&&typeof document<`u`&&document.visibilityState===`visible`&&e.presence(l.current),t.liveMode&&(W(t.liveMode),K(t.assignedAgentName||void 0)),t.liveMode&&t.liveMode!==`ai`&&!t.answer.trim()){T(e=>e.filter(e=>e.id!==r)),v(`done`);return}let o=!!x.current[r];delete x.current[r];let s=!!(a.forceVoicePlayback&&f&&!t.liveAudio&&t.audioBase64&&t.answer.trim()&&!o);if(s&&(b.current[r]=t.answer),T(e=>e.map(e=>e.id===r?{...e,content:s?``:t.answer||e.content||n.strings.emptyReply,pending:!1,streaming:s,error:!1,retryText:void 0,sources:t.sources,suggestedReplies:t.suggestedReplies,availableActions:t.availableActions,actions:t.actions,selectedAction:t.selectedAction,handoffOffered:t.handoffOffered,requestedContactFields:t.requestedContactFields,visualization:t.visualization,artifacts:t.artifacts}:e)),la(`receive`),t.liveAudio?(y.ended=!0,k()):a.forceVoicePlayback&&!t.audioBase64&&Na(f?`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:S?.voiceOutputEnabled,talkbackMode:S?.talkbackMode,voiceProvider:S?.voiceProvider,hasAudioBase64:!!t.audioBase64}),a.forceVoicePlayback&&!t.liveAudio){let e=Pa(p,m,t.audioBase64,t.mimeType,S?.voiceSpeed??1,Ca(t.answer,t.visualization),!0,e=>{M(!0),v(`speaking`),s&&ve(r,t.answer,e)},()=>{M(!1),v(`done`),s&&_e(r,t.answer)});e||v(`done`),s&&!e&&_e(r,t.answer)}t.answer&&n.onMessage?.({role:`assistant`,content:t.answer}),t.handoffOffered&&n.onHandoff?.(),t.conversationEnded&&L(!0)}).catch(e=>{if(c.signal.aborted){y.stopped||N(),delete x.current[r],T(e=>e.flatMap(e=>e.id===r?e.content.trim()?[{...e,pending:!1,streaming:!1}]:[]:[e])),v(`done`);return}v(`failed`),delete x.current[r],X(r,{content:_a(e,n.strings),pending:!1,streaming:!1,error:!0,retryText:t})}).finally(()=>{ya(`data-complete`,o),delete x.current[r],u.current===c&&(A(!1),u.current=null,d.current?.agentId===r&&(d.current=null))})},[e,i,n,X,S?.allowVoiceInput,S?.talkbackMode,S?.voiceOutputEnabled,S?.voiceSpeed,ye]),Se=t((e,t={})=>{let r=e.trim(),{imageUrl:i,attachmentName:a,attachmentText:o,attachmentId:s,attachmentFile:c,forceVoicePlayback:l,userMessageId:f}=t,p=t.attachments??(a||s||o?[{id:s,name:a??``,text:o,file:c}]:[]);if(!r&&!i&&p.length===0||u.current&&!u.current.signal.aborted||I)return;O.current=!0;let m=r;for(let e of p){let t=e.name?` "${e.name}"`:``;e.text?m=`${m}\n\n[Attached file${t}]:\n${e.text}`.trim():e.id&&(m=`${m}\n\n[The visitor attached a file${t}. It is saved for staff, but its contents were not available to the AI. Do not claim to have inspected it.]`.trim())}!m&&i&&(m=i);let h=p.map(e=>({id:e.id,name:e.name})),_=p.flatMap(e=>e.id?[e.id]:[]),v={id:f||Ma(),role:`user`,content:r,imageUrl:i,attachments:h.length>0?h:void 0};p.forEach((e,t)=>{e.file&&(g.current.set(`${v.id}:${t}`,e.file),e.id&&g.current.set(e.id,e.file))});let y=Ma();T(e=>[...f&&e.some(e=>e.id===f)?e.map(e=>e.id===f?{...e,content:r,pending:!1,streaming:!1,imageUrl:i,attachments:v.attachments}:e):[...e,v],{id:y,role:`assistant`,content:``,pending:!0}]),la(`send`),n.onMessage?.({role:`user`,content:m}),F.current[y]=v.id,d.current={userId:v.id,agentId:y,text:r,backendText:m},xe(m,y,{forceVoicePlayback:l,clientMessageId:v.id,attachmentId:_[0],attachmentIds:_})},[I,n,xe]),Z=t((e,t,r,i,a)=>{let o=Ma();T(n=>[...n.filter(t=>t.id!==e.agentId&&(!i.userMessageId||t.id!==i.userMessageId)).map(n=>n.id===e.userId?{...n,content:t,pending:!1,streaming:!1}:n),{id:o,role:`assistant`,content:``,pending:!0}]),a&&n.onMessage?.({role:`user`,content:a}),F.current[o]=e.userId,d.current={userId:e.userId,agentId:o,text:t,backendText:r},xe(r,o,{forceVoicePlayback:i.forceVoicePlayback,clientMessageId:Ma()})},[n,xe]),Ce=t((e,t={})=>{let n=e.trim();if(!n||I)return;let r=u.current&&!u.current.signal.aborted?d.current:null,i=r??f.current;if(f.current=null,!i){Se(n,t);return}r&&u.current?.abort(),Z(i,`${i.text} ${n}`.replace(/\s+/g,` `).trim(),`${i.backendText}\n${n}`.trim(),t,n)},[I,Z,Se]),we=t(()=>{let e=u.current&&!u.current.signal.aborted?d.current:null;return e?(f.current=e,u.current?.abort(),!0):!1},[]),Te=t(()=>{let e=f.current;f.current=null,!(!e||I)&&Z(e,e.text,e.backendText,{forceVoicePlayback:!0})},[I,Z]),Ee=t(()=>u.current?.abort(),[]),De=t(e=>{_.current=e;let t=p.current;t&&(t.volume=e?.2:1),m.current&&typeof window<`u`&&`speechSynthesis`in window&&(e?window.speechSynthesis.pause():window.speechSynthesis.resume())},[]),Oe=t(()=>{h.current?.(),h.current=null,_.current=!1,ye(),P(e=>e.status===`speaking`||e.status===`answering`?{...e,status:`done`}:e),p.current?.pause(),p.current=null,typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel(),m.current=null,M(!1)},[ye]),ke=t(t=>{let n=Sa(t);if(!n)return Promise.resolve(!1);ye();let r=!!(S?.allowVoiceInput&&S?.voiceOutputEnabled&&S.talkbackMode!==`text`),i=(e,t)=>new Promise(r=>{let i=!1;Pa(p,m,e,t,S?.voiceSpeed??1,n,!0,()=>{i=!0,M(!0)},()=>{M(!1),r(i)})||(M(!1),r(!1))});return r?e.speak(n).then(e=>e.audioBase64?i(e.audioBase64,e.mimeType):(Na(`Talkback prompt TTS did not return provider audio.`,{providerReady:e.providerReady,message:e.message,voiceProvider:S?.voiceProvider,voiceOutputEnabled:S?.voiceOutputEnabled,talkbackMode:S?.talkbackMode}),i())).catch(e=>(Na(`Talkback prompt TTS request failed before audio playback.`,{error:e instanceof Error?e.message:String(e),voiceProvider:S?.voiceProvider,voiceOutputEnabled:S?.voiceOutputEnabled,talkbackMode:S?.talkbackMode}),i())):(Na(`Talkback prompt wanted voice, but the loaded widget token config has provider TTS disabled.`,{voiceOutputEnabled:S?.voiceOutputEnabled,talkbackMode:S?.talkbackMode,voiceProvider:S?.voiceProvider}),i())},[S?.allowVoiceInput,S?.talkbackMode,S?.voiceOutputEnabled,S?.voiceSpeed,ye,e]),Ae=t((e,t,n={})=>{if(k||I||!t)return;X(e,{content:``,pending:!0,streaming:!1,error:!1}),la(`send`);let r=w.findIndex(t=>t.id===e),i=r>0?w[r-1]:void 0;xe(t,e,{...n,clientMessageId:F.current[e]??(i?.role===`user`?i.id:void 0)})},[k,I,w,X,xe]),je=t((t,n,r)=>{X(t,{feedback:n});let i=w.findIndex(e=>e.id===t),a=i>=0?w[i]?.content:void 0,o;for(let e=i-1;e>=0;e--)if(w[e]?.role===`user`){o=w[e]?.content;break}e.sendFeedback({sessionId:l.current,messageId:t,rating:n,comment:r,question:o,answer:a}).catch(()=>{})},[e,X,w]),Me=t(async(t,r,i={},a)=>{n.onAction?.(t);let o=t===`public_contact_support`||t===`public_submit_inquiry`?{actionId:t}:{},s=await e.action(t,{sessionId:l.current,...r,...o},a),c={};return i.name?.trim()&&(c.name=i.name.trim()),i.email?.trim()&&(c.email=i.email.trim()),i.phone?.trim()&&(c.phone=i.phone.trim()),Object.keys(c).length>0&&(ee(e=>{let t={...e,...c};return de(t),t}),c.email&&t!==`contact`&&e.action(`contact`,{sessionId:l.current,...c}).catch(()=>{})),la(`receive`),s},[e,n,de]),Ne=t((t,n,r)=>e.confirmHostedBooking?.({sessionId:l.current,inquiryId:t,eventUri:n,inviteeUri:r})??Promise.resolve(void 0),[e]),Pe=t(e=>{let t=e.trim();t&&T(e=>e.some(e=>e.role===`assistant`&&e.content===t)?e:[...e,{id:Ma(),role:`assistant`,content:t}])},[]),Fe=t(()=>{let e=ao(S?.actions);return e?(T(t=>[...t,{id:Ma(),role:`assistant`,content:n.strings.reconnectPrompt,actions:[e],selectedAction:e.id,handoffOffered:!0,reconnectOffer:!0,createdAt:new Date().toISOString()}]),!0):!1},[n.strings.reconnectPrompt,S?.actions]),Ie=t(e=>{O.current=!0;let t=Ma();return T(n=>[...n,{id:t,role:`user`,content:e.trim(),pending:!0}]),t},[]),Le=t((e,t)=>{T(n=>n.map(n=>n.id===e?{...n,...t}:n))},[]),Re=t(e=>{T(t=>t.filter(t=>t.id!==e))},[]),ze=t(async(t,n=`widget`)=>{if(!e.sendExplanationFeedback)throw Error(`Explanation feedback is unavailable.`);await e.sendExplanationFeedback({...t,sessionId:l.current,surface:n})},[e]),Be=t((t=`widget`)=>{let n=e.fetchExplanation?.bind(e);if(!n)return;let r=e.retryExplanation?.bind(e),i=e=>e;return{poll:async(e,r)=>i(await n(e,l.current,t,r)),settled:(e,t)=>{t!==`not_requested`&&T(n=>n.map(n=>{let r=n.visualization?.explanation?.aiExplanation;return!r||(r.explanationId??n.visualization?.explanation?.explanationId)!==e||r.status===t?n:{...n,visualization:{...n.visualization,explanation:{...n.visualization.explanation,aiExplanation:{...r,status:t}}}}}))},...r?{retry:async e=>i(await r(e,l.current,t))}:{}}},[e]),Ve=t((t,n)=>{e.sendFeedback({sessionId:l.current,messageId:`__csat__`,rating:t,comment:n}).catch(()=>{})},[e]),He=t(async(t,n,r,i)=>{let a=va();try{if(typeof t!=`string`&&e.transcribeAudio)return await e.transcribeAudio(t,n,r,i);let a=typeof t==`string`?t:await ma(t);return await e.transcribe(a,n,r,i)}finally{ya(`voice-transcription`,a)}},[e]),Ue=t(async(t,n,r=0)=>{let i=g.current.get(`${t.id}:${r}`)??(n.id?g.current.get(n.id):void 0);if(i)return i;if(!n.id||!e.fetchAttachment)throw Error(`This file is no longer available.`);return e.fetchAttachment(n.id,l.current)},[e]),We=t((t,n,r,i)=>e.uploadAttachment?e.uploadAttachment(t,n,r,l.current,i):Promise.reject(Error(`File upload is unavailable`)),[e]),Ge=t(t=>e.searchGifs(t),[e]),Ke=t((t,n)=>e.demoSlots(t,n),[e]),qe=t(e=>Se(``,{imageUrl:e}),[Se]),Je=n.demo||!!n.gifApiKey,Ye=t(()=>{u.current?.abort(),L(!0),e.endConversation(l.current).catch(()=>{})},[e]),Xe=t(()=>{u.current?.abort();let e=za(n);l.current=e;try{a?.setItem(Va(c),e)}catch{}H(null),ne([]),L(!1),W(`ai`),K(void 0),J(void 0),Y.current=new Date().toISOString(),T(S?[{id:Ma(),role:`assistant`,content:S.greeting,availableActions:S.availableActions,actions:S.actions}]:[])},[a,c,S]),Ze=t(e=>{if(se){if(e===l.current){H(null);return}ne(Ya(a,c,e)),H(e)}},[a,c,se]),Qe=t(()=>{H(null),ne([])},[]);return{persona:S,messages:w,sending:k,assistantSpeaking:j,voiceReply:N,visitor:R,starters:n.starters.length>0?n.starters:S?.starterQuestions??[],featuredLinks:S?.featuredLinks??[],hasEmail:!!R.email,liveMode:U,assignedAgentName:G,agentTypingName:q,send:Se,amend:Ce,hold:we,resumeHeld:Te,duckSpeaking:De,sendGif:qe,notifyTyping:be,stop:Ee,retry:Ae,rateMessage:je,rateExplanation:ze,explanationTransport:Be,injectAssistant:Pe,reconnectSupport:Fe,appendUserDraft:Ie,patchMessage:Le,removeMessage:Re,submitCsat:Ve,submitForm:Me,confirmHostedBooking:Ne,transcribe:He,uploadAttachment:We,loadAttachment:Ue,searchGifs:Ge,demoSlots:Ke,gifEnabled:Je,identify:fe,ended:I,endConversation:Ye,startNew:Xe,history:se?z:[],viewingSessionId:V,viewMessages:te,openConversation:Ze,closeHistoryView:Qe,shutdown:ue,stopSpeaking:Oe,speakAssistantText:ke}},co=()=>typeof navigator<`u`&&(navigator.languages?.[0]||navigator.language)||`en`,lo=(e,t)=>{if(!e)return;let n=t.trim().toLowerCase(),r=n.split(`-`)[0]??n,i=Object.entries(e);return i.find(([e])=>e.toLowerCase()===n)?.[1]??i.find(([e])=>e.toLowerCase()===r)?.[1]},uo=e=>{if(!e||typeof e.token!=`string`||e.token.length===0)throw Error("[centrinfo-widget] `token` is required — pass your pub_* token to Centrinfo.init({ token }).");let t=e.locale?.trim()||co(),n=lo(e.translations,t);return{token:e.token,chatSurface:e.chatSurface??`floating`,analyticsContextToken:e.analyticsContextToken,identityToken:e.identityToken,getIdentityToken:e.getIdentityToken,apiBaseUrl:(e.apiBaseUrl??`https://api.accurixtech.com`).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:er({...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:sr(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}},fo=`
170
+ `).replace(/[ \t]{2,}/g,` `).trim(),wa=(e,t)=>Ca(kn(e,t)),Ta=e=>e.type===`visualization`,Ea=e=>{let t=!!e.visualization,n=(e.artifacts??[]).some(Ta);if(!t&&!n)return e;let{visualization:r,artifacts:i,...a}=e,o=(i??[]).filter(e=>!Ta(e)),s=r?.title??(i??[]).find(Ta)?.visualization?.title??e.resultExpired?.title;return{...a,...o.length>0?{artifacts:o}:{},resultExpired:s?{title:s}:{}}},Da=e=>e.map(Ea),Oa=(e,t=Date.now())=>{let n=e.visualization?.explanation?.aiExplanation;if(!e.visualization?.explanation||!n||n.status!==`pending`)return e;let r=e.createdAt?Date.parse(e.createdAt):NaN;return Number.isFinite(r)&&t-r<45e3?e:{...e,visualization:{...e.visualization,explanation:{...e.visualization.explanation,aiExplanation:{...n,status:`failed`,retryAvailable:!1}}}}},ka=e=>e instanceof DOMException&&(e.name===`QuotaExceededError`||e.name===`NS_ERROR_DOM_QUOTA_REACHED`),Aa=(e,t,n,r)=>{let i=r;for(let r=0;r<4&&i.length>0;r+=1)try{return e.setItem(t,n(i)),!0}catch(e){if(!ka(e))return!1;i=i.slice(Math.ceil(i.length/2))}try{e.removeItem(t)}catch{}return!1},ja=(e,t)=>{if(e)try{let n=[];for(let r=0;r<e.length;r+=1){let i=e.key(r);i?.startsWith(t)&&n.push(i)}for(let t of n){let n=e.getItem(t);if(!n)continue;let r=JSON.parse(n);if(!Array.isArray(r.messages))continue;let i=Da(r.messages);i.some((e,t)=>e!==r.messages[t])&&e.setItem(t,JSON.stringify({...r,messages:i}))}}catch{}},Ma=(e,t=()=>Date.now())=>{let n=null,r=null,i=-1/0,a=()=>{r!==null&&(clearTimeout(r),r=null);let e=n;n=null,e&&(i=t(),e())};return{schedule:o=>{if(n=o,r!==null)return;let s=e-(t()-i);s<=0?a():r=setTimeout(a,s)},flush:a,cancel:()=>{r!==null&&clearTimeout(r),r=null,n=null}}},Na=()=>typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.round(Math.random()*1e9)}`,Pa=(e,t)=>{typeof console>`u`||console.warn(`[centrinfo-widget] ${e}`,t??{})},Fa=(e,t,n,r,i=1,a,o=!1,s,c)=>{e.current?.pause(),e.current=null,typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel(),t.current=null;let l=()=>{let e=a?.trim();if(!o||!e||typeof window>`u`||!(`speechSynthesis`in window)||typeof SpeechSynthesisUtterance>`u`)return!1;let n=new SpeechSynthesisUtterance(e),r=!1,l=()=>{r||(r=!0,t.current===n&&(t.current=null,c?.()))};return n.rate=i,n.lang=typeof navigator<`u`&&(navigator.languages?.[0]||navigator.language)||`en-US`,n.onend=l,n.onerror=l,t.current=n,s?.(),window.speechSynthesis.cancel(),window.speechSynthesis.speak(n),!0};if(!n||typeof Audio>`u`)return l();let u=new Audio(`data:${r||`audio/mpeg`};base64,${n}`),d=!1,f=!1,p=()=>{d||(d=!0,e.current===u&&(e.current=null,c?.()))},m=()=>{if(!d){if(f||e.current!==u){p();return}d=!0,e.current=null,l()||c?.()}};return u.playbackRate=i,u.onended=p,u.onerror=m,e.current=u,u.play().then(()=>{if(!d){if(e.current!==u){p();return}f=!0,s?.(Number.isFinite(u.duration)?u.duration*1e3:void 0)}}).catch(m),!0},Ia=e=>{try{return e===`none`?null:e===`session`?sessionStorage:localStorage}catch{return null}},La=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)},Ra=e=>{try{let t=e?.split(`.`)[1];if(!t)return;let n=t.replace(/-/g,`+`).replace(/_/g,`/`),r=JSON.parse(atob(n.padEnd(Math.ceil(n.length/4)*4,`=`)));for(let e of[`sub`,`external_user_id`,`user_id`]){let t=r[e];if(typeof t==`string`&&t.trim())return t.trim()}}catch{}},za=e=>{let t=e.user?.externalId?.trim()||e.user?.userId?.trim()||e.user?.email?.trim().toLowerCase()||Ra(e.identityToken)||(e.identityToken||e.getIdentityToken?`authenticated`:`anonymous`);return`${e.token.slice(0,12)}:${e.chatSurface}:${La(t)}`},Ba=e=>`${e.chatSurface}:${Na()}`,Va=e=>e.slice(0,12),Ha=e=>`centrinfo:session:${e}`,Ua=e=>`centrinfo:visitor:${e}`,Wa=(e,t)=>`centrinfo:chat:${e}:${t}`,Ga=e=>`centrinfo:history:${e}`,Ka=720*60*60*1e3,qa=(e,t)=>{try{return JSON.parse(e?.getItem(Ua(t))||`{}`)}catch{return{}}},Ja=(e,t,n)=>{if(!e)return Ba(n);try{let r=Ha(t),i=e.getItem(r);if(i)return i;let a=Ba(n);return e.setItem(r,a),a}catch{return Ba(n)}},Ya=(e,t,n)=>{if(!e)return{};try{let r=e.getItem(Wa(t,n));return r?JSON.parse(r):{}}catch{return{}}},Xa=(e,t,n)=>{let{ts:r,expiresAt:i,messages:a}=Ya(e,t,n);return!Array.isArray(a)||typeof i==`number`&&Date.now()>i||typeof r==`number`&&Date.now()-r>Ka?[]:Da(a)},Za=(e,t,n)=>{let{ts:r,expiresAt:i,messages:a,ended:o}=Ya(e,t,n);return!Array.isArray(a)||a.length===0||typeof i==`number`&&Date.now()>i||typeof r==`number`&&Date.now()-r>Ka?!1:o===!0||typeof r==`number`&&Date.now()-r>864e5},Qa=e=>Number.isFinite(e??NaN)?Math.max(5,Math.min(200,Math.round(e))):50,$a=e=>Number.isFinite(e??NaN)?Math.max(1,Math.min(365,Math.round(e)))*24*60*60*1e3:Ka,eo=(e,t,n,r,i,a,o,s)=>{if(e)try{if(!a){e.removeItem(Wa(t,n));return}let c=r.filter(e=>!e.pending).slice(-o);if(c.length===0)return;let l=Date.now();Aa(e,Wa(t,n),e=>JSON.stringify({ts:l,expiresAt:l+s,messages:Da(e),ended:i}),c)}catch{}},to=(e,t)=>{if(!e)return[];try{let n=e.getItem(Ga(t)),r=n?JSON.parse(n):[];return Array.isArray(r)?r:[]}catch{return[]}},no=(e,t,n)=>{if(e)try{e.setItem(Ga(t),JSON.stringify(n.slice(0,20)))}catch{}},ro=(e,t)=>{if(e)try{let n=`centrinfo:chat:${t}:`,r=new Set([Ha(t),Ua(t),Ga(t)]),i=[];for(let t=0;t<e.length;t++){let a=e.key(t);a&&(r.has(a)||a.startsWith(n))&&i.push(a)}i.forEach(t=>e.removeItem(t))}catch{}},io=e=>{let t=(e.find(e=>e.role===`user`&&e.content.trim())?.content||e.find(e=>e.content.trim())?.content||``).trim().replace(/\s+/g,` `);return t.length>60?t.slice(0,60)+`…`:t||`Conversation`},ao=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}),oo=e=>(e??[]).find(e=>e.category===`support`&&e.enabled&&e.readiness!==`unavailable`&&(e.liveHandoff??e.id===`public_contact_support`)),so=(e,t)=>{if(t===`ai`)for(let t=e.length-1;t>=0;t--){let n=e[t];if(n){if(n.reconnectOffer)return;if(n.liveEventType===`ai_handback`)return n.offerReconnect?n.id:void 0}}},co=(e,n,i=!0)=>{let a=o(Ia(n.persistence)).current,c=za(n),l=o(Ja(a,c,n)),u=o(null),d=o(null),f=o(null),p=o(null),m=o(null),h=o(null),g=o(new Map),_=o(!1),v=o(void 0),y=o(null),b=o({}),x=o({}),[S,C]=s(null),[w,T]=s(()=>Xa(a,c,l.current)),E=o(null);E.current||(E.current=Ma(1e3));let D=o(w.length>0),O=o(w.some(e=>e.role===`user`)),[k,A]=s(!1),[j,M]=s(!1),[N,P]=s({status:`idle`}),F=o({}),[I,L]=s(()=>Za(a,c,l.current)),[R,ee]=s(()=>qa(a,c)),[z,B]=s(()=>to(a,c)),[V,H]=s(null),[U,te]=s([]),[W,G]=s(`ai`),[K,q]=s(void 0),[J,ne]=s(void 0),Y=o(new Date().toISOString()),re=o(void 0),ie=o(!1),ae=o(0),oe=o(R);r(()=>{oe.current=R},[R]);let se=S?.memoryEnabled!==!1,ce=Qa(S?.memoryMessageCap),le=$a(S?.memoryRetentionDays),ue=t(()=>{u.current?.abort(),E.current?.cancel(),ro(a,c),ro(a,Va(n.token));let e=Ba(n);l.current=e;try{a?.setItem(Ha(c),e)}catch{}H(null),te([]),L(!1),B([]),ee({}),G(`ai`),q(void 0),ne(void 0),Y.current=new Date().toISOString(),T(S?[{id:Na(),role:`assistant`,content:S.greeting,availableActions:S.availableActions,actions:S.actions}]:[])},[a,c,n.token,S]),de=t(e=>{try{a?.setItem(Ua(c),JSON.stringify(e))}catch{}},[a,c]),fe=t(t=>{let n=(t.email??``).trim().toLowerCase(),r=(oe.current.email??``).trim().toLowerCase();n&&r&&n!==r&&ue();let i={};t.email?.trim()&&(i.email=t.email.trim()),t.phone?.trim()&&(i.phone=t.phone.trim());let a=[t.firstName,t.lastName].filter(e=>!!e?.trim()).join(` `).trim()||t.name?.trim()||``;a&&(i.name=a),Object.keys(i).length>0&&ee(e=>{let t={...i,...e};return de(t),t}),e.identify(l.current,t).catch(()=>{})},[e,de,ue]),pe=o(0),me=t(e=>{pe.current=Date.now(),C(e),T(t=>{if(t.length===0)return[{id:Na(),role:`assistant`,content:e.greeting,availableActions:e.availableActions,actions:e.actions}];let n=t.some(e=>e.role===`user`),r=t[0];return!n&&r?.role===`assistant`?[{...r,content:e.greeting,availableActions:e.availableActions,actions:e.actions},...t.slice(1)]:t})},[]);r(()=>{if(S?.memoryEnabled===!1){E.current?.cancel();try{a?.removeItem(Wa(c,l.current))}catch{}no(a,c,[]),B([]),H(null),te([]),T(e=>D.current?(D.current=!1,S?[{id:Na(),role:`assistant`,content:S.greeting,availableActions:S.availableActions,actions:S.actions}]:[]):e)}},[S,a,c]);let he=t(async()=>{me(await e.bootstrap())},[me,e]);r(()=>{let t=!0,n=e=>e.messages.map(e=>Oa({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(e=>{if(!t||e.conversations.length===0)return;let r=e.conversations.map(e=>({sessionId:e.sessionId,ts:Date.parse(e.lastSeenAt)||Date.now(),title:e.title,ended:e.ended}));for(let t of e.conversations)eo(a,c,t.sessionId,n(t),t.ended,!0,ce,le);no(a,c,r),B(r);let i=e.conversations.find(t=>t.sessionId===e.activeSessionId);if(!i||O.current)return;let o=n(i);l.current=i.sessionId,D.current=o.length>0;try{a?.setItem(Ha(c),i.sessionId)}catch{}let s=o[o.length-1]?.createdAt;s&&(Y.current=s),L(i.ended),T(o)}).catch(()=>{}),()=>{t=!1}},[ce,le,c,a,e]),r(()=>{let t=!0;return pe.current=Date.now(),e.bootstrap().then(e=>{t&&me(e)}),n.user&&fe(n.user),()=>{t=!1}},[me,e]),r(()=>{let e=n.configRefreshSeconds;if(!i||e<=0||typeof window>`u`)return;let t=!0,r=!1,a=Math.max(10,e)*1e3,o=()=>typeof document>`u`||document.visibilityState!==`hidden`,s=async()=>{if(!(!t||r||!o())){r=!0;try{await he()}catch{}finally{r=!1}}};Date.now()-pe.current>=a&&s();let c=window.setInterval(s,a),l=()=>void s(),u=()=>void s();return window.addEventListener(`focus`,l),document?.addEventListener?.(`visibilitychange`,u),()=>{t=!1,window.clearInterval(c),window.removeEventListener(`focus`,l),document?.removeEventListener?.(`visibilitychange`,u)}},[i,n.configRefreshSeconds,he]),r(()=>{let e=l.current;E.current.schedule(()=>eo(a,c,e,w,I,se,ce,le))},[w,I,a,c,se,ce,le]),r(()=>{let e=E.current,t=()=>{document.visibilityState===`hidden`&&e.flush()};return document.addEventListener(`visibilitychange`,t),window.addEventListener(`pagehide`,e.flush),()=>{document.removeEventListener(`visibilitychange`,t),window.removeEventListener(`pagehide`,e.flush),e.flush()}},[]),r(()=>{ja(a,`centrinfo:chat:`)},[a]),r(()=>{if(!i||I||V)return;let t=()=>{document.visibilityState===`visible`&&e.presence(l.current)};t();let n=window.setInterval(t,1e4);return document.addEventListener(`visibilitychange`,t),()=>{window.clearInterval(n),document.removeEventListener(`visibilitychange`,t)}},[i,I,e,V]),r(()=>{if(!i||I||V)return;let t=!0,r=!1,a=0,o,s=()=>{o!==void 0&&window.clearTimeout(o),!(!t||document.hidden)&&(o=window.setTimeout(()=>{c()},Math.min(3e4,2200*2**a)))},c=async()=>{if(!(r||document.hidden||!t)){r=!0;try{let r=await e.liveEvents(l.current,Y.current);if(!t)return;if(a=0,G(r.mode),q(r.assignedAgentName||void 0),ne(r.agentTyping?r.agentTypingName||r.assignedAgentName||`Agent`:void 0),r.conversationEnded){L(!0),G(`ai`),q(void 0),ne(void 0),T(e=>e.some(e=>e.id===`live:conversation-ended`)?e:[...e,{id:`live:conversation-ended`,role:`system`,content:n.strings.conversationEnded,liveEventType:`conversation_ended`,createdAt:new Date().toISOString()}]);return}if(r.events.length>0){let e=Y.current,t=Date.parse(e),n=r.events.map(n=>{let r=Date.parse(n.createdAt);return Number.isFinite(r)&&r>t&&(t=r,e=n.createdAt),ao(n)});Y.current=e,T(e=>{let t=new Set(e.map(e=>e.id)),r=n.filter(e=>!t.has(e.id));return r.length>0?[...e,...r]:e}),n.some(e=>e.role===`assistant`)&&ua(`receive`)}}catch{a=Math.min(a+1,4)}finally{r=!1,s()}}},u=()=>{document.hidden?o!==void 0&&window.clearTimeout(o):c()};return document.addEventListener(`visibilitychange`,u),document.hidden||c(),()=>{t=!1,o!==void 0&&window.clearTimeout(o),document.removeEventListener(`visibilitychange`,u)}},[i,n.strings.conversationEnded,e,I,V]),r(()=>{if(!se){no(a,c,[]),B(e=>e.length>0?[]:e);return}w.some(e=>e.role===`user`)&&B(e=>{let t=l.current,n=[{sessionId:t,ts:Date.now(),title:io(w),ended:I},...e.filter(e=>e.sessionId!==t)];return no(a,c,n),n.slice(0,20)})},[w,I,a,c,se]);let X=t((e,t)=>{T(n=>n.map(n=>n.id===e?{...n,...t}:n))},[]),ge=t(()=>{v.current!==void 0&&typeof window<`u`&&window.clearInterval(v.current),v.current=void 0},[]),_e=t((e,t)=>{ge(),delete b.current[e],y.current===e&&(y.current=null),X(e,{content:t,pending:!1,streaming:!1})},[ge,X]),ve=t((e,t,n)=>{let r=t.trim();if(!r||typeof window>`u`){_e(e,r);return}ge(),y.current=e;let i=r.match(/\S+\s*/g)??[r],a=n&&n>0?n:i.length*95,o=Math.max(28,Math.min(150,a/Math.max(i.length,1))),s=0;X(e,{content:``,pending:!1,streaming:!0}),v.current=window.setInterval(()=>{s+=1,X(e,{content:i.slice(0,s).join(``),pending:!1,streaming:s<i.length}),s>=i.length&&(ge(),delete b.current[e],y.current===e&&(y.current=null),X(e,{content:r,pending:!1,streaming:!1}))},o)},[ge,_e,X]),ye=t(()=>{let e=y.current;ge(),y.current=null;let t=b.current;b.current={};for(let[e,n]of Object.entries(t))X(e,{content:n,pending:!1,streaming:!1});e&&!(e in t)&&X(e,{pending:!1,streaming:!1})},[ge,X]),be=t(t=>{if(I||V||W===`ai`||typeof window>`u`)return;if(re.current!==void 0&&window.clearTimeout(re.current),!t){if(!ie.current)return;ie.current=!1,ae.current=0,e.typing(l.current,!1).catch(()=>{});return}let n=Date.now();(!ie.current||n-ae.current>2500)&&(ie.current=!0,ae.current=n,e.typing(l.current,!0).catch(()=>{})),re.current=window.setTimeout(()=>{ie.current&&(ie.current=!1,ae.current=0,e.typing(l.current,!1).catch(()=>{}))},1600)},[e,I,V,W]);r(()=>()=>{re.current!==void 0&&typeof window<`u`&&window.clearTimeout(re.current)},[]),r(()=>()=>ge(),[ge]);let xe=t((t,r,a={})=>{ye(),A(!0);let o=ya(),s=!1,c=new AbortController;u.current=c;let f=!!(S?.allowVoiceInput&&S?.voiceOutputEnabled&&S.talkbackMode!==`text`),g=!!a.forceVoicePlayback,v=e=>{g&&P(t=>t.agentId===r?{status:e,agentId:r}:t)};g&&P({status:`answering`,agentId:r});let y={pending:new Map,nextSeq:0,highestSeq:-1,playing:!1,ended:!1,started:!1,stopped:!1,utterance:null},C=()=>{h.current===N&&(h.current=null),y.started&&(y.started=!1,M(!1),v(`done`))},w=()=>{y.stopped||y.started||(y.started=!0,ba(`voice-first-audio`,o),M(!0),v(`speaking`))},E=()=>typeof window<`u`&&`speechSynthesis`in window&&typeof SpeechSynthesisUtterance<`u`,D=()=>{p.current&&y.playing&&(p.current.pause(),p.current=null),y.utterance&&(m.current===y.utterance&&(m.current=null),y.utterance=null,E()&&window.speechSynthesis.cancel()),y.playing=!1},O=(e,t)=>{let n=e?.trim();if(!n||!E())return!1;let r=new SpeechSynthesisUtterance(n);return r.rate=S?.voiceSpeed??1,r.lang=typeof navigator<`u`&&(navigator.languages?.[0]||navigator.language)||`en-US`,r.onstart=w,r.onend=t,r.onerror=t,y.utterance=r,m.current=r,window.speechSynthesis.speak(r),_.current&&window.speechSynthesis.pause(),!0},k=()=>{for(;!y.stopped&&!y.playing;){let e=y.pending.get(y.nextSeq);if(!e&&y.ended&&y.pending.size>0&&(y.nextSeq=Math.min(...y.pending.keys()),e=y.pending.get(y.nextSeq)),!e){y.ended&&C();return}if(y.pending.delete(y.nextSeq),y.nextSeq+=1,j(e))return}},j=e=>{let t=!1,n=()=>{t||(t=!0,m.current===y.utterance&&(m.current=null),y.utterance=null,y.playing=!1,k())};if(!e.audioBase64||typeof Audio>`u`)return y.playing=O(e.text,n),y.playing;let r=new Audio(`data:${e.mimeType||`audio/mpeg`};base64,${e.audioBase64}`);r.playbackRate=S?.voiceSpeed??1,r.volume=_.current?.2:1,y.playing=!0,p.current=r;let i=!1,a=!1,o=()=>{t||a||(a=!0,p.current===r&&(p.current=null),!(!i&&!y.stopped&&O(e.text,n))&&n())};return r.onended=()=>{p.current===r&&(p.current=null),n()},r.onerror=o,r.play().then(()=>{i=!0,w()}).catch(o),!0},N=()=>{y.stopped=!0,y.pending.clear(),D(),C()};e.stream(t,l.current,{voicePlaybackRequested:!!a.forceVoicePlayback,clientMessageId:a.clientMessageId,attachmentId:a.attachmentId,attachmentIds:a.attachmentIds,signal:c.signal,onChunk:e=>{e&&!s&&(s=!0,ba(`data-first-chunk`,o)),a.forceVoicePlayback&&e&&(x.current[r]=!0),T(t=>t.map(t=>t.id===r?{...t,content:t.content+e,pending:!1,streaming:!0}:t))},onTextReady:()=>{T(e=>e.map(e=>e.id===r?{...e,pending:!1,streaming:!1}:e))},onReset:()=>{T(e=>e.map(e=>e.id===r?{...e,content:``,pending:!0,streaming:!1}:e)),y.pending.clear(),y.nextSeq=y.highestSeq+1,D()},onAudioSegment:e=>{!g||y.stopped||e.seq<y.nextSeq||y.pending.has(e.seq)||(h.current=N,y.highestSeq=Math.max(y.highestSeq,e.seq),y.pending.set(e.seq,e),k())}}).then(t=>{if(i&&!t.conversationEnded&&typeof document<`u`&&document.visibilityState===`visible`&&e.presence(l.current),t.liveMode&&(G(t.liveMode),q(t.assignedAgentName||void 0)),t.liveMode&&t.liveMode!==`ai`&&!t.answer.trim()){T(e=>e.filter(e=>e.id!==r)),v(`done`);return}let o=!!x.current[r];delete x.current[r];let s=!!(a.forceVoicePlayback&&f&&!t.liveAudio&&t.audioBase64&&t.answer.trim()&&!o);if(s&&(b.current[r]=t.answer),T(e=>e.map(e=>e.id===r?{...e,content:s?``:t.answer||e.content||n.strings.emptyReply,pending:!1,streaming:s,error:!1,retryText:void 0,sources:t.sources,suggestedReplies:t.suggestedReplies,availableActions:t.availableActions,actions:t.actions,selectedAction:t.selectedAction,handoffOffered:t.handoffOffered,requestedContactFields:t.requestedContactFields,visualization:t.visualization,artifacts:t.artifacts}:e)),ua(`receive`),t.liveAudio?(y.ended=!0,k()):a.forceVoicePlayback&&!t.audioBase64&&Pa(f?`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:S?.voiceOutputEnabled,talkbackMode:S?.talkbackMode,voiceProvider:S?.voiceProvider,hasAudioBase64:!!t.audioBase64}),a.forceVoicePlayback&&!t.liveAudio){let e=Fa(p,m,t.audioBase64,t.mimeType,S?.voiceSpeed??1,wa(t.answer,t.visualization),!0,e=>{M(!0),v(`speaking`),s&&ve(r,t.answer,e)},()=>{M(!1),v(`done`),s&&_e(r,t.answer)});e||v(`done`),s&&!e&&_e(r,t.answer)}t.answer&&n.onMessage?.({role:`assistant`,content:t.answer}),t.handoffOffered&&n.onHandoff?.(),t.conversationEnded&&L(!0)}).catch(e=>{if(c.signal.aborted){y.stopped||N(),delete x.current[r],T(e=>e.flatMap(e=>e.id===r?e.content.trim()?[{...e,pending:!1,streaming:!1}]:[]:[e])),v(`done`);return}v(`failed`),delete x.current[r],X(r,{content:va(e,n.strings),pending:!1,streaming:!1,error:!0,retryText:t})}).finally(()=>{ba(`data-complete`,o),delete x.current[r],u.current===c&&(A(!1),u.current=null,d.current?.agentId===r&&(d.current=null))})},[e,i,n,X,S?.allowVoiceInput,S?.talkbackMode,S?.voiceOutputEnabled,S?.voiceSpeed,ye]),Se=t((e,t={})=>{let r=e.trim(),{imageUrl:i,attachmentName:a,attachmentText:o,attachmentId:s,attachmentFile:c,forceVoicePlayback:l,userMessageId:f}=t,p=t.attachments??(a||s||o?[{id:s,name:a??``,text:o,file:c}]:[]);if(!r&&!i&&p.length===0||u.current&&!u.current.signal.aborted||I)return;O.current=!0;let m=r;!m&&p.length>0&&(m=`Please look at the attached file.`),!m&&i&&(m=i);let h=p.map(e=>({id:e.id,name:e.name})),_=p.flatMap(e=>e.id?[e.id]:[]),v={id:f||Na(),role:`user`,content:r,imageUrl:i,attachments:h.length>0?h:void 0};p.forEach((e,t)=>{e.file&&(g.current.set(`${v.id}:${t}`,e.file),e.id&&g.current.set(e.id,e.file))});let y=Na();T(e=>[...f&&e.some(e=>e.id===f)?e.map(e=>e.id===f?{...e,content:r,pending:!1,streaming:!1,imageUrl:i,attachments:v.attachments}:e):[...e,v],{id:y,role:`assistant`,content:``,pending:!0}]),ua(`send`),n.onMessage?.({role:`user`,content:m}),F.current[y]=v.id,d.current={userId:v.id,agentId:y,text:r,backendText:m},xe(m,y,{forceVoicePlayback:l,clientMessageId:v.id,attachmentId:_[0],attachmentIds:_})},[I,n,xe]),Ce=t((e,t,r,i,a)=>{let o=Na();T(n=>[...n.filter(t=>t.id!==e.agentId&&(!i.userMessageId||t.id!==i.userMessageId)).map(n=>n.id===e.userId?{...n,content:t,pending:!1,streaming:!1}:n),{id:o,role:`assistant`,content:``,pending:!0}]),a&&n.onMessage?.({role:`user`,content:a}),F.current[o]=e.userId,d.current={userId:e.userId,agentId:o,text:t,backendText:r},xe(r,o,{forceVoicePlayback:i.forceVoicePlayback,clientMessageId:Na()})},[n,xe]),Z=t((e,t={})=>{let n=e.trim();if(!n||I)return;let r=u.current&&!u.current.signal.aborted?d.current:null,i=r??f.current;if(f.current=null,!i){Se(n,t);return}r&&u.current?.abort(),Ce(i,`${i.text} ${n}`.replace(/\s+/g,` `).trim(),`${i.backendText}\n${n}`.trim(),t,n)},[I,Ce,Se]),we=t(()=>{let e=u.current&&!u.current.signal.aborted?d.current:null;return e?(f.current=e,u.current?.abort(),!0):!1},[]),Te=t(()=>{let e=f.current;f.current=null,!(!e||I)&&Ce(e,e.text,e.backendText,{forceVoicePlayback:!0})},[I,Ce]),Ee=t(()=>u.current?.abort(),[]),De=t(e=>{_.current=e;let t=p.current;t&&(t.volume=e?.2:1),m.current&&typeof window<`u`&&`speechSynthesis`in window&&(e?window.speechSynthesis.pause():window.speechSynthesis.resume())},[]),Oe=t(()=>{h.current?.(),h.current=null,_.current=!1,ye(),P(e=>e.status===`speaking`||e.status===`answering`?{...e,status:`done`}:e),p.current?.pause(),p.current=null,typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel(),m.current=null,M(!1)},[ye]),ke=t(t=>{let n=Ca(t);if(!n)return Promise.resolve(!1);ye();let r=!!(S?.allowVoiceInput&&S?.voiceOutputEnabled&&S.talkbackMode!==`text`),i=(e,t)=>new Promise(r=>{let i=!1;Fa(p,m,e,t,S?.voiceSpeed??1,n,!0,()=>{i=!0,M(!0)},()=>{M(!1),r(i)})||(M(!1),r(!1))});return r?e.speak(n).then(e=>e.audioBase64?i(e.audioBase64,e.mimeType):(Pa(`Talkback prompt TTS did not return provider audio.`,{providerReady:e.providerReady,message:e.message,voiceProvider:S?.voiceProvider,voiceOutputEnabled:S?.voiceOutputEnabled,talkbackMode:S?.talkbackMode}),i())).catch(e=>(Pa(`Talkback prompt TTS request failed before audio playback.`,{error:e instanceof Error?e.message:String(e),voiceProvider:S?.voiceProvider,voiceOutputEnabled:S?.voiceOutputEnabled,talkbackMode:S?.talkbackMode}),i())):(Pa(`Talkback prompt wanted voice, but the loaded widget token config has provider TTS disabled.`,{voiceOutputEnabled:S?.voiceOutputEnabled,talkbackMode:S?.talkbackMode,voiceProvider:S?.voiceProvider}),i())},[S?.allowVoiceInput,S?.talkbackMode,S?.voiceOutputEnabled,S?.voiceSpeed,ye,e]),Ae=t((e,t,n={})=>{if(k||I||!t)return;X(e,{content:``,pending:!0,streaming:!1,error:!1}),ua(`send`);let r=w.findIndex(t=>t.id===e),i=r>0?w[r-1]:void 0;xe(t,e,{...n,clientMessageId:F.current[e]??(i?.role===`user`?i.id:void 0)})},[k,I,w,X,xe]),je=t((t,n,r)=>{X(t,{feedback:n});let i=w.findIndex(e=>e.id===t),a=i>=0?w[i]?.content:void 0,o;for(let e=i-1;e>=0;e--)if(w[e]?.role===`user`){o=w[e]?.content;break}e.sendFeedback({sessionId:l.current,messageId:t,rating:n,comment:r,question:o,answer:a}).catch(()=>{})},[e,X,w]),Me=t(e=>{let t=e.content.trim();if(!t)return;let n=e.id.trim()||Na();T(e=>e.some(e=>e.id===n)?e:[...e,{id:n,role:`assistant`,content:t,createdAt:new Date().toISOString()}])},[]),Ne=t(async(t,r,i={},a)=>{n.onAction?.(t);let o=t===`public_contact_support`||t===`public_submit_inquiry`?{actionId:t}:{},s=await e.action(t,{sessionId:l.current,...r,...o},a),c={};return i.name?.trim()&&(c.name=i.name.trim()),i.email?.trim()&&(c.email=i.email.trim()),i.phone?.trim()&&(c.phone=i.phone.trim()),Object.keys(c).length>0&&(ee(e=>{let t={...e,...c};return de(t),t}),c.email&&t!==`contact`&&e.action(`contact`,{sessionId:l.current,...c}).catch(()=>{})),Me({id:s.receipt?.id||Na(),content:s.receipt?.content||s.note||(s.caseReference?`Action completed.\nReference: ${s.caseReference}`:`Action completed.`)}),ua(`receive`),s},[e,n,de,Me]),Pe=t(async(t,n,r)=>{let i=await e.confirmHostedBooking?.({sessionId:l.current,inquiryId:t,eventUri:n,inviteeUri:r});return i?.receipt&&Me(i.receipt),i},[e,Me]),Fe=t(e=>{let t=e.trim();t&&T(e=>e.some(e=>e.role===`assistant`&&e.content===t)?e:[...e,{id:Na(),role:`assistant`,content:t}])},[]),Ie=t(()=>{let e=oo(S?.actions);return e?(T(t=>[...t,{id:Na(),role:`assistant`,content:n.strings.reconnectPrompt,actions:[e],selectedAction:e.id,handoffOffered:!0,reconnectOffer:!0,createdAt:new Date().toISOString()}]),!0):!1},[n.strings.reconnectPrompt,S?.actions]),Le=t(e=>{O.current=!0;let t=Na();return T(n=>[...n,{id:t,role:`user`,content:e.trim(),pending:!0}]),t},[]),Re=t((e,t)=>{T(n=>n.map(n=>n.id===e?{...n,...t}:n))},[]),ze=t(e=>{T(t=>t.filter(t=>t.id!==e))},[]),Be=t(async(t,n=`widget`)=>{if(!e.sendExplanationFeedback)throw Error(`Explanation feedback is unavailable.`);await e.sendExplanationFeedback({...t,sessionId:l.current,surface:n})},[e]),Ve=t((t=`widget`)=>{let n=e.fetchExplanation?.bind(e);if(!n)return;let r=e.retryExplanation?.bind(e),i=e=>e;return{poll:async(e,r)=>i(await n(e,l.current,t,r)),settled:(e,t)=>{t!==`not_requested`&&T(n=>n.map(n=>{let r=n.visualization?.explanation?.aiExplanation;return!r||(r.explanationId??n.visualization?.explanation?.explanationId)!==e||r.status===t?n:{...n,visualization:{...n.visualization,explanation:{...n.visualization.explanation,aiExplanation:{...r,status:t}}}}}))},...r?{retry:async e=>i(await r(e,l.current,t))}:{}}},[e]),He=t((t,n)=>{e.sendFeedback({sessionId:l.current,messageId:`__csat__`,rating:t,comment:n}).catch(()=>{})},[e]),Ue=t(async(t,n,r,i)=>{let a=ya();try{if(typeof t!=`string`&&e.transcribeAudio)return await e.transcribeAudio(t,n,r,i);let a=typeof t==`string`?t:await ha(t);return await e.transcribe(a,n,r,i)}finally{ba(`voice-transcription`,a)}},[e]),We=t(async(t,n,r=0)=>{let i=g.current.get(`${t.id}:${r}`)??(n.id?g.current.get(n.id):void 0);if(i)return i;if(!n.id||!e.fetchAttachment)throw Error(`This file is no longer available.`);return e.fetchAttachment(n.id,l.current)},[e]),Ge=t((t,n,r,i)=>e.uploadAttachment?e.uploadAttachment(t,n,r,l.current,i):Promise.reject(Error(`File upload is unavailable`)),[e]),Ke=t(t=>e.searchGifs(t),[e]),qe=t((t,n)=>e.demoSlots(t,n),[e]),Je=t(e=>Se(``,{imageUrl:e}),[Se]),Ye=n.demo||!!n.gifApiKey,Xe=t(()=>{u.current?.abort(),L(!0),e.endConversation(l.current).catch(()=>{})},[e]),Ze=t(()=>{u.current?.abort();let e=Ba(n);l.current=e;try{a?.setItem(Ha(c),e)}catch{}H(null),te([]),L(!1),G(`ai`),q(void 0),ne(void 0),Y.current=new Date().toISOString(),T(S?[{id:Na(),role:`assistant`,content:S.greeting,availableActions:S.availableActions,actions:S.actions}]:[])},[a,c,S]),Qe=t(e=>{if(se){if(e===l.current){H(null);return}te(Xa(a,c,e)),H(e)}},[a,c,se]),$e=t(()=>{H(null),te([])},[]);return{persona:S,messages:w,sending:k,assistantSpeaking:j,voiceReply:N,visitor:R,starters:n.starters.length>0?n.starters:S?.starterQuestions??[],featuredLinks:S?.featuredLinks??[],hasEmail:!!R.email,liveMode:W,assignedAgentName:K,agentTypingName:J,send:Se,amend:Z,hold:we,resumeHeld:Te,duckSpeaking:De,sendGif:Je,notifyTyping:be,stop:Ee,retry:Ae,rateMessage:je,rateExplanation:Be,explanationTransport:Ve,injectAssistant:Fe,reconnectSupport:Ie,appendUserDraft:Le,patchMessage:Re,removeMessage:ze,submitCsat:He,submitForm:Ne,confirmHostedBooking:Pe,transcribe:Ue,uploadAttachment:Ge,loadAttachment:We,searchGifs:Ke,demoSlots:qe,gifEnabled:Ye,identify:fe,ended:I,endConversation:Xe,startNew:Ze,history:se?z:[],viewingSessionId:V,viewMessages:U,openConversation:Qe,closeHistoryView:$e,shutdown:ue,stopSpeaking:Oe,speakAssistantText:ke}},lo=()=>typeof navigator<`u`&&(navigator.languages?.[0]||navigator.language)||`en`,uo=(e,t)=>{if(!e)return;let n=t.trim().toLowerCase(),r=n.split(`-`)[0]??n,i=Object.entries(e);return i.find(([e])=>e.toLowerCase()===n)?.[1]??i.find(([e])=>e.toLowerCase()===r)?.[1]},fo=e=>{if(!e||typeof e.token!=`string`||e.token.length===0)throw Error("[centrinfo-widget] `token` is required — pass your pub_* token to Centrinfo.init({ token }).");let t=e.locale?.trim()||lo(),n=uo(e.translations,t);return{token:e.token,chatSurface:e.chatSurface??`floating`,analyticsContextToken:e.analyticsContextToken,identityToken:e.identityToken,getIdentityToken:e.getIdentityToken,apiBaseUrl:(e.apiBaseUrl??`https://api.accurixtech.com`).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:tr({...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:cr(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}},po=`
171
171
  :host {
172
172
  all: initial;
173
173
  }
@@ -312,7 +312,7 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
312
312
  /* Grid (not flex) so theater mode below can reflow header/video/chat into a
313
313
  two-column split purely in CSS, without reordering the DOM. */
314
314
  display: grid;
315
- grid-template-columns: 1fr;
315
+ grid-template-columns: minmax(0, 1fr);
316
316
  grid-template-rows: auto auto minmax(0, 1fr);
317
317
  grid-template-areas: 'header' 'video' 'chat';
318
318
  overflow: hidden;
@@ -610,6 +610,7 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
610
610
  .cf-msg {
611
611
  display: flex;
612
612
  gap: 8px;
613
+ min-width: 0;
613
614
  max-width: 100%;
614
615
  animation: cf-msg-in 0.32s cubic-bezier(0.22, 1, 0.36, 1) both;
615
616
  }
@@ -663,6 +664,7 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
663
664
  .cf-msg__bubble p { margin: 0 0 8px; }
664
665
  .cf-msg__bubble p:last-child { margin-bottom: 0; }
665
666
  .cf-msg__col { min-width: 0; max-width: 85%; display: flex; flex-direction: column; gap: 8px; align-items: flex-start; }
667
+ .cf-msg__col--actions { flex: 1; max-width: 100%; }
666
668
  .cf-msg--user .cf-msg__col { align-items: flex-end; }
667
669
  .cf-artifact {
668
670
  width: min(100%, 560px);
@@ -1102,6 +1104,9 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1102
1104
  display: flex;
1103
1105
  flex-direction: column;
1104
1106
  gap: 8px;
1107
+ width: 100%;
1108
+ min-width: 0;
1109
+ max-width: 100%;
1105
1110
  }
1106
1111
 
1107
1112
  .cf-form {
@@ -1109,6 +1114,7 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1109
1114
  flex-direction: column;
1110
1115
  gap: 8px;
1111
1116
  width: 100%;
1117
+ min-width: 0;
1112
1118
  max-width: 300px;
1113
1119
  padding: 12px;
1114
1120
  border-radius: 14px;
@@ -1117,9 +1123,11 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1117
1123
  animation: cf-msg-in 0.2s ease both;
1118
1124
  }
1119
1125
  .cf-form__title { font-size: 13.5px; font-weight: 700; color: var(--cf-fg, var(--cf-text)); }
1120
- .cf-form__as { font-size: 12.5px; color: var(--cf-muted); margin-top: -2px; }
1126
+ .cf-form__as { font-size: 12.5px; color: var(--cf-muted); margin-top: -2px; overflow-wrap: anywhere; }
1121
1127
  .cf-form__input {
1122
1128
  width: 100%;
1129
+ min-width: 0;
1130
+ max-width: 100%;
1123
1131
  padding: 9px 11px;
1124
1132
  border: 1.5px solid var(--cf-border);
1125
1133
  border-radius: 10px;
@@ -1239,14 +1247,17 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1239
1247
  .cf-phone__option-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1240
1248
  .cf-phone__option-code { color: var(--cf-muted); font-variant-numeric: tabular-nums; }
1241
1249
  .cf-phone__empty { padding: 12px 8px; color: var(--cf-muted); font-size: 12px; text-align: center; }
1242
- .cf-form__actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 2px; }
1250
+ .cf-form__actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; margin-top: 2px; }
1243
1251
  .cf-form__submit {
1252
+ min-height: 36px;
1253
+ max-width: 100%;
1244
1254
  padding: 8px 14px;
1245
1255
  border-radius: 10px;
1246
1256
  font-size: 13.5px;
1247
1257
  font-weight: 600;
1248
1258
  background: linear-gradient(135deg, var(--cf-accent, #2f7f55) 0%, var(--cf-accent-2, #2f7de8) 160%);
1249
1259
  color: var(--cf-accent-ink);
1260
+ overflow-wrap: anywhere;
1250
1261
  transition: opacity 0.15s ease, transform 0.1s ease;
1251
1262
  }
1252
1263
  .cf-form__submit:disabled { opacity: 0.45; cursor: default; }
@@ -1422,8 +1433,9 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1422
1433
 
1423
1434
  /* ---------- Demo booking picker ---------- */
1424
1435
  .cf-booking { max-width: 320px; }
1425
- .cf-booking__hint { font-size: 12.5px; color: var(--cf-muted); margin-top: -2px; }
1436
+ .cf-booking__hint { font-size: 12.5px; color: var(--cf-muted); margin-top: -2px; line-height: 1.45; overflow-wrap: anywhere; }
1426
1437
  .cf-booking__dur { font-weight: 600; color: var(--cf-text); }
1438
+ .cf-booking__timezone { display: block; margin-top: 3px; font-size: 11.5px; }
1427
1439
  .cf-booking__state {
1428
1440
  padding: 12px;
1429
1441
  border: 1px dashed var(--cf-border);
@@ -1437,6 +1449,9 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1437
1449
  .cf-booking__dates {
1438
1450
  display: flex;
1439
1451
  gap: 6px;
1452
+ width: 100%;
1453
+ min-width: 0;
1454
+ max-width: 100%;
1440
1455
  overflow-x: auto;
1441
1456
  padding-bottom: 4px;
1442
1457
  scrollbar-width: thin;
@@ -1470,7 +1485,9 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1470
1485
  .cf-booking__dom { font-size: 15px; font-weight: 700; line-height: 1.1; }
1471
1486
  .cf-booking__slots {
1472
1487
  display: grid;
1473
- grid-template-columns: repeat(3, 1fr);
1488
+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 80px), 1fr));
1489
+ width: 100%;
1490
+ min-width: 0;
1474
1491
  gap: 6px;
1475
1492
  max-height: 156px;
1476
1493
  overflow-y: auto;
@@ -1479,7 +1496,9 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1479
1496
  .cf-booking__slots::-webkit-scrollbar { width: 6px; }
1480
1497
  .cf-booking__slots::-webkit-scrollbar-thumb { background: var(--cf-border); border-radius: 3px; }
1481
1498
  .cf-booking__slot {
1482
- padding: 8px 0;
1499
+ min-width: 0;
1500
+ min-height: 36px;
1501
+ padding: 8px 4px;
1483
1502
  border-radius: 9px;
1484
1503
  border: 1px solid var(--cf-border);
1485
1504
  background: var(--cf-bg);
@@ -1765,6 +1784,9 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1765
1784
  white-space: nowrap;
1766
1785
  }
1767
1786
  .cf-action-drawer {
1787
+ width: 100%;
1788
+ min-width: 0;
1789
+ max-width: 100%;
1768
1790
  border: 1px solid color-mix(in oklab, var(--cf-border) 86%, var(--cf-accent));
1769
1791
  border-radius: 18px 18px 12px 12px;
1770
1792
  padding: 7px;
@@ -1785,18 +1807,24 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1785
1807
  background: color-mix(in oklab, var(--cf-muted) 42%, transparent);
1786
1808
  }
1787
1809
  .cf-action-drawer__head {
1810
+ position: sticky;
1811
+ top: -7px;
1812
+ z-index: 1;
1788
1813
  display: flex;
1789
1814
  align-items: center;
1790
1815
  justify-content: space-between;
1791
1816
  gap: 10px;
1792
1817
  padding: 0 3px 6px;
1818
+ background: var(--cf-bg);
1793
1819
  color: var(--cf-text);
1794
1820
  }
1795
1821
  .cf-action-drawer__head strong {
1796
1822
  display: block;
1797
1823
  font-size: 13px;
1798
1824
  line-height: 1.2;
1825
+ overflow-wrap: anywhere;
1799
1826
  }
1827
+ .cf-action-drawer__head > div { min-width: 0; }
1800
1828
  .cf-action-drawer__eyebrow {
1801
1829
  display: block;
1802
1830
  margin-bottom: 2px;
@@ -1808,6 +1836,7 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1808
1836
  }
1809
1837
  .cf-action-drawer__close {
1810
1838
  display: inline-flex;
1839
+ flex-shrink: 0;
1811
1840
  align-items: center;
1812
1841
  justify-content: center;
1813
1842
  width: 28px;
@@ -1921,6 +1950,13 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1921
1950
  background: transparent;
1922
1951
  box-shadow: none;
1923
1952
  }
1953
+ .cf-action-drawer .cf-form__actions {
1954
+ position: sticky;
1955
+ bottom: -7px;
1956
+ z-index: 1;
1957
+ padding-top: 8px;
1958
+ background: var(--cf-bg);
1959
+ }
1924
1960
  .cf-footer-actions .cf-actions {
1925
1961
  display: grid;
1926
1962
  grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -1945,6 +1981,14 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
1945
1981
  .cf-footer-actions .cf-booking {
1946
1982
  max-width: none;
1947
1983
  }
1984
+ .cf-body .cf-action-drawer,
1985
+ .cf-footer-actions .cf-action-drawer {
1986
+ max-height: min(420px, 45dvh);
1987
+ overflow-y: auto;
1988
+ overflow-x: hidden;
1989
+ overscroll-behavior: contain;
1990
+ scrollbar-width: thin;
1991
+ }
1948
1992
 
1949
1993
  @keyframes cf-drawer-up {
1950
1994
  from {
@@ -3347,8 +3391,8 @@ $2`),Yr=e=>{let t=[],n=0,r=0,i;for(qr.lastIndex=0;(i=qr.exec(e))!==null;){i.inde
3347
3391
  .cf-analytics-explanation .cf-xp { font-size: 12px; }
3348
3392
  .cf-analytics-explanation.is-expanded .cf-xp { font-size: 14px; }
3349
3393
  .cf-analytics-explanation .cf-xp__headline { font-size: 15px; }
3350
- ${Ae(`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)`})}
3351
- ${xn(`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:yn,chartDark:bn,darkSelector:`.cf-root[data-theme='dark']`})}
3394
+ ${je(`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)`})}
3395
+ ${Sn(`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:bn,chartDark:xn,darkSelector:`.cf-root[data-theme='dark']`})}
3352
3396
 
3353
3397
  @media (max-width: 639px) {
3354
3398
  .cf-panel.cf-panel--analytics-focus {
@@ -3469,4 +3513,4 @@ ${xn(`cf`,{bg:`var(--cf-bg)`,surface:`var(--cf-surface)`,surface2:`var(--cf-surf
3469
3513
  max-height: calc(100dvh - 24px);
3470
3514
  }
3471
3515
  }
3472
- `;export{gr as A,Q as B,Li as C,Qr as D,zi as E,Ir as F,Zt as G,In as H,Vr as I,Wt as J,qt as K,Br as L,zr as M,Mr as N,Kr as O,jr as P,ir as R,Ji as S,Ri as T,En as U,cr as V,en as W,M as X,jt as Y,h as Z,Ai as _,so as a,Xi as b,fa as c,oa as d,ra as f,na as g,Zi as h,oo as i,Rr as j,hr as k,ga as l,ta as m,uo as n,pa as o,ea as p,Yt as q,ao as r,ha as s,fo as t,la as u,ai as v,Ni as w,Pi as x,li as y,nr as z};
3516
+ `;export{_r as A,Q as B,Ri as C,$r as D,Bi as E,Lr as F,Qt as G,Ln as H,Hr as I,Gt as J,Jt as K,Vr as L,Br as M,Nr as N,qr as O,Mr as P,ar as R,Yi as S,zi as T,Dn as U,lr as V,tn as W,N as X,Mt as Y,h as Z,ji as _,co as a,Zi as b,pa as c,sa as d,ia as f,ra as g,Qi as h,so as i,zr as j,gr as k,_a as l,na as m,fo as n,ma as o,ta as p,Xt as q,oo as r,ga as s,po as t,ua as u,oi as v,Pi as w,Fi as x,ui as y,rr as z};