@flowengage/react-chatbot 8.0.141 → 8.0.142

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,7 +1,7 @@
1
1
  "use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(e&&(t=e(e=0)),t),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=e=>a.call(e,`module.exports`)?e[`module.exports`]:c(t({},`__esModule`,{value:!0}),e);let d=require(`react`);d=l(d);let f=require(`react/jsx-runtime`);var p=e=>{if(!e||typeof e!=`object`)throw Error(`FlowEngage config is required`);if(!e.siteId||typeof e.siteId!=`string`)throw Error(`[FlowEngage] config.siteId is required. Pass it as <FlowEngageProvider siteId="your-site-id" /> or config={{ siteId: 'your-site-id' }}.`);let t=(e.apiBaseUrl||`https://be-flowengage-dev.oslabs.app`).replace(/\/+$/,``);return{siteId:e.siteId.trim(),apiBaseUrl:t}},m=(e,t)=>{let n=Number.parseInt(String(e??``),10);return Number.isFinite(n)&&n>0?n:t},h=m(void 0,1e4),g=m(void 0,15e3),_={chatId:`flowengage.chatId`,isOpen:`flowengage.isOpen`,activeScreen:`flowengage.activeScreen`,isHumanHandled:`flowengage.isHumanHandled`,agentName:`flowengage.agentName`,agentHeadshot:`flowengage.agentHeadshot`,visitorEmail:`flowengage.visitorEmail`},v=6e4,y=480*60,b=3e4,x=typeof window<`u`,S=e=>e?`flowengage.visitorEmail.${e}`:null,C=()=>{if(!x)return null;let e=window.localStorage.getItem(_.chatId);return e&&String(e).trim()?String(e).trim():null},w=()=>{if(x)try{window.localStorage.removeItem(_.chatId)}catch{}},T=()=>x?typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`:`server-chat-id`,E=e=>e?`flowengage.entrySeen.${e}`:null,ee=e=>{if(!x||!e)return!1;try{let t=E(e);return t?window.localStorage.getItem(t)===`1`:!1}catch{return!1}},D=e=>{if(!(!x||!e))try{let t=E(e);t&&window.localStorage.setItem(t,`1`)}catch{}},te=e=>e?`flowengage.navPreference.${e}`:null,ne=e=>e?`flowengage.navPreferencePromptShown.${e}`:null,re=e=>{if(!x||!e)return null;try{let t=te(e),n=t?window.localStorage.getItem(t):null;return n===`auto`||n===`ask`?n:null}catch{return null}},O=(e,t)=>{if(!(!x||!e||t!==`auto`&&t!==`ask`))try{let n=te(e);n&&window.localStorage.setItem(n,t),ae(e)}catch{}},ie=e=>{if(!x||!e)return!1;try{let t=ne(e);return t?window.localStorage.getItem(t)===`1`:!1}catch{return!1}},ae=e=>{if(!(!x||!e))try{let t=ne(e);t&&window.localStorage.setItem(t,`1`)}catch{}},k=e=>e?`flowengage.persistedChatId.${e}`:null,oe=e=>{if(!x||!e)return null;try{let t=k(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},se=e=>{if(!(!x||!e))try{let t=k(e);t&&window.localStorage.removeItem(t)}catch{}},ce=(e,t)=>{if(!(!x||!e||!t))try{let n=k(e);n&&window.localStorage.setItem(n,String(t).trim())}catch{}},le=()=>x?{isOpen:!1,activeScreen:window.sessionStorage.getItem(_.activeScreen)||`ai`,isHumanHandled:window.sessionStorage.getItem(_.isHumanHandled)===`true`,agentName:window.sessionStorage.getItem(_.agentName),agentHeadshot:window.sessionStorage.getItem(_.agentHeadshot),visitorEmail:``}:{isOpen:!1,activeScreen:`ai`,isHumanHandled:!1,agentName:null,agentHeadshot:null,visitorEmail:``},ue=e=>{x&&Object.entries(e).forEach(([e,t])=>{let n=_[e];if(n){if(t==null||t===!1){window.sessionStorage.removeItem(n);return}window.sessionStorage.setItem(n,String(t))}})},de=e=>{if(!x||!e)return``;let t=S(e),n=window.localStorage.getItem(t);if(!n){let e=window.sessionStorage.getItem(_.visitorEmail);e&&(window.localStorage.setItem(t,e),window.sessionStorage.removeItem(_.visitorEmail),n=e)}return n||``},fe=(e,t)=>{if(!x)return;let n=S(t);if(!n)return;let r=typeof e==`string`?e.trim():``;if(!r){window.localStorage.removeItem(n),window.sessionStorage.removeItem(_.visitorEmail);return}window.localStorage.setItem(n,r),window.sessionStorage.removeItem(_.visitorEmail)},A=e=>e?`flowengage.visitorId.${e}`:null,pe=()=>`v_${Date.now().toString(36)}_${typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,``).slice(0,16):Math.random().toString(36).slice(2,18)}`,j=e=>{if(!x||!e)return null;try{let t=A(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},me=e=>{if(!x||!e)return null;try{let t=j(e);if(t)return t;let n=pe(),r=A(e);return r&&window.localStorage.setItem(r,n),n}catch{return pe()}},he=`flowengage.tabId`,M=()=>{if(!x)return`default`;try{let e=window.sessionStorage.getItem(he);return e||(e=typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,``).slice(0,12):Math.random().toString(36).slice(2,14),window.sessionStorage.setItem(he,e)),e}catch{return`default`}},N=e=>e?`flowengage.voice.transcript.${e}.${M()}`:null,ge=600*1e3,_e=(e,t,n={})=>{if(!x||!e)return;let r=typeof t==`string`?t.trim():``;if(!r)return;let i=Number.isFinite(n.ttlMs)?n.ttlMs:ge,a={transcript:r,expiresAt:Date.now()+i};try{let t=N(e);t&&window.localStorage.setItem(t,JSON.stringify(a))}catch{}},ve=e=>{if(!x||!e)return null;try{let t=N(e),n=t?window.localStorage.getItem(t):null;if(!n)return null;let r=JSON.parse(n);return!r||typeof r.transcript!=`string`?null:Number.isFinite(r.expiresAt)&&Date.now()>r.expiresAt?(window.localStorage.removeItem(t),null):r}catch{return null}},ye=e=>{if(!(!x||!e))try{let t=N(e);t&&window.localStorage.removeItem(t)}catch{}},P=`flowengage.voice.pendingResume`,F=()=>{if(x)try{window.sessionStorage.setItem(P,`1`)}catch{}},be=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(P)===`1`?(window.sessionStorage.removeItem(P),!0):!1}catch{return!1}},I=`flowengage.chat.pendingReopen`,xe=()=>{if(x)try{window.sessionStorage.setItem(I,`1`)}catch{}},Se=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(I)===`1`?(window.sessionStorage.removeItem(I),!0):!1}catch{return!1}},Ce=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(P)===`1`}catch{return!1}},L=e=>e?`flowengage.voice.navState.${e}.${M()}`:null,we=(e,t,n,r)=>{if(!(!x||!e||!t))try{let i=L(e);i&&window.sessionStorage.setItem(i,JSON.stringify({previousPage:String(t),targetPath:n?new URL(String(n),window.location.href).pathname:null,pageName:r||null,ts:Date.now()}))}catch{}},Te=e=>{if(!x||!e)return null;try{let t=L(e);if(!t)return null;let n=window.sessionStorage.getItem(t);if(!n)return null;window.sessionStorage.removeItem(t);let r=JSON.parse(n);return!r||typeof r.previousPage!=`string`||Number.isFinite(r.ts)&&Date.now()-r.ts>6e4||r.targetPath&&(window.location.pathname.replace(/\/$/,``)||`/`)!==(r.targetPath.replace(/\/$/,``)||`/`)?null:{previousPage:r.previousPage,pageName:r.pageName||null}}catch{return null}},Ee=async e=>{let t=await e.json().catch(()=>({}));if(!e.ok){let n=Error(t.message||t.error||`Request failed with status ${e.status}`);throw n.status=e.status,n}return t},De=async(e,t={})=>{try{return await fetch(e,{mode:`cors`,...t})}catch(t){let n=Error(`Network error reaching ${e}. Check: (1) backend is running, (2) CORS allows this origin, (3) siteId is correct. Original: ${t.message}`);throw n.status=0,n.cause=t,n}},Oe=async({apiBaseUrl:e,userId:t,siteId:n,priorChatId:r=null,forceNew:i=!1,resumeChatId:a=null,visitorId:o=null})=>{let s=`${e}/api/visitors/resolve-session`,c={siteId:n};return r&&String(r).trim()&&(c.priorChatId=String(r).trim()),i&&(c.forceNew=!0),a&&(c.resumeChatId=a),o&&(c.visitorId=o),Ee(await De(s,{method:`POST`,mode:`cors`,headers:{"Content-Type":`application/json`,"x-user-id":t==null?``:String(t),...n?{"x-site-id":n}:{},...o?{"x-visitor-id":o}:{}},body:JSON.stringify(c)}))},ke=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`;return(await Ee(await De(`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`,{method:`GET`}))).data},Ae=({apiBaseUrl:e,userId:t,siteId:n,visitorId:r=null})=>{let i=(t,n)=>{let r=`${e}${t}`,i=JSON.stringify(n);if(typeof navigator<`u`&&navigator.sendBeacon)try{let e=new Blob([i],{type:`application/json`});return navigator.sendBeacon(r,e)}catch{}return typeof fetch<`u`?(fetch(r,{method:`POST`,mode:`cors`,keepalive:!0,headers:{"Content-Type":`application/json`},body:i}).catch(()=>{}),!0):!1},a=async(i,a={})=>Ee(await De(`${e}${i}`,{...a,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...r?{"x-visitor-id":r}:{},...a.headers||{}}})),o=async(r,i,a={})=>{let o={"x-user-id":t,...n?{"x-site-id":n}:{},...a.headers||{}};return Ee(await De(`${e}${r}`,{...a,body:i,headers:o}))};return{async loadHistory(e,t=`en`,n=``){return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:``,lang:t,category:n})})},async sendAiMessage(i,o,s=`en`,c=``,l=null,u={},d=null){let f={session_id:i,user_query:o,lang:s,category:c,...u||{},...l||{}};if(typeof d!=`function`)return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify(f)});let p=await De(`${e}/api/ai/chat`,{method:`POST`,headers:{"Content-Type":`application/json`,"x-user-id":t,...n?{"x-site-id":n}:{},...r?{"x-visitor-id":r}:{}},body:JSON.stringify({...f,stream:!0})});if(!(p.headers.get(`content-type`)||``).includes(`text/event-stream`))return Ee(p);let m=p.body.getReader(),h=new TextDecoder,g=``,_=null,v=e=>{let t=e.split(`
2
2
  `).find(e=>e.startsWith(`data: `));if(t)try{let e=JSON.parse(t.slice(6));e.type===`delta`&&e.text?d(e.text):e.type===`done`&&(_=e.payload)}catch{}};for(;;){let{done:e,value:t}=await m.read();if(e)break;g+=h.decode(t,{stream:!0});let n;for(;(n=g.indexOf(`
3
3
 
4
- `))!==-1;)v(g.slice(0,n)),g=g.slice(n+2)}if(!_){let e=Error(`The response stream ended unexpectedly — please try again.`);throw e.status=0,e}return _},async uploadChatFile(e){let t=new FormData;return t.append(`file`,e),o(`/api/upload`,t,{method:`POST`})},async checkHumanHandled(e){return a(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return a(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return a(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return a(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:r,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}})})},async trackVisitor(e){return a(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async getVisitorChatHistory(){return a(`/api/visitors/my-chats`,{method:`GET`})},async getVisitorChatThread(e){return a(`/api/visitors/my-chats/${e}`,{method:`GET`})},async getOlderMessages(e,t,n=30){return a(`/api/visitors/my-chats/${e}?before=${encodeURIComponent(t)}&limit=${n}`,{method:`GET`})},async acceptCall(e,t){return a(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return a(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async getIceServersConfig(){return Ee(await De(`${e}/api/calls/ice-config`,{method:`GET`,headers:{"x-user-id":t,...n?{"x-site-id":n}:{}}}))},async endWebRTCCall(e,t){return a(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return a(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async uploadRecording(e,t,n){let r=new FormData,i=`call-rec-${Date.now()}.webm`;return r.append(`audio`,t,i),r.append(`duration`,String(n)),o(`/api/calls/${e}/recording`,r,{method:`POST`})},beaconEndWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a=new URLSearchParams;return a.append(`session_id`,r),a.append(`messages`,JSON.stringify(i)),t&&a.append(`userId`,String(t)),n&&a.append(`siteId`,String(n)),navigator.sendBeacon(`${e}/api/ai/voice/sync`,a)},beaconWidgetClosed(r){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let i=new URLSearchParams;return i.append(`chatId`,r),i.append(`type`,`widget_closed`),t&&i.append(`userId`,String(t)),n&&i.append(`siteId`,String(n)),navigator.sendBeacon(`${e}/api/chat/status`,i)}}},R=Object.create(null);R.open=`0`,R.close=`1`,R.ping=`2`,R.pong=`3`,R.message=`4`,R.upgrade=`5`,R.noop=`6`;var je=Object.create(null);Object.keys(R).forEach(e=>{je[R[e]]=e});var Me={type:`error`,data:`parser error`},Ne=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,Pe=typeof ArrayBuffer==`function`,Fe=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Ie=({type:e,data:t},n,r)=>Ne&&t instanceof Blob?n?r(t):Le(t,r):Pe&&(t instanceof ArrayBuffer||Fe(t))?n?r(t):Le(new Blob([t]),r):r(R[e]+(t||``)),Le=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function Re(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var ze;function z(e,t){if(Ne&&e.data instanceof Blob)return e.data.arrayBuffer().then(Re).then(t);if(Pe&&(e.data instanceof ArrayBuffer||Fe(e.data)))return t(Re(e.data));Ie(e,!1,e=>{ze||=new TextEncoder,t(ze.encode(e))})}var Be=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,B=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)B[Be.charCodeAt(e)]=e;var Ve=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=B[e.charCodeAt(r)],o=B[e.charCodeAt(r+1)],s=B[e.charCodeAt(r+2)],c=B[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},He=typeof ArrayBuffer==`function`,Ue=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Ge(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:We(e.substring(1),t)}:je[n]?e.length>1?{type:je[n],data:e.substring(1)}:{type:je[n]}:Me},We=(e,t)=>He?Ge(Ve(e),t):{base64:!0,data:e},Ge=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Ke=``,qe=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{Ie(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Ke))})})},Je=(e,t)=>{let n=e.split(Ke),r=[];for(let e=0;e<n.length;e++){let i=Ue(n[e],t);if(r.push(i),i.type===`error`)break}return r};function Ye(){return new TransformStream({transform(e,t){z(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var Xe;function V(e){return e.reduce((e,t)=>e+t.length,0)}function H(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function U(e,t){Xe||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(V(n)<1)break;let e=H(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(V(n)<2)break;let e=H(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(V(n)<8)break;let e=H(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(Me);break}i=a*2**32+t.getUint32(4),r=3}else{if(V(n)<i)break;let e=H(n,i);s.enqueue(Ue(a?e:Xe.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(Me);break}}}})}function W(e){if(e)return Ze(e)}function Ze(e){for(var t in W.prototype)e[t]=W.prototype[t];return e}W.prototype.on=W.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},W.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},W.prototype.off=W.prototype.removeListener=W.prototype.removeAllListeners=W.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},W.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},W.prototype.emitReserved=W.prototype.emit,W.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},W.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Qe=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),$e=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),et=`arraybuffer`;function tt(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var nt=$e.setTimeout,rt=$e.clearTimeout;function it(e,t){t.useNativeTimers?(e.setTimeoutFn=nt.bind($e),e.clearTimeoutFn=rt.bind($e)):(e.setTimeoutFn=$e.setTimeout.bind($e),e.clearTimeoutFn=$e.clearTimeout.bind($e))}var at=1.33;function ot(e){return typeof e==`string`?st(e):Math.ceil((e.byteLength||e.size)*at)}function st(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function ct(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function G(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function lt(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var ut=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},dt=class extends W{constructor(e){super(),this.writable=!1,it(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new ut(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=Ue(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=G(e);return t.length?`?`+t:``}},ft=class extends dt{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){Je(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,qe(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=ct()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},pt=!1;try{pt=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var mt=pt;function ht(){}var gt=class extends ft{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},_t=class e extends W{constructor(e,t,n){super(),this.createRequest=e,it(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=tt(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(this._xhr===void 0||this._xhr===null)){if(this._xhr.onreadystatechange=ht,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(_t.requestsCount=0,_t.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,vt);else if(typeof addEventListener==`function`){let e=`onpagehide`in $e?`pagehide`:`unload`;addEventListener(e,vt,!1)}}function vt(){for(let e in _t.requests)_t.requests.hasOwnProperty(e)&&_t.requests[e].abort()}var yt=(function(){let e=xt({xdomain:!1});return e&&e.responseType!==null})(),bt=class extends gt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=yt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new _t(xt,this.uri(),e)}};function xt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||mt))return new XMLHttpRequest}catch{}if(!t)try{return new $e[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var St=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,Ct=class extends dt{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=St?{}:tt(this.opts,`agent`,`perMessageDeflate`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`localAddress`,`protocolVersion`,`origin`,`maxPayload`,`family`,`checkServerIdentity`);this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;Ie(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&Qe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ct()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},wt=$e.WebSocket||$e.MozWebSocket,Tt={websocket:class extends Ct{createSocket(e,t,n){return St?new wt(e,t,n):t?new wt(e,t):new wt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends dt{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=U(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=Ye();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&Qe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:bt},Et=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Dt=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function Ot(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=Et.exec(e||``),a={},o=14;for(;o--;)a[Dt[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=kt(a,a.path),a.queryKey=At(a,a.query),a}function kt(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function At(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var jt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,Mt=[];jt&&addEventListener(`offline`,()=>{Mt.forEach(e=>e())},!1);var Nt=class e extends W{constructor(e,t){if(super(),this.binaryType=et,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=Ot(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Ot(t.host).host);it(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:`/engine.io`,agent:!1,withCredentials:!1,upgrade:!0,timestampParam:`t`,rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=lt(this.opts.query)),jt&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},Mt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data);break}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=ot(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Qe(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),jt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=Mt.indexOf(this._offlineEventListener);e!==-1&&Mt.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Nt.protocol=4;var Pt=class extends Nt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Nt.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n)if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;Nt.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},Ft=class extends Pt{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>Tt[e]).filter(e=>!!e)),super(e,n)}};Ft.protocol;function It(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=Ot(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var Lt=typeof ArrayBuffer==`function`,Rt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,zt=Object.prototype.toString,Bt=typeof Blob==`function`||typeof Blob<`u`&&zt.call(Blob)===`[object BlobConstructor]`,Vt=typeof File==`function`||typeof File<`u`&&zt.call(File)===`[object FileConstructor]`;function Ht(e){return Lt&&(e instanceof ArrayBuffer||Rt(e))||Bt&&e instanceof Blob||Vt&&e instanceof File}function Ut(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Ut(e[t]))return!0;return!1}if(Ht(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Ut(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ut(e[t]))return!0;return!1}function Wt(e){let t=[],n=e.data,r=e;return r.data=Gt(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Gt(e,t){if(!e)return e;if(Ht(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=Gt(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=Gt(e[r],t));return n}return e}function Kt(e,t){return e.data=qt(e.data,t),delete e.attachments,e}function qt(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=qt(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=qt(e[n],t));return e}var Jt=s({Decoder:()=>Zt,Encoder:()=>Xt,PacketType:()=>K,isPacketValid:()=>an,protocol:()=>5}),Yt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],K;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(K||={});var Xt=class{constructor(e){this.replacer=e}encode(e){return(e.type===K.EVENT||e.type===K.ACK)&&Ut(e)?this.encodeAsBinary({type:e.type===K.EVENT?K.BINARY_EVENT:K.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===K.BINARY_EVENT||e.type===K.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Wt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Zt=class e extends W{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===K.BINARY_EVENT;n||t.type===K.BINARY_ACK?(t.type=n?K.EVENT:K.ACK,this.reconstructor=new Qt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(Ht(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`);else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(K[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===K.BINARY_EVENT||r.type===K.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!en(a)||a<0)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&!(t.charAt(n)===`,`||n===t.length););r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case K.CONNECT:return nn(t);case K.DISCONNECT:return t===void 0;case K.CONNECT_ERROR:return typeof t==`string`||nn(t);case K.EVENT:case K.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Yt.indexOf(t[0])===-1);case K.ACK:case K.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Qt=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=Kt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function $t(e){return typeof e==`string`}var en=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function tn(e){return e===void 0||en(e)}function nn(e){return Object.prototype.toString.call(e)===`[object Object]`}function rn(e,t){switch(e){case K.CONNECT:return t===void 0||nn(t);case K.DISCONNECT:return t===void 0;case K.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Yt.indexOf(t[0])===-1);case K.ACK:return Array.isArray(t);case K.CONNECT_ERROR:return typeof t==`string`||nn(t);default:return!1}}function an(e){return $t(e.nsp)&&tn(e.id)&&rn(e.type,e.data)}function on(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var sn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),cn=class extends W{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[on(e,`open`,this.onopen.bind(this)),on(e,`packet`,this.onpacket.bind(this)),on(e,`error`,this.onerror.bind(this)),on(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(sn.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:K.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:K.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case K.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,Error(`It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)`));break;case K.EVENT:case K.BINARY_EVENT:this.onevent(e);break;case K.ACK:case K.BINARY_ACK:this.onack(e);break;case K.DISCONNECT:this.ondisconnect();break;case K.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:K.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:K.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function ln(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ln.prototype.duration=function(){var e=this.ms*this.factor**+ this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},ln.prototype.reset=function(){this.attempts=0},ln.prototype.setMin=function(e){this.ms=e},ln.prototype.setMax=function(e){this.max=e},ln.prototype.setJitter=function(e){this.jitter=e};var un=class extends W{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,it(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new ln({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||Jt;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new Ft(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=on(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=on(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(on(e,`ping`,this.onping.bind(this)),on(e,`data`,this.ondata.bind(this)),on(e,`error`,this.onerror.bind(this)),on(e,`close`,this.onclose.bind(this)),on(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){Qe(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new cn(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},dn={};function fn(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=It(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=dn[i]&&a in dn[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new un(r,t):(dn[i]||(dn[i]=new un(r,t)),c=dn[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(fn,{Manager:un,Socket:cn,io:fn,connect:fn});var pn=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>fn(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),mn=({socket:e,chatId:t})=>{if(!e||!t||typeof window>`u`)return()=>{};let n=window.location.pathname+window.location.search,r=Date.now(),i=null,a=null,o=()=>{console.log(`[FlowEngageTracking] visitor:session_start`,{chatId:t,path:n}),e.emit(`visitor:session_start`,{chatId:t,path:n,title:document.title,referrer:document.referrer,userAgent:navigator.userAgent,timestamp:Date.now()})},s=()=>{console.log(`[FlowEngageTracking] visitor:page_enter`,{chatId:t,path:n}),e.emit(`visitor:page_enter`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},c=(n,r)=>{console.log(`[FlowEngageTracking] visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3))}),e.emit(`visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3)),timestamp:Date.now()})},l=()=>{console.log(`[FlowEngageTracking] visitor:heartbeat`,{chatId:t,path:n}),e.emit(`visitor:heartbeat`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},u=()=>{i&&window.clearInterval(i),i=window.setInterval(l,h)},d=()=>{i&&=(window.clearInterval(i),null)},f=r=>{console.log(`[FlowEngageTracking] visitor:visibility`,{chatId:t,state:r}),e.emit(`visitor:visibility`,{chatId:t,state:r,path:n,title:document.title,timestamp:Date.now()})},p=()=>{if(document.hidden){a&&window.clearTimeout(a),a=window.setTimeout(()=>{a=null,d(),f(`hidden`)},g);return}a&&=(window.clearTimeout(a),null),f(`visible`),l(),u()},m=()=>{let e=window.location.pathname+window.location.search;if(e===n){console.log(`[FlowEngageTracking] route unchanged`,{currentPath:n});return}console.log(`[FlowEngageTracking] route changed`,{from:n,to:e}),c(n,r),n=e,r=Date.now(),s()},_=window.history.pushState.bind(window.history),v=window.history.replaceState.bind(window.history);window.history.pushState=(...e)=>{_(...e),m()},window.history.replaceState=(...e)=>{v(...e),m()};let y=()=>{c(n,r),e.emit(`visitor:session_end`,{chatId:t,timestamp:Date.now()})},b=()=>{y()},x=e=>{e.persisted||y()};return window.addEventListener(`popstate`,m),window.addEventListener(`hashchange`,m),window.addEventListener(`beforeunload`,b),window.addEventListener(`pagehide`,x),window.addEventListener(`visibilitychange`,p),o(),document.hidden?a=window.setTimeout(()=>{a=null,d(),f(`hidden`)},g):(l(),u()),{notifyRouteChange:m,cleanup:()=>{a&&=(window.clearTimeout(a),null),d(),window.history.pushState=_,window.history.replaceState=v,window.removeEventListener(`popstate`,m),window.removeEventListener(`hashchange`,m),window.removeEventListener(`beforeunload`,b),window.removeEventListener(`pagehide`,x),window.removeEventListener(`visibilitychange`,p)}}},hn=(0,d.createContext)(null),gn=()=>{let e=(0,d.useContext)(hn);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function _n(){if(typeof window>`u`)return!1;try{let e=window.localStorage?.getItem(`FE_DEBUG_VOICE`);if(e===`0`||e===`false`)return!1;if(e===`1`||e===`true`)return!0}catch{}return window.__FE_DEBUG_VOICE_TOOLS__===!1?!1:window.__FE_DEBUG_VOICE_TOOLS__===!0}var vn=16,yn=.4;function bn(){let e=0;for(let t of document.querySelectorAll(`header, nav, [role='banner'], [class*='header'], [class*='navbar']`)){if(t.closest(`.flowengage-widget-root, #flowengage-root, .flowengage-shell`))continue;let{position:n}=getComputedStyle(t);if(n!==`fixed`&&n!==`sticky`)continue;let r=t.getBoundingClientRect();r.top<=1&&r.bottom>0&&r.height<window.innerHeight*yn&&(e=Math.max(e,r.bottom))}return e}function xn(e){requestAnimationFrame(()=>{let t=bn()+vn,n=e.getBoundingClientRect(),r=window.innerHeight-t,i=n.height<r?(r-n.height)/2:0;window.scrollTo({top:Math.max(0,window.pageYOffset+n.top-t-i),behavior:`smooth`})})}function Sn(e){e&&(e.hasAttribute(`data-fe-highlighted`)||(Cn(),e.classList?.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`),xn(e),e.setAttribute(`data-fe-orig-style`,e.style.cssText),e.setAttribute(`data-fe-highlighted`,`true`),e.style.outline=`3px solid #2563eb`,e.style.outlineOffset=e.getBoundingClientRect().width>=document.documentElement.clientWidth-vn?`-8px`:`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.transition=`all 0.4s ease`))}function Cn(){let e=document.querySelector(`[data-fe-highlighted]`);e&&(e.style.cssText=e.getAttribute(`data-fe-orig-style`)||``,e.removeAttribute(`data-fe-highlighted`),e.removeAttribute(`data-fe-orig-style`))}var wn=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function Tn(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(wn)}catch{return!1}}function En(e){let t=e.cloneNode(!0);return t.querySelectorAll(`[aria-hidden], svg, .icon, [class*="icon"]`).forEach(e=>e.remove()),t.textContent.replace(/\s+/g,` `).trim()}function q(...e){_n()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var Dn=`fe_pending_nav_section`,On=15e3,kn=`fe_voice_nav_state`,An=2e4,jn=!1,Mn=null;function Nn(e=3e3){jn=!0,Mn&&clearTimeout(Mn),Mn=setTimeout(()=>{jn=!1,Mn=null},e)}function Pn(){return jn}var Fn=!1,In=null;function Ln(){Fn||typeof window>`u`||(Fn=!0,window.addEventListener(`popstate`,async()=>{let e=window.location.href;if(q(`popstate: body-swap to`,e),In){try{Kn(In)}catch{}try{Yn(In)}catch{}}try{if(await Sr(e,{skipPushState:!0,isBack:!0})){q(`popstate: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] popstate body-swap error:`,e)}q(`popstate: body-swap failed, falling back to reload`),window.location.reload()}))}var Rn=!1;function zn(){Rn||typeof window>`u`||typeof document>`u`||(Rn=!0,document.addEventListener(`click`,async e=>{try{if(!window.history.state?.flowengageSpa)return}catch{return}let t=e.target.closest?.(`a[href]`);if(!t||t.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`))return;let n=t.getAttribute(`href`)||``;if(!n||n===`#`||n.startsWith(`javascript:`)||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||t.hasAttribute(`download`)||t.target===`_blank`||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;let r;try{if(r=new URL(n,window.location.href),r.origin!==window.location.origin)return}catch{return}if(!(r.pathname===window.location.pathname&&r.hash)&&!(r.pathname===window.location.pathname&&r.search===window.location.search)){e.preventDefault(),e.stopPropagation(),q(`link-intercept: body-swap to`,r.href),$n();try{try{Kn()}catch{}try{Yn()}catch{}if(await Sr(r.href)){q(`link-intercept: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] link-intercept body-swap error:`,e)}q(`link-intercept: body-swap failed, falling back to normal navigation`),er(),window.location.href=r.href}},!0))}var Bn=null;function Vn(e){Bn=e===`spa`||e===`traditional`?e:null}function Hn(){if(typeof window>`u`||Bn===`traditional`)return null;if(window.next?.router||window.__NEXT_ROUTER__)return`nextjs`;if(window.__remixRouter||window.__staticRouterHydrationData)return`react-router`;if(window.___gatsby||window.___navigate)return`gatsby`;if(window.__VUE_ROUTER__)return`vue-router`;if(window.__NUXT__||window.$nuxt)return`nuxt`;if(window.ng?.getComponent||document.querySelector(`[ng-version]`))return`angular`;if(window[Symbol.for(`wouter_v3`)])return`wouter`;if(window.__sveltekit_data||document.querySelector(`[data-sveltekit-hydrate]`))return`sveltekit`;if(document.querySelector(`[data-astro-transition]`))return`astro`;for(let e of document.body.children)if(e.tagName?.toUpperCase()===`DIV`&&e.id!==`flowengage-root`&&(e.id===`root`||e.id===`app`)&&e.children.length>0)return`generic-spa`;return Bn===`spa`?`backend-spa`:null}var Un=`data-fe-swap-css`;function Wn(){typeof document>`u`||document.querySelectorAll(`[${Un}]`).forEach(e=>e.remove())}var Gn=`fe_form_state:`;function Kn(e){if(typeof document>`u`||typeof sessionStorage>`u`)return;let t=document.querySelectorAll(`form`);if(!t.length)return;let n=[];if(t.forEach((e,t)=>{let r={};e.querySelectorAll(`input, textarea, select`).forEach(e=>{let t=e.name||e.id;t&&(e.type===`password`||e.type===`hidden`||(e.type===`checkbox`||e.type===`radio`?r[t+`::`+e.value]=e.checked:r[t]=e.value))}),Object.keys(r).length&&n.push({formIndex:t,fields:r})}),n.length)try{let t=Gn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({state:n,ts:Date.now()}))}catch{}}function qn(){if(typeof document>`u`||typeof sessionStorage>`u`)return;let e=Gn+window.location.pathname,t;try{t=JSON.parse(sessionStorage.getItem(e)||`null`)}catch{return}if(!t||!t.state)return;if(Date.now()-t.ts>1800*1e3){try{sessionStorage.removeItem(e)}catch{}return}let n=document.querySelectorAll(`form`);for(let{formIndex:e,fields:r}of t.state){let t=n[e];if(t)for(let[e,n]of Object.entries(r))if(e.includes(`::`)){let[r,i]=e.split(`::`),a=t.querySelector(`input[name="${r}"][value="${i}"], input[id="${r}"][value="${i}"]`);a&&(a.checked=!!n)}else{let r=t.querySelector(`[name="${e}"], [id="${e}"]`);if(r&&r.type!==`file`){r.value=n;try{r.dispatchEvent(new Event(`input`,{bubbles:!0}))}catch{}try{r.dispatchEvent(new Event(`change`,{bubbles:!0}))}catch{}}}}try{sessionStorage.removeItem(e)}catch{}}var Jn=`fe_scroll:`;function Yn(e){if(!(typeof window>`u`||typeof sessionStorage>`u`))try{let t=Jn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({y:window.scrollY,ts:Date.now()}))}catch{}}function Xn(){if(typeof window>`u`||typeof sessionStorage>`u`)return;let e=Jn+window.location.pathname,t;try{t=JSON.parse(sessionStorage.getItem(e)||`null`)}catch{return}if(t){try{sessionStorage.removeItem(e)}catch{}Date.now()-t.ts>1800*1e3||setTimeout(()=>{window.scrollTo({top:t.y,behavior:`instant`})},80)}}function Zn(e){if(!(typeof window>`u`))try{window.dispatchEvent(new CustomEvent(`flowengage:pageswap`,{detail:{url:e,timestamp:Date.now()}}))}catch{}}var Qn=`fe-nav-loader`;function $n(){if(typeof document>`u`||document.getElementById(Qn))return;let e=document.createElement(`div`);e.id=Qn,e.style.cssText=[`position:fixed`,`top:0`,`left:0`,`width:0`,`height:3px`,`background:linear-gradient(90deg,#7c3aed,#6366f1)`,`z-index:2147483647`,`transition:width 0.4s ease`,`pointer-events:none`].join(`;`),document.body.appendChild(e),requestAnimationFrame(()=>{e.style.width=`70%`})}function er(){if(typeof document>`u`)return;let e=document.getElementById(Qn);e&&(e.style.width=`100%`,setTimeout(()=>{e.style.opacity=`0`,e.style.transition=`opacity 0.3s ease`,setTimeout(()=>e.remove(),350)},200))}function tr(){if(typeof window>`u`||typeof document>`u`)return;try{window.history.state?.flowengageSpa&&Ln()}catch{}let e;try{e=JSON.parse(sessionStorage.getItem(Dn)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(Dn)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>On){q(`initNavigationHighlight: pending section expired, skipping:`,t);return}q(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=rr(null,t);if(e){gr(e),q(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):q(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var nr=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
4
+ `))!==-1;)v(g.slice(0,n)),g=g.slice(n+2)}if(!_){let e=Error(`The response stream ended unexpectedly — please try again.`);throw e.status=0,e}return _},async uploadChatFile(e){let t=new FormData;return t.append(`file`,e),o(`/api/upload`,t,{method:`POST`})},async checkHumanHandled(e){return a(`/api/ai/check_human_handled`,{method:`POST`,body:JSON.stringify({session_id:e})})},async setChatMode(e,t){return a(`/api/ai/set_chat_mode`,{method:`POST`,body:JSON.stringify({session_id:e,mode:t})})},async toggleVoice(e){return a(`/api/ai/voice/toggle`,{method:`POST`,body:JSON.stringify({session_id:e})})},async syncVoice(e,r){return a(`/api/ai/voice/sync`,{method:`POST`,body:JSON.stringify({session_id:e,messages:r,...t?{userId:String(t)}:{},...n?{siteId:String(n)}:{}})})},async trackVisitor(e){return a(`/api/visitors/track`,{method:`POST`,body:JSON.stringify(e)})},async updateChatStatus(e,t){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:t})})},async startConversation(e,t=`en`){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`open`,lang:t})})},async endConversation(e){return a(`/api/chat/status`,{method:`POST`,body:JSON.stringify({chatId:e,type:`closed`})})},async getVisitorChatHistory(){return a(`/api/visitors/my-chats`,{method:`GET`})},async getVisitorChatThread(e){return a(`/api/visitors/my-chats/${e}`,{method:`GET`})},async getOlderMessages(e,t,n=30){return a(`/api/visitors/my-chats/${e}?before=${encodeURIComponent(t)}&limit=${n}`,{method:`GET`})},async acceptCall(e,t){return a(`/api/calls/${e}/accept`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async rejectCall(e,t){return a(`/api/calls/${e}/reject`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async getIceServersConfig(){return Ee(await De(`${e}/api/calls/ice-config`,{method:`GET`,headers:{"x-user-id":t,...n?{"x-site-id":n}:{}}}))},async endWebRTCCall(e,t){return a(`/api/calls/${e}/end`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n,endedBy:`customer`})})},async markCustomerUnavailable(e,t){return a(`/api/calls/${e}/customer-unavailable`,{method:`POST`,body:JSON.stringify({session_id:t,site_id:n})})},async uploadRecording(e,t,n){let r=new FormData,i=`call-rec-${Date.now()}.webm`;return r.append(`audio`,t,i),r.append(`duration`,String(n)),o(`/api/calls/${e}/recording`,r,{method:`POST`})},beaconEndWebRTCCall(e,t){return i(`/api/calls/${e}/end`,{session_id:t,site_id:n,endedBy:`customer`})},beaconCustomerUnavailable(e,t){return i(`/api/calls/${e}/customer-unavailable`,{session_id:t,site_id:n})},beaconSyncVoice(r,i){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let a=new URLSearchParams;return a.append(`session_id`,r),a.append(`messages`,JSON.stringify(i)),t&&a.append(`userId`,String(t)),n&&a.append(`siteId`,String(n)),navigator.sendBeacon(`${e}/api/ai/voice/sync`,a)},beaconWidgetClosed(r){if(typeof navigator>`u`||!navigator.sendBeacon)return!1;let i=new URLSearchParams;return i.append(`chatId`,r),i.append(`type`,`widget_closed`),t&&i.append(`userId`,String(t)),n&&i.append(`siteId`,String(n)),navigator.sendBeacon(`${e}/api/chat/status`,i)}}},R=Object.create(null);R.open=`0`,R.close=`1`,R.ping=`2`,R.pong=`3`,R.message=`4`,R.upgrade=`5`,R.noop=`6`;var je=Object.create(null);Object.keys(R).forEach(e=>{je[R[e]]=e});var Me={type:`error`,data:`parser error`},Ne=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,Pe=typeof ArrayBuffer==`function`,Fe=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Ie=({type:e,data:t},n,r)=>Ne&&t instanceof Blob?n?r(t):Le(t,r):Pe&&(t instanceof ArrayBuffer||Fe(t))?n?r(t):Le(new Blob([t]),r):r(R[e]+(t||``)),Le=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function Re(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var ze;function z(e,t){if(Ne&&e.data instanceof Blob)return e.data.arrayBuffer().then(Re).then(t);if(Pe&&(e.data instanceof ArrayBuffer||Fe(e.data)))return t(Re(e.data));Ie(e,!1,e=>{ze||=new TextEncoder,t(ze.encode(e))})}var Be=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,B=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)B[Be.charCodeAt(e)]=e;var Ve=e=>{let t=e.length*.75,n=e.length,r,i=0,a,o,s,c;e[e.length-1]===`=`&&(t--,e[e.length-2]===`=`&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(r=0;r<n;r+=4)a=B[e.charCodeAt(r)],o=B[e.charCodeAt(r+1)],s=B[e.charCodeAt(r+2)],c=B[e.charCodeAt(r+3)],u[i++]=a<<2|o>>4,u[i++]=(o&15)<<4|s>>2,u[i++]=(s&3)<<6|c&63;return l},He=typeof ArrayBuffer==`function`,Ue=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Ge(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:We(e.substring(1),t)}:je[n]?e.length>1?{type:je[n],data:e.substring(1)}:{type:je[n]}:Me},We=(e,t)=>He?Ge(Ve(e),t):{base64:!0,data:e},Ge=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Ke=``,qe=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{Ie(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Ke))})})},Je=(e,t)=>{let n=e.split(Ke),r=[];for(let e=0;e<n.length;e++){let i=Ue(n[e],t);if(r.push(i),i.type===`error`)break}return r};function Ye(){return new TransformStream({transform(e,t){z(e,n=>{let r=n.length,i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);let e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);let e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!=`string`&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}var Xe;function V(e){return e.reduce((e,t)=>e+t.length,0)}function H(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function U(e,t){Xe||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(V(n)<1)break;let e=H(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(V(n)<2)break;let e=H(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(V(n)<8)break;let e=H(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(Me);break}i=a*2**32+t.getUint32(4),r=3}else{if(V(n)<i)break;let e=H(n,i);s.enqueue(Ue(a?e:Xe.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(Me);break}}}})}function W(e){if(e)return Ze(e)}function Ze(e){for(var t in W.prototype)e[t]=W.prototype[t];return e}W.prototype.on=W.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},W.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},W.prototype.off=W.prototype.removeListener=W.prototype.removeAllListeners=W.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks[`$`+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks[`$`+e],this;for(var r,i=0;i<n.length;i++)if(r=n[i],r===t||r.fn===t){n.splice(i,1);break}return n.length===0&&delete this._callbacks[`$`+e],this},W.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks[`$`+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,i=n.length;r<i;++r)n[r].apply(this,t)}return this},W.prototype.emitReserved=W.prototype.emit,W.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},W.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Qe=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),$e=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),et=`arraybuffer`;function tt(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var nt=$e.setTimeout,rt=$e.clearTimeout;function it(e,t){t.useNativeTimers?(e.setTimeoutFn=nt.bind($e),e.clearTimeoutFn=rt.bind($e)):(e.setTimeoutFn=$e.setTimeout.bind($e),e.clearTimeoutFn=$e.clearTimeout.bind($e))}var at=1.33;function ot(e){return typeof e==`string`?st(e):Math.ceil((e.byteLength||e.size)*at)}function st(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}function ct(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function G(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function lt(e){let t={},n=e.split(`&`);for(let e=0,r=n.length;e<r;e++){let r=n[e].split(`=`);t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}var ut=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},dt=class extends W{constructor(e){super(),this.writable=!1,it(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved(`error`,new ut(e,t,n)),this}open(){return this.readyState=`opening`,this.doOpen(),this}close(){return(this.readyState===`opening`||this.readyState===`open`)&&(this.doClose(),this.onClose()),this}send(e){this.readyState===`open`&&this.write(e)}onOpen(){this.readyState=`open`,this.writable=!0,super.emitReserved(`open`)}onData(e){let t=Ue(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved(`packet`,e)}onClose(e){this.readyState=`closed`,super.emitReserved(`close`,e)}pause(e){}createUri(e,t={}){return e+`://`+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(`:`)===-1?e:`[`+e+`]`}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?`:`+this.opts.port:``}_query(e){let t=G(e);return t.length?`?`+t:``}},ft=class extends dt{constructor(){super(...arguments),this._polling=!1}get name(){return`polling`}doOpen(){this._poll()}pause(e){this.readyState=`pausing`;let t=()=>{this.readyState=`paused`,e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once(`pollComplete`,function(){--e||t()})),this.writable||(e++,this.once(`drain`,function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved(`poll`)}onData(e){Je(e,this.socket.binaryType).forEach(e=>{if(this.readyState===`opening`&&e.type===`open`&&this.onOpen(),e.type===`close`)return this.onClose({description:`transport closed by the server`}),!1;this.onPacket(e)}),this.readyState!==`closed`&&(this._polling=!1,this.emitReserved(`pollComplete`),this.readyState===`open`&&this._poll())}doClose(){let e=()=>{this.write([{type:`close`}])};this.readyState===`open`?e():this.once(`open`,e)}write(e){this.writable=!1,qe(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved(`drain`)})})}uri(){let e=this.opts.secure?`https`:`http`,t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=ct()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},pt=!1;try{pt=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var mt=pt;function ht(){}var gt=class extends ft{constructor(e){if(super(e),typeof location<`u`){let t=location.protocol===`https:`,n=location.port;n||=t?`443`:`80`,this.xd=typeof location<`u`&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:`POST`,data:e});n.on(`success`,t),n.on(`error`,(e,t)=>{this.onError(`xhr post error`,e,t)})}doPoll(){let e=this.request();e.on(`data`,this.onData.bind(this)),e.on(`error`,(e,t)=>{this.onError(`xhr poll error`,e,t)}),this.pollXhr=e}},_t=class e extends W{constructor(e,t,n){super(),this.createRequest=e,it(this,n),this._opts=n,this._method=n.method||`GET`,this._uri=t,this._data=n.data===void 0?null:n.data,this._create()}_create(){var t;let n=tt(this._opts,`agent`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`autoUnref`);n.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this._opts.extraHeaders[e])}}catch{}if(this._method===`POST`)try{r.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`)}catch{}try{r.setRequestHeader(`Accept`,`*/*`)}catch{}(t=this._opts.cookieJar)==null||t.addCookies(r),`withCredentials`in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var e;r.readyState===3&&((e=this._opts.cookieJar)==null||e.parseCookies(r.getResponseHeader(`set-cookie`))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status==`number`?r.status:0)},0))},r.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}typeof document<`u`&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved(`error`,e,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(this._xhr===void 0||this._xhr===null)){if(this._xhr.onreadystatechange=ht,t)try{this._xhr.abort()}catch{}typeof document<`u`&&delete e.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved(`data`,e),this.emitReserved(`success`),this._cleanup())}abort(){this._cleanup()}};if(_t.requestsCount=0,_t.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,vt);else if(typeof addEventListener==`function`){let e=`onpagehide`in $e?`pagehide`:`unload`;addEventListener(e,vt,!1)}}function vt(){for(let e in _t.requests)_t.requests.hasOwnProperty(e)&&_t.requests[e].abort()}var yt=(function(){let e=xt({xdomain:!1});return e&&e.responseType!==null})(),bt=class extends gt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=yt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new _t(xt,this.uri(),e)}};function xt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||mt))return new XMLHttpRequest}catch{}if(!t)try{return new $e[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var St=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,Ct=class extends dt{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=St?{}:tt(this.opts,`agent`,`perMessageDeflate`,`pfx`,`key`,`passphrase`,`cert`,`ca`,`ciphers`,`rejectUnauthorized`,`localAddress`,`protocolVersion`,`origin`,`maxPayload`,`family`,`checkServerIdentity`);this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved(`error`,e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:`websocket connection closed`,context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError(`websocket error`,e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;Ie(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&Qe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){this.ws!==void 0&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?`wss`:`ws`,t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ct()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},wt=$e.WebSocket||$e.MozWebSocket,Tt={websocket:class extends Ct{createSocket(e,t,n){return St?new wt(e,t,n):t?new wt(e,t):new wt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends dt{get name(){return`webtransport`}doOpen(){try{this._transport=new WebTransport(this.createUri(`https`),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved(`error`,e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError(`webtransport error`,e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=U(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=Ye();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();let a={type:`open`};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&Qe(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:bt},Et=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Dt=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function Ot(e){if(e.length>8e3)throw`URI too long`;let t=e,n=e.indexOf(`[`),r=e.indexOf(`]`);n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,`;`)+e.substring(r,e.length));let i=Et.exec(e||``),a={},o=14;for(;o--;)a[Dt[o]]=i[o]||``;return n!=-1&&r!=-1&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,`:`),a.authority=a.authority.replace(`[`,``).replace(`]`,``).replace(/;/g,`:`),a.ipv6uri=!0),a.pathNames=kt(a,a.path),a.queryKey=At(a,a.query),a}function kt(e,t){let n=t.replace(/\/{2,9}/g,`/`).split(`/`);return(t.slice(0,1)==`/`||t.length===0)&&n.splice(0,1),t.slice(-1)==`/`&&n.splice(n.length-1,1),n}function At(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var jt=typeof addEventListener==`function`&&typeof removeEventListener==`function`,Mt=[];jt&&addEventListener(`offline`,()=>{Mt.forEach(e=>e())},!1);var Nt=class e extends W{constructor(e,t){if(super(),this.binaryType=et,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e==`object`&&(t=e,e=null),e){let n=Ot(e);t.hostname=n.host,t.secure=n.protocol===`https`||n.protocol===`wss`,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Ot(t.host).host);it(this,t),this.secure=t.secure==null?typeof location<`u`&&location.protocol===`https:`:t.secure,t.hostname&&!t.port&&(t.port=this.secure?`443`:`80`),this.hostname=t.hostname||(typeof location<`u`?location.hostname:`localhost`),this.port=t.port||(typeof location<`u`&&location.port?location.port:this.secure?`443`:`80`),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:`/engine.io`,agent:!1,withCredentials:!1,upgrade:!0,timestampParam:`t`,rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,``)+(this.opts.addTrailingSlash?`/`:``),typeof this.opts.query==`string`&&(this.opts.query=lt(this.opts.query)),jt&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener(`beforeunload`,this._beforeunloadEventListener,!1)),this.hostname!==`localhost`&&(this._offlineEventListener=()=>{this._onClose(`transport close`,{description:`network connection lost`})},Mt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved(`error`,`No transports available`)},0);return}let t=this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&this.transports.indexOf(`websocket`)!==-1?`websocket`:this.transports[0];this.readyState=`opening`;let n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on(`drain`,this._onDrain.bind(this)).on(`packet`,this._onPacket.bind(this)).on(`error`,this._onError.bind(this)).on(`close`,e=>this._onClose(`transport close`,e))}onOpen(){this.readyState=`open`,e.priorWebsocketSuccess=this.transport.name===`websocket`,this.emitReserved(`open`),this.flush()}_onPacket(e){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`)switch(this.emitReserved(`packet`,e),this.emitReserved(`heartbeat`),e.type){case`open`:this.onHandshake(JSON.parse(e.data));break;case`ping`:this._sendPacket(`pong`),this.emitReserved(`ping`),this.emitReserved(`pong`),this._resetPingTimeout();break;case`error`:let t=Error(`server error`);t.code=e.data,this._onError(t);break;case`message`:this.emitReserved(`data`,e.data),this.emitReserved(`message`,e.data);break}}onHandshake(e){this.emitReserved(`handshake`,e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!==`closed`&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose(`ping timeout`)},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved(`drain`):this.flush()}flush(){if(this.readyState!==`closed`&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved(`flush`)}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name===`polling`&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+=ot(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Qe(()=>{this._onClose(`ping timeout`)},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket(`message`,e,t,n),this}send(e,t,n){return this._sendPacket(`message`,e,t,n),this}_sendPacket(e,t,n,r){if(typeof t==`function`&&(r=t,t=void 0),typeof n==`function`&&(r=n,n=null),this.readyState===`closing`||this.readyState===`closed`)return;n||={},n.compress=!1!==n.compress;let i={type:e,data:t,options:n};this.emitReserved(`packetCreate`,i),this.writeBuffer.push(i),r&&this.once(`flush`,r),this.flush()}close(){let e=()=>{this._onClose(`forced close`),this.transport.close()},t=()=>{this.off(`upgrade`,t),this.off(`upgradeError`,t),e()},n=()=>{this.once(`upgrade`,t),this.once(`upgradeError`,t)};return(this.readyState===`opening`||this.readyState===`open`)&&(this.readyState=`closing`,this.writeBuffer.length?this.once(`drain`,()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(t){if(e.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState===`opening`)return this.transports.shift(),this._open();this.emitReserved(`error`,t),this._onClose(`transport error`,t)}_onClose(e,t){if(this.readyState===`opening`||this.readyState===`open`||this.readyState===`closing`){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners(`close`),this.transport.close(),this.transport.removeAllListeners(),jt&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=Mt.indexOf(this._offlineEventListener);e!==-1&&Mt.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Nt.protocol=4;var Pt=class extends Nt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState===`open`&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Nt.priorWebsocketSuccess=!1;let r=()=>{n||(t.send([{type:`ping`,data:`probe`}]),t.once(`packet`,e=>{if(!n)if(e.type===`pong`&&e.data===`probe`){if(this.upgrading=!0,this.emitReserved(`upgrading`,t),!t)return;Nt.priorWebsocketSuccess=t.name===`websocket`,this.transport.pause(()=>{n||this.readyState!==`closed`&&(l(),this.setTransport(t),t.send([{type:`upgrade`}]),this.emitReserved(`upgrade`,t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error(`probe error`);e.transport=t.name,this.emitReserved(`upgradeError`,e)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}let a=e=>{let n=Error(`probe error: `+e);n.transport=t.name,i(),this.emitReserved(`upgradeError`,n)};function o(){a(`transport closed`)}function s(){a(`socket closed`)}function c(e){t&&e.name!==t.name&&i()}let l=()=>{t.removeListener(`open`,r),t.removeListener(`error`,a),t.removeListener(`close`,o),this.off(`close`,s),this.off(`upgrading`,c)};t.once(`open`,r),t.once(`error`,a),t.once(`close`,o),this.once(`close`,s),this.once(`upgrading`,c),this._upgrades.indexOf(`webtransport`)!==-1&&e!==`webtransport`?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}},Ft=class extends Pt{constructor(e,t={}){let n=typeof e==`object`?e:t;(!n.transports||n.transports&&typeof n.transports[0]==`string`)&&(n.transports=(n.transports||[`polling`,`websocket`,`webtransport`]).map(e=>Tt[e]).filter(e=>!!e)),super(e,n)}};Ft.protocol;function It(e,t=``,n){let r=e;n||=typeof location<`u`&&location,e??=n.protocol+`//`+n.host,typeof e==`string`&&(e.charAt(0)===`/`&&(e=e.charAt(1)===`/`?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=n===void 0?`https://`+e:n.protocol+`//`+e),r=Ot(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port=`80`:/^(http|ws)s$/.test(r.protocol)&&(r.port=`443`)),r.path=r.path||`/`;let i=r.host.indexOf(`:`)===-1?r.host:`[`+r.host+`]`;return r.id=r.protocol+`://`+i+`:`+r.port+t,r.href=r.protocol+`://`+i+(n&&n.port===r.port?``:`:`+r.port),r}var Lt=typeof ArrayBuffer==`function`,Rt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,zt=Object.prototype.toString,Bt=typeof Blob==`function`||typeof Blob<`u`&&zt.call(Blob)===`[object BlobConstructor]`,Vt=typeof File==`function`||typeof File<`u`&&zt.call(File)===`[object FileConstructor]`;function Ht(e){return Lt&&(e instanceof ArrayBuffer||Rt(e))||Bt&&e instanceof Blob||Vt&&e instanceof File}function Ut(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Ut(e[t]))return!0;return!1}if(Ht(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Ut(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ut(e[t]))return!0;return!1}function Wt(e){let t=[],n=e.data,r=e;return r.data=Gt(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Gt(e,t){if(!e)return e;if(Ht(e)){let n={_placeholder:!0,num:t.length};return t.push(e),n}else if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++)n[r]=Gt(e[r],t);return n}else if(typeof e==`object`&&!(e instanceof Date)){let n={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=Gt(e[r],t));return n}return e}function Kt(e,t){return e.data=qt(e.data,t),delete e.attachments,e}function qt(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num==`number`&&e.num>=0&&e.num<t.length)return t[e.num];throw Error(`illegal attachments`)}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=qt(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=qt(e[n],t));return e}var Jt=s({Decoder:()=>Zt,Encoder:()=>Xt,PacketType:()=>K,isPacketValid:()=>an,protocol:()=>5}),Yt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],K;(function(e){e[e.CONNECT=0]=`CONNECT`,e[e.DISCONNECT=1]=`DISCONNECT`,e[e.EVENT=2]=`EVENT`,e[e.ACK=3]=`ACK`,e[e.CONNECT_ERROR=4]=`CONNECT_ERROR`,e[e.BINARY_EVENT=5]=`BINARY_EVENT`,e[e.BINARY_ACK=6]=`BINARY_ACK`})(K||={});var Xt=class{constructor(e){this.replacer=e}encode(e){return(e.type===K.EVENT||e.type===K.ACK)&&Ut(e)?this.encodeAsBinary({type:e.type===K.EVENT?K.BINARY_EVENT:K.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===K.BINARY_EVENT||e.type===K.BINARY_ACK)&&(t+=e.attachments+`-`),e.nsp&&e.nsp!==`/`&&(t+=e.nsp+`,`),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Wt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Zt=class e extends W{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e==`function`?{reviver:e}:e)}add(e){let t;if(typeof e==`string`){if(this.reconstructor)throw Error(`got plaintext data when reconstructing a packet`);t=this.decodeString(e);let n=t.type===K.BINARY_EVENT;n||t.type===K.BINARY_ACK?(t.type=n?K.EVENT:K.ACK,this.reconstructor=new Qt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(Ht(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved(`decoded`,t));else throw Error(`got binary data when not reconstructing a packet`);else throw Error(`Unknown type: `+e)}decodeString(t){let n=0,r={type:Number(t.charAt(0))};if(K[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===K.BINARY_EVENT||r.type===K.BINARY_ACK){let e=n+1;for(;t.charAt(++n)!==`-`&&n!=t.length;);let i=t.substring(e,n);if(i!=Number(i)||t.charAt(n)!==`-`)throw Error(`Illegal attachments`);let a=Number(i);if(!en(a)||a<0)throw Error(`Illegal attachments`);if(a>this.opts.maxAttachments)throw Error(`too many attachments`);r.attachments=a}if(t.charAt(n+1)===`/`){let e=n+1;for(;++n&&!(t.charAt(n)===`,`||n===t.length););r.nsp=t.substring(e,n)}else r.nsp=`/`;let i=t.charAt(n+1);if(i!==``&&Number(i)==i){let e=n+1;for(;++n;){let e=t.charAt(n);if(e==null||Number(e)!=e){--n;break}if(n===t.length)break}r.id=Number(t.substring(e,n+1))}if(t.charAt(++n)){let i=this.tryParse(t.substr(n));if(e.isPayloadValid(r.type,i))r.data=i;else throw Error(`invalid payload`)}return r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case K.CONNECT:return nn(t);case K.DISCONNECT:return t===void 0;case K.CONNECT_ERROR:return typeof t==`string`||nn(t);case K.EVENT:case K.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Yt.indexOf(t[0])===-1);case K.ACK:case K.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&=(this.reconstructor.finishedReconstruction(),null)}},Qt=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let e=Kt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function $t(e){return typeof e==`string`}var en=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function tn(e){return e===void 0||en(e)}function nn(e){return Object.prototype.toString.call(e)===`[object Object]`}function rn(e,t){switch(e){case K.CONNECT:return t===void 0||nn(t);case K.DISCONNECT:return t===void 0;case K.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Yt.indexOf(t[0])===-1);case K.ACK:return Array.isArray(t);case K.CONNECT_ERROR:return typeof t==`string`||nn(t);default:return!1}}function an(e){return $t(e.nsp)&&tn(e.id)&&rn(e.type,e.data)}function on(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var sn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),cn=class extends W{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[on(e,`open`,this.onopen.bind(this)),on(e,`packet`,this.onpacket.bind(this)),on(e,`error`,this.onerror.bind(this)),on(e,`close`,this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState===`open`&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift(`message`),this.emit.apply(this,e),this}emit(e,...t){if(sn.hasOwnProperty(e))throw Error(`"`+e.toString()+`" is a reserved event name`);if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let n={type:K.EVENT,data:t};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof t[t.length-1]==`function`){let e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.id=e}let r=this.io.engine?.transport?.writable,i=this.connected&&!this.io.engine?._hasPingExpired();return this.flags.volatile&&!r||(i?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,t){let n=this.flags.timeout??this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error(`operation has timed out`))},n),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,r)=>{let i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]==`function`&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],e===null?(this._queue.shift(),t&&t(null,...r)):n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth==`function`?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:K.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved(`connect_error`,e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved(`disconnect`,e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error(`socket has been disconnected`))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case K.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved(`connect_error`,Error(`It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)`));break;case K.EVENT:case K.BINARY_EVENT:this.onevent(e);break;case K.ACK:case K.BINARY_ACK:this.onack(e);break;case K.DISCONNECT:this.ondisconnect();break;case K.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved(`connect_error`,t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]==`string`&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...r){n||(n=!0,t.packet({type:K.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t==`function`&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved(`connect`)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose(`io server disconnect`)}destroy(){this.subs&&=(this.subs.forEach(e=>e()),void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:K.DISCONNECT}),this.destroy(),this.connected&&this.onclose(`io client disconnect`),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let n of t)n.apply(this,e.data)}}};function ln(e){e||={},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ln.prototype.duration=function(){var e=this.ms*this.factor**+ this.attempts++;if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0},ln.prototype.reset=function(){this.attempts=0},ln.prototype.setMin=function(e){this.ms=e},ln.prototype.setMax=function(e){this.max=e},ln.prototype.setJitter=function(e){this.jitter=e};var un=class extends W{constructor(e,t){super(),this.nsps={},this.subs=[],e&&typeof e==`object`&&(t=e,e=void 0),t||={},t.path=t.path||`/socket.io`,this.opts=t,it(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(t.randomizationFactor??.5),this.backoff=new ln({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState=`closed`,this.uri=e;let n=t.parser||Jt;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)==null||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)==null||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)==null||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf(`open`))return this;this.engine=new Ft(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=on(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=on(t,`error`,i);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(Error(`timeout`)),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState=`open`,this.emitReserved(`open`);let e=this.engine;this.subs.push(on(e,`ping`,this.onping.bind(this)),on(e,`data`,this.ondata.bind(this)),on(e,`error`,this.onerror.bind(this)),on(e,`close`,this.onclose.bind(this)),on(this.decoder,`decoded`,this.ondecoded.bind(this)))}onping(){this.emitReserved(`ping`)}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose(`parse error`,e)}}ondecoded(e){Qe(()=>{this.emitReserved(`packet`,e)},this.setTimeoutFn)}onerror(e){this.emitReserved(`error`,e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new cn(this,e,t),this.nsps[e]=n),n}_destroy(e){let t=Object.keys(this.nsps);for(let e of t)if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose(`forced close`)}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)==null||n.close(),this.backoff.reset(),this._readyState=`closed`,this.emitReserved(`close`,e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved(`reconnect_failed`),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved(`reconnect_attempt`,e.backoff.attempts),!e.skipReconnect&&e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved(`reconnect_error`,t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved(`reconnect`,e)}},dn={};function fn(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=It(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=dn[i]&&a in dn[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new un(r,t):(dn[i]||(dn[i]=new un(r,t)),c=dn[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(fn,{Manager:un,Socket:cn,io:fn,connect:fn});var pn=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>fn(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),mn=({socket:e,chatId:t})=>{if(!e||!t||typeof window>`u`)return()=>{};let n=window.location.pathname+window.location.search,r=Date.now(),i=null,a=null,o=()=>{console.log(`[FlowEngageTracking] visitor:session_start`,{chatId:t,path:n}),e.emit(`visitor:session_start`,{chatId:t,path:n,title:document.title,referrer:document.referrer,userAgent:navigator.userAgent,timestamp:Date.now()})},s=()=>{console.log(`[FlowEngageTracking] visitor:page_enter`,{chatId:t,path:n}),e.emit(`visitor:page_enter`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},c=(n,r)=>{console.log(`[FlowEngageTracking] visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3))}),e.emit(`visitor:page_leave`,{chatId:t,path:n,duration:Math.max(0,Math.floor((Date.now()-r)/1e3)),timestamp:Date.now()})},l=()=>{console.log(`[FlowEngageTracking] visitor:heartbeat`,{chatId:t,path:n}),e.emit(`visitor:heartbeat`,{chatId:t,path:n,title:document.title,timestamp:Date.now()})},u=()=>{i&&window.clearInterval(i),i=window.setInterval(l,h)},d=()=>{i&&=(window.clearInterval(i),null)},f=r=>{console.log(`[FlowEngageTracking] visitor:visibility`,{chatId:t,state:r}),e.emit(`visitor:visibility`,{chatId:t,state:r,path:n,title:document.title,timestamp:Date.now()})},p=()=>{if(document.hidden){a&&window.clearTimeout(a),a=window.setTimeout(()=>{a=null,d(),f(`hidden`)},g);return}a&&=(window.clearTimeout(a),null),f(`visible`),l(),u()},m=()=>{let e=window.location.pathname+window.location.search;if(e===n){console.log(`[FlowEngageTracking] route unchanged`,{currentPath:n});return}console.log(`[FlowEngageTracking] route changed`,{from:n,to:e}),c(n,r),n=e,r=Date.now(),s()},_=window.history.pushState.bind(window.history),v=window.history.replaceState.bind(window.history);window.history.pushState=(...e)=>{_(...e),m()},window.history.replaceState=(...e)=>{v(...e),m()};let y=()=>{c(n,r),e.emit(`visitor:session_end`,{chatId:t,timestamp:Date.now()})},b=()=>{y()},x=e=>{e.persisted||y()};return window.addEventListener(`popstate`,m),window.addEventListener(`hashchange`,m),window.addEventListener(`beforeunload`,b),window.addEventListener(`pagehide`,x),window.addEventListener(`visibilitychange`,p),o(),document.hidden?a=window.setTimeout(()=>{a=null,d(),f(`hidden`)},g):(l(),u()),{notifyRouteChange:m,cleanup:()=>{a&&=(window.clearTimeout(a),null),d(),window.history.pushState=_,window.history.replaceState=v,window.removeEventListener(`popstate`,m),window.removeEventListener(`hashchange`,m),window.removeEventListener(`beforeunload`,b),window.removeEventListener(`pagehide`,x),window.removeEventListener(`visibilitychange`,p)}}},hn=(0,d.createContext)(null),gn=()=>{let e=(0,d.useContext)(hn);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function _n(){if(typeof window>`u`)return!1;try{let e=window.localStorage?.getItem(`FE_DEBUG_VOICE`);if(e===`0`||e===`false`)return!1;if(e===`1`||e===`true`)return!0}catch{}return window.__FE_DEBUG_VOICE_TOOLS__===!1?!1:window.__FE_DEBUG_VOICE_TOOLS__===!0}var vn=16,yn=.4;function bn(){let e=0;for(let t of document.querySelectorAll(`header, nav, [role='banner'], [class*='header'], [class*='navbar']`)){if(t.closest(`.flowengage-widget-root, #flowengage-root, .flowengage-shell`))continue;let{position:n}=getComputedStyle(t);if(n!==`fixed`&&n!==`sticky`)continue;let r=t.getBoundingClientRect();r.top<=1&&r.bottom>0&&r.height<window.innerHeight*yn&&(e=Math.max(e,r.bottom))}return e}function xn(e){requestAnimationFrame(()=>{let t=bn()+vn,n=e.getBoundingClientRect(),r=window.innerHeight-t,i=n.height<r?(r-n.height)/2:0;window.scrollTo({top:Math.max(0,window.pageYOffset+n.top-t-i),behavior:`smooth`})})}function Sn(e){if(e&&!e.hasAttribute(`data-fe-highlighted`)){Cn();for(let e of document.querySelectorAll(`.fe-highlight-section, .fe-highlight-speaking`))e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`);xn(e),e.setAttribute(`data-fe-orig-style`,e.style.cssText),e.setAttribute(`data-fe-highlighted`,`true`),e.style.outline=`3px solid #2563eb`,e.style.outlineOffset=e.getBoundingClientRect().width>=document.documentElement.clientWidth-vn?`-8px`:`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.transition=`all 0.4s ease`}}function Cn(){let e=document.querySelector(`[data-fe-highlighted]`);e&&(e.style.cssText=e.getAttribute(`data-fe-orig-style`)||``,e.removeAttribute(`data-fe-highlighted`),e.removeAttribute(`data-fe-orig-style`))}var wn=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function Tn(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(wn)}catch{return!1}}function En(e){let t=e.cloneNode(!0);return t.querySelectorAll(`[aria-hidden], svg, .icon, [class*="icon"]`).forEach(e=>e.remove()),t.textContent.replace(/\s+/g,` `).trim()}function q(...e){_n()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var Dn=`fe_pending_nav_section`,On=15e3,kn=`fe_voice_nav_state`,An=2e4,jn=!1,Mn=null;function Nn(e=3e3){jn=!0,Mn&&clearTimeout(Mn),Mn=setTimeout(()=>{jn=!1,Mn=null},e)}function Pn(){return jn}var Fn=!1,In=null;function Ln(){Fn||typeof window>`u`||(Fn=!0,window.addEventListener(`popstate`,async()=>{let e=window.location.href;if(q(`popstate: body-swap to`,e),In){try{Kn(In)}catch{}try{Yn(In)}catch{}}try{if(await Cr(e,{skipPushState:!0,isBack:!0})){q(`popstate: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] popstate body-swap error:`,e)}q(`popstate: body-swap failed, falling back to reload`),window.location.reload()}))}var Rn=!1;function zn(){Rn||typeof window>`u`||typeof document>`u`||(Rn=!0,document.addEventListener(`click`,async e=>{try{if(!window.history.state?.flowengageSpa)return}catch{return}let t=e.target.closest?.(`a[href]`);if(!t||t.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`))return;let n=t.getAttribute(`href`)||``;if(!n||n===`#`||n.startsWith(`javascript:`)||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||t.hasAttribute(`download`)||t.target===`_blank`||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;let r;try{if(r=new URL(n,window.location.href),r.origin!==window.location.origin)return}catch{return}if(!(r.pathname===window.location.pathname&&r.hash)&&!(r.pathname===window.location.pathname&&r.search===window.location.search)){e.preventDefault(),e.stopPropagation(),q(`link-intercept: body-swap to`,r.href),$n();try{try{Kn()}catch{}try{Yn()}catch{}if(await Cr(r.href)){q(`link-intercept: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] link-intercept body-swap error:`,e)}q(`link-intercept: body-swap failed, falling back to normal navigation`),er(),window.location.href=r.href}},!0))}var Bn=null;function Vn(e){Bn=e===`spa`||e===`traditional`?e:null}function Hn(){if(typeof window>`u`||Bn===`traditional`)return null;if(window.next?.router||window.__NEXT_ROUTER__)return`nextjs`;if(window.__remixRouter||window.__staticRouterHydrationData)return`react-router`;if(window.___gatsby||window.___navigate)return`gatsby`;if(window.__VUE_ROUTER__)return`vue-router`;if(window.__NUXT__||window.$nuxt)return`nuxt`;if(window.ng?.getComponent||document.querySelector(`[ng-version]`))return`angular`;if(window[Symbol.for(`wouter_v3`)])return`wouter`;if(window.__sveltekit_data||document.querySelector(`[data-sveltekit-hydrate]`))return`sveltekit`;if(document.querySelector(`[data-astro-transition]`))return`astro`;for(let e of document.body.children)if(e.tagName?.toUpperCase()===`DIV`&&e.id!==`flowengage-root`&&(e.id===`root`||e.id===`app`)&&e.children.length>0)return`generic-spa`;return Bn===`spa`?`backend-spa`:null}var Un=`data-fe-swap-css`;function Wn(){typeof document>`u`||document.querySelectorAll(`[${Un}]`).forEach(e=>e.remove())}var Gn=`fe_form_state:`;function Kn(e){if(typeof document>`u`||typeof sessionStorage>`u`)return;let t=document.querySelectorAll(`form`);if(!t.length)return;let n=[];if(t.forEach((e,t)=>{let r={};e.querySelectorAll(`input, textarea, select`).forEach(e=>{let t=e.name||e.id;t&&(e.type===`password`||e.type===`hidden`||(e.type===`checkbox`||e.type===`radio`?r[t+`::`+e.value]=e.checked:r[t]=e.value))}),Object.keys(r).length&&n.push({formIndex:t,fields:r})}),n.length)try{let t=Gn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({state:n,ts:Date.now()}))}catch{}}function qn(){if(typeof document>`u`||typeof sessionStorage>`u`)return;let e=Gn+window.location.pathname,t;try{t=JSON.parse(sessionStorage.getItem(e)||`null`)}catch{return}if(!t||!t.state)return;if(Date.now()-t.ts>1800*1e3){try{sessionStorage.removeItem(e)}catch{}return}let n=document.querySelectorAll(`form`);for(let{formIndex:e,fields:r}of t.state){let t=n[e];if(t)for(let[e,n]of Object.entries(r))if(e.includes(`::`)){let[r,i]=e.split(`::`),a=t.querySelector(`input[name="${r}"][value="${i}"], input[id="${r}"][value="${i}"]`);a&&(a.checked=!!n)}else{let r=t.querySelector(`[name="${e}"], [id="${e}"]`);if(r&&r.type!==`file`){r.value=n;try{r.dispatchEvent(new Event(`input`,{bubbles:!0}))}catch{}try{r.dispatchEvent(new Event(`change`,{bubbles:!0}))}catch{}}}}try{sessionStorage.removeItem(e)}catch{}}var Jn=`fe_scroll:`;function Yn(e){if(!(typeof window>`u`||typeof sessionStorage>`u`))try{let t=Jn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({y:window.scrollY,ts:Date.now()}))}catch{}}function Xn(){if(typeof window>`u`||typeof sessionStorage>`u`)return;let e=Jn+window.location.pathname,t;try{t=JSON.parse(sessionStorage.getItem(e)||`null`)}catch{return}if(t){try{sessionStorage.removeItem(e)}catch{}Date.now()-t.ts>1800*1e3||setTimeout(()=>{window.scrollTo({top:t.y,behavior:`instant`})},80)}}function Zn(e){if(!(typeof window>`u`))try{window.dispatchEvent(new CustomEvent(`flowengage:pageswap`,{detail:{url:e,timestamp:Date.now()}}))}catch{}}var Qn=`fe-nav-loader`;function $n(){if(typeof document>`u`||document.getElementById(Qn))return;let e=document.createElement(`div`);e.id=Qn,e.style.cssText=[`position:fixed`,`top:0`,`left:0`,`width:0`,`height:3px`,`background:linear-gradient(90deg,#7c3aed,#6366f1)`,`z-index:2147483647`,`transition:width 0.4s ease`,`pointer-events:none`].join(`;`),document.body.appendChild(e),requestAnimationFrame(()=>{e.style.width=`70%`})}function er(){if(typeof document>`u`)return;let e=document.getElementById(Qn);e&&(e.style.width=`100%`,setTimeout(()=>{e.style.opacity=`0`,e.style.transition=`opacity 0.3s ease`,setTimeout(()=>e.remove(),350)},200))}function tr(){if(typeof window>`u`||typeof document>`u`)return;try{window.history.state?.flowengageSpa&&Ln()}catch{}let e;try{e=JSON.parse(sessionStorage.getItem(Dn)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(Dn)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>On){q(`initNavigationHighlight: pending section expired, skipping:`,t);return}q(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=rr(null,t);if(e){_r(e),q(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):q(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var nr=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
5
5
  .fe-highlight-section {
6
6
  outline: 3px solid #7c3aed !important;
7
7
  box-shadow: 0 0 15px rgba(124, 58, 237, 0.6) !important;
@@ -25,7 +25,7 @@
25
25
  box-shadow: none !important;
26
26
  transition: outline-color 0.25s ease, box-shadow 0.25s ease !important;
27
27
  }
28
- `,document.head.appendChild(e)};function rr(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1.h2.h3.h4.h5.h6.[data-section].section[id].[id].main li.article li.[role='main'] li.[class*='card'].[class*='Card'].[class*='feature'].[class*='Feature'].[class*='tier'].[class*='Tier'].[class*='plan'].[class*='Plan'].[class*='pricing'].[class*='Pricing'].[class*='testimonial'].[class*='Testimonial'].[class*='team'].[class*='Team'].[class*='service'].[class*='Service'].[class*='block'].[role='listitem'].[role='article'].[role='region'].dt.dd`.split(`.`).join(`, `))).filter(e=>{if(Tn(e))return!1;let t=e.textContent.trim();return!(t.length<3||t.length>5e3||e.closest(`nav, footer, header, aside, .nav, .footer, .header`))});for(let e of i)if(En(e).toLowerCase()===n)return e;for(let e of i){let t=En(e).toLowerCase();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=En(e).toLowerCase();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=En(e).toLowerCase();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=En(n).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!Tn(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(Tn(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(Tn(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(Tn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!Tn(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(Tn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function ir(){return document.querySelector(`[itemprop='articleBody'], .article-body, .post-content, .entry-content, .field--name-body, .field--body, .node__content, article .content, .prose, article .prose`)||document.querySelector(`main article, main, [role='main'], article`)||document.body}var ar=new Set(`the.and.for.are.but.not.you.all.can.her.was.one.our.out.day.get.has.him.his.how.its.may.new.now.old.see.two.way.who.did.let.put.say.she.too.use.has.have.this.that.with.from.they.will.your.about.into.than.then.some.very.when.come.here.just.like.also.back.after.over.such.take.only.know.think.each.made.look.more.most.other.well`.split(`.`)),or=`section, article, li, a, [class*='card']`,sr=`h1, h2, h3, h4, h5, h6`,cr={january:`jan`,february:`feb`,march:`mar`,april:`apr`,june:`jun`,july:`jul`,august:`aug`,september:`sep`,sept:`sep`,october:`oct`,november:`nov`,december:`dec`},lr=3,ur=2,dr=.8,fr=.6,pr=.5;function mr(e){return new Set(String(e||``).toLowerCase().replace(/(\d),(?=\d{3})/g,`$1`).replace(/[^\p{L}\p{N}\s]/gu,` `).split(/\s+/).map(e=>cr[e]||e).filter(e=>(/^\d+$/.test(e)?e.length>=2:e.length>=3)&&!ar.has(e)))}function hr(e){if(typeof document>`u`)return null;let t=mr(e);if(t.size<lr)return null;let n=ir(),r=n.textContent.length||1,i=[];for(let e of n.querySelectorAll(or))Tn(e)||e.closest(`nav, header, footer, aside, [role='navigation']`)||!/^(SECTION|ARTICLE)$/.test(e.tagName)&&!e.querySelector(sr)||e.textContent.length>r*pr||i.push({el:e,length:e.textContent.length,terms:mr(e.innerText)});if(!i.length)return null;let a=i.filter(e=>!i.some(t=>t!==e&&e.el.contains(t.el))),o=new Map;for(let e of a)for(let n of e.terms)t.has(n)&&o.set(n,(o.get(n)||0)+1);let s=[];for(let e of i){let n=0,r=0,i=0;for(let a of t){if(!e.terms.has(a))continue;let t=Math.max(1,o.get(a)||0);r+=1,n+=1/t,t<=2&&(i+=1)}r>=lr&&i>=ur&&s.push({...e,score:n})}if(!s.length)return null;s.sort((e,t)=>t.score-e.score);let[c]=s,l=s.find(e=>!c.el.contains(e.el)&&!e.el.contains(c.el));return l&&l.score>=c.score*fr?null:s.filter(e=>e.score>=c.score*dr).sort((e,t)=>e.length-t.length)[0].el}function gr(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;nr();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function _r(){typeof document>`u`||(document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`)),Cn())}function vr(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function yr(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href),n=t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href;return(await fetch(n,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok}catch{return!1}}async function br(e,{siteId:t,apiBaseUrl:n}){if(!e)return{allowed:!1,correctedUrl:null};let r=!1;try{r=!!Hn()}catch{r=!1}let i=async()=>({allowed:r?!1:await yr(e),correctedUrl:null});if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),i();let a=String(n).replace(/\/$/,``),o=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let e=await(await fetch(`${a}/api/widget/navigate-allowed?${o.toString()}`)).json().catch(()=>({}));return e.success&&e.allowed?{allowed:!0,correctedUrl:e.correctedUrl||null}:i()}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),i()}}function xr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Dn,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function Sr(e,{skipPushState:t=!1,isBack:n=!1}={}){if(typeof window>`u`||typeof document>`u`)return!1;try{if(new URL(e,window.location.href).origin!==window.location.origin)return!1}catch{return!1}$n();let r=new AbortController,i=setTimeout(()=>r.abort(),8e3);try{let a=await fetch(e,{credentials:`same-origin`,cache:`no-store`,signal:r.signal});if(clearTimeout(i),!a.ok)return er(),!1;let o=await a.text(),s=new DOMParser().parseFromString(o,`text/html`),c=document.getElementById(`flowengage-root`);if(!c)return er(),!1;try{typeof window.Drupal?.detachBehaviors==`function`&&window.Drupal.detachBehaviors(document.body,window.drupalSettings)}catch{}document.querySelectorAll(`script`).forEach(e=>{e.setAttribute(`data-fe-original`,`true`)}),Array.from(document.body.children).forEach(e=>{if(e===c)return;let t=e.tagName?.toUpperCase();t===`AUDIO`||t===`VIDEO`||e.remove()}),Wn();let l=new Set(Array.from(document.querySelectorAll(`link[rel='stylesheet']`)).map(e=>{try{return new URL(e.getAttribute(`href`)||``,window.location.href).href}catch{return``}}));for(let t of Array.from(s.head.querySelectorAll(`link[rel='stylesheet']`))){let n=t.getAttribute(`href`);if(!n)continue;let r;try{r=new URL(n,e).href}catch{continue}if(l.has(r))continue;let i=document.createElement(`link`);i.rel=`stylesheet`,i.href=r,i.setAttribute(Un,`true`),t.media&&(i.media=t.media),document.head.appendChild(i)}for(let e of Array.from(s.head.querySelectorAll(`style`))){if(!e.textContent.trim())continue;let t=e.textContent.trim().slice(0,120);if(Array.from(document.head.querySelectorAll(`style:not([data-fe-swap-css])`)).some(e=>e.textContent.trim().slice(0,120)===t))continue;let n=document.createElement(`style`);n.textContent=e.textContent,n.setAttribute(Un,`true`),document.head.appendChild(n)}Array.from(s.body.children).forEach(e=>{e.tagName?.toUpperCase()!==`SCRIPT`&&document.body.insertBefore(document.importNode(e,!0),c)});let u=document.querySelectorAll(`script:not([data-fe-replayed])`);for(let e of u){if(e.closest(`#flowengage-root, .flowengage-shell`)||e.hasAttribute(`data-fe-original`)||e.hasAttribute(`data-fe-replayed`))continue;let t=e.getAttribute(`src`),n=e.getAttribute(`type`)||``;if(!(n&&n!==`text/javascript`&&n!==``&&!n.includes(`drupal-ajax`))){if(n.includes(`drupal-ajax`)){e.setAttribute(`data-fe-replayed`,`true`);try{let t=JSON.parse(e.textContent);if(Array.isArray(t))for(let e of t){if((e.command===`insert`||e.command===`insert_new_content`)&&e.selector&&e.data){let t=document.querySelector(e.selector);t&&(e.method===`replaceWith`?t.outerHTML=e.data:e.method===`html`||e.method===`replace`?t.innerHTML=e.data:e.method===`append`?t.insertAdjacentHTML(`beforeend`,e.data):e.method===`prepend`?t.insertAdjacentHTML(`afterbegin`,e.data):t.innerHTML=e.data,q(`trySpaNavigate: BigPipe replacement →`,e.selector))}if(e.command===`settings`&&e.settings)try{window.drupalSettings&&typeof window.drupalSettings==`object`&&Object.assign(window.drupalSettings,e.settings)}catch{}}}catch(e){q(`trySpaNavigate: BigPipe parse error:`,e.message)}continue}if(!t&&e.textContent.trim()){let t=e.textContent;if(/window\.location\s*[.=]|location\s*\.\s*(href|assign|replace|reload)\s*[=(]/i.test(t)){e.setAttribute(`data-fe-replayed`,`true`);continue}let n=document.createElement(`script`);n.textContent=t,n.setAttribute(`data-fe-replayed`,`true`),e.parentNode.replaceChild(n,e)}}}try{for(let e of Array.from(s.querySelectorAll(`script`))){let t=(e.textContent||``).match(/drupalSettings\s*[,=]\s*(\{[\s\S]*?\})\s*[;)]/);if(t){try{let e=JSON.parse(t[1]);window.drupalSettings&&typeof window.drupalSettings==`object`?Object.assign(window.drupalSettings,e):window.drupalSettings=e,q(`trySpaNavigate: updated drupalSettings from new page`)}catch{}break}}}catch{}let d=window.location.assign.bind(window.location),f=window.location.replace.bind(window.location),p=!0;window.location.assign=e=>{if(p){q(`trySpaNavigate: blocked location.assign from replayed script:`,e);return}return d(e)},window.location.replace=e=>{if(p){q(`trySpaNavigate: blocked location.replace from replayed script:`,e);return}return f(e)};function m(e){let t=e.toLowerCase();return!!(/\/jquery[.\-\/]/.test(t)||/\/jquery\.min\.js/.test(t)||/\/jquery-once/.test(t)||/\/jquery\.once/.test(t)||/\/jquery\.ui[\./]/.test(t)||/\/jqueryui/.test(t)||/\/core\/misc\//.test(t)||/\/core\/modules\//.test(t)||/\/misc\/drupal\.js/.test(t)||/\/lodash[.\-\/]/.test(t)||/\/underscore[.\-\/]/.test(t)||/\/backbone[.\-\/]/.test(t)||/\/modernizr[.\-\/]/.test(t)||/\/popper[.\-\/]/.test(t)||/\/bootstrap\.min\.js/.test(t)||/\/bootstrap\.bundle/.test(t))}let h=new Set(Array.from(document.querySelectorAll(`script[src]`)).map(e=>{try{return new URL(e.getAttribute(`src`)||``,window.location.href).href}catch{return``}}));function g(t,n){let r=t.getAttribute(`src`)||``;if(r.includes(`flowengage`))return;let i=document.createElement(`script`);if(r){let n;try{n=new URL(r,e).href}catch{return}if(h.has(n)){if(m(n))return;q(`trySpaNavigate: re-running theme/custom script:`,n)}h.add(n),i.src=n,i.async=t.async,i.defer=t.defer}else if(t.textContent.trim()){let e=t.textContent;if(/window\.location\s*[.=]|location\s*\.\s*(href|assign|replace|reload)\s*[=(]/i.test(e)){q(`trySpaNavigate: skipping inline script with navigation:`,e.slice(0,120));return}if(/^\s*\(?\s*(?:window\.)?drupalSettings\s*[,=]/.test(e))return;i.textContent=e}else return;let a=t.getAttribute(`type`);a&&a!==`text/javascript`&&a!==``&&(i.type=a),n.parentNode.insertBefore(i,n)}for(let e of Array.from(s.head.querySelectorAll(`script`)))g(e,c);for(let e of Array.from(s.body.querySelectorAll(`script`)))g(e,c);try{typeof window.Drupal?.attachBehaviors==`function`&&window.Drupal.attachBehaviors(document.body,window.drupalSettings)}catch{}try{typeof window.jQuery==`function`&&(window.jQuery(document).trigger(`ready`),window.dispatchEvent(new Event(`resize`)))}catch{}try{document.dispatchEvent(new Event(`DOMContentLoaded`,{bubbles:!0,cancelable:!1}))}catch{}try{window.dispatchEvent(new Event(`load`))}catch{}try{let e=document.querySelectorAll(`iframe:not([data-fe-skip-reload])`);for(let t of e){if(t.closest(`#flowengage-root, .flowengage-shell`))continue;let e=t.getAttribute(`src`)||t.src;e&&e!==`about:blank`&&!e.startsWith(`javascript:`)&&(q(`trySpaNavigate: reloading iframe:`,e),t.src=e)}}catch{}try{let e=document.querySelectorAll(`.g-recaptcha, [data-sitekey]`);if(e.length>0){if(typeof window.grecaptcha?.render==`function`){for(let t of e)if(!t.closest(`#flowengage-root`)){t.innerHTML=``;try{window.grecaptcha.render(t,{sitekey:t.getAttribute(`data-sitekey`)||``}),q(`trySpaNavigate: re-rendered reCAPTCHA`)}catch{}}}else if(!document.querySelector(`script[src*='recaptcha']`)){let e=document.createElement(`script`);e.src=`https://www.google.com/recaptcha/api.js?render=explicit`,e.async=!0,document.head.appendChild(e),q(`trySpaNavigate: injected reCAPTCHA script`)}}}catch{}if(setTimeout(()=>{p=!1,window.location.assign=d,window.location.replace=f},2e3),s.title&&(document.title=s.title),!t)try{history.pushState({flowengageSpa:!0},``,e)}catch{}if(Ln(),zn(),n){try{qn()}catch{}try{Xn()}catch{}}else window.scrollTo(0,0);er(),Zn(e);try{sessionStorage.removeItem(Dn)}catch{}try{sessionStorage.removeItem(kn)}catch{}try{In=new URL(e,window.location.origin).pathname}catch{}return q(`trySpaNavigate: succeeded →`,e),!0}catch{return clearTimeout(i),er(),!1}}function Cr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(kn,JSON.stringify({voiceWasActive:!0,targetUrl:String(e),ts:Date.now()}))}catch{}}function wr(){if(!(typeof sessionStorage>`u`))try{sessionStorage.removeItem(kn)}catch{}}function Tr(){if(typeof window>`u`||typeof sessionStorage>`u`)return{shouldResumeVoice:!1,targetUrl:null};let e;try{e=JSON.parse(sessionStorage.getItem(kn)||`null`)}catch{return{shouldResumeVoice:!1,targetUrl:null}}if(!e)return{shouldResumeVoice:!1,targetUrl:null};try{sessionStorage.removeItem(kn)}catch{}return e.voiceWasActive?Date.now()-e.ts>An?(q(`initVoiceNavResume: state expired, skipping`),{shouldResumeVoice:!1,targetUrl:null}):(q(`initVoiceNavResume: voice was active during navigation to`,e.targetUrl),{shouldResumeVoice:!0,targetUrl:e.targetUrl||null}):{shouldResumeVoice:!1,targetUrl:null}}function Er(){if(typeof document>`u`)return!1;let e=/(^|\W)(404|page not found|not found|page (?:doesn'?t|does not) exist|no longer exists|couldn'?t find (?:this|that|the) page|error 404|oops[!,. ].*(?:not found|doesn'?t exist))(\W|$)/i,t=(document.title||``).trim();if(t&&e.test(t))return!0;let n=document.querySelector(`main, [role="main"], #content, .content`)||document.body;if(n){let t=n.querySelectorAll(`h1, h2`);for(let n of t){let t=(n.textContent||``).replace(/\s+/g,` `).trim();if(t&&t.length<80&&e.test(t))return!0}}return!1}var Dr=6e3,Or=250,kr=700;async function Ar(){if(typeof window>`u`)return;let e=window.__fe_agentAudioPlaying;if(typeof e!=`function`){await new Promise(e=>setTimeout(e,kr));return}let t=Date.now()+Dr;for(;Date.now()<t;){let t=!1;try{t=e()}catch{t=!1}if(!t)break;await new Promise(e=>setTimeout(e,100))}await new Promise(e=>setTimeout(e,Or))}async function jr(e,t={}){if(typeof window>`u`)return{navigated:!1};let{sectionText:n,voiceActive:r=!1}=t;try{let t=vr(e),i=new URL(t,window.location.origin);if(i.hash&&i.pathname===window.location.pathname){let e=document.getElementById(i.hash.slice(1));if(e)return e.scrollIntoView({behavior:`smooth`,block:`start`}),{navigated:!0}}if(i.pathname===window.location.pathname&&i.search===window.location.search&&!i.hash)return{navigated:!1,reason:`already-on-page`};let a=i.pathname+i.search+i.hash;if(window.Shopify)return n&&xr(n),r||xe(),r?Ar().then(()=>window.location.assign(i.href)):window.location.assign(i.href),{navigated:!0};let o=window.next?.router;if(o?.push)return new Promise(e=>{let t=()=>{o.events?.off(`routeChangeComplete`,t),e({navigated:!0})};o.events?.on(`routeChangeComplete`,t),o.push(a),setTimeout(t,5e3)});if(window.__NEXT_ROUTER__?.push)return window.__NEXT_ROUTER__.push(a),{navigated:!0};if(Hn()){n&&xr(n);let e=window.location.href;try{window.history.pushState({},``,i.href),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}}))}catch{}if(await new Promise(e=>setTimeout(e,400)),Er()){try{window.history.pushState({},``,e),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}}))}catch{}return n&&xr(n),r||xe(),window.location.assign(i.href),{navigated:!0}}return{navigated:!0}}return n&&xr(n),r||xe(),window.location.assign(i.href),{navigated:!0}}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&xr(n);try{window.location.href=vr(e)}catch{window.location.href=e}return{navigated:!0}}}var Mr=!1,Nr=null;function Pr(e){Nr=e,typeof window<`u`&&(window.__fe_triggerVoiceNavHooks=()=>{try{e.onBeforeNavigate()}catch{}}),!Mr&&(Mr=!0,!(typeof document>`u`)&&(document.addEventListener(`click`,e=>{if(!Nr)return;let t=e.target.closest?.(`a[href]`);if(!t||t.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`))return;let n=t.getAttribute(`href`)||``;if(!n||n===`#`||n.startsWith(`javascript:`)||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||t.hasAttribute(`download`)||t.target===`_blank`||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;let r;try{if(r=new URL(n,window.location.href),r.origin!==window.location.origin)return}catch{return}if(!(r.pathname===window.location.pathname&&r.hash)&&!(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)){q(`voice-link-hook: saving state before navigation →`,r.href);try{Nr.onBeforeNavigate()}catch{}}},!0),document.addEventListener(`submit`,e=>{if(Nr&&!e.target?.closest?.(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)){q(`voice-form-hook: saving state before form submit`);try{Nr.onBeforeNavigate()}catch{}}},!0)))}function Fr(){Nr=null,q(`voice-nav-hooks: deactivated`)}var Ir=4e3,Lr=null;function Rr(){let e=typeof window<`u`&&window.Shopify?.routes?.root||`/`;return e.endsWith(`/`)?e:`${e}/`}async function zr(e,t={}){let n=new AbortController,r=setTimeout(()=>n.abort(),Ir);try{let r=await fetch(e,{credentials:`same-origin`,signal:n.signal,...t,headers:{Accept:`application/json`,...t.body?{"Content-Type":`application/json`}:{},...t.headers||{}}}),i=await r.json().catch(()=>({}));if(!r.ok){let e=Error(i.description||i.message||`Cart request failed (${r.status})`);throw e.status=r.status,r.status===422&&i.description&&(e.userMessage=i.description),e}return i}finally{clearTimeout(r)}}async function Br(){if(Lr!==null)return Lr;if(typeof window>`u`)return Lr=!1;if(window.Shopify)return Lr=!0;try{let e=await zr(`${Rr()}cart.js`);Lr=e&&typeof e.item_count==`number`}catch{Lr=!1}return Lr}async function Vr(){return zr(`${Rr()}cart.js`)}function Hr(){return typeof window>`u`?null:window.__flowengageCustomer?.id||null}function Ur(e){return typeof e!=`number`||Number.isNaN(e)?null:(e/100).toFixed(2)}async function Wr(){try{if(!await Br())return null;let e=await Vr();return{itemCount:e.item_count,subtotal:Ur(e.items_subtotal_price),currency:e.currency||null,items:(e.items||[]).map(e=>({title:e.product_title||e.title,variantTitle:e.variant_title||null,quantity:e.quantity,linePrice:Ur(e.final_line_price??e.line_price),handle:e.handle||null}))}}catch{return null}}async function Gr(e,t=null){let n=await zr(`${Rr()}products/${encodeURIComponent(e)}.js`),r=n.variants||[];if(!r.length){let t=Error(`No variants for ${e}`);throw t.userMessage=`"${n.title||e}" has no purchasable options right now.`,t}let i=null;if(t){let e=t.toLowerCase();if(i=r.find(t=>(t.title||``).toLowerCase()===e)||r.find(t=>{let n=[t.title,...t.options||[]].join(` `).toLowerCase();return e.split(/[\s/,-]+/).filter(Boolean).every(e=>n.includes(e))}),!i){let e=Error(`Variant not found: ${t}`);throw e.userMessage=`I couldn't find a "${t}" option for ${n.title}. Available: ${r.map(e=>e.title).slice(0,6).join(`, `)}.`,e}}else i=r.find(e=>e.available)||r[0];if(!i.available){let e=Error(`Variant unavailable: ${i.title}`);throw e.userMessage=`Sorry — ${n.title}${i.title&&i.title!==`Default Title`?` (${i.title})`:``} is currently sold out.`,e}return{variant:i,product:n}}async function Kr(e,t=1){return zr(`${Rr()}cart/add.js`,{method:`POST`,body:JSON.stringify({items:[{id:e,quantity:t}]})})}async function qr(e,t){return zr(`${Rr()}cart/change.js`,{method:`POST`,body:JSON.stringify({line:e,quantity:t})})}function Jr(){return`${Rr()}cart`}function Yr(){return`${Rr()}checkout`}function Xr(e){return`${Rr()}products/${encodeURIComponent(e)}`}async function Zr(e,t=6){let n=new URLSearchParams({q:e,"resources[type]":`product`,"resources[limit]":String(t)});try{return((await zr(`${Rr()}search/suggest.json?${n.toString()}`))?.resources?.results?.products||[]).map(e=>({title:e.title,handle:e.handle,price:e.price||null,url:e.url||(e.handle?Xr(e.handle):null),image:e.featured_image?.url||e.image||e.images?.[0]||null,type:e.type||e.product_type||null,vendor:e.vendor||null}))}catch{return[]}}function Qr(){return typeof window>`u`?!1:/\/cart\/?$/.test(window.location.pathname)}var $r=[`form[action*="/cart"]`,`cart-items`,`cart-drawer-items`,`.cart-items`,`.cart__items`,`#main-cart-items`,`[data-cart-items]`].join(`, `);function ei(e){if(/cart/i.test(e.id))return!0;try{return!!e.querySelector($r)}catch{return!1}}async function ti(){if(typeof document>`u`)return!1;let e=Array.from(document.querySelectorAll(`[id^="shopify-section-"]`)).filter(ei);if(!e.length)return!1;let t=e.map(e=>e.id.replace(/^shopify-section-/,``));try{let e=await zr(`${window.location.pathname}?sections=${encodeURIComponent(t.join(`,`))}`),n=!1;for(let[t,r]of Object.entries(e||{})){if(!r||typeof r!=`string`)continue;let e=document.getElementById(`shopify-section-${t}`);if(!e)continue;let i=document.createElement(`div`);i.innerHTML=r;let a=i.querySelector(`#shopify-section-${t}`)||i.firstElementChild;a&&(e.innerHTML=a.innerHTML,n=!0)}return n}catch{return!1}}var ni=[`[data-cart-count]`,`.cart-count-bubble`,`.cart-count`,`#CartCount`,`.cart-link__bubble`,`.site-header__cart-count`,`#cart-icon-bubble`];function ri(e){if(typeof document>`u`)return;let t=String(e);for(let e of ni)document.querySelectorAll(e).forEach(e=>{e.hasAttribute(`data-cart-count`)&&e.setAttribute(`data-cart-count`,t),e.querySelectorAll(`span, div, sup`).forEach(e=>{e.children.length===0&&/\d/.test(e.textContent||``)&&(e.textContent=(e.textContent||``).replace(/\d+/,t))}),e.children.length===0&&/^\s*\d+\s*$/.test(e.textContent||``)&&(e.textContent=t)})}function ii(e){if(typeof document>`u`)return;let t={cart:e,source:`flowengage`};[`cart:updated`,`cart:refresh`,`cart:change`,`cart-drawer:refresh`].forEach(e=>{try{document.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0}))}catch{}});try{window.dispatchEvent(new CustomEvent(`cart:refresh`,{detail:t}))}catch{}}async function ai(e){let t=await ti();return!t&&Qr()&&(await new Promise(e=>setTimeout(e,600)),t=await ti()),e&&typeof e.item_count==`number`&&ri(e.item_count),ii(e||null),{sectionsSwapped:t}}async function oi(e){try{let{sectionsSwapped:t}=await ai(e);if(!t&&Qr())return` (The list on this page may need a quick refresh to show it.)`}catch{}return``}function si(e){let t=Ur(e.items_subtotal_price),n=e.item_count;return t==null?``:` Your cart now has ${n} item${n===1?``:`s`} — subtotal ${t}${e.currency?` ${e.currency}`:``}.`}function ci(e,t){let n=t.title&&t.title!==`Default Title`;return`${e.title}${n?` (${t.title})`:``}`}function li(e,t){return e?.userMessage||t}var ui={async add(e){let{variant:t,product:n}=await Gr(e.productHandle,e.variantTitle||null);await Kr(t.id,e.quantity||1);let r=await Vr(),i=await oi(r);return{message:`✅ Added ${e.quantity||1} × ${ci(n,t)} to your cart.${si(r)}${i}`}},async update(e){let t=(await Vr()).items?.[e.line-1];if(!t)return{message:`⚠️ I couldn't find item #${e.line} in your cart — it may have changed. Ask me "what's in my cart?" to see the current list.`};let n=await qr(e.line,e.quantity),r=await oi(n);return{message:`✅ Updated ${t.product_title||t.title} to quantity ${e.quantity}.${si(n)}${r}`}},async remove(e){let t=(await Vr()).items?.[e.line-1];if(!t)return{message:`⚠️ I couldn't find item #${e.line} in your cart — it may have changed. Ask me "what's in my cart?" to see the current list.`};let n=await qr(e.line,0),r=await oi(n);return{message:`🗑️ Removed ${t.product_title||t.title} from your cart.${si(n)}${r}`}},async view_cart(){return{message:`Opening your cart…`,navigateTo:Jr()}},async checkout(){return(await Vr()).item_count?{message:`Taking you to checkout…`,navigateTo:Yr()}:{message:`Your cart is empty — add something first and I'll take you straight to checkout.`}},async view_product(e){return{message:`Opening the product page…`,navigateTo:Xr(e.productHandle)}}},di={add:`⚠️ I couldn't add that to your cart — please try from the product page.`,update:`⚠️ I couldn't update that cart item — please try again.`,remove:`⚠️ I couldn't remove that cart item — please try again.`,view_cart:`⚠️ I couldn't open the cart page.`,checkout:`⚠️ I couldn't start checkout — you can open the cart and check out from there.`,view_product:`⚠️ I couldn't open that product page.`};async function fi(e){let t={messages:[],navigateTo:null};if(!Array.isArray(e)||e.length===0)return t;if(!await Br())return t.messages.push(`⚠️ Cart actions only work on the store's own website — please try from the shop page.`),t;for(let n of e){let e=ui[n?.type];if(e)try{let r=await e(n);r.message&&t.messages.push(r.message),r.navigateTo&&(t.navigateTo=r.navigateTo)}catch(e){console.warn(`[FlowEngage:Cart] ${n.type} failed:`,e),t.messages.push(li(e,di[n.type]))}}return t}var pi=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request[^>]*>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),mi=(e=[])=>e.filter(e=>e.type!==`call_recording`&&!(typeof e.message==`string`&&e.message.includes(`AI chat recording`))).map(e=>({...e,message:pi(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),hi=50,gi=(e,t)=>{let n=t[0]?.timestamp;if(!n)return t;let r=new Set(t.map(e=>e.id)),i=e.filter(e=>!e.isPending&&e.timestamp&&e.timestamp<n&&!r.has(e.id));return i.length?[...i,...t]:t};function _i(e){if(!e||typeof e!=`string`)return null;let t=e.match(/<navigate([^>]*?)(?:\/>|>[\s\S]*?<\/navigate>)/i);if(!t)return null;let n=t[1],r=n.match(/url=["']([^"']+)["']/i);if(!r)return null;let i=n.match(/section=["']([^"']+)["']/i)||n.match(/highlight=["']([^"']+)["']/i);return{url:r[1].trim(),section:i?.[1]?.trim()||null}}var vi=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,yi=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},bi=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},xi=(e=[],t,n=6)=>!t?.message||e.slice(-n).some(e=>e.sender===`system`&&e.message===t.message)?e:[...e,t];function Si({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,d.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),[a,o]=(0,d.useState)(0),[s,c]=(0,d.useState)(`booting`),[l,u]=(0,d.useState)(null),[m,h]=(0,d.useState)(null),[g,_]=(0,d.useState)(``),[x,S]=(0,d.useState)([]),[E,ee]=(0,d.useState)(!1),D=(0,d.useRef)(!1),te=(0,d.useCallback)(()=>{S(e=>[...e,{id:`nav-fail-${e.length}-${Math.random().toString(36).slice(2,8)}`,sender:`bot`,message:`I couldn't find that page on our site — could you tell me more about what you're looking for?`,timestamp:new Date().toISOString()}])},[]),ne=(0,d.useCallback)(e=>{fi(e).then(({messages:e,navigateTo:t})=>{e.length&&S(t=>[...t,...e.map((e,n)=>({id:`cart-${t.length+n}-${Math.random().toString(36).slice(2,8)}`,sender:`bot`,message:e,timestamp:new Date().toISOString()}))]),t&&setTimeout(()=>{window.location.assign(t)},900)})},[]),O=(0,d.useCallback)(()=>{S(e=>e.slice(-3).some(e=>(e.sender===`bot`||e.sender===`assistant`)&&/already on (that|this|the)\b/i.test(String(e.message||``)))?e:[...e,{id:`nav-already-${e.length}-${Math.random().toString(36).slice(2,8)}`,sender:`bot`,message:`Looks like you're already on this page!`,timestamp:new Date().toISOString()}])},[]),[k,A]=(0,d.useState)(le().isOpen),[pe,j]=(0,d.useState)(le().activeScreen),[he,M]=(0,d.useState)(le().isHumanHandled),[N,ge]=(0,d.useState)(le().agentName),[_e,ve]=(0,d.useState)(le().agentHeadshot),[ye,P]=(0,d.useState)(()=>de(i?.siteId)),[be,I]=(0,d.useState)(!1),[xe,Se]=(0,d.useState)(!1),[Ce,L]=(0,d.useState)(`idle`),[we,Te]=(0,d.useState)(!1),[Ee,De]=(0,d.useState)(!1),[R,je]=(0,d.useState)(``),[Me,Ne]=(0,d.useState)(!1),[Pe,Fe]=(0,d.useState)(0),[Ie,Le]=(0,d.useState)(0),[Re,ze]=(0,d.useState)(!1),[z,Be]=(0,d.useState)(null),[B,Ve]=(0,d.useState)(null),[He,Ue]=(0,d.useState)(`idle`),[We,Ge]=(0,d.useState)(null),[Ke,qe]=(0,d.useState)(!1),[Je,Ye]=(0,d.useState)(``),[Xe,V]=(0,d.useState)(!1),H=(0,d.useRef)(null),U=(0,d.useRef)(null),W=(0,d.useRef)(``),Ze=(0,d.useRef)(!1),Qe=(0,d.useRef)(null),$e=(0,d.useRef)(null),et=(0,d.useRef)(null),tt=(0,d.useRef)(null),nt=(0,d.useRef)(null),rt=(0,d.useRef)(null),it=(0,d.useRef)(null),at=(0,d.useRef)(!1),ot=(0,d.useRef)({url:null,at:0}),st=(0,d.useCallback)((e,t)=>{Nn(6e3);let n=e;try{n=new URL(e,window.location.origin).href}catch{}let r=ot.current;return r.url===n&&Date.now()-r.at<4e3?Promise.resolve({navigated:!0,deduped:!0}):(ot.current={url:n,at:Date.now()},jr(e,t))},[]),ct=(0,d.useRef)([]),G=(0,d.useRef)(null),lt=(0,d.useRef)(null),ut=(0,d.useRef)(null),dt=(0,d.useRef)(!1),ft=(0,d.useRef)(!1),pt=(0,d.useRef)(``),mt=(0,d.useRef)(null),ht=(0,d.useRef)(null),gt=(0,d.useRef)([]),_t=(0,d.useRef)(0),vt=(0,d.useRef)(N),yt=(0,d.useRef)([]),bt=(0,d.useRef)(!1),xt=(0,d.useRef)(!1),St=(0,d.useRef)(i),Ct=(0,d.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),wt=(0,d.useCallback)((e={})=>{let t=!!e.is_human_handled;return M(t),t?(j(`agent`),e.agent_info?.name&&ge(e.agent_info.name),e.agent_info?.headshot&&ve(e.agent_info.headshot),t):(j(`ai`),t)},[]),Tt=(0,d.useMemo)(()=>{let e=m?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:y},[i,m]);(0,d.useEffect)(()=>{$e.current=z},[z]),(0,d.useEffect)(()=>{vt.current=N},[N]),(0,d.useEffect)(()=>{xt.current=Me},[Me]),(0,d.useEffect)(()=>{St.current=i},[i]);let Et=()=>{Ye(``)},Dt=(0,d.useCallback)(()=>{ut.current&&=(window.clearTimeout(ut.current),null)},[]),Ot=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return P(t),fe(t,i?.siteId),t};(0,d.useEffect)(()=>{let e=i?.siteId;if(!e)return;let t=de(e);if(t){P(t);return}P(t=>(t&&fe(t,e),t))},[i?.siteId]);let kt=(e=`unspecified`)=>{let t=G.current||rt.current?.callId,n=_t.current,r=mt.current;if(mt.current=null,_t.current=0,r&&r.state!==`inactive`){r.onstop=()=>{let e=gt.current;if(gt.current=[],e.length>0&&t&&U.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;U.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}};try{r.stop()}catch{r.onstop=null,gt.current=[]}}else if(r&&r.state===`inactive`){let e=gt.current;if(gt.current=[],e.length>0&&t&&U.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;U.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}}else gt.current=[];if(ht.current){try{ht.current.close()}catch{}ht.current=null}et.current&&=(et.current.close(),null),tt.current&&=(tt.current.getTracks().forEach(e=>e.stop()),null),nt.current&&=(nt.current.srcObject=null,nt.current.remove(),null),Dt(),rt.current=null,ct.current=[],G.current=null,lt.current=null,dt.current=!1,qe(!1),Be(null),Ve(null),Ue(`idle`),Ge(null)},At=(e=new Date().toISOString())=>{let t=H.current,n=G.current||rt.current?.callId;if(!(!t?.connected||!n||dt.current)){dt.current=!0,t.emit(`call:connected`,{callId:n,chatId:W.current,connectedAt:e});try{let e=tt.current,t=nt.current?.srcObject;if(e&&t&&!mt.current){gt.current=[];let n=new(window.AudioContext||window.webkitAudioContext);ht.current=n;let r=n.createMediaStreamDestination();n.createMediaStreamSource(e).connect(r),n.createMediaStreamSource(t).connect(r);let i=window.MediaRecorder.isTypeSupported(`audio/webm`)?`audio/webm`:`audio/mp4`,a=new window.MediaRecorder(r.stream,{mimeType:i});a.ondataavailable=e=>{e.data&&e.data.size>0&&gt.current.push(e.data)},mt.current=a,_t.current=Date.now(),a.start(1e3),setTimeout(()=>{try{if(!window.speechSynthesis)return;let e=new SpeechSynthesisUtterance(`This call is being recorded for quality and training purposes.`);if(e.rate=.95,e.pitch=1,e.volume=1,window.MediaStreamTrackGenerator||window.AudioContext)try{let t=n.createMediaStreamDestination();e.onstart=()=>{try{let i=document.createElement(`audio`);i.style.display=`none`,i.srcObject=t.stream,document.body.appendChild(i),i.play().catch(()=>{});let a=n.createMediaStreamSource(t.stream);a.connect(r),e.onend=()=>{try{a.disconnect()}catch{}try{i.remove()}catch{}}}catch{}}}catch{}window.speechSynthesis.speak(e)}catch{}},200)}}catch{}}},jt=(e={})=>{if(!e.callId)return;let t=lt.current===e.callId,n=G.current===e.callId,r=$e.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(Dt(),Be(null),t||n){G.current=e.callId,Ve(e.callId),Ue(e=>e===`connected`?e:`connecting`),A(!0);return}Ue(`idle`)}},Mt=(e={})=>{if(!e.callId)return;let t=lt.current===e.callId,n=G.current===e.callId,r=$e.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(Dt(),n){kt();return}lt.current=null,rt.current=null,ct.current=[],Be(null),Ue(`idle`)}},Nt=async(e={})=>{let t=et.current,n=H.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:W.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),rt.current=e;return}if(await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),ct.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:W.current,queuedCount:ct.current.length});for(let e of ct.current)await t.addIceCandidate(new RTCIceCandidate(e));ct.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:W.current})};(0,d.useEffect)(()=>{ue({isOpen:k,activeScreen:pe,isHumanHandled:he,agentName:N,agentHeadshot:_e})},[k,pe,he,N,_e]),(0,d.useEffect)(()=>{let e=!0;return(async()=>{V(!0);try{let t=p(i),n=await ke(t);if(!e)return;let a=t.siteId,o=oe(a),s=me(a),l=``;try{let e=Ze.current,r=Qe.current;if(Ze.current=!1,Qe.current=null,l=(await Oe({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:a,priorChatId:e||r?null:o||C(),forceNew:e,resumeChatId:r,visitorId:s}))?.data?.chatId,!l)throw Error(`resolve-session returned no chatId`);w(),ce(a,l)}catch(e){console.warn(`[FlowEngageProvider] resolve-session failed, reusing persisted or ephemeral chat id`,e?.message||e),l=o||T(),ce(a,l)}W.current=l;let u=Ae({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId,visitorId:s});U.current=u,h({...n,apiBaseUrl:t.apiBaseUrl}),_(l);let d=n?.widgetSettings?.branding?.fallbackAgentName||`Agent`,f=pn({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:l,siteId:t.siteId});H.current=f,f.on(`connect`,async()=>{L(`connected`);let e=W.current;if(e&&U.current)try{wt(await U.current.checkHumanHandled(e))}catch{}}),f.on(`disconnect`,()=>{L(`disconnected`)}),f.on(`aiTyping`,()=>{Se(!0)}),f.on(`ai:typing`,()=>{Se(!0)}),f.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:pi(t.message)};Se(!1),I(!1),!(n.type===`call_recording`||typeof n.message==`string`&&n.message.includes(`AI chat recording`))&&S(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),f.on(`conversationStarted`,e=>{e?.message&&S(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),f.on(`message:new`,e=>{let t=e.message||e,n={...t,message:pi(t.message)};Se(!1),!(n.type===`call_recording`||typeof n.message==`string`&&n.message.includes(`AI chat recording`))&&((n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&I(!1),S(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(M(!0),j(`agent`),ge(bi([n.agent_name,n.agentName,n.metadata?.agentName],d)),n.sender_headshot&&ve(n.sender_headshot),A(!0),Fe(e=>e+1)))});let m=(e={})=>{let t=bi([e.agent?.name,e.agentName,e.agent_name,vt.current],d);M(!0),j(`agent`),ge(t),ve(e.agent?.headshot||null),A(!0),Fe(e=>e+1),S(e=>xi(e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}))},g=(e={})=>{let t=bi([e.agent?.name,e.agentName,e.agent_name,vt.current],d);M(!1),j(`ai`),S(e=>xi(e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}))};f.on(`agent:joined`,m),f.on(`agentJoined`,m),f.on(`agent:left`,g),f.on(`agentLeft`,g),f.on(`conversationEnded`,e=>{ze(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;S(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),f.on(`chat:history_update`,e=>{let t=mi(e.chat_history||[]);S(e=>gi(e,t)),t.length===0&&(ze(!1),M(!1),j(`ai`),Se(!1),I(!1))}),f.on(`conversation:reset`,()=>{S([]),ze(!1),M(!1),j(`ai`),Se(!1),I(!1)}),f.on(`voice:end_session`,(e={})=>{console.log(`[FlowEngageProvider] voice:end_session received — ending voice session`),Le(e=>e+1),A(!0),Fe(e=>e+1)}),f.on(`typing:start`,e=>{e.sender===`agent`&&I(!0)}),f.on(`typing:stop`,e=>{e.sender===`agent`&&I(!1)}),f.on(`call:incoming`,(e={})=>{let t=bi([e.agentName,e.ownerName,e.agent?.name,vt.current],`Agent`);Et(),Dt(),dt.current=!1,Be({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ge(e=>bi([t,e],`Agent`)),Ue(`incoming`),Ge(null),A(!0)}),f.on(`call:offer`,async(e={})=>{rt.current=e;try{await Nt(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),f.on(`call:ice-candidate-from-agent`,async(e={})=>{if(e.candidate)try{let t=yi(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(!et.current||!et.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||W.current,queueSize:ct.current.length+1}),ct.current.push(t);return}await et.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),f.on(`call:ended`,()=>{Et(),kt(`socket:call_ended`)}),f.on(`call:accepted`,(e={})=>{jt(e)}),f.on(`call:accepted_by_other`,(e={})=>{jt(e)}),f.on(`call:rejected`,(e={})=>{Mt(e)}),f.on(`call:missed`,(e={})=>{Mt(e)}),f.on(`call:failed`,(e={})=>{Mt(e)}),f.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=lt.current===e.callId,n=G.current===e.callId,r=rt.current?.callId===e.callId,i=$e.current?.callId===e.callId;if(!t&&!n&&!r){i&&(Be(null),Ue(`idle`));return}dt.current=!0,lt.current=null,G.current=e.callId,Ve(e.callId),Be(null),Ue(`connected`),Ge(e.connectedAt||new Date().toISOString()),A(!0)}),f.on(`call:unavailable`,(e={})=>{kt(`socket:call_unavailable`),Ye(vi(e,`This visitor is not available for a call right now.`)),A(!0)}),f.on(`call:error`,(e={})=>{kt(`socket:call_error`),Ye(vi(e,`We couldn't connect the call right now.`)),A(!0)}),f.on(`visitor:navigate`,async({url:e,section:t,highlight:n}={})=>{e&&st(e,{voiceActive:xt.current}).then(({navigated:e,reason:r})=>{if(!e){r===`not-found`?te():r===`already-on-page`&&O();return}let i=t||n;i&&setTimeout(()=>{let e=rr(null,i);e&&gr(e)},300)})}),f.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;let n=rr(e||null,t||null);n&&gr(n)}),f.on(`visitor:clear_highlight`,()=>{_r()}),Ct.current=mn({socket:f,chatId:l});let v=await u.loadHistory(l,r);if(!e)return;S(mi(v.chat_history||[])),ee((v.chat_history||[]).length>=hi),M(!!v.is_human_handled),j(v.is_human_handled?`agent`:pe);let y=v?.visitor_email||v?.visitorEmail;if(y&&String(y).trim()&&Ot(String(y).trim()),await new Promise(e=>setTimeout(e,500)),!e)return;c(`ready`)}catch(t){if(!e)return;u(t),c(`error`)}finally{e&&V(!1)}})(),()=>{e=!1,Ct.current?.cleanup?.(),kt(),H.current?.disconnect()}},[i,r,a]),(0,d.useEffect)(()=>()=>{if(Me&&!bt.current&&yt.current.length>0){let e=W.current,t=yt.current,n=U.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),bt.current=!0)}},[Me,m]);let Pt=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e=U.current;!e||!g||Pt.current!==k&&(k&&Pt.current!==null?e.updateChatStatus(g,`open`).catch(()=>{}):Pt.current===!0&&e.updateChatStatus(g,`widget_closed`).catch(()=>{}),Pt.current=k)},[k,g]),(0,d.useEffect)(()=>{let e=()=>{let e=W.current,t=U.current;!e||!t||typeof navigator>`u`||t.beaconWidgetClosed?.(e)||t.updateChatStatus(e,`widget_closed`).catch(()=>{})};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[]);let Ft=async()=>{if(!(!z?.callId||!U.current||!H.current||!g)){Et(),lt.current=z.callId,Dt();try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});tt.current=e;let t=[{urls:`stun:stun.l.google.com:19302`}];try{let e=await U.current.getIceServersConfig();e?.data?.iceServers?.length&&(t=e.data.iceServers)}catch(e){console.warn(`[FlowEngageProvider] ice-config fetch failed, using STUN default`,e)}let n=new RTCPeerConnection({iceServers:t});et.current=n,n.onconnectionstatechange=()=>{let e=n.connectionState;if(e===`connected`){let e=new Date().toISOString();Ue(`connected`),Ge(t=>t||e),At(e);return}if(e===`connecting`){Ue(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&kt(`peer:connection_${e}`)},n.oniceconnectionstatechange=()=>{let e=n.iceConnectionState;if(e===`connected`||e===`completed`){let e=new Date().toISOString();Ue(`connected`),Ge(t=>t||e),At(e);return}if(e===`checking`||e===`new`){Ue(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&kt(`peer:ice_${e}`)},n.onsignalingstatechange=()=>{},n.onicegatheringstatechange=()=>{},e.getTracks().forEach(t=>{n.addTrack(t,e)}),n.onicecandidate=e=>{if(!e.candidate||!H.current?.connected)return;let t=e.candidate;H.current.emit(`call:ice-candidate`,{callId:z.callId,candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,chatId:g,from:`customer`})},n.ontrack=e=>{let[t]=e.streams||[],[n]=t?.getAudioTracks?.()||[];if(!nt.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,e.playsInline=!0,e.onplay=()=>{},e.onpause=()=>{},e.onended=()=>{},e.onerror=e=>{},nt.current=e,document.body.appendChild(e)}nt.current.srcObject=e.streams[0];let r=z?.callId,i=r&&(lt.current===r||G.current===r);if(!dt.current&&i){let e=new Date().toISOString();Ue(`connected`),Ge(t=>t||e),G.current=r,Ve(r),At(e)}nt.current.srcObject=t||null;let a=nt.current.play?.();a?.catch&&a.catch(e=>{})};let r=rt.current;r&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:r.callId||z.callId,chatId:g}),await Nt({...r,callId:r.callId||z.callId})),await U.current.acceptCall(z.callId,g),H.current?.emit(`call:accepted`,{callId:z.callId,chatId:g}),G.current=z.callId,Ve(z.callId),Ue(e=>e===`connected`||dt.current?`connected`:`connecting`),Be(null),A(!0)}catch(e){if(lt.current=null,kt(`accept_call_failed`),e?.status===404||e?.status===409||e?.status===422){Ye(vi(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await U.current.rejectCall(z.callId,g)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Ye(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Ye(`We couldn't connect the call right now. Please try again.`)}}},It=async()=>{if(!z?.callId||!U.current||!g){kt(`reject_call_without_server_context`);return}let e=z.callId;Dt(),Et(),H.current?.emit(`call:rejected`,{callId:e,chatId:g,reason:`visitor_declined`});try{await U.current.rejectCall(e,g)}catch(e){Ye(vi(e,`We couldn't decline the call cleanly.`))}finally{kt(`reject_call_finally`)}},Lt=(0,d.useRef)(It);Lt.current=It,(0,d.useEffect)(()=>{if(!z?.callId||B){Dt();return}let e=z.callId;return Dt(),ut.current=window.setTimeout(()=>{$e.current?.callId===e&&lt.current!==e&&G.current!==e&&Lt.current()},b),()=>{ut.current&&=(window.clearTimeout(ut.current),null)}},[B,Dt,z?.callId]);let Rt=async()=>{if(!B||!U.current||!g){kt(`end_call_without_server_context`);return}Et();try{await U.current.endWebRTCCall(B,g)}catch(e){Ye(vi(e,`The call ended locally, but the server could not be updated.`))}finally{kt(`end_call_finally`)}},zt=()=>{let e=tt.current?.getAudioTracks?.()||[],t=et.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0)return;let r=!Ke;n.forEach(e=>{e.enabled=!r}),qe(r)},Bt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(A(!0),!(!t||!U.current||!g||typeof window>`u`)){try{await U.current.trackVisitor({chatId:g,currentPagePath:window.location.pathname||`/`})}catch{}try{await U.current.updateChatStatus(g,`open`)}catch{}}},Vt=async e=>{let t=Ot(e);if(!t||!U.current||!W.current)return t;try{await U.current.trackVisitor({chatId:W.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Ht=()=>{!g||!H.current?.connected||ft.current||(ft.current=!0,H.current.emit(`typing:start`,{chatId:g,sender:`user`}))},Ut=()=>{!g||!H.current?.connected||!ft.current||(ft.current=!1,H.current.emit(`typing:stop`,{chatId:g,sender:`user`}))},Wt=(e=``)=>{let t=typeof e==`string`?e:``;!g||!H.current?.connected||t!==``&&pt.current===t||(pt.current=t,H.current.emit(`typing:update`,{chatId:g,sender:`user`,text:t}))};function Gt(){if(typeof document>`u`)return null;try{let e=(document.querySelector(`main`)||document.querySelector(`[role='main']`)||document.querySelector(`article`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);e.querySelectorAll(`nav, footer, header, aside, script, style, noscript, #flowengage-root, .flowengage-shell, .flowengage-widget-root, [id*='flowengage'], [class*='flowengage']`).forEach(e=>e.remove());let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>0?t.substring(0,3e3):null}catch{return null}}let Kt=async(e,t=``,n=null,a={})=>{let o=typeof e==`string`?e.trim():``;if(!o||!U.current||!g||s!==`ready`||Re)return;Ut(),at.current=!1;let c=/^\s*(yes|yeah|sure|ok|okay|go ahead|take me(?: there)?(?!\s+\w)|navigate(?!\s+(?:me\s+)?to\s+\w)|yep|absolutely|please do|do it|let'?s go|go there|show me(?!\s+(?:the|a|an)\s+\w)|go to it|bring me there|navigate me there)\b/i,l=/^\s*(?:yes|yeah|sure|ok|okay|yep|absolutely)\s+(?!(?:please|do\s+it|let'?s|that|this|there|it|thanks|go|cool|great|perfect|sounds|alright|proceed)\b)\w/i,d=/\b(take me|navigate|go to|show me|bring me|open|go there|navigate to|take me to|let'?s go to)\b/i;if(it.current&&c.test(o)&&!l.test(o)){let{url:e,section:t}=it.current;it.current=null,at.current=!0,console.log(`[FWH Nav] Client-side nav firing →`,e),st(e,{voiceActive:xt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?te():n===`already-on-page`&&O();return}!t||!xt.current||setTimeout(()=>{let e=rr(null,t);e&&gr(e)},300)})}else c.test(o)||(it.current=null);let f=`pending-user-${Date.now()}`,p={id:f,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,type:a?.type||`text`,metadata:a?.metadata||void 0,...n||{}};S(e=>[...e,p]);let m=he;if(m)try{m=wt(await U.current.checkHumanHandled(g))}catch{}if(m&&H.current?.connected){H.current.emit(`customer:message`,{chatId:g,content:e,sender:`user`,email:ye||void 0,type:a?.type||`text`,metadata:a?.metadata||{},...n||{}});return}Te(!0);try{let s=await Wr(),c=Hr(),l=`stream-preview-${Date.now().toString(36)}`,u=e=>{Se(!1),S(t=>{let n=t.findIndex(e=>e.id===l);if(n===-1)return[...t,{id:l,sender:`bot`,message:e,timestamp:new Date().toISOString(),isStreaming:!0}];let r=[...t];return r[n]={...r[n],message:r[n].message+e},r})},f=await U.current.sendAiMessage(g,e,r,t,{...n||{},...ye?{email:ye}:{}},{...a,currentPageUrl:typeof window<`u`?window.location.href:void 0,currentPageTitle:typeof window<`u`?document.title:void 0,currentPagePath:typeof window<`u`?window.location.pathname:void 0,currentPageContent:Gt()||void 0,navPreference:re(i?.siteId)||void 0,...s?{shopifyCart:s}:{},...c?{shopifyCustomerId:c}:{}},u),p=f.chat_history||[];if(console.log(`[FWH Nav Debug] API response fields:`,{has_navigate:!!f.navigate,navigate:f.navigate,has_pending_navigate:!!f.pending_navigate,pending_navigate:f.pending_navigate,last_bot_msg:[...p].reverse().find(e=>e.sender===`bot`)?.message?.substring(0,80)}),f.pending_navigate?.url){let e={url:f.pending_navigate.url,section:f.pending_navigate.section||null};d.test(o)?(console.log(`[FWH Nav] Auto-navigating (intent detected) →`,e.url),st(e.url,{voiceActive:xt.current}).then(({navigated:t,reason:n})=>{if(!t){n===`not-found`?te():n===`already-on-page`&&O();return}e.section&&setTimeout(()=>{let t=rr(null,e.section);t&&gr(t)},300)})):(it.current=e,console.log(`[FWH Nav] Stored pending nav →`,it.current));let t=i?.siteId;t&&!ie(t)&&(ae(t),S(e=>[...e,{id:`nav-pref-${Date.now()}`,type:`nav_pref_choice`,sender:`system`,message:``,timestamp:new Date().toISOString()}]))}if(f.navigate?.url)if(at.current)at.current=!1;else{let{url:e,section:t}=f.navigate;st(e,{voiceActive:xt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?te():n===`already-on-page`&&O();return}t&&setTimeout(()=>{let e=rr(null,t);e&&gr(e)},300)})}else if(f.highlight?.section){let e=f.highlight.section;setTimeout(()=>{let t=rr(null,e);t&&gr(t)},150)}else{let e=[...p].reverse().find(e=>e.sender===`bot`||e.sender===`assistant`);if(e?.message){let t=_i(e.message);t&&br(t.url,{siteId:St.current?.siteId,apiBaseUrl:St.current?.apiBaseUrl}).then(({allowed:e,correctedUrl:n})=>{if(!e){te();return}st(n||t.url,{voiceActive:xt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?te():n===`already-on-page`&&O();return}!t.section||!xt.current||setTimeout(()=>{let e=rr(null,t.section);e&&gr(e)},300)})})}}S(e=>gi(e,mi(p))),Array.isArray(f.cart_actions)&&f.cart_actions.length&&ne(f.cart_actions),M(!!f.is_human_handled),j(f.is_human_handled?`agent`:`ai`),Se(!1),Te(!1),await U.current.updateChatStatus(g,`messageSent`)}catch(e){S(e=>e.filter(e=>!e.isStreaming).map(e=>e.id===f?{...e,isPending:!1,failed:!0}:e)),Se(!1),Te(!1),e.status===429?(De(!0),je(e.message),window.setTimeout(()=>{De(!1),je(``)},v)):u(e)}},qt=async e=>{if(!U.current||!e)throw Error(`Upload is unavailable right now.`);return U.current.uploadChatFile(e)},Jt=async e=>{if(!(!U.current||!g)){try{let t=e?`voice`:`text`;await U.current.setChatMode(g,t)}catch{}Ne(e),e&&(bt.current=!1)}},Yt=async e=>{if(bt.current)return;if(bt.current=!0,!U.current||!g||!e?.length){Ne(!1);return}let t=()=>{let t=mi(e);S(e=>{if(!e.length)return t;let n=e[e.length-1],r=t[0];return n&&r&&n.sender===r.sender&&n.message===r.message?e:[...e,...t]})};try{let n=await U.current.syncVoice(g,e);if(n?.chat_history?.length)S(e=>gi(e,mi(n.chat_history)));else if(n?.success)try{let e=await U.current.loadHistory(g,r);e?.chat_history?.length?S(t=>gi(t,mi(e.chat_history))):t()}catch{t()}else t()}catch{t()}finally{Ne(!1)}},K=async()=>{if(!(!U.current||!g)){Me&&!bt.current&&yt.current.length>0&&await Yt(yt.current);try{await U.current.endConversation(g)}catch{try{await U.current.updateChatStatus(g,`ended`)}catch{}}ze(!0),S(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,d.useEffect)(()=>{if(He!==`connected`||!B||!g||!We||!Tt)return;let e=new Date(We).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,Tt*1e3-t),r=window.setTimeout(()=>{Ye(`The call ended because it reached the time limit.`),Rt()},n);return()=>window.clearTimeout(r)},[B,We,He,g,Rt,Tt]),(0,d.useEffect)(()=>{let e=()=>{let e=W.current,t=U.current;if(!t||!e)return;if(xt.current&&yt.current.length>0&&F(),!bt.current&&yt.current.length>0&&(t.beaconSyncVoice(e,yt.current)||t.syncVoice(e,yt.current).catch(()=>{}),bt.current=!0),G.current){t.beaconEndWebRTCCall(G.current,e);return}let n=lt.current||$e.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let Xt=(0,d.useCallback)(async e=>{let t=W.current;if(!t||!e||!U.current||D.current)return 0;D.current=!0;try{let n=await U.current.getOlderMessages(t,e);if(W.current!==t)return 0;let r=mi(n?.history||[]);return ee(!!n?.hasMore),r.length?(S(e=>{let t=new Set(e.map(e=>e.id));return[...r.filter(e=>!t.has(e.id)),...e]}),r.length):0}catch{return 0}finally{D.current=!1}},[]),Zt=(0,d.useCallback)(()=>{let e=i?.siteId;se(e),Ze.current=!0,Qe.current=null,H.current?.disconnect(),S([]),_(``),W.current=``,ze(!1),M(!1),ge(null),ve(null),V(!0),o(e=>e+1)},[i?.siteId]),Qt=(0,d.useCallback)(e=>{i?.siteId,Ze.current=!1,Qe.current=e,H.current?.disconnect(),S([]),_(``),W.current=``,ze(!1),M(!1),ge(null),ve(null),V(!0),o(e=>e+1)},[i?.siteId]),$t=(0,d.useMemo)(()=>({status:s,error:l,runtimeConfig:m,resolvedConfig:i,chatId:g,chatHistory:x,isOpen:k,activeScreen:pe,isHumanHandled:he,agentName:N,agentHeadshot:_e,visitorEmail:ye,isAgentTyping:be,isAiTyping:xe,connectionStatus:Ce,isLoading:we,isVoiceMode:Me,isRateLimited:Ee,rateLimitMessage:R,isConversationEnded:Re,isSessionRestoring:Xe,openToChatCounter:Pe,voiceEndCounter:Ie,incomingCall:z,activeCallId:B,callConnectionState:He,callConnectedAt:We,isCallMuted:Ke,webRTCError:Je,language:r,historyRef:yt,hasSyncedRef:bt,dismissCallError:Et,captureVisitorEmail:Vt,startTyping:Ht,stopTyping:Ut,updateTypingDraft:Wt,notifyRouteChange:()=>Ct.current?.notifyRouteChange?.(),openWidget:Bt,closeWidget:()=>A(!1),toggleWidget:()=>{if(k){A(!1);return}Bt({notifyChatInitiated:!0})},sendMessage:Kt,uploadChatFile:qt,setVoiceMode:Jt,onMessageSync:Yt,beaconSyncVoiceTranscript:e=>{let t=U.current,n=W.current;return!t||!n||!Array.isArray(e)||!e.length?!1:(t.beaconSyncVoice(n,e)||t.syncVoice(n,e).catch(()=>{}),!0)},endConversation:K,startNewChat:Zt,resumeChat:Qt,getVisitorChatHistory:()=>U.current?.getVisitorChatHistory?.(),getVisitorChatThread:e=>U.current?.getVisitorChatThread?.(e),hasOlderMessages:E,loadOlderMessages:Xt,acceptCall:Ft,rejectCall:It,endWebRTCCall:Rt,toggleCallMute:zt}),[s,l,m,i,g,x,k,pe,he,N,_e,ye,be,xe,Ce,we,Me,Ee,R,Re,Xe,Pe,Ie,z,B,He,We,Ke,Je,r,Vt,Ht,Ut,Wt,Ft,It,Rt,zt,Bt,Kt,qt,Jt,Yt,K,Zt,Et,E,Xt]);return(0,f.jsx)(hn.Provider,{value:$t,children:n})}var Ci=(0,d.createContext)({});function wi(e){let t=(0,d.useRef)(null);return t.current===null&&(t.current=e()),t.current}var Ti=typeof window<`u`?d.useLayoutEffect:d.useEffect,Ei=(0,d.createContext)(null);function Di(e,t){e.indexOf(t)===-1&&e.push(t)}function Oi(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var ki=(e,t,n)=>n>t?t:n<e?e:n;function Ai(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}var ji=()=>{},Mi=()=>{};typeof process<`u`&&process.env.NODE_ENV!==`production`&&(ji=(e,t,n)=>{!e&&typeof console<`u`&&console.warn(Ai(t,n))},Mi=(e,t,n)=>{if(!e)throw Error(Ai(t,n))});var Ni={},Pi=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Fi(e){return typeof e==`object`&&!!e}var Ii=e=>/^0[^.\s]+$/u.test(e);function Li(e){let t;return()=>(t===void 0&&(t=e()),t)}var Ri=e=>e,zi=(e,t)=>n=>t(e(n)),Bi=(...e)=>e.reduce(zi),Vi=(e,t,n)=>{let r=t-e;return r===0?1:(n-e)/r},Hi=class{constructor(){this.subscriptions=[]}add(e){return Di(this.subscriptions,e),()=>Oi(this.subscriptions,e)}notify(e,t,n){let r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,t,n);else for(let i=0;i<r;i++){let r=this.subscriptions[i];r&&r(e,t,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}},Ui=e=>e*1e3,Wi=e=>e/1e3;function Gi(e,t){return t?1e3/t*e:0}var Ki=new Set;function qi(e,t,n){e||Ki.has(t)||(console.warn(Ai(t,n)),Ki.add(t))}var Ji=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Yi=1e-7,Xi=12;function Zi(e,t,n,r,i){let a,o,s=0;do o=t+(n-t)/2,a=Ji(o,r,i)-e,a>0?n=o:t=o;while(Math.abs(a)>Yi&&++s<Xi);return o}function Qi(e,t,n,r){if(e===t&&n===r)return Ri;let i=t=>Zi(t,0,1,e,n);return e=>e===0||e===1?e:Ji(i(e),t,r)}var $i=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,ea=e=>t=>1-e(1-t),ta=Qi(.33,1.53,.69,.99),na=ea(ta),ra=$i(na),ia=e=>e>=1?1:(e*=2)<1?.5*na(e):.5*(2-2**(-10*(e-1))),aa=e=>1-Math.sin(Math.acos(e)),oa=ea(aa),sa=$i(aa),ca=Qi(.42,0,1,1),la=Qi(0,0,.58,1),ua=Qi(.42,0,.58,1),da=e=>Array.isArray(e)&&typeof e[0]!=`number`,fa=e=>Array.isArray(e)&&typeof e[0]==`number`,pa={linear:Ri,easeIn:ca,easeInOut:ua,easeOut:la,circIn:aa,circInOut:sa,circOut:oa,backIn:na,backInOut:ra,backOut:ta,anticipate:ia},ma=e=>typeof e==`string`,ha=e=>{if(fa(e)){Mi(e.length===4,`Cubic bezier arrays must contain four numerical values.`,`cubic-bezier-length`);let[t,n,r,i]=e;return Qi(t,n,r,i)}else if(ma(e))return Mi(pa[e]!==void 0,`Invalid easing type '${e}'`,`invalid-easing-type`),pa[e];return e},ga=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`],_a={value:null,addProjectionMetrics:null};function va(e,t){let n=new Set,r=new Set,i=!1,a=!1,o=new WeakSet,s={delta:0,timestamp:0,isProcessing:!1},c=0;function l(t){o.has(t)&&(u.schedule(t),e()),c++,t(s)}let u={schedule:(e,t=!1,a=!1)=>{let s=a&&i?n:r;return t&&o.add(e),s.add(e),e},cancel:e=>{r.delete(e),o.delete(e)},process:e=>{if(s=e,i){a=!0;return}i=!0;let o=n;n=r,r=o,n.forEach(l),t&&_a.value&&_a.value.frameloop[t].push(c),c=0,n.clear(),i=!1,a&&(a=!1,u.process(e))}};return u}var ya=40;function ba(e,t){let n=!1,r=!0,i={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,o=ga.reduce((e,n)=>(e[n]=va(a,t?n:void 0),e),{}),{setup:s,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:f,render:p,postRender:m}=o,h=()=>{let a=Ni.useManualTiming,o=a?i.timestamp:performance.now();n=!1,a||(i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,ya),1)),i.timestamp=o,i.isProcessing=!0,s.process(i),c.process(i),l.process(i),u.process(i),d.process(i),f.process(i),p.process(i),m.process(i),i.isProcessing=!1,n&&t&&(r=!1,e(h))},g=()=>{n=!0,r=!0,i.isProcessing||e(h)};return{schedule:ga.reduce((e,t)=>{let r=o[t];return e[t]=(e,t=!1,i=!1)=>(n||g(),r.schedule(e,t,i)),e},{}),cancel:e=>{for(let t=0;t<ga.length;t++)o[ga[t]].cancel(e)},state:i,steps:o}}var{schedule:J,cancel:xa,state:Sa,steps:Ca}=ba(typeof requestAnimationFrame<`u`?requestAnimationFrame:Ri,!0),wa;function Ta(){wa=void 0}var Ea={now:()=>(wa===void 0&&Ea.set(Sa.isProcessing||Ni.useManualTiming?Sa.timestamp:performance.now()),wa),set:e=>{wa=e,queueMicrotask(Ta)}},Da={layout:0,mainThread:0,waapi:0},Oa=e=>t=>typeof t==`string`&&t.startsWith(e),ka=Oa(`--`),Aa=Oa(`var(--`),ja=e=>Aa(e)?Ma.test(e.split(`/*`)[0].trim()):!1,Ma=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Na(e){return typeof e==`string`?e.split(`/*`)[0].includes(`var(--`):!1}var Pa={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},Fa={...Pa,transform:e=>ki(0,1,e)},Ia={...Pa,default:1},La=e=>Math.round(e*1e5)/1e5,Ra=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function za(e){return e==null}var Ba=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Va=(e,t)=>n=>!!(typeof n==`string`&&Ba.test(n)&&n.startsWith(e)||t&&!za(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ha=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(Ra);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},Ua=e=>ki(0,255,e),Wa={...Pa,transform:e=>Math.round(Ua(e))},Ga={test:Va(`rgb`,`red`),parse:Ha(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Wa.transform(e)+`, `+Wa.transform(t)+`, `+Wa.transform(n)+`, `+La(Fa.transform(r))+`)`};function Ka(e){let t=``,n=``,r=``,i=``;return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}var qa={test:Va(`#`),parse:Ka,transform:Ga.transform},Ja=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Ya=Ja(`deg`),Xa=Ja(`%`),Y=Ja(`px`),Za=Ja(`vh`),Qa=Ja(`vw`),$a={...Xa,parse:e=>Xa.parse(e)/100,transform:e=>Xa.transform(e*100)},eo={test:Va(`hsl`,`hue`),parse:Ha(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+Xa.transform(La(t))+`, `+Xa.transform(La(n))+`, `+La(Fa.transform(r))+`)`},to={test:e=>Ga.test(e)||qa.test(e)||eo.test(e),parse:e=>Ga.test(e)?Ga.parse(e):eo.test(e)?eo.parse(e):qa.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?Ga.transform(e):eo.transform(e),getAnimatableNone:e=>{let t=to.parse(e);return t.alpha=0,to.transform(t)}},no=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ro(e){return isNaN(e)&&typeof e==`string`&&(e.match(Ra)?.length||0)+(e.match(no)?.length||0)>0}var io=`number`,ao=`color`,oo=`var`,so=`var(`,co="${}",lo=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function uo(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(lo,e=>(to.test(e)?(r.color.push(a),i.push(ao),n.push(to.parse(e))):e.startsWith(so)?(r.var.push(a),i.push(oo),n.push(e)):(r.number.push(a),i.push(io),n.push(parseFloat(e))),++a,co)).split(co),indexes:r,types:i}}function fo(e){return uo(e).values}function po({split:e,types:t}){let n=e.length;return r=>{let i=``;for(let a=0;a<n;a++)if(i+=e[a],r[a]!==void 0){let e=t[a];e===io?i+=La(r[a]):e===ao?i+=to.transform(r[a]):i+=r[a]}return i}}function mo(e){return po(uo(e))}var ho=e=>typeof e==`number`?0:to.test(e)?to.getAnimatableNone(e):e,go=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:ho(e);function _o(e){let t=uo(e);return po(t)(t.values.map((e,n)=>go(e,t.split[n])))}var vo={test:ro,parse:fo,createTransformer:mo,getAnimatableNone:_o};function yo(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function bo({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let i=0,a=0,o=0;if(!t)i=a=o=n;else{let r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=yo(s,r,e+1/3),a=yo(s,r,e),o=yo(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function xo(e,t){return n=>n>0?t:e}var X=(e,t,n)=>e+(t-e)*n,So=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},Co=[qa,Ga,eo],wo=e=>Co.find(t=>t.test(e));function To(e){let t=wo(e);if(ji(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,`color-not-animatable`),!t)return!1;let n=t.parse(e);return t===eo&&(n=bo(n)),n}var Eo=(e,t)=>{let n=To(e),r=To(t);if(!n||!r)return xo(e,t);let i={...n};return e=>(i.red=So(n.red,r.red,e),i.green=So(n.green,r.green,e),i.blue=So(n.blue,r.blue,e),i.alpha=X(n.alpha,r.alpha,e),Ga.transform(i))},Do=new Set([`none`,`hidden`]);function Oo(e,t){return Do.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function ko(e,t){return n=>X(e,t,n)}function Ao(e){return typeof e==`number`?ko:typeof e==`string`?ja(e)?xo:to.test(e)?Eo:Po:Array.isArray(e)?jo:typeof e==`object`?to.test(e)?Eo:Mo:xo}function jo(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>Ao(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function Mo(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=Ao(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function No(e,t){let n=[],r={color:0,var:0,number:0};for(let i=0;i<t.values.length;i++){let a=t.types[i],o=e.indexes[a][r[a]];n[i]=e.values[o]??0,r[a]++}return n}var Po=(e,t)=>{let n=vo.createTransformer(t),r=uo(e),i=uo(t);return r.indexes.var.length===i.indexes.var.length&&r.indexes.color.length===i.indexes.color.length&&r.indexes.number.length>=i.indexes.number.length?Do.has(e)&&!i.values.length||Do.has(t)&&!r.values.length?Oo(e,t):Bi(jo(No(r,i),i.values),n):(ji(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,`complex-values-different`),xo(e,t))};function Fo(e,t,n){return typeof e==`number`&&typeof t==`number`&&typeof n==`number`?X(e,t,n):Ao(e)(e,t)}var Io=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>J.update(t,e),stop:()=>xa(t),now:()=>Sa.isProcessing?Sa.timestamp:Ea.now()}},Lo=(e,t,n=10)=>{let r=``,i=Math.max(Math.round(t/n),2);for(let t=0;t<i;t++)r+=Math.round(e(t/(i-1))*1e4)/1e4+`, `;return`linear(${r.substring(0,r.length-2)})`},Ro=2e4;function zo(e){let t=0,n=e.next(t);for(;!n.done&&t<2e4;)t+=50,n=e.next(t);return t>=2e4?1/0:t}function Bo(e,t=100,n){let r=n({...e,keyframes:[0,t]}),i=Math.min(zo(r),Ro);return{type:`keyframes`,ease:e=>r.next(i*e).value/t,duration:Wi(i)}}var Z={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function Vo(e,t){return e*Math.sqrt(1-t*t)}var Ho=12;function Uo(e,t,n){let r=n;for(let n=1;n<Ho;n++)r-=e(r)/t(r);return r}var Wo=.001;function Go({duration:e=Z.duration,bounce:t=Z.bounce,velocity:n=Z.velocity,mass:r=Z.mass}){let i,a;ji(e<=Ui(Z.maxDuration),`Spring duration must be 10 seconds or less`,`spring-duration-limit`);let o=1-t;o=ki(Z.minDamping,Z.maxDamping,o),e=ki(Z.minDuration,Z.maxDuration,Wi(e)),o<1?(i=t=>{let r=t*o,i=r*e,a=r-n,s=Vo(t,o),c=Math.exp(-i);return Wo-a/s*c},a=t=>{let r=t*o*e,a=r*n+n,s=o**2*t**2*e,c=Math.exp(-r),l=Vo(t**2,o);return(-i(t)+Wo>0?-1:1)*((a-s)*c)/l}):(i=t=>{let r=Math.exp(-t*e),i=(t-n)*e+1;return-Wo+r*i},a=t=>Math.exp(-t*e)*((n-t)*(e*e)));let s=5/e,c=Uo(i,a,s);if(e=Ui(e),isNaN(c))return{stiffness:Z.stiffness,damping:Z.damping,duration:e};{let t=c**2*r;return{stiffness:t,damping:o*2*Math.sqrt(r*t),duration:e}}}var Ko=[`duration`,`bounce`],qo=[`stiffness`,`damping`,`mass`];function Jo(e,t){return t.some(t=>e[t]!==void 0)}function Yo(e){let t={velocity:Z.velocity,stiffness:Z.stiffness,damping:Z.damping,mass:Z.mass,isResolvedFromDuration:!1,...e};if(!Jo(e,qo)&&Jo(e,Ko))if(t.velocity=0,e.visualDuration){let n=e.visualDuration,r=2*Math.PI/(n*1.2),i=r*r,a=2*ki(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:Z.mass,stiffness:i,damping:a}}else{let n=Go({...e,velocity:0});t={...t,...n,mass:Z.mass},t.isResolvedFromDuration=!0}return t}function Xo(e=Z.visualDuration,t=Z.bounce){let n=typeof e==`object`?e:{visualDuration:e,keyframes:[0,1],bounce:t},{restSpeed:r,restDelta:i}=n,a=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],s={done:!1,value:a},{stiffness:c,damping:l,mass:u,duration:d,velocity:f,isResolvedFromDuration:p}=Yo({...n,velocity:-Wi(n.velocity||0)}),m=f||0,h=l/(2*Math.sqrt(c*u)),g=o-a,_=Wi(Math.sqrt(c/u)),v=Math.abs(g)<5;r||=v?Z.restSpeed.granular:Z.restSpeed.default,i||=v?Z.restDelta.granular:Z.restDelta.default;let y,b,x,S,C,w;if(h<1)x=Vo(_,h),S=(m+h*_*g)/x,y=e=>o-Math.exp(-h*_*e)*(S*Math.sin(x*e)+g*Math.cos(x*e)),C=h*_*S+g*x,w=h*_*g-S*x,b=e=>Math.exp(-h*_*e)*(C*Math.sin(x*e)+w*Math.cos(x*e));else if(h===1){y=e=>o-Math.exp(-_*e)*(g+(m+_*g)*e);let e=m+_*g;b=t=>Math.exp(-_*t)*(_*e*t-m)}else{let e=_*Math.sqrt(h*h-1);y=t=>{let n=Math.exp(-h*_*t),r=Math.min(e*t,300);return o-n*((m+h*_*g)*Math.sinh(r)+e*g*Math.cosh(r))/e};let t=(m+h*_*g)/e,n=h*_*t-g*e,r=h*_*g-t*e;b=t=>{let i=Math.exp(-h*_*t),a=Math.min(e*t,300);return i*(n*Math.sinh(a)+r*Math.cosh(a))}}let T={calculatedDuration:p&&d||null,velocity:e=>Ui(b(e)),next:e=>{if(!p&&h<1){let t=Math.exp(-h*_*e),n=Math.sin(x*e),a=Math.cos(x*e),c=o-t*(S*n+g*a),l=Ui(t*(C*n+w*a));return s.done=Math.abs(l)<=r&&Math.abs(o-c)<=i,s.value=s.done?o:c,s}let t=y(e);if(p)s.done=e>=d;else{let n=Ui(b(e));s.done=Math.abs(n)<=r&&Math.abs(o-t)<=i}return s.value=s.done?o:t,s},toString:()=>{let e=Math.min(zo(T),Ro),t=Lo(t=>T.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return T}Xo.applyToOptions=e=>{let t=Bo(e,100,Xo);return e.ease=t.ease,e.duration=Ui(t.duration),e.type=`keyframes`,e};var Zo=5;function Qo(e,t,n){let r=Math.max(t-Zo,0);return Gi(n-e(r),t-r)}function $o({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:a=500,modifyTarget:o,min:s,max:c,restDelta:l=.5,restSpeed:u}){let d=e[0],f={done:!1,value:d},p=e=>s!==void 0&&e<s||c!==void 0&&e>c,m=e=>s===void 0?c:c===void 0||Math.abs(s-e)<Math.abs(c-e)?s:c,h=n*t,g=d+h,_=o===void 0?g:o(g);_!==g&&(h=_-d);let v=e=>-h*Math.exp(-e/r),y=e=>_+v(e),b=e=>{let t=v(e),n=y(e);f.done=Math.abs(t)<=l,f.value=f.done?_:n},x,S,C=e=>{p(f.value)&&(x=e,S=Xo({keyframes:[f.value,m(f.value)],velocity:Qo(y,e,f.value),damping:i,stiffness:a,restDelta:l,restSpeed:u}))};return C(0),{calculatedDuration:null,next:e=>{let t=!1;return!S&&x===void 0&&(t=!0,b(e),C(e)),x!==void 0&&e>=x?S.next(e-x):(!t&&b(e),f)}}}function es(e,t,n){let r=[],i=n||Ni.mix||Fo,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=Bi(Array.isArray(t)?t[n]||Ri:t,a)),r.push(a)}return r}function ts(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(Mi(a===t.length,`Both input and output ranges must be the same length`,`range-length`),a===1)return()=>t[0];if(a===2&&t[0]===t[1])return()=>t[1];let o=e[0]===e[1];e[0]>e[a-1]&&(e=[...e].reverse(),t=[...t].reverse());let s=es(t,r,i),c=s.length,l=n=>{if(o&&n<e[0])return t[0];let r=0;if(c>1)for(;r<e.length-2&&!(n<e[r+1]);r++);let i=Vi(e[r],e[r+1],n);return s[r](i)};return n?t=>l(ki(e[0],e[a-1],t)):l}function ns(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=Vi(0,t,r);e.push(X(n,1,i))}}function rs(e){let t=[0];return ns(t,e.length-1),t}function is(e,t){return e.map(e=>e*t)}function as(e,t){return e.map(()=>t||ua).splice(0,e.length-1)}function os({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=da(r)?r.map(ha):ha(r),a={done:!1,value:t[0]},o=ts(is(n&&n.length===t.length?n:rs(t),e),t,{ease:Array.isArray(i)?i:as(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var ss=e=>e!==null;function cs(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(ss),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var ls={decay:$o,inertia:$o,tween:os,keyframes:os,spring:Xo};function us(e){typeof e.type==`string`&&(e.type=ls[e.type])}var ds=class{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,t){return this.finished.then(e,t)}},fs=e=>e/100,ps=class extends ds{constructor(e){super(),this.state=`idle`,this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{let{motionValue:e}=this.options;e&&e.updatedAt!==Ea.now()&&this.tick(Ea.now()),this.isStopped=!0,this.state!==`idle`&&(this.teardown(),this.options.onStop?.())},Da.mainThread++,this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){let{options:e}=this;us(e);let{type:t=os,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||os;process.env.NODE_ENV!==`production`&&s!==os&&Mi(o.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${o}`,`spring-two-frames`),s!==os&&typeof o[0]!=`number`&&(this.mixKeyframes=Bi(fs,Fo(o[0],o[1])),o=[0,100]);let c=s({...e,keyframes:o});i===`mirror`&&(this.mirroredGenerator=s({...e,keyframes:[...o].reverse(),velocity:-a})),c.calculatedDuration===null&&(c.calculatedDuration=zo(c));let{calculatedDuration:l}=c;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(n+1)-r,this.generator=c}updateTime(e){let t=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime===null?this.currentTime=t:this.currentTime=this.holdTime}tick(e,t=!1){let{generator:n,totalDuration:r,mixKeyframes:i,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:s}=this;if(this.startTime===null)return n.next(0);let{delay:c=0,keyframes:l,repeat:u,repeatType:d,repeatDelay:f,type:p,onUpdate:m,finalKeyframe:h}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),t?this.currentTime=e:this.updateTime(e);let g=this.currentTime-c*(this.playbackSpeed>=0?1:-1),_=this.playbackSpeed>=0?g<0:g>r;this.currentTime=Math.max(g,0),this.state===`finished`&&this.holdTime===null&&(this.currentTime=r);let v=this.currentTime,y=n;if(u){let e=Math.min(this.currentTime,r)/o,t=Math.floor(e),n=e%1;!n&&e>=1&&(n=1),n===1&&t--,t=Math.min(t,u+1),t%2&&(d===`reverse`?(n=1-n,f&&(n-=f/o)):d===`mirror`&&(y=a)),v=ki(0,1,n)*o}let b;_?(this.delayState.value=l[0],b=this.delayState):b=y.next(v),i&&!_&&(b.value=i(b.value));let{done:x}=b;!_&&s!==null&&(x=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);let S=this.holdTime===null&&(this.state===`finished`||this.state===`running`&&x);return S&&p!==$o&&(b.value=cs(l,this.options,h,this.speed)),m&&m(b.value),S&&this.finish(),b}then(e,t){return this.finished.then(e,t)}get duration(){return Wi(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Wi(e)}get time(){return Wi(this.currentTime)}set time(e){e=Ui(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state=`paused`,this.holdTime=e,this.tick(e))}getGeneratorVelocity(){let e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);let t=this.generator.next(e).value;return Qo(e=>this.generator.next(e).value,e,t)}get speed(){return this.playbackSpeed}set speed(e){let t=this.playbackSpeed!==e;t&&this.driver&&this.updateTime(Ea.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=Wi(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=Io,startTime:t}=this.options;this.driver||=e(e=>this.tick(e)),this.options.onPlay?.();let n=this.driver.now();this.state===`finished`?(this.updateFinished(),this.startTime=n):this.holdTime===null?this.startTime||=t??n:this.startTime=n-this.holdTime,this.state===`finished`&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state=`running`,this.driver.start()}pause(){this.state=`paused`,this.updateTime(Ea.now()),this.holdTime=this.currentTime}complete(){this.state!==`running`&&this.play(),this.state=`finished`,this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state=`finished`,this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state=`idle`,this.stopDriver(),this.startTime=this.holdTime=null,Da.mainThread--}stopDriver(){this.driver&&=(this.driver.stop(),void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type=`keyframes`,this.options.ease=`linear`,this.initAnimation()),this.driver?.stop(),e.observe(this)}};function ms(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var hs=e=>e*180/Math.PI,gs=e=>vs(hs(Math.atan2(e[1],e[0]))),_s={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:gs,rotateZ:gs,skewX:e=>hs(Math.atan(e[1])),skewY:e=>hs(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},vs=e=>(e%=360,e<0&&(e+=360),e),ys=gs,bs=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),xs=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),Ss={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:bs,scaleY:xs,scale:e=>(bs(e)+xs(e))/2,rotateX:e=>vs(hs(Math.atan2(e[6],e[5]))),rotateY:e=>vs(hs(Math.atan2(-e[2],e[0]))),rotateZ:ys,rotate:ys,skewX:e=>hs(Math.atan(e[4])),skewY:e=>hs(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function Cs(e){return e.includes(`scale`)?1:0}function ws(e,t){if(!e||e===`none`)return Cs(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=Ss,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=_s,i=t}if(!i)return Cs(t);let a=r[t],o=i[1].split(`,`).map(Es);return typeof a==`function`?a(o):o[a]}var Ts=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return ws(n,t)};function Es(e){return parseFloat(e.trim())}var Ds=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],Os=new Set(Ds),ks=e=>e===Pa||e===Y,As=new Set([`x`,`y`,`z`]),js=Ds.filter(e=>!As.has(e));function Ms(e){let t=[];return js.forEach(n=>{let r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith(`scale`)?1:0))}),t}var Ns={width:({x:e},{paddingLeft:t=`0`,paddingRight:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},height:({y:e},{paddingTop:t=`0`,paddingBottom:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>ws(t,`x`),y:(e,{transform:t})=>ws(t,`y`)};Ns.translateX=Ns.x,Ns.translateY=Ns.y;var Ps=new Set,Fs=!1,Is=!1,Ls=!1;function Rs(){if(Is){let e=Array.from(Ps).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),n=new Map;t.forEach(e=>{let t=Ms(e);t.length&&(n.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();let t=n.get(e);t&&t.forEach(([t,n])=>{e.getValue(t)?.set(n)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{e.suspendedScrollY!==void 0&&window.scrollTo(0,e.suspendedScrollY)})}Is=!1,Fs=!1,Ps.forEach(e=>e.complete(Ls)),Ps.clear()}function zs(){Ps.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Is=!0)})}function Bs(){Ls=!0,zs(),Rs(),Ls=!1}var Vs=class{constructor(e,t,n,r,i,a=!1){this.state=`pending`,this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=n,this.motionValue=r,this.element=i,this.isAsync=a}scheduleResolve(){this.state=`scheduled`,this.isAsync?(Ps.add(this),Fs||(Fs=!0,J.read(zs),J.resolveKeyframes(Rs))):(this.readKeyframes(),this.complete())}readKeyframes(){let{unresolvedKeyframes:e,name:t,element:n,motionValue:r}=this;if(e[0]===null){let i=r?.get(),a=e[e.length-1];if(i!==void 0)e[0]=i;else if(n&&t){let r=n.readValue(t,a);r!=null&&(e[0]=r)}e[0]===void 0&&(e[0]=a),r&&i===void 0&&r.set(e[0])}ms(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Ps.delete(this)}cancel(){this.state===`scheduled`&&(Ps.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},Hs=e=>e.startsWith(`--`);function Us(e,t,n){Hs(t)?e.style.setProperty(t,n):e.style[t]=n}var Ws={};function Gs(e,t){let n=Li(e);return()=>Ws[t]??n()}var Ks=Gs(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),qs=Gs(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),Js=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,Ys={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:Js([0,.65,.55,1]),circOut:Js([.55,0,1,.45]),backIn:Js([.31,.01,.66,-.59]),backOut:Js([.33,1.53,.69,.99])};function Xs(e,t){if(e)return typeof e==`function`?qs()?Lo(e,t):`ease-out`:fa(e)?Js(e):Array.isArray(e)?e.map(e=>Xs(e,t)||Ys.easeOut):Ys[e]}function Zs(e,t,n,{delay:r=0,duration:i=300,repeat:a=0,repeatType:o=`loop`,ease:s=`easeOut`,times:c}={},l=void 0){let u={[t]:n};c&&(u.offset=c);let d=Xs(s,i);Array.isArray(d)&&(u.easing=d),_a.value&&Da.waapi++;let f={delay:r,duration:i,easing:Array.isArray(d)?`linear`:d,fill:`both`,iterations:a+1,direction:o===`reverse`?`alternate`:`normal`};l&&(f.pseudoElement=l);let p=e.animate(u,f);return _a.value&&p.finished.finally(()=>{Da.waapi--}),p}function Qs(e){return typeof e==`function`&&`applyToOptions`in e}function $s({type:e,...t}){return Qs(e)&&qs()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var ec=class extends ds{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;let{element:t,name:n,keyframes:r,pseudoElement:i,allowFlatten:a=!1,finalKeyframe:o,onComplete:s}=e;this.isPseudoElement=!!i,this.allowFlatten=a,this.options=e,Mi(typeof e.type!=`string`,`Mini animate() doesn't support "type" as a string.`,`mini-spring`);let c=$s(e);this.animation=Zs(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=cs(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),Us(t,n,e),this.animation.cancel()}s?.(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state===`finished`&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;let{state:e}=this;e===`idle`||e===`finished`||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){let e=this.options?.element;!this.isPseudoElement&&e?.isConnected&&this.animation.commitStyles?.()}get duration(){let e=this.animation.effect?.getComputedTiming?.().duration||0;return Wi(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Wi(e)}get time(){return Wi(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Ui(e),t&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime===null?this.animation.playState:`finished`}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:t,rangeEnd:n,observe:r}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:`linear`}),this.animation.onfinish=null,e&&Ks()?(this.animation.timeline=e,t&&(this.animation.rangeStart=t),n&&(this.animation.rangeEnd=n),Ri):r(this)}},tc={anticipate:ia,backInOut:ra,circInOut:sa};function nc(e){return e in tc}function rc(e){typeof e.ease==`string`&&nc(e.ease)&&(e.ease=tc[e.ease])}var ic=10,ac=class extends ec{constructor(e){rc(e),us(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){let{motionValue:t,onUpdate:n,onComplete:r,element:i,...a}=this.options;if(!t)return;if(e!==void 0){t.set(e);return}let o=new ps({...a,autoplay:!1}),s=Math.max(ic,Ea.now()-this.startTime),c=ki(0,ic,s-ic),l=o.sample(s).value,{name:u}=this.options;i&&u&&Us(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},oc=(e,t)=>t===`zIndex`?!1:!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(vo.test(e)||e===`0`)&&!e.startsWith(`url(`));function sc(e){let t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function cc(e,t,n,r){let i=e[0];if(i===null)return!1;if(t===`display`||t===`visibility`)return!0;let a=e[e.length-1],o=oc(i,t),s=oc(a,t);return ji(o===s,`You are trying to animate ${t} from "${i}" to "${a}". "${o?a:i}" is not an animatable value.`,`value-not-animatable`),!o||!s?!1:sc(e)||(n===`spring`||Qs(n))&&r}function lc(e){e.duration=0,e.type=`keyframes`}var uc=new Set([`opacity`,`clipPath`,`filter`,`transform`]),dc=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function fc(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&dc.test(e[t]))return!0;return!1}var pc=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),mc=Li(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function hc(e){let{motionValue:t,name:n,repeatDelay:r,repeatType:i,damping:a,type:o,keyframes:s}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;let{onUpdate:c,transformTemplate:l}=t.owner.getProps();return mc()&&n&&(uc.has(n)||pc.has(n)&&fc(s))&&(n!==`transform`||!l)&&!c&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var gc=40,_c=class extends ds{constructor({autoplay:e=!0,delay:t=0,type:n=`keyframes`,repeat:r=0,repeatDelay:i=0,repeatType:a=`loop`,keyframes:o,name:s,motionValue:c,element:l,...u}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Ea.now();let d={autoplay:e,delay:t,type:n,repeat:r,repeatDelay:i,repeatType:a,name:s,motionValue:c,element:l,...u};this.keyframeResolver=new(l?.KeyframeResolver||Vs)(o,(e,t,n)=>this.onKeyframesResolved(e,t,d,!n),s,c,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,t,n,r){this.keyframeResolver=void 0;let{name:i,type:a,velocity:o,delay:s,isHandoff:c,onUpdate:l}=n;this.resolvedAt=Ea.now();let u=!0;cc(e,i,a,o)||(u=!1,(Ni.instantAnimations||!s)&&l?.(cs(e,n,t)),e[0]=e[e.length-1],lc(n),n.repeat=0);let d={startTime:r?this.resolvedAt&&this.resolvedAt-this.createdAt>gc?this.resolvedAt:this.createdAt:void 0,finalKeyframe:t,...n,keyframes:e},f=u&&!c&&hc(d),p=d.motionValue?.owner?.current,m;if(f)try{m=new ac({...d,element:p})}catch{m=new ps(d)}else m=new ps(d);m.finished.then(()=>{this.notifyFinished()}).catch(Ri),this.pendingTimeline&&=(this.stopTimeline=m.attachTimeline(this.pendingTimeline),void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,t){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Bs()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}};function vc(e,t,n,r=0,i=1){let a=Array.from(e).sort((e,t)=>e.sortNodePosition(t)).indexOf(t),o=e.size,s=(o-1)*r;return typeof n==`function`?n(a,o):i===1?a*r:s-a*r}var yc=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function bc(e){let t=yc.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}var xc=4;function Sc(e,t,n=1){Mi(n<=xc,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,`max-css-var-depth`);let[r,i]=bc(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return Pi(e)?parseFloat(e):e}return ja(i)?Sc(i,t,n+1):i}var Cc={type:`spring`,stiffness:500,damping:25,restSpeed:10},wc=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Tc={type:`keyframes`,duration:.8},Ec={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},Dc=(e,{keyframes:t})=>t.length>2?Tc:Os.has(e)?e.startsWith(`scale`)?wc(t[1]):Cc:Ec;function Oc(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function kc(e,t){let n=e?.[t]??e?.default??e;return n===e?n:Oc(n,e)}var Ac=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function jc(e){for(let t in e)if(!Ac.has(t))return!0;return!1}var Mc=(e,t,n,r={},i,a)=>o=>{let s=kc(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=Ui(c);let u={keyframes:Array.isArray(n)?n:[null,n],ease:`easeOut`,velocity:t.getVelocity(),...s,delay:-l,onUpdate:e=>{t.set(e),s.onUpdate&&s.onUpdate(e)},onComplete:()=>{o(),s.onComplete&&s.onComplete()},name:e,motionValue:t,element:a?void 0:i};jc(s)||Object.assign(u,Dc(e,u)),u.duration&&=Ui(u.duration),u.repeatDelay&&=Ui(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(lc(u),u.delay===0&&(d=!0)),(Ni.instantAnimations||Ni.skipAnimations||i?.shouldSkipAnimations)&&(d=!0,lc(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=cs(u.keyframes,s);if(e!==void 0){J.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new ps(u):new _c(u)};function Nc(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function Pc(e,t,n,r){if(typeof t==`function`){let[i,a]=Nc(r);t=t(n===void 0?e.custom:n,i,a)}if(typeof t==`string`&&(t=e.variants&&e.variants[t]),typeof t==`function`){let[i,a]=Nc(r);t=t(n===void 0?e.custom:n,i,a)}return t}function Fc(e,t,n){let r=e.getProps();return Pc(r,t,n===void 0?r.custom:n,e)}var Ic=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...Ds]),Lc=30,Rc=e=>!isNaN(parseFloat(e)),zc={current:void 0},Bc=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=Ea.now();if(this.updatedAt!==t&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(let e of this.dependents)e.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=Ea.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Rc(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!==`production`&&qi(!1,`value.onChange(callback) is deprecated. Switch to value.on("change", callback).`),this.on(`change`,e)}on(e,t){this.events[e]||(this.events[e]=new Hi);let n=this.events[e].add(t);return e===`change`?()=>{n(),J.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(let e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,t,n){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||=new Set,this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return zc.current&&zc.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=Ea.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Lc)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,Lc);return Gi(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=e(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}};function Vc(e,t){return new Bc(e,t)}var Hc=e=>Array.isArray(e);function Uc(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Vc(n))}function Wc(e){return Hc(e)?e[e.length-1]||0:e}function Gc(e,t){let{transitionEnd:n={},transition:r={},...i}=Fc(e,t)||{};i={...i,...n};for(let t in i)Uc(e,t,Wc(i[t]))}var Kc=e=>!!(e&&e.getVelocity);function qc(e){return!!(Kc(e)&&e.add)}function Jc(e,t){let n=e.getValue(`willChange`);if(qc(n))return n.add(t);if(!n&&Ni.WillChange){let n=new Ni.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function Yc(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var Xc=`data-`+Yc(`framerAppearId`);function Zc(e){return e.props[Xc]}function Qc({protectedKeys:e,needsAnimating:t},n){let r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function $c(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:a,transitionEnd:o,...s}=t,c=e.getDefaultTransition();a=a?Oc(a,c):c;let l=a?.reduceMotion;r&&(a=r);let u=[],d=i&&e.animationState&&e.animationState.getState()[i];for(let t in s){let r=e.getValue(t,e.latestValues[t]??null),i=s[t];if(i===void 0||d&&Qc(d,t))continue;let o={delay:n,...kc(a||{},t)},c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){J.update(()=>r.set(i));continue}let f=!1;if(window.MotionHandoffAnimation){let n=Zc(e);if(n){let e=window.MotionHandoffAnimation(n,t,J);e!==null&&(o.startTime=e,f=!0)}}Jc(e,t);let p=l??e.shouldReduceMotion;r.start(Mc(t,r,i,p&&Ic.has(t)?{type:!1}:o,e,f));let m=r.animation;m&&u.push(m)}if(o){let t=()=>J.update(()=>{o&&Gc(e,o)});u.length?Promise.all(u).then(t):t()}return u}function el(e,t,n={}){let r=Fc(e,t,n.type===`exit`?e.presenceContext?.custom:void 0),{transition:i=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(i=n.transitionOverride);let a=r?()=>Promise.all($c(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{let{delayChildren:a=0,staggerChildren:o,staggerDirection:s}=i;return tl(e,t,r,a,o,s,n)}:()=>Promise.resolve(),{when:s}=i;if(s){let[e,t]=s===`beforeChildren`?[a,o]:[o,a];return e().then(()=>t())}else return Promise.all([a(),o(n.delay)])}function tl(e,t,n=0,r=0,i=0,a=1,o){let s=[];for(let c of e.variantChildren)c.notify(`AnimationStart`,t),s.push(el(c,t,{...o,delay:n+(typeof r==`function`?0:r)+vc(e.variantChildren,c,r,i,a)}).then(()=>c.notify(`AnimationComplete`,t)));return Promise.all(s)}function nl(e,t,n={}){e.notify(`AnimationStart`,t);let r;if(Array.isArray(t)){let i=t.map(t=>el(e,t,n));r=Promise.all(i)}else if(typeof t==`string`)r=el(e,t,n);else{let i=typeof t==`function`?Fc(e,t,n.custom):t;r=Promise.all($c(e,i,n))}return r.then(()=>{e.notify(`AnimationComplete`,t)})}var rl={test:e=>e===`auto`,parse:e=>e},il=e=>t=>t.test(e),al=[Pa,Y,Xa,Ya,Qa,Za,rl],ol=e=>al.find(il(e));function sl(e){return typeof e==`number`?e===0:e===null?!0:e===`none`||e===`0`||Ii(e)}var cl=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function ll(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(Ra)||[];if(!r)return e;let i=n.replace(r,``),a=cl.has(t)?1:0;return r!==n&&(a*=100),t+`(`+a+i+`)`}var ul=/\b([a-z-]*)\(.*?\)/gu,dl={...vo,getAnimatableNone:e=>{let t=e.match(ul);return t?t.map(ll).join(` `):e}},fl={...vo,getAnimatableNone:e=>{let t=vo.parse(e);return vo.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},pl={...Pa,transform:Math.round},ml={borderWidth:Y,borderTopWidth:Y,borderRightWidth:Y,borderBottomWidth:Y,borderLeftWidth:Y,borderRadius:Y,borderTopLeftRadius:Y,borderTopRightRadius:Y,borderBottomRightRadius:Y,borderBottomLeftRadius:Y,width:Y,maxWidth:Y,height:Y,maxHeight:Y,top:Y,right:Y,bottom:Y,left:Y,inset:Y,insetBlock:Y,insetBlockStart:Y,insetBlockEnd:Y,insetInline:Y,insetInlineStart:Y,insetInlineEnd:Y,padding:Y,paddingTop:Y,paddingRight:Y,paddingBottom:Y,paddingLeft:Y,paddingBlock:Y,paddingBlockStart:Y,paddingBlockEnd:Y,paddingInline:Y,paddingInlineStart:Y,paddingInlineEnd:Y,margin:Y,marginTop:Y,marginRight:Y,marginBottom:Y,marginLeft:Y,marginBlock:Y,marginBlockStart:Y,marginBlockEnd:Y,marginInline:Y,marginInlineStart:Y,marginInlineEnd:Y,fontSize:Y,backgroundPositionX:Y,backgroundPositionY:Y,rotate:Ya,rotateX:Ya,rotateY:Ya,rotateZ:Ya,scale:Ia,scaleX:Ia,scaleY:Ia,scaleZ:Ia,skew:Ya,skewX:Ya,skewY:Ya,distance:Y,translateX:Y,translateY:Y,translateZ:Y,x:Y,y:Y,z:Y,perspective:Y,transformPerspective:Y,opacity:Fa,originX:$a,originY:$a,originZ:Y,zIndex:pl,fillOpacity:Fa,strokeOpacity:Fa,numOctaves:pl},hl={...ml,color:to,backgroundColor:to,outlineColor:to,fill:to,stroke:to,borderColor:to,borderTopColor:to,borderRightColor:to,borderBottomColor:to,borderLeftColor:to,filter:dl,WebkitFilter:dl,mask:fl,WebkitMask:fl},gl=e=>hl[e],_l=new Set([dl,fl]);function vl(e,t){let n=gl(e);return _l.has(n)||(n=vo),n.getAnimatableNone?n.getAnimatableNone(t):void 0}var yl=new Set([`auto`,`none`,`0`]);function bl(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!yl.has(t)&&uo(t).values.length&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]=vl(n,i)}var xl=class extends Vs{constructor(e,t,n,r,i){super(e,t,n,r,i,!0)}readKeyframes(){let{unresolvedKeyframes:e,element:t,name:n}=this;if(!t||!t.current)return;super.readKeyframes();for(let n=0;n<e.length;n++){let r=e[n];if(typeof r==`string`&&(r=r.trim(),ja(r))){let i=Sc(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!Ic.has(n)||e.length!==2)return;let[r,i]=e,a=ol(r),o=ol(i);if(Na(r)!==Na(i)&&Ns[n]){this.needsMeasurement=!0;return}if(a!==o)if(ks(a)&&ks(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else Ns[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||sl(e[t]))&&n.push(t);n.length&&bl(e,n,t)}measureInitialState(){let{element:e,unresolvedKeyframes:t,name:n}=this;if(!e||!e.current)return;n===`height`&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Ns[n](e.measureViewportBox(),window.getComputedStyle(e.current)),t[0]=this.measuredOrigin;let r=t[t.length-1];r!==void 0&&e.getValue(n,r).jump(r,!1)}measureEndState(){let{element:e,name:t,unresolvedKeyframes:n}=this;if(!e||!e.current)return;let r=e.getValue(t);r&&r.jump(this.measuredOrigin,!1);let i=n.length-1,a=n[i];n[i]=Ns[t](e.measureViewportBox(),window.getComputedStyle(e.current)),a!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=a),this.removedTransforms?.length&&this.removedTransforms.forEach(([t,n])=>{e.getValue(t).set(n)}),this.resolveNoneKeyframes()}};function Sl(e,t,n){if(e==null)return[];if(e instanceof EventTarget)return[e];if(typeof e==`string`){let r=document;t&&(r=t.current);let i=n?.[e]??r.querySelectorAll(e);return i?Array.from(i):[]}return Array.from(e).filter(e=>e!=null)}var Cl=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function wl(e){return Fi(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}var{schedule:Tl,cancel:El}=ba(queueMicrotask,!1),Dl={x:!1,y:!1};function Ol(){return Dl.x||Dl.y}function kl(e){return e===`x`||e===`y`?Dl[e]?null:(Dl[e]=!0,()=>{Dl[e]=!1}):Dl.x||Dl.y?null:(Dl.x=Dl.y=!0,()=>{Dl.x=Dl.y=!1})}function Al(e,t){let n=Sl(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function jl(e){return!(e.pointerType===`touch`||Ol())}function Ml(e,t,n={}){let[r,i,a]=Al(e,n);return r.forEach(e=>{let n=!1,r=!1,a,o=()=>{e.removeEventListener(`pointerleave`,u)},s=e=>{a&&=(a(e),void 0),o()},c=e=>{n=!1,window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),r&&(r=!1,s(e))},l=()=>{n=!0,window.addEventListener(`pointerup`,c,i),window.addEventListener(`pointercancel`,c,i)},u=e=>{if(e.pointerType!==`touch`){if(n){r=!0;return}s(e)}};e.addEventListener(`pointerenter`,n=>{if(!jl(n))return;r=!1;let o=t(e,n);typeof o==`function`&&(a=o,e.addEventListener(`pointerleave`,u,i))},i),e.addEventListener(`pointerdown`,l,i)}),a}var Nl=(e,t)=>t?e===t?!0:Nl(e,t.parentElement):!1,Pl=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,Fl=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function Il(e){return Fl.has(e.tagName)||e.isContentEditable===!0}var Ll=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function Rl(e){return Ll.has(e.tagName)||e.isContentEditable===!0}var zl=new WeakSet;function Bl(e){return t=>{t.key===`Enter`&&e(t)}}function Vl(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var Hl=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=Bl(()=>{if(zl.has(n))return;Vl(n,`down`);let e=Bl(()=>{Vl(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>Vl(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function Ul(e){return Pl(e)&&!Ol()}var Wl=new WeakSet;function Gl(e,t,n={}){let[r,i,a]=Al(e,n),o=e=>{let r=e.currentTarget;if(!Ul(e)||Wl.has(e))return;zl.add(r),n.stopPropagation&&Wl.add(e);let a=t(r,e),o=(e,t)=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c),zl.has(r)&&zl.delete(r),Ul(e)&&typeof a==`function`&&a(e,{success:t})},s=e=>{o(e,r===window||r===document||n.useGlobalTarget||Nl(r,e.target))},c=e=>{o(e,!1)};window.addEventListener(`pointerup`,s,i),window.addEventListener(`pointercancel`,c,i)};return r.forEach(e=>{(n.useGlobalTarget?window:e).addEventListener(`pointerdown`,o,i),wl(e)&&(e.addEventListener(`focus`,e=>Hl(e,i)),!Il(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}function Kl(e){return Fi(e)&&`ownerSVGElement`in e}var ql=new WeakMap,Jl,Yl=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:Kl(r)&&`getBBox`in r?r.getBBox()[t]:r[n],Xl=Yl(`inline`,`width`,`offsetWidth`),Zl=Yl(`block`,`height`,`offsetHeight`);function Ql({target:e,borderBoxSize:t}){ql.get(e)?.forEach(n=>{n(e,{get width(){return Xl(e,t)},get height(){return Zl(e,t)}})})}function $l(e){e.forEach(Ql)}function eu(){typeof ResizeObserver>`u`||(Jl=new ResizeObserver($l))}function tu(e,t){Jl||eu();let n=Sl(e);return n.forEach(e=>{let n=ql.get(e);n||(n=new Set,ql.set(e,n)),n.add(t),Jl?.observe(e)}),()=>{n.forEach(e=>{let n=ql.get(e);n?.delete(t),n?.size||Jl?.unobserve(e)})}}var nu=new Set,ru;function iu(){ru=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};nu.forEach(t=>t(e))},window.addEventListener(`resize`,ru)}function au(e){return nu.add(e),ru||iu(),()=>{nu.delete(e),!nu.size&&typeof ru==`function`&&(window.removeEventListener(`resize`,ru),ru=void 0)}}function ou(e,t){return typeof e==`function`?au(e):tu(e,t)}function su(e){return Kl(e)&&e.tagName===`svg`}var cu=[...al,to,vo],lu=e=>cu.find(il(e)),uu=()=>({translate:0,scale:1,origin:0,originPoint:0}),du=()=>({x:uu(),y:uu()}),fu=()=>({min:0,max:0}),pu=()=>({x:fu(),y:fu()}),mu=new WeakMap;function hu(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function gu(e){return typeof e==`string`||Array.isArray(e)}var _u=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],vu=[`initial`,..._u];function yu(e){return hu(e.animate)||vu.some(t=>gu(e[t]))}function bu(e){return!!(yu(e)||e.variants)}function xu(e,t,n){for(let r in t){let i=t[r],a=n[r];if(Kc(i))e.addValue(r,i);else if(Kc(a))e.addValue(r,Vc(i,{owner:e}));else if(a!==i)if(e.hasValue(r)){let t=e.getValue(r);t.liveStyle===!0?t.jump(i):t.hasAnimated||t.set(i)}else{let t=e.getStaticValue(r);e.addValue(r,Vc(t===void 0?i:t,{owner:e}))}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var Su={current:null},Cu={current:!1},wu=typeof window<`u`;function Tu(){if(Cu.current=!0,wu)if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>Su.current=e.matches;e.addEventListener(`change`,t),t()}else Su.current=!1}var Eu=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],Du={};function Ou(e){Du=e}function ku(){return Du}var Au=class{scrapeMotionValuesFromProps(e,t,n){return{}}constructor({parent:e,props:t,presenceContext:n,reducedMotionConfig:r,skipAnimations:i,blockInitialAnimation:a,visualState:o},s={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=Vs,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify(`Update`,this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{let e=Ea.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,J.render(this.render,!1,!0))};let{latestValues:c,renderState:l}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=t.initial?{...c}:{},this.renderState=l,this.parent=e,this.props=t,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.skipAnimationsConfig=i,this.options=s,this.blockInitialAnimation=!!a,this.isControllingVariants=yu(t),this.isVariantNode=bu(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);let{willChange:u,...d}=this.scrapeMotionValuesFromProps(t,{},this);for(let e in d){let t=d[e];c[e]!==void 0&&Kc(t)&&t.set(c[e])}}mount(e){if(this.hasBeenMounted)for(let e in this.initialValues)this.values.get(e)?.jump(this.initialValues[e]),this.latestValues[e]=this.initialValues[e];this.current=e,mu.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((e,t)=>this.bindToMotionValue(t,e)),this.reducedMotionConfig===`never`?this.shouldReduceMotion=!1:this.reducedMotionConfig===`always`?this.shouldReduceMotion=!0:(Cu.current||Tu(),this.shouldReduceMotion=Su.current),process.env.NODE_ENV!==`production`&&qi(this.shouldReduceMotion!==!0,`You have Reduced Motion enabled on your device. Animations may not appear as expected.`,`reduced-motion-disabled`),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),xa(this.notifyUpdate),xa(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(let e in this.events)this.events[e].clear();for(let e in this.features){let t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??=new Set,this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,t){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),t.accelerate&&uc.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new ec({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:Ui(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=Os.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&J.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()}),i;typeof window<`u`&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i&&i(),t.owner&&t.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e=`animation`;for(e in Du){let t=Du[e];if(!t)continue;let{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(this)),this.features[e]){let t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):pu()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let t=0;t<Eu.length;t++){let n=Eu[t];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);let r=e[`on`+n];r&&(this.propEventSubscriptions[n]=this.on(n,r))}this.prevMotionValues=xu(this,this.scrapeMotionValuesFromProps(e,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){let t=this.getClosestVariantNode();if(t)return t.variantChildren&&t.variantChildren.add(e),()=>t.variantChildren.delete(e)}addValue(e,t){let n=this.values.get(e);t!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t),this.latestValues[e]=t.get())}removeValue(e){this.values.delete(e);let t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&t!==void 0&&(n=Vc(t===null?void 0:t,{owner:this}),this.addValue(e,n)),n}readValue(e,t){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n==`string`&&(Pi(n)||Ii(n))?n=parseFloat(n):!lu(n)&&vo.test(t)&&(n=vl(e,t)),this.setBaseTarget(e,Kc(n)?n.get():n)),Kc(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){let{initial:t}=this.props,n;if(typeof t==`string`||typeof t==`object`){let r=Pc(this.props,t,this.presenceContext?.custom);r&&(n=r[e])}if(t&&n!==void 0)return n;let r=this.getBaseTargetFromProps(this.props,e);return r!==void 0&&!Kc(r)?r:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,t){return this.events[e]||(this.events[e]=new Hi),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){Tl.render(this.render)}},ju=class extends Au{constructor(){super(...arguments),this.KeyframeResolver=xl}sortInstanceNodePosition(e,t){return e.compareDocumentPosition(t)&2?1:-1}getBaseTargetFromProps(e,t){let n=e.style;return n?n[t]:void 0}removeValueFromRenderState(e,{vars:t,style:n}){delete t[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);let{children:e}=this.props;Kc(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},Mu=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function Nu({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function Pu({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Fu(e,t){if(!t)return e;let n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function Iu(e){return e===void 0||e===1}function Lu({scale:e,scaleX:t,scaleY:n}){return!Iu(e)||!Iu(t)||!Iu(n)}function Ru(e){return Lu(e)||zu(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function zu(e){return Bu(e.x)||Bu(e.y)}function Bu(e){return e&&e!==`0%`}function Vu(e,t,n){return n+t*(e-n)}function Hu(e,t,n,r,i){return i!==void 0&&(e=Vu(e,i,r)),Vu(e,n,r)+t}function Uu(e,t=0,n=1,r,i){e.min=Hu(e.min,t,n,r,i),e.max=Hu(e.max,t,n,r,i)}function Wu(e,{x:t,y:n}){Uu(e.x,t.translate,t.scale,t.originPoint),Uu(e.y,n.translate,n.scale,n.originPoint)}var Gu=.999999999999,Ku=1.0000000000001;function qu(e,t,n,r=!1){let i=n.length;if(!i)return;t.x=t.y=1;let a,o;for(let s=0;s<i;s++){a=n[s],o=a.projectionDelta;let{visualElement:i}=a.options;i&&i.props.style&&i.props.style.display===`contents`||(r&&a.options.layoutScroll&&a.scroll&&a!==a.root&&(Ju(e.x,-a.scroll.offset.x),Ju(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Wu(e,o)),r&&Ru(a.latestValues)&&Zu(e,a.latestValues,a.layout?.layoutBox))}t.x<Ku&&t.x>Gu&&(t.x=1),t.y<Ku&&t.y>Gu&&(t.y=1)}function Ju(e,t){e.min+=t,e.max+=t}function Yu(e,t,n,r,i=.5){Uu(e,t,n,X(e.min,e.max,i),r)}function Xu(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function Zu(e,t,n){let r=n??e;Yu(e.x,Xu(t.x,r.x),t.scaleX,t.scale,t.originX),Yu(e.y,Xu(t.y,r.y),t.scaleY,t.scale,t.originY)}function Qu(e,t){return Nu(Fu(e.getBoundingClientRect(),t))}function $u(e,t,n){let r=Qu(e,n),{scroll:i}=t;return i&&(Ju(r.x,i.offset.x),Ju(r.y,i.offset.y)),r}var ed={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},td=Ds.length;function nd(e,t,n){let r=``,i=!0;for(let a=0;a<td;a++){let o=Ds[a],s=e[o];if(s===void 0)continue;let c=!0;if(typeof s==`number`)c=s===(o.startsWith(`scale`)?1:0);else{let e=parseFloat(s);c=o.startsWith(`scale`)?e===1:e===0}if(!c||n){let e=Cl(s,ml[o]);if(!c){i=!1;let t=ed[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}return r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function rd(e,t,n){let{style:r,vars:i,transformOrigin:a}=e,o=!1,s=!1;for(let e in t){let n=t[e];if(Os.has(e)){o=!0;continue}else if(ka(e)){i[e]=n;continue}else{let t=Cl(n,ml[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=nd(t,e.transform,n):r.transform&&=`none`),s){let{originX:e=`50%`,originY:t=`50%`,originZ:n=0}=a;r.transformOrigin=`${e} ${t} ${n}`}}function id(e,{style:t,vars:n},r,i){let a=e.style,o;for(o in t)a[o]=t[o];for(o in i?.applyProjectionStyles(a,r),n)a.setProperty(o,n[o])}function ad(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var od={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`)if(Y.test(e))e=parseFloat(e);else return e;return`${ad(e,t.target.x)}% ${ad(e,t.target.y)}%`}},sd={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=vo.parse(e);if(i.length>5)return r;let a=vo.createTransformer(e),o=typeof i[0]==`number`?0:1,s=n.x.scale*t.x,c=n.y.scale*t.y;i[0+o]/=s,i[1+o]/=c;let l=X(s,c,.5);return typeof i[2+o]==`number`&&(i[2+o]/=l),typeof i[3+o]==`number`&&(i[3+o]/=l),a(i)}},cd={borderRadius:{...od,applyTo:[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`]},borderTopLeftRadius:od,borderTopRightRadius:od,borderBottomLeftRadius:od,borderBottomRightRadius:od,boxShadow:sd};function ld(e,{layout:t,layoutId:n}){return Os.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!cd[e]||e===`opacity`)}function ud(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(Kc(r[t])||i&&Kc(i[t])||ld(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function dd(e){return window.getComputedStyle(e)}var fd=class extends ju{constructor(){super(...arguments),this.type=`html`,this.renderInstance=id}readValueFromInstance(e,t){if(Os.has(t))return this.projection?.isProjecting?Cs(t):Ts(e,t);{let n=dd(e),r=(ka(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return Qu(e,t)}build(e,t,n){rd(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return ud(e,t,n)}},pd={offset:`stroke-dashoffset`,array:`stroke-dasharray`},md={offset:`strokeDashoffset`,array:`strokeDasharray`};function hd(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?pd:md;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var gd=[`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function _d(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(rd(e,s,l),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};let{attrs:d,style:f}=e;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??`50% 50%`,delete d.transformOrigin),f.transform&&(f.transformBox=u?.transformBox??`fill-box`,delete d.transformBox);for(let e of gd)d[e]!==void 0&&(f[e]=d[e],delete d[e]);t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&hd(d,i,a,o,!1)}var vd=new Set([`baseFrequency`,`diffuseConstant`,`kernelMatrix`,`kernelUnitLength`,`keySplines`,`keyTimes`,`limitingConeAngle`,`markerHeight`,`markerWidth`,`numOctaves`,`targetX`,`targetY`,`surfaceScale`,`specularConstant`,`specularExponent`,`stdDeviation`,`tableValues`,`viewBox`,`gradientTransform`,`pathLength`,`startOffset`,`textLength`,`lengthAdjust`]),yd=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function bd(e,t,n,r){id(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(vd.has(n)?n:Yc(n),t.attrs[n])}function xd(e,t,n){let r=ud(e,t,n);for(let n in e)if(Kc(e[n])||Kc(t[n])){let t=Ds.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var Sd=class extends ju{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=pu}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(Os.has(t)){let e=gl(t);return e&&e.default||0}return t=vd.has(t)?t:Yc(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return xd(e,t,n)}build(e,t,n){_d(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){bd(e,t,n,r)}mount(e){this.isSVGTag=yd(e.tagName),super.mount(e)}},Cd=vu.length;function wd(e){if(!e)return;if(!e.isControllingVariants){let t=e.parent&&wd(e.parent)||{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}let t={};for(let n=0;n<Cd;n++){let r=vu[n],i=e.props[r];(gu(i)||i===!1)&&(t[r]=i)}return t}function Td(e,t){if(!Array.isArray(t))return!1;let n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}var Ed=[..._u].reverse(),Dd=_u.length;function Od(e){return t=>Promise.all(t.map(({animation:t,options:n})=>nl(e,t,n)))}function kd(e){let t=Od(e),n=Md(),r=!0,i=!1,a=t=>(n,r)=>{let i=Fc(e,r,t===`exit`?e.presenceContext?.custom:void 0);if(i){let{transition:e,transitionEnd:t,...r}=i;n={...n,...r,...t}}return n};function o(n){t=n(e)}function s(o){let{props:s}=e,c=wd(e.parent)||{},l=[],u=new Set,d={},f=1/0;for(let t=0;t<Dd;t++){let p=Ed[t],m=n[p],h=s[p]===void 0?c[p]:s[p],g=gu(h),_=p===o?m.isActive:null;_===!1&&(f=t);let v=h===c[p]&&h!==s[p]&&g;if(v&&(r||i)&&e.manuallyAnimateOnMount&&(v=!1),m.protectedKeys={...d},!m.isActive&&_===null||!h&&!m.prevProp||hu(h)||typeof h==`boolean`)continue;if(p===`exit`&&m.isActive&&_!==!0){m.prevResolvedValues&&(d={...d,...m.prevResolvedValues});continue}let y=Ad(m.prevProp,h),b=y||p===o&&m.isActive&&!v&&g||t>f&&g,x=!1,S=Array.isArray(h)?h:[h],C=S.reduce(a(p),{});_===!1&&(C={});let{prevResolvedValues:w={}}=m,T={...w,...C},E=t=>{b=!0,u.has(t)&&(x=!0,u.delete(t)),m.needsAnimating[t]=!0;let n=e.getValue(t);n&&(n.liveStyle=!1)};for(let e in T){let t=C[e],n=w[e];if(d.hasOwnProperty(e))continue;let r=!1;r=Hc(t)&&Hc(n)?!Td(t,n):t!==n,r?t==null?u.add(e):E(e):t!==void 0&&u.has(e)?E(e):m.protectedKeys[e]=!0}m.prevProp=h,m.prevResolvedValues=C,m.isActive&&(d={...d,...C}),(r||i)&&e.blockInitialAnimation&&(b=!1);let ee=v&&y;b&&(!ee||x)&&l.push(...S.map(t=>{let n={type:p};if(typeof t==`string`&&(r||i)&&!ee&&e.manuallyAnimateOnMount&&e.parent){let{parent:r}=e,i=Fc(r,t);if(r.enteringChildren&&i){let{delayChildren:t}=i.transition||{};n.delay=vc(r.enteringChildren,e,t)}}return{animation:t,options:n}}))}if(u.size){let t={};if(typeof s.initial!=`boolean`){let n=Fc(e,Array.isArray(s.initial)?s.initial[0]:s.initial);n&&n.transition&&(t.transition=n.transition)}u.forEach(n=>{let r=e.getBaseTarget(n),i=e.getValue(n);i&&(i.liveStyle=!0),t[n]=r??null}),l.push({animation:t})}let p=!!l.length;return r&&(s.initial===!1||s.initial===s.animate)&&!e.manuallyAnimateOnMount&&(p=!1),r=!1,i=!1,p?t(l):Promise.resolve()}function c(t,r){if(n[t].isActive===r)return Promise.resolve();e.variantChildren?.forEach(e=>e.animationState?.setActive(t,r)),n[t].isActive=r;let i=s(t);for(let e in n)n[e].protectedKeys={};return i}return{animateChanges:s,setActive:c,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Md(),i=!0}}}function Ad(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!Td(t,e):!1}function jd(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Md(){return{animate:jd(!0),whileInView:jd(),whileHover:jd(),whileTap:jd(),whileDrag:jd(),whileFocus:jd(),exit:jd()}}function Nd(e,t){e.min=t.min,e.max=t.max}function Pd(e,t){Nd(e.x,t.x),Nd(e.y,t.y)}function Fd(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var Id=1e-4,Ld=1-Id,Rd=1+Id,zd=.01,Bd=0-zd,Vd=0+zd;function Hd(e){return e.max-e.min}function Ud(e,t,n){return Math.abs(e-t)<=n}function Wd(e,t,n,r=.5){e.origin=r,e.originPoint=X(t.min,t.max,e.origin),e.scale=Hd(n)/Hd(t),e.translate=X(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Ld&&e.scale<=Rd||isNaN(e.scale))&&(e.scale=1),(e.translate>=Bd&&e.translate<=Vd||isNaN(e.translate))&&(e.translate=0)}function Gd(e,t,n,r){Wd(e.x,t.x,n.x,r?r.originX:void 0),Wd(e.y,t.y,n.y,r?r.originY:void 0)}function Kd(e,t,n,r=0){e.min=(r?X(n.min,n.max,r):n.min)+t.min,e.max=e.min+Hd(t)}function qd(e,t,n,r){Kd(e.x,t.x,n.x,r?.x),Kd(e.y,t.y,n.y,r?.y)}function Jd(e,t,n,r=0){let i=r?X(n.min,n.max,r):n.min;e.min=t.min-i,e.max=e.min+Hd(t)}function Yd(e,t,n,r){Jd(e.x,t.x,n.x,r?.x),Jd(e.y,t.y,n.y,r?.y)}function Xd(e,t,n,r,i){return e-=t,e=Vu(e,1/n,r),i!==void 0&&(e=Vu(e,1/i,r)),e}function Zd(e,t=0,n=1,r=.5,i,a=e,o=e){if(Xa.test(t)&&(t=parseFloat(t),t=X(o.min,o.max,t/100)-o.min),typeof t!=`number`)return;let s=X(a.min,a.max,r);e===a&&(s-=t),e.min=Xd(e.min,t,n,s,i),e.max=Xd(e.max,t,n,s,i)}function Qd(e,t,[n,r,i],a,o){Zd(e,t[n],t[r],t[i],t.scale,a,o)}var $d=[`x`,`scaleX`,`originX`],ef=[`y`,`scaleY`,`originY`];function tf(e,t,n,r){Qd(e.x,t,$d,n?n.x:void 0,r?r.x:void 0),Qd(e.y,t,ef,n?n.y:void 0,r?r.y:void 0)}function nf(e){return e.translate===0&&e.scale===1}function rf(e){return nf(e.x)&&nf(e.y)}function af(e,t){return e.min===t.min&&e.max===t.max}function of(e,t){return af(e.x,t.x)&&af(e.y,t.y)}function sf(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function cf(e,t){return sf(e.x,t.x)&&sf(e.y,t.y)}function lf(e){return Hd(e.x)/Hd(e.y)}function uf(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function df(e){return[e(`x`),e(`y`)]}function ff(e,t,n){let r=``,i=e.x.translate/t.x,a=e.y.translate/t.y,o=n?.z||0;if((i||a||o)&&(r=`translate3d(${i}px, ${a}px, ${o}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){let{transformPerspective:e,rotate:t,rotateX:i,rotateY:a,skewX:o,skewY:s}=n;e&&(r=`perspective(${e}px) ${r}`),t&&(r+=`rotate(${t}deg) `),i&&(r+=`rotateX(${i}deg) `),a&&(r+=`rotateY(${a}deg) `),o&&(r+=`skewX(${o}deg) `),s&&(r+=`skewY(${s}deg) `)}let s=e.x.scale*t.x,c=e.y.scale*t.y;return(s!==1||c!==1)&&(r+=`scale(${s}, ${c})`),r||`none`}var pf=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`],mf=pf.length,hf=e=>typeof e==`string`?parseFloat(e):e,gf=e=>typeof e==`number`||Y.test(e);function _f(e,t,n,r,i,a){i?(e.opacity=X(0,n.opacity??1,yf(r)),e.opacityExit=X(t.opacity??1,0,bf(r))):a&&(e.opacity=X(t.opacity??1,n.opacity??1,r));for(let i=0;i<mf;i++){let a=pf[i],o=vf(t,a),s=vf(n,a);o===void 0&&s===void 0||(o||=0,s||=0,o===0||s===0||gf(o)===gf(s)?(e[a]=Math.max(X(hf(o),hf(s),r),0),(Xa.test(s)||Xa.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=X(t.rotate||0,n.rotate||0,r))}function vf(e,t){return e[t]===void 0?e.borderRadius:e[t]}var yf=xf(0,.5,oa),bf=xf(.5,.95,Ri);function xf(e,t,n){return r=>r<e?0:r>t?1:n(Vi(e,t,r))}function Sf(e,t,n){let r=Kc(e)?e:Vc(e);return r.start(Mc(``,r,t,n)),r.animation}function Cf(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}var wf=(e,t)=>e.depth-t.depth,Tf=class{constructor(){this.children=[],this.isDirty=!1}add(e){Di(this.children,e),this.isDirty=!0}remove(e){Oi(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(wf),this.isDirty=!1,this.children.forEach(e)}};function Ef(e,t){let n=Ea.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(xa(r),e(a-t))};return J.setup(r,!0),()=>xa(r)}function Df(e){return Kc(e)?e.get():e}var Of=class{constructor(){this.members=[]}add(e){Di(this.members,e);for(let t=this.members.length-1;t>=0;t--){let n=this.members[t];if(n===e||n===this.lead||n===this.prevLead)continue;let r=n.instance;(!r||r.isConnected===!1)&&!n.snapshot&&(Oi(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(Oi(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){let e=this.members[this.members.length-1];e&&this.promote(e)}}relegate(e){for(let t=this.members.indexOf(e)-1;t>=0;t--){let e=this.members[t];if(e.isPresent!==!1&&e.instance?.isConnected!==!1)return this.promote(e),!0}return!1}promote(e,t){let n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.updateSnapshot(),e.scheduleRender();let{layoutDependency:r}=n.options,{layoutDependency:i}=e.options;(r===void 0||r!==i)&&(e.resumeFrom=n,t&&(n.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root?.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{e.options.onExitComplete?.(),e.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}},kf={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Af={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},jf=[``,`X`,`Y`,`Z`],Mf=1e3,Nf=0;function Pf(e,t,n,r){let{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function Ff(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=Zc(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,J,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&Ff(r)}function If({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=Nf++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,_a.value&&(Af.nodes=Af.calculatedTargetDeltas=Af.calculatedProjections=0),this.nodes.forEach(zf),this.nodes.forEach(Jf),this.nodes.forEach(Yf),this.nodes.forEach(Bf),_a.addProjectionMetrics&&_a.addProjectionMetrics(Af)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let e=0;e<this.path.length;e++)this.path[e].shouldResetTransform=!0;this.root===this&&(this.nodes=new Tf)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new Hi),this.eventHandlers.get(e).add(t)}notifyListeners(e,...t){let n=this.eventHandlers.get(e);n&&n.notify(...t)}hasListeners(e){return this.eventHandlers.has(e)}mount(t){if(this.instance)return;this.isSVG=Kl(t)&&!su(t),this.instance=t;let{layoutId:n,layout:r,visualElement:i}=this.options;if(i&&!i.current&&i.mount(t),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(r||n)&&(this.isLayoutDirty=!0),e){let n,r=0,i=()=>this.root.updateBlockedByResize=!1;J.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=Ef(i,250),kf.hasAnimatedSinceResize&&(kf.hasAnimatedSinceResize=!1,this.nodes.forEach(qf)))})}n&&this.root.registerSharedNode(n,this),this.options.animate!==!1&&i&&(n||r)&&this.addEventListener(`didUpdate`,({delta:e,hasLayoutChanged:t,hasRelativeLayoutChanged:n,layout:r})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}let a=this.options.transition||i.getDefaultTransition()||np,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!cf(this.targetLayout,r),l=!t&&n;if(this.options.layoutRoot||this.resumeFrom||l||t&&(c||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);let t={...kc(a,`layout`),onPlay:o,onComplete:s};(i.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t),this.setAnimationOrigin(e,l)}else t||qf(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=r})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);let e=this.getStack();e&&e.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),xa(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Xf),this.animationId++)}getTransformTemplate(){let{visualElement:e}=this.options;return e&&e.getProps().transformTemplate}willUpdate(e=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Ff(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let e=0;e<this.path.length;e++){let t=this.path[e];t.shouldResetTransform=!0,(typeof t.latestValues.x==`string`||typeof t.latestValues.y==`string`)&&(t.isLayoutDirty=!0),t.updateScroll(`snapshot`),t.options.layoutRoot&&t.willUpdate(!1)}let{layoutId:t,layout:n}=this.options;if(t===void 0&&!n)return;let r=this.getTransformTemplate();this.prevTransformTemplateValue=r?r(this.latestValues,``):void 0,this.updateSnapshot(),e&&this.notifyListeners(`willUpdate`)}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){let e=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),e&&this.nodes.forEach(Uf),this.nodes.forEach(Hf);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Wf);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Gf),this.nodes.forEach(Kf),this.nodes.forEach(Lf),this.nodes.forEach(Rf)):this.nodes.forEach(Wf),this.clearAllSnapshots();let e=Ea.now();Sa.delta=ki(0,1e3/60,e-Sa.timestamp),Sa.timestamp=e,Sa.isProcessing=!0,Ca.update.process(Sa),Ca.preRender.process(Sa),Ca.render.process(Sa),Sa.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Tl.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Vf),this.sharedNodes.forEach(Zf)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,J.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){J.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Hd(this.snapshot.measuredBox.x)&&!Hd(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let e=0;e<this.path.length;e++)this.path[e].updateScroll();let e=this.layout;this.layout=this.measure(!1),this.layoutVersion++,this.layoutCorrected||=pu(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners(`measure`,this.layout.layoutBox);let{visualElement:t}=this.options;t&&t.notify(`LayoutMeasure`,this.layout.layoutBox,e?e.layoutBox:void 0)}updateScroll(e=`measure`){let t=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===e&&(t=!1),t&&this.instance){let t=r(this.instance);this.scroll={animationId:this.root.animationId,phase:e,isRoot:t,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:t}}}resetTransform(){if(!i)return;let e=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,t=this.projectionDelta&&!rf(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||Ru(this.latestValues)||a)&&(i(this.instance,r),this.shouldResetTransform=!1,this.scheduleRender())}measure(e=!0){let t=this.measurePageBox(),n=this.removeElementScroll(t);return e&&(n=this.removeTransform(n)),op(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return pu();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(cp))){let{scroll:e}=this.root;e&&(Ju(t.x,e.offset.x),Ju(t.y,e.offset.y))}return t}removeElementScroll(e){let t=pu();if(Pd(t,e),this.scroll?.wasRoot)return t;for(let n=0;n<this.path.length;n++){let r=this.path[n],{scroll:i,options:a}=r;r!==this.root&&i&&a.layoutScroll&&(i.wasRoot&&Pd(t,e),Ju(t.x,i.offset.x),Ju(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||pu();Pd(r,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];!t&&n.options.layoutScroll&&n.scroll&&n!==n.root&&(Ju(r.x,-n.scroll.offset.x),Ju(r.y,-n.scroll.offset.y)),Ru(n.latestValues)&&Zu(r,n.latestValues,n.layout?.layoutBox)}return Ru(this.latestValues)&&Zu(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=pu();Pd(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!Ru(n.latestValues))continue;let r;n.instance&&(Lu(n.latestValues)&&n.updateSnapshot(),r=pu(),Pd(r,n.measurePageBox())),tf(t,n.latestValues,n.snapshot?.layoutBox,r)}return Ru(this.latestValues)&&tf(t,this.latestValues),t}setTargetDelta(e){this.targetDelta=e,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(e){this.options={...this.options,...e,crossfade:e.crossfade===void 0?!0:e.crossfade}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Sa.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(e=!1){let t=this.getLead();this.isProjectionDirty||=t.isProjectionDirty,this.isTransformDirty||=t.isTransformDirty,this.isSharedProjectionDirty||=t.isSharedProjectionDirty;let n=!!this.resumingFrom||this!==t;if(!(e||n&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;let{layout:r,layoutId:i}=this.options;if(!this.layout||!(r||i))return;this.resolvedRelativeTargetAt=Sa.timestamp;let a=this.getClosestProjectingParent();a&&this.linkedParentVersion!==a.layoutVersion&&!a.options.layoutRoot&&this.removeRelativeTarget(),!this.targetDelta&&!this.relativeTarget&&(this.options.layoutAnchor!==!1&&a&&a.layout?this.createRelativeTarget(a,this.layout.layoutBox,a.layout.layoutBox):this.removeRelativeTarget()),!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=pu(),this.targetWithTransforms=pu()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),qd(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):Pd(this.target,this.layout.layoutBox),Wu(this.target,this.targetDelta)):Pd(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget&&(this.attemptToResolveRelativeTarget=!1,this.options.layoutAnchor!==!1&&a&&!!a.resumingFrom==!!this.resumingFrom&&!a.options.layoutScroll&&a.target&&this.animationProgress!==1?this.createRelativeTarget(a,this.target,a.target):this.relativeParent=this.relativeTarget=void 0),_a.value&&Af.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||Lu(this.parent.latestValues)||zu(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}createRelativeTarget(e,t,n){this.relativeParent=e,this.linkedParentVersion=e.layoutVersion,this.forceRelativeParentToResolveTarget(),this.relativeTarget=pu(),this.relativeTargetOrigin=pu(),Yd(this.relativeTargetOrigin,t,n,this.options.layoutAnchor||void 0),Pd(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){let e=this.getLead(),t=!!this.resumingFrom||this!==e,n=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(n=!1),t&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(n=!1),this.resolvedRelativeTargetAt===Sa.timestamp&&(n=!1),n)return;let{layout:r,layoutId:i}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(r||i))return;Pd(this.layoutCorrected,this.layout.layoutBox);let a=this.treeScale.x,o=this.treeScale.y;qu(this.layoutCorrected,this.treeScale,this.path,t),e.layout&&!e.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(e.target=e.layout.layoutBox,e.targetWithTransforms=pu());let{target:s}=e;if(!s){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Fd(this.prevProjectionDelta.x,this.projectionDelta.x),Fd(this.prevProjectionDelta.y,this.projectionDelta.y)),Gd(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!uf(this.projectionDelta.x,this.prevProjectionDelta.x)||!uf(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),_a.value&&Af.calculatedProjections++}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){if(this.options.visualElement?.scheduleRender(),e){let e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=du(),this.projectionDelta=du(),this.projectionDeltaWithTransform=du()}setAnimationOrigin(e,t=!1){let n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},a=du();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let o=pu(),s=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),c=this.getStack(),l=!c||c.members.length<=1,u=!!(s&&!l&&this.options.crossfade===!0&&!this.path.some(tp));this.animationProgress=0;let d;this.mixTargetDelta=t=>{let n=t/1e3;Qf(a.x,e.x,n),Qf(a.y,e.y,n),this.setTargetDelta(a),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Yd(o,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),ep(this.relativeTarget,this.relativeTargetOrigin,o,n),d&&of(this.relativeTarget,d)&&(this.isProjectionDirty=!1),d||=pu(),Pd(d,this.relativeTarget)),s&&(this.animationValues=i,_f(i,r,this.latestValues,n,u,l)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=n},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(e){this.notifyListeners(`animationStart`),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&=(xa(this.pendingAnimation),void 0),this.pendingAnimation=J.update(()=>{kf.hasAnimatedSinceResize=!0,Da.layout++,this.motionValue||=Vc(0),this.motionValue.jump(0,!1),this.currentAnimation=Sf(this.motionValue,[0,1e3],{...e,velocity:0,isSync:!0,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onStop:()=>{Da.layout--},onComplete:()=>{Da.layout--,e.onComplete&&e.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);let e=this.getStack();e&&e.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners(`animationComplete`)}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Mf),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){let e=this.getLead(),{targetWithTransforms:t,target:n,layout:r,latestValues:i}=e;if(!(!t||!n||!r)){if(this!==e&&this.layout&&r&&sp(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||pu();let t=Hd(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;let r=Hd(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}Pd(t,n),Zu(t,i),Gd(this.projectionDeltaWithTransform,this.layoutCorrected,t,i)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new Of),this.sharedNodes.get(e).add(t);let n=t.options.initialPromotionConfig;t.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(t):void 0})}isLead(){let e=this.getStack();return e?e.lead===this:!0}getLead(){let{layoutId:e}=this.options;return e&&this.getStack()?.lead||this}getPrevLead(){let{layoutId:e}=this.options;return e?this.getStack()?.prevLead:void 0}getStack(){let{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:n}={}){let r=this.getStack();r&&r.promote(this,n),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){let e=this.getStack();return e?e.relegate(this):!1}resetSkewAndRotation(){let{visualElement:e}=this.options;if(!e)return;let t=!1,{latestValues:n}=e;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(t=!0),!t)return;let r={};n.z&&Pf(`z`,e,r,this.animationValues);for(let t=0;t<jf.length;t++)Pf(`rotate${jf[t]}`,e,r,this.animationValues),Pf(`skew${jf[t]}`,e,r,this.animationValues);e.render();for(let t in r)e.setStaticValue(t,r[t]),this.animationValues&&(this.animationValues[t]=r[t]);e.scheduleRender()}applyProjectionStyles(e,t){if(!this.instance||this.isSVG)return;if(!this.isVisible){e.visibility=`hidden`;return}let n=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,e.visibility=``,e.opacity=``,e.pointerEvents=Df(t?.pointerEvents)||``,e.transform=n?n(this.latestValues,``):`none`;return}let r=this.getLead();if(!this.projectionDelta||!this.layout||!r.target){this.options.layoutId&&(e.opacity=this.latestValues.opacity===void 0?1:this.latestValues.opacity,e.pointerEvents=Df(t?.pointerEvents)||``),this.hasProjected&&!Ru(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=ff(this.projectionDeltaWithTransform,this.treeScale,i);n&&(a=n(i,a)),e.transform=a;let{x:o,y:s}=this.projectionDelta;e.transformOrigin=`${o.origin*100}% ${s.origin*100}% 0`,r.animationValues?e.opacity=r===this?i.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:i.opacityExit:e.opacity=r===this?i.opacity===void 0?``:i.opacity:i.opacityExit===void 0?0:i.opacityExit;for(let t in cd){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=cd[t],c=a===`none`?i[t]:n(i[t],r);if(o){let t=o.length;for(let n=0;n<t;n++)e[o[n]]=c}else s?this.options.visualElement.renderState.vars[t]=c:e[t]=c}this.options.layoutId&&(e.pointerEvents=r===this?Df(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(Hf),this.root.sharedNodes.clear()}}}function Lf(e){e.updateLayout()}function Rf(e){let t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners(`didUpdate`)){let{layoutBox:n,measuredBox:r}=e.layout,{animationType:i}=e.options,a=t.source!==e.layout.source;if(i===`size`)df(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=Hd(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;Nd(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else sp(i,t.layoutBox,n)&&df(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=Hd(n[r]);i.max=i.min+o,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[r].max=e.relativeTarget[r].min+o)});let o=du();Gd(o,n,t.layoutBox);let s=du();a?Gd(s,e.applyTransform(r,!0),t.measuredBox):Gd(s,n,t.layoutBox);let c=!rf(o),l=!1;if(!e.resumeFrom){let r=e.getClosestProjectingParent();if(r&&!r.resumeFrom){let{snapshot:i,layout:a}=r;if(i&&a){let o=e.options.layoutAnchor||void 0,s=pu();Yd(s,t.layoutBox,i.layoutBox,o);let c=pu();Yd(c,n,a.layoutBox,o),cf(s,c)||(l=!0),r.options.layoutRoot&&(e.relativeTarget=c,e.relativeTargetOrigin=s,e.relativeParent=r)}}}e.notifyListeners(`didUpdate`,{layout:n,snapshot:t,delta:s,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:l})}else if(e.isLead()){let{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function zf(e){_a.value&&Af.nodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty),e.isTransformDirty||=e.parent.isTransformDirty)}function Bf(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Vf(e){e.clearSnapshot()}function Hf(e){e.clearMeasurements()}function Uf(e){e.isLayoutDirty=!0,e.updateLayout()}function Wf(e){e.isLayoutDirty=!1}function Gf(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function Kf(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function qf(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Jf(e){e.resolveTargetDelta()}function Yf(e){e.calcProjection()}function Xf(e){e.resetSkewAndRotation()}function Zf(e){e.removeLeadSnapshot()}function Qf(e,t,n){e.translate=X(t.translate,0,n),e.scale=X(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function $f(e,t,n,r){e.min=X(t.min,n.min,r),e.max=X(t.max,n.max,r)}function ep(e,t,n,r){$f(e.x,t.x,n.x,r),$f(e.y,t.y,n.y,r)}function tp(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var np={duration:.45,ease:[.4,0,.1,1]},rp=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),ip=rp(`applewebkit/`)&&!rp(`chrome/`)?Math.round:Ri;function ap(e){e.min=ip(e.min),e.max=ip(e.max)}function op(e){ap(e.x),ap(e.y)}function sp(e,t,n){return e===`position`||e===`preserve-aspect`&&!Ud(lf(t),lf(n),.2)}function cp(e){return e!==e.root&&e.scroll?.wasRoot}var lp=If({attachResizeListener:(e,t)=>Cf(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),up={current:void 0},dp=If({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!up.current){let e=new lp({});e.mount(window),e.setOptions({layoutScroll:!0}),up.current=e}return up.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),fp=(0,d.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function pp(e=!0){let t=(0,d.useContext)(Ei);if(t===null)return[!0,null];let{isPresent:n,onExitComplete:r,register:i}=t,a=(0,d.useId)();(0,d.useEffect)(()=>{if(e)return i(a)},[e]);let o=(0,d.useCallback)(()=>e&&r&&r(a),[a,r,e]);return!n&&r?[!1,o]:[!0]}var mp=(0,d.createContext)({strict:!1}),hp={animation:[`animate`,`variants`,`whileHover`,`whileTap`,`exit`,`whileInView`,`whileFocus`,`whileDrag`],exit:[`exit`],drag:[`drag`,`dragControls`],focus:[`whileFocus`],hover:[`whileHover`,`onHoverStart`,`onHoverEnd`],tap:[`whileTap`,`onTap`,`onTapStart`,`onTapCancel`],pan:[`onPan`,`onPanStart`,`onPanSessionStart`,`onPanEnd`],inView:[`whileInView`,`onViewportEnter`,`onViewportLeave`],layout:[`layout`,`layoutId`]},gp=!1;function _p(){if(gp)return;let e={};for(let t in hp)e[t]={isEnabled:e=>hp[t].some(t=>!!e[t])};Ou(e),gp=!0}function vp(){return _p(),ku()}function yp(e){let t=vp();for(let n in e)t[n]={...t[n],...e[n]};Ou(t)}var bp=new Set(`animate.exit.variants.initial.style.values.variants.transition.transformTemplate.custom.inherit.onBeforeLayoutMeasure.onAnimationStart.onAnimationComplete.onUpdate.onDragStart.onDrag.onDragEnd.onMeasureDragConstraints.onDirectionLock.onDragTransitionEnd._dragX._dragY.onHoverStart.onHoverEnd.onViewportEnter.onViewportLeave.globalTapTarget.propagate.ignoreStrict.viewport`.split(`.`));function xp(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||bp.has(e)}var Sp=s({default:()=>Cp}),Cp,wp=o((()=>{throw Cp={},Error(`Could not resolve "@emotion/is-prop-valid" imported by "framer-motion". Is it installed?`)})),Tp=e=>!xp(e);function Ep(e){typeof e==`function`&&(Tp=t=>t.startsWith(`on`)?!xp(t):e(t))}try{Ep((wp(),u(Sp)).default)}catch{}function Dp(e,t,n){let r={};for(let i in e)i===`values`&&typeof e.values==`object`||Kc(e[i])||(Tp(i)||n===!0&&xp(i)||!t&&!xp(i)||e.draggable&&i.startsWith(`onDrag`))&&(r[i]=e[i]);return r}var Op=(0,d.createContext)({});function kp(e,t){if(yu(e)){let{initial:t,animate:n}=e;return{initial:t===!1||gu(t)?t:void 0,animate:gu(n)?n:void 0}}return e.inherit===!1?{}:t}function Ap(e){let{initial:t,animate:n}=kp(e,(0,d.useContext)(Op));return(0,d.useMemo)(()=>({initial:t,animate:n}),[jp(t),jp(n)])}function jp(e){return Array.isArray(e)?e.join(` `):e}var Mp=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Np(e,t,n){for(let r in t)!Kc(t[r])&&!ld(r,n)&&(e[r]=t[r])}function Pp({transformTemplate:e},t){return(0,d.useMemo)(()=>{let n=Mp();return rd(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Fp(e,t){let n=e.style||{},r={};return Np(r,n,e),Object.assign(r,Pp(e,t)),r}function Ip(e,t){let n={},r=Fp(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout=`none`,r.touchAction=e.drag===!0?`none`:`pan-${e.drag===`x`?`y`:`x`}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=r,n}var Lp=()=>({...Mp(),attrs:{}});function Rp(e,t,n,r){let i=(0,d.useMemo)(()=>{let n=Lp();return _d(n,t,yd(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};Np(t,e.style,e),i.style={...t,...i.style}}return i}var zp=[`animate`,`circle`,`defs`,`desc`,`ellipse`,`g`,`image`,`line`,`filter`,`marker`,`mask`,`metadata`,`path`,`pattern`,`polygon`,`polyline`,`rect`,`stop`,`switch`,`symbol`,`svg`,`text`,`tspan`,`use`,`view`];function Bp(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(zp.indexOf(e)>-1||/[A-Z]/u.test(e))}function Vp(e,t,n,{latestValues:r},i,a=!1,o){let s=(o??Bp(e)?Rp:Ip)(t,r,i,e),c=Dp(t,typeof e==`string`,a),l=e===d.Fragment?{}:{...c,...s,ref:n},{children:u}=t,f=(0,d.useMemo)(()=>Kc(u)?u.get():u,[u]);return(0,d.createElement)(e,{...l,children:f})}function Hp({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:Up(n,r,i,e),renderState:t()}}function Up(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=Df(a[e]);let{initial:o,animate:s}=e,c=yu(e),l=bu(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),s===void 0&&(s=t.animate));let u=n?n.initial===!1:!1;u||=o===!1;let d=u?s:o;if(d&&typeof d!=`boolean`&&!hu(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=Pc(e,t[n]);if(r){let{transitionEnd:e,transition:t,...n}=r;for(let e in n){let t=n[e];if(Array.isArray(t)){let e=u?t.length-1:0;t=t[e]}t!==null&&(i[e]=t)}for(let t in e)i[t]=e[t]}}}return i}var Wp=e=>(t,n)=>{let r=(0,d.useContext)(Op),i=(0,d.useContext)(Ei),a=()=>Hp(e,t,r,i);return n?a():wi(a)},Gp=Wp({scrapeMotionValuesFromProps:ud,createRenderState:Mp}),Kp=Wp({scrapeMotionValuesFromProps:xd,createRenderState:Lp}),qp=Symbol.for(`motionComponentSymbol`);function Jp(e,t,n){let r=(0,d.useRef)(n);(0,d.useInsertionEffect)(()=>{r.current=n});let i=(0,d.useRef)(null);return(0,d.useCallback)(n=>{n&&e.onMount?.(n);let a=r.current;if(typeof a==`function`)if(n){let e=a(n);typeof e==`function`&&(i.current=e)}else i.current?(i.current(),i.current=null):a(n);else a&&(a.current=n);t&&(n?t.mount(n):t.unmount())},[t])}var Yp=(0,d.createContext)({});function Xp(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function Zp(e,t,n,r,i,a){let{visualElement:o}=(0,d.useContext)(Op),s=(0,d.useContext)(mp),c=(0,d.useContext)(Ei),l=(0,d.useContext)(fp),u=l.reducedMotion,f=l.skipAnimations,p=(0,d.useRef)(null),m=(0,d.useRef)(!1);r||=s.renderer,!p.current&&r&&(p.current=r(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:f,isSVG:a}),m.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));let h=p.current,g=(0,d.useContext)(Yp);h&&!h.projection&&i&&(h.type===`html`||h.type===`svg`)&&Qp(p.current,n,i,g);let _=(0,d.useRef)(!1);(0,d.useInsertionEffect)(()=>{h&&_.current&&h.update(n,c)});let v=n[Xc],y=(0,d.useRef)(!!v&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(v)&&window.MotionHasOptimisedAnimation?.(v));return Ti(()=>{m.current=!0,h&&(_.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),y.current&&h.animationState&&h.animationState.animateChanges())}),(0,d.useEffect)(()=>{h&&(!y.current&&h.animationState&&h.animationState.animateChanges(),y.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(v)}),!1),h.enteringChildren=void 0)}),h}function Qp(e,t,n,r){let{layoutId:i,layout:a,drag:o,dragConstraints:s,layoutScroll:c,layoutRoot:l,layoutAnchor:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t[`data-framer-portal-id`]?void 0:$p(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&Xp(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function $p(e){if(e)return e.options.allowProjection===!1?$p(e.parent):e.projection}function em(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&yp(r);let a=n?n===`svg`:Bp(e),o=a?Kp:Gp;function s(n,s){let c,l={...(0,d.useContext)(fp),...n,layoutId:tm(n)},{isStatic:u}=l,p=Ap(n),m=o(n,u);if(!u&&typeof window<`u`){nm(l,r);let t=rm(l);c=t.MeasureLayout,p.visualElement=Zp(e,m,l,i,t.ProjectionNode,a)}return(0,f.jsxs)(Op.Provider,{value:p,children:[c&&p.visualElement?(0,f.jsx)(c,{visualElement:p.visualElement,...l}):null,Vp(e,n,Jp(m,p.visualElement,s),m,u,t,a)]})}s.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let c=(0,d.forwardRef)(s);return c[qp]=e,c}function tm({layoutId:e}){let t=(0,d.useContext)(Ci).id;return t&&e!==void 0?t+`-`+e:e}function nm(e,t){let n=(0,d.useContext)(mp).strict;if(process.env.NODE_ENV!==`production`&&t&&n){let t="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?ji(!1,t,`lazy-strict-mode`):Mi(!1,t,`lazy-strict-mode`)}}function rm(e){let{drag:t,layout:n}=vp();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function im(e,t){if(typeof Proxy>`u`)return em;let n=new Map,r=(n,r)=>em(n,r,e,t);return new Proxy((e,t)=>(process.env.NODE_ENV!==`production`&&qi(!1,`motion() is deprecated. Use motion.create() instead.`),r(e,t)),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,em(a,void 0,e,t)),n.get(a))})}var am=(e,t)=>t.isSVG??Bp(e)?new Sd(t):new fd(t,{allowProjection:e!==d.Fragment}),om=class extends Mu{constructor(e){super(e),e.animationState||=kd(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();hu(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){let{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}},sm=0,cm={animation:{Feature:om},exit:{Feature:class extends Mu{constructor(){super(...arguments),this.id=sm++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;let{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;if(e&&n===!1){if(this.isExitComplete){let{initial:e,custom:t}=this.node.getProps();if(typeof e==`string`){let n=Fc(this.node,e,t);if(n){let{transition:e,transitionEnd:t,...r}=n;for(let e in r)this.node.getValue(e)?.jump(r[e])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive(`exit`,!1);this.isExitComplete=!1;return}let r=this.node.animationState.setActive(`exit`,!e);t&&!e&&r.then(()=>{this.isExitComplete=!0,t(this.id)})}mount(){let{register:e,onExitComplete:t}=this.node.presenceContext||{};t&&t(this.id),e&&(this.unmount=e(this.id))}unmount(){}}}};function lm(e){return{point:{x:e.pageX,y:e.pageY}}}var um=e=>t=>Pl(t)&&e(t,lm(t));function dm(e,t,n,r){return Cf(e,t,um(n),r)}var fm=({current:e})=>e?e.ownerDocument.defaultView:null,pm=(e,t)=>Math.abs(e-t);function mm(e,t){let n=pm(e.x,t.x),r=pm(e.y,t.y);return Math.sqrt(n**2+r**2)}var hm=new Set([`auto`,`scroll`]),gm=class{constructor(e,t,{transformPagePoint:n,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:a=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=e=>{this.handleScroll(e.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=_m(this.lastRawMoveEventInfo,this.transformPagePoint));let e=ym(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=mm(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e,{timestamp:i}=Sa;this.history.push({...r,timestamp:i});let{onStart:a,onMove:o}=this.handlers;t||(a&&a(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),o&&o(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastRawMoveEventInfo=t,this.lastMoveEventInfo=_m(t,this.transformPagePoint),J.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.end();let{onEnd:n,onSessionEnd:r,resumeAnimation:i}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&i&&i(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let a=ym(e.type===`pointercancel`?this.lastMoveEventInfo:_m(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,a),r&&r(e,a)},!Pl(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.distanceThreshold=a,this.contextWindow=r||window;let s=_m(lm(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=Sa;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,ym(s,this.history)),this.removeListeners=Bi(dm(this.contextWindow,`pointermove`,this.handlePointerMove),dm(this.contextWindow,`pointerup`,this.handlePointerUp),dm(this.contextWindow,`pointercancel`,this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let t=e.parentElement;for(;t;){let e=getComputedStyle(t);(hm.has(e.overflowX)||hm.has(e.overflowY))&&this.scrollPositions.set(t,{x:t.scrollLeft,y:t.scrollTop}),t=t.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.addEventListener(`scroll`,this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.removeEventListener(`scroll`,this.onWindowScroll)}}handleScroll(e){let t=this.scrollPositions.get(e);if(!t)return;let n=e===window,r=n?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},i={x:r.x-t.x,y:r.y-t.y};i.x===0&&i.y===0||(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(e,r),J.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),xa(this.updatePoint)}};function _m(e,t){return t?{point:t(e.point)}:e}function vm(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ym({point:e},t){return{point:e,delta:vm(e,xm(t)),offset:vm(e,bm(t)),velocity:Sm(t,.1)}}function bm(e){return e[0]}function xm(e){return e[e.length-1]}function Sm(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=xm(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>Ui(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>Ui(t)*2&&(r=e[1]);let a=Wi(i.timestamp-r.timestamp);if(a===0)return{x:0,y:0};let o={x:(i.x-r.x)/a,y:(i.y-r.y)/a};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function Cm(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?X(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?X(n,e,r.max):Math.min(e,n)),e}function wm(e,t,n){return{min:t===void 0?void 0:e.min+t,max:n===void 0?void 0:e.max+n-(e.max-e.min)}}function Tm(e,{top:t,left:n,bottom:r,right:i}){return{x:wm(e.x,n,i),y:wm(e.y,t,r)}}function Em(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,r]=[r,n]),{min:n,max:r}}function Dm(e,t){return{x:Em(e.x,t.x),y:Em(e.y,t.y)}}function Om(e,t){let n=.5,r=Hd(e),i=Hd(t);return i>r?n=Vi(t.min,t.max-r,e.min):r>i&&(n=Vi(e.min,e.max-i,t.min)),ki(0,1,n)}function km(e,t){let n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}var Am=.35;function jm(e=Am){return e===!1?e=0:e===!0&&(e=Am),{x:Mm(e,`left`,`right`),y:Mm(e,`top`,`bottom`)}}function Mm(e,t,n){return{min:Nm(e,t),max:Nm(e,n)}}function Nm(e,t){return typeof e==`number`?e:e[t]||0}var Pm=new WeakMap,Fm=class{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=pu(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:t=!1,distanceThreshold:n}={}){let{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;let i=e=>{t&&this.snapToCursor(lm(e).point),this.stopAnimation()},a=(e,t)=>{let{drag:n,dragPropagation:r,onDragStart:i}=this.getProps();if(n&&!r&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kl(n),!this.openDragLock))return;this.latestPointerEvent=e,this.latestPanInfo=t,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),df(e=>{let t=this.getAxisMotionValue(e).get()||0;if(Xa.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=Hd(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&J.update(()=>i(e,t),!1,!0),Jc(this.visualElement,`transform`);let{animationState:a}=this.visualElement;a&&a.setActive(`whileDrag`,!0)},o=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t;let{dragPropagation:n,dragDirectionLock:r,onDirectionLock:i,onDrag:a}=this.getProps();if(!n&&!this.openDragLock)return;let{offset:o}=t;if(r&&this.currentDirection===null){this.currentDirection=zm(o),this.currentDirection!==null&&i&&i(this.currentDirection);return}this.updateAxis(`x`,t.point,o),this.updateAxis(`y`,t.point,o),this.visualElement.render(),a&&J.update(()=>a(e,t),!1,!0)},s=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t,this.stop(e,t),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>{let{dragSnapToOrigin:e}=this.getProps();(e||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:l}=this.getProps();this.panSession=new gm(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:fm(this.visualElement),element:this.visualElement.current})}stop(e,t){let n=e||this.latestPointerEvent,r=t||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!r||!n)return;let{velocity:a}=r;this.startAnimation(a);let{onDragEnd:o}=this.getProps();o&&J.postRender(()=>o(n,r))}cancel(){this.isDragging=!1;let{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();let{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive(`whileDrag`,!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,t,n){let{drag:r}=this.getProps();if(!n||!Rm(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=Cm(a,this.constraints[e],this.elastic[e])),i.set(a)}resolveConstraints(){let{dragConstraints:e,dragElastic:t}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;e&&Xp(e)?this.constraints||=this.resolveRefConstraints():e&&n?this.constraints=Tm(n.layoutBox,e):this.constraints=!1,this.elastic=jm(t),r!==this.constraints&&!Xp(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&df(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=km(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Xp(e))return!1;let n=e.current;Mi(n!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.",`drag-constraints-ref`);let{projection:r}=this.visualElement;if(!r||!r.layout)return!1;let i=$u(n,r.root,this.visualElement.getTransformPagePoint()),a=Dm(r.layout.layoutBox,i);if(t){let e=t(Pu(a));this.hasMutatedConstraints=!!e,e&&(a=Nu(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=df(o=>{if(!Rm(o,t,this.currentDirection))return;let c=s&&s[o]||{};(a===!0||a===o)&&(c={min:0,max:0});let l=r?200:1e6,u=r?40:1e7,d={type:`inertia`,velocity:n?e[o]:0,bounceStiffness:l,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...c};return this.startAxisValueAnimation(o,d)});return Promise.all(c).then(o)}startAxisValueAnimation(e,t){let n=this.getAxisMotionValue(e);return Jc(this.visualElement,e),n.start(Mc(e,n,0,t,this.visualElement,!1))}stopAnimation(){df(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){let t=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps();return n[t]||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){df(t=>{let{drag:n}=this.getProps();if(!Rm(t,n,this.currentDirection))return;let{projection:r}=this.visualElement,i=this.getAxisMotionValue(t);if(r&&r.layout){let{min:n,max:a}=r.layout.layoutBox[t],o=i.get()||0;i.set(e[t]-X(n,a,.5)+o)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!Xp(t)||!n||!this.constraints)return;this.stopAnimation();let r={x:0,y:0};df(e=>{let t=this.getAxisMotionValue(e);if(t&&this.constraints!==!1){let n=t.get();r[e]=Om({min:n,max:n},this.constraints[e])}});let{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},``):`none`,n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),df(t=>{if(!Rm(t,e,null))return;let n=this.getAxisMotionValue(t),{min:i,max:a}=this.constraints[t];n.set(X(i,a,r[t]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;Pm.set(this.visualElement,this);let e=this.visualElement.current,t=dm(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&Rl(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();Xp(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=Lm(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),J.read(r);let o=Cf(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(df(t=>{let n=this.getAxisMotionValue(t);n&&(this.originPoint[t]+=e[t].translate,n.set(n.get()+e[t].translate))}),this.visualElement.render())}));return()=>{o(),t(),a(),s&&s(),n&&n()}}getProps(){let e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:n=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:a=Am,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function Im(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function Lm(e,t,n){let r=ou(e,Im(n)),i=ou(t,Im(n));return()=>{r(),i()}}function Rm(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function zm(e,t=10){let n=null;return Math.abs(e.y)>t?n=`y`:Math.abs(e.x)>t&&(n=`x`),n}var Bm=class extends Mu{constructor(e){super(e),this.removeGroupControls=Ri,this.removeListeners=Ri,this.controls=new Fm(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ri}update(){let{dragControls:e}=this.node.getProps(),{dragControls:t}=this.node.prevProps||{};e!==t&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}},Vm=e=>(t,n)=>{e&&J.update(()=>e(t,n),!1,!0)},Hm=class extends Mu{constructor(){super(...arguments),this.removePointerDownListener=Ri}onPointerDown(e){this.session=new gm(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:fm(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:Vm(e),onStart:Vm(t),onMove:Vm(n),onEnd:(e,t)=>{delete this.session,r&&J.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=dm(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},Um=!1,Wm=class extends d.Component{componentDidMount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n,layoutId:r}=this.props,{projection:i}=e;i&&(t.group&&t.group.add(i),n&&n.register&&r&&n.register(i),Um&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),kf.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){let{layoutDependency:t,visualElement:n,drag:r,isPresent:i}=this.props,{projection:a}=n;return a?(a.isPresent=i,e.layoutDependency!==t&&a.setOptions({...a.options,layoutDependency:t}),Um=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||J.postRender(()=>{let e=a.getStack();(!e||!e.members.length)&&this.safeToRemove()})),null):null}componentDidUpdate(){let{visualElement:e,layoutAnchor:t}=this.props,{projection:n}=e;n&&(n.options.layoutAnchor=t,n.root.didUpdate(),Tl.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;Um=!0,r&&(r.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(r),n&&n.deregister&&n.deregister(r))}safeToRemove(){let{safeToRemove:e}=this.props;e&&e()}render(){return null}};function Gm(e){let[t,n]=pp(),r=(0,d.useContext)(Ci);return(0,f.jsx)(Wm,{...e,layoutGroup:r,switchLayoutGroup:(0,d.useContext)(Yp),isPresent:t,safeToRemove:n})}var Km={pan:{Feature:Hm},drag:{Feature:Bm,ProjectionNode:dp,MeasureLayout:Gm}};function qm(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&J.postRender(()=>i(t,lm(t)))}var Jm=class extends Mu{mount(){let{current:e}=this.node;e&&(this.unmount=Ml(e,(e,t)=>(qm(this.node,t,`Start`),e=>qm(this.node,e,`End`))))}unmount(){}},Ym=class extends Mu{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(`:focus-visible`)}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive(`whileFocus`,!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive(`whileFocus`,!1),this.isActive=!1)}mount(){this.unmount=Bi(Cf(this.node.current,`focus`,()=>this.onFocus()),Cf(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function Xm(e,t,n){let{props:r}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&r.whileTap&&e.animationState.setActive(`whileTap`,n===`Start`);let i=r[`onTap`+(n===`End`?``:n)];i&&J.postRender(()=>i(t,lm(t)))}var Zm=class extends Mu{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=Gl(e,(e,t)=>(Xm(this.node,t,`Start`),(e,{success:t})=>Xm(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},Qm=new WeakMap,$m=new WeakMap,eh=e=>{let t=Qm.get(e.target);t&&t(e)},th=e=>{e.forEach(eh)};function nh({root:e,...t}){let n=e||document;$m.has(n)||$m.set(n,{});let r=$m.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(th,{root:e,...t})),r[i]}function rh(e,t,n){let r=nh(t);return Qm.set(e,n),r.observe(e),()=>{Qm.delete(e),r.unobserve(e)}}var ih={some:0,all:1},ah=class extends Mu{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();let{viewport:e={}}=this.node.getProps(),{root:t,margin:n,amount:r=`some`,once:i}=e,a={root:t?t.current:void 0,rootMargin:n,threshold:typeof r==`number`?r:ih[r]};this.stopObserver=rh(this.node.current,a,e=>{let{isIntersecting:t}=e;if(this.isInView===t||(this.isInView=t,i&&!t&&this.hasEnteredView))return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(`whileInView`,t);let{onViewportEnter:n,onViewportLeave:r}=this.node.getProps(),a=t?n:r;a&&a(e)})}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>`u`)return;let{props:e,prevProps:t}=this.node;[`amount`,`margin`,`root`].some(oh(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function oh({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var sh={inView:{Feature:ah},tap:{Feature:Zm},focus:{Feature:Ym},hover:{Feature:Jm}},ch={layout:{ProjectionNode:dp,MeasureLayout:Gm}},lh=im({...cm,...sh,...Km,...ch},am),uh=16e3,dh=512,fh=64,ph=`silero_vad_v6.onnx`,mh=`ort.wasm.min.js`,hh=null;function gh(e){return typeof window<`u`&&window.ort?Promise.resolve(window.ort):(hh||=new Promise((t,n)=>{let r=document.createElement(`script`);r.src=`${e}/${mh}`,r.async=!0,r.onload=()=>window.ort?t(window.ort):n(Error(`speech model runtime did not initialise`)),r.onerror=()=>n(Error(`speech model runtime failed to load`)),document.head.appendChild(r)}).catch(e=>{throw hh=null,e}),hh)}function _h(e,t=uh){let n=e/t,r=0,i=0;return e=>{let t=[];for(;r<e.length-1;){let a=Math.floor(r),o=a<0?i:e[a];t.push(o+(e[a+1]-o)*(r-a)),r+=n}return r-=e.length,i=e[e.length-1],t}}async function vh({ort:e,modelUrl:t,inputRate:n}){let r=await e.InferenceSession.create(t,{executionProviders:[`wasm`]}),i=new e.Tensor(`int64`,BigInt64Array.from([BigInt(uh)]),[]),a=_h(n),o=new e.Tensor(`float32`,new Float32Array(256),[2,1,128]),s=new Float32Array(fh),c=[],l=!1,u=!1,d=0,f=async()=>{if(!l){l=!0;try{for(;!u&&c.length>=dh;){let t=Float32Array.from(c.slice(0,dh));c=c.slice(dh);let n=new Float32Array(fh+dh);n.set(s,0),n.set(t,fh);let a=await r.run({input:new e.Tensor(`float32`,n,[1,n.length]),state:o,sr:i});o=a.stateN,s=t.slice(dh-fh),d=a.output.data[0]}}finally{l=!1}}};return{push(e){u||(c=c.concat(a(e)),f().catch(()=>{}))},get speechProbability(){return d},close(){u=!0,r.release?.().catch?.(()=>{})}}}async function yh({assetBase:e,inputRate:t}){let n=await gh(e);return n.env.wasm.wasmPaths=`${e}/`,n.env.wasm.numThreads=1,vh({ort:n,modelUrl:`${e}/${ph}`,inputRate:t})}var bh=1500,xh=128e3,Sh=(e,t,n)=>Promise.race([e,new Promise((e,r)=>setTimeout(()=>r(Error(`${n} timed out`)),t))]),Ch=e=>e.iceGatheringState===`complete`?Promise.resolve():new Promise(t=>{e.addEventListener(`icegatheringstatechange`,()=>e.iceGatheringState===`complete`&&t())}),wh=e=>new Promise((t,n)=>{let r=()=>{e.connectionState===`connected`?t():(e.connectionState===`failed`||e.connectionState===`closed`)&&n(Error(`loopback ${e.connectionState}`))};e.addEventListener(`connectionstatechange`,r),r()});async function Th(e,t){return await e.setLocalDescription(t),await Sh(Ch(e),bh,`candidate gathering`),e.localDescription}async function Eh(e){if(typeof RTCPeerConnection>`u`)throw Error(`WebRTC unavailable`);let t=e.createMediaStreamDestination(),n=new RTCPeerConnection,r=new RTCPeerConnection,i=new Audio,a=()=>{i.pause(),i.srcObject=null,n.close(),r.close()};try{let e=new Promise(e=>{r.ontrack=t=>e(t.streams[0]||new MediaStream([t.track]))}),o=n.addTrack(t.stream.getAudioTracks()[0],t.stream);await r.setRemoteDescription(await Th(n,await n.createOffer())),await n.setRemoteDescription(await Th(r,await r.createAnswer())),await Sh(Promise.all([wh(n),wh(r)]),bh,`loopback connection`);let s=o.getParameters();return s.encodings?.length&&(s.encodings[0].maxBitrate=xh,await o.setParameters(s).catch(()=>{})),i.srcObject=await Sh(e,bh,`loopback track`),await Sh(i.play(),bh,`loopback playback`),{node:t,close:a}}catch(e){throw a(),e}}var Dh=24e3,Oh=2048,kh=1200,Ah=.05,jh=.005,Mh=.35,Nh=3,Ph=3,Fh=5,Ih=1.6,Lh=.5;function Rh(e){let t=0;for(let n=1;n<e.length;n++)e[n-1]>=0!=e[n]>=0&&(t+=1);return t/(e.length-1)}function zh(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}function Bh(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++){let r=Math.max(-1,Math.min(1,e[n]));t[n]=r<0?r*32768:r*32767}return t}function Vh(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]/32768;return t}var Hh=.13,Uh=[`audio/webm`,`audio/mp4`];function Wh(){return typeof window>`u`||window.MediaRecorder===void 0?null:Uh.find(e=>window.MediaRecorder.isTypeSupported(e))||null}function Gh(e,t,n,r,i){if(!r.length||!n||!e)return;let a=new Blob(r,{type:i}),o=new FormData;o.append(`audio`,a,`aichat-${n}.webm`),o.append(`voiceSessionId`,n),o.append(`siteId`,t||``),fetch(`${e}/api/voice/upload-chat-recording`,{method:`POST`,body:o}).then(e=>{if(!e.ok)throw Error(`HTTP ${e.status}`)}).catch(e=>console.warn(`[FlowEngage] voice recording upload failed:`,e.message))}var Kh=.02;function qh(e,t,n){let r=e.destination,i=0,a=0,o=[],s=()=>{let t=e.currentTime;o.forEach(({source:e,gain:n})=>{try{n.gain.cancelScheduledValues(t),n.gain.setValueAtTime(n.gain.value,t),n.gain.linearRampToValueAtTime(0,t+Kh),e.stop(t+Kh)}catch{}}),o=[],i=0,a=0},c=()=>i>e.currentTime;return{enqueue:s=>{let l=Vh(s),u=e.createBuffer(1,l.length,Dh);u.copyToChannel(l,0);let d=e.createBufferSource();d.buffer=u;let f=e.createGain();d.connect(f),f.connect(r),n&&f.connect(n);let p=c()?i:e.currentTime+Hh;a||=p,d.start(p),i=p+u.duration;let m={source:d,gain:f};o.push(m),d.onended=()=>{o=o.filter(e=>e!==m),!o.length&&!c()&&t?.()}},stop:s,isPlaying:c,playedMs:()=>Math.max(0,(e.currentTime-a)*1e3),useOutput:e=>(r=e,i)}}async function Jh(e,t,n){let r=new URLSearchParams({siteId:t||``});n&&r.set(`chatId`,n);let i=Hr();i&&r.set(`shopifyCustomerId`,String(i)),re(t)===`auto`&&r.set(`navPreference`,`auto`);let a=await fetch(`${e}/api/voice/session?${r.toString()}`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(a.status===429){let e=await a.json().catch(()=>({}));throw Error(e.message||`Too many voice sessions started. Please wait a minute before trying again.`)}if(!a.ok)throw Error(`Could not start a voice session.`);let o=await a.json();if(!o?.success||!o.wsUrl)throw Error(o?.error||`Voice session was refused.`);return o}async function Yh(e){let{apiBaseUrl:t,siteId:n,chatId:r,clientTools:i={},onConnect:a,onDisconnect:o,onMessage:s,onAgentAnswer:c,onModeChange:l,onError:u,onUnhandledClientToolCall:d,onAgentTurnEnd:f,onSessionInfo:p,onSessionEnding:m,onPanel:h,onStartWalkthrough:g}=e,_=await Jh(t,n,r);p?.({emailOnFile:!!_.emailOnFile});let v={type:`Start`};e.greeting!==void 0&&(v.greeting=e.greeting||null);let y=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),b=new(window.AudioContext||window.webkitAudioContext)({sampleRate:Dh});b.state===`suspended`&&await b.resume();let x=b.createMediaStreamDestination(),S=Wh(),C=[],w=null,T=r||n||null;S&&(w=new window.MediaRecorder(x.stream,{mimeType:S}),w.ondataavailable=e=>{e.data&&e.data.size>0&&C.push(e.data)},w.start());let E=new WebSocket(_.wsUrl);E.binaryType=`arraybuffer`;let ee=new Set,D={role:null,text:``,timer:null,debug:null},te=``,ne=()=>{D.timer&&=(clearTimeout(D.timer),null);let e=D.text.trim(),t=D.role,n=D.debug;if(D.text=``,D.role=null,D.debug=null,!(!e||!t)){if(t===`agent`){if(e===te){console.debug(`[FlowEngage] duplicate agent turn suppressed`);return}te=e}s?.({role:t,message:e,debug:n})}},re=(e,t,n)=>{t&&(D.role&&D.role!==e&&ne(),D.role=e,D.text=D.text?`${D.text} ${t}`.replace(/\s+/g,` `):t,n&&(D.debug=n),D.timer&&clearTimeout(D.timer),D.timer=setTimeout(ne,kh))},O=!1,ie=!1,ae=!1,k=!1,oe=!1,se=!0,ce=0,le=0,ue=!1,de=!1,fe=Ah,A=0,pe=0,j=null,me=!1,he=!1,M=()=>{j&&clearTimeout(j);let e=()=>{if(!O){if(N.isPlaying()){j=setTimeout(e,150);return}if(j=null,me){m?.();return}!O&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:`PlaybackDrained`})),he&&(he=!1,f?.())}};j=setTimeout(e,150)},N=qh(b,()=>{k&&(k=!1,l?.({mode:oe?`thinking`:`listening`}))},x);typeof window<`u`&&(window.__fe_agentAudioPlaying=()=>N.isPlaying());let ge=null,_e=1/0;Eh(b).then(e=>{if(O)return e.close();ge=e,_e=N.useOutput(e.node),console.log(`[FlowEngage] agent audio routed through echo cancellation`)}).catch(e=>console.warn(`[FlowEngage] agent audio is not echo-cancelled, using the cautious interruption check:`,e?.message));let ve=b.createMediaStreamSource(y);ve.connect(x);let ye=b.createScriptProcessor(Oh,1,1),P=!1,F=null,be=!1;yh({assetBase:`${t}/vad`,inputRate:Dh}).then(e=>{if(O)return e.close();F=e,console.log(`[FlowEngage] speech model ready`)}).catch(e=>console.warn(`[FlowEngage] speech model unavailable, using the basic speech check:`,e?.message)),ye.onaudioprocess=e=>{if(O||E.readyState!==WebSocket.OPEN)return;let t=e.inputBuffer.getChannelData(0),n=()=>E.send(new Int16Array(t.length).buffer);if(ie){ae||(ae=!0,console.debug(`[FlowEngage] mic held — streaming silence to keep socket alive`)),P=!1,ce=0,le=0,n();return}let r=zh(t),i=Rh(t),a=N.isPlaying()||de,o=a&&!(F&&b.currentTime>=_e),s=o?fe*Ih:fe,c=o?Fh:Nh;F?.push(t),(F?r>=s&&F.speechProbability>=Lh:r>=s&&i>=jh&&i<=Mh)?(le=0,ce+=1):++le>=Ph&&(ce=0),a&&F?.speechProbability>=Lh&&(A=Math.max(A,r)),a&&(pe=Math.max(pe,ce));let u=ce>=Nh;if(F&&u!==be&&(be=u,E.send(JSON.stringify({type:`VisitorSpeech`,active:u}))),a?P=!1:!P&&ce>=Nh?(P=!0,l?.({mode:`user-speaking`})):P&&ce===0&&(P=!1),a&&!ue&&!me&&ce>=c){ue=!0,oe=!1;let e=N.playedMs();N.stop(),se=!1,de=!1,j&&!me&&(clearTimeout(j),j=null),he=!1,E.send(JSON.stringify({type:`VisitorInterrupted`,played_ms:Math.round(e)})),console.log(`[FlowEngage] barge-in — visitor spoke over the agent`)}E.send(Bh(t).buffer)},ve.connect(ye),ye.connect(b.destination);let I=()=>{if(!O){O=!0,F?.close(),ge?.close(),j&&=(clearTimeout(j),null),ne(),N.stop(),typeof window<`u`&&delete window.__fe_agentAudioPlaying;try{ye.disconnect(),ve.disconnect()}catch{}if(y.getTracks().forEach(e=>e.stop()),w&&w.state!==`inactive`){w.onstop=()=>Gh(t,n,T,C,S);try{w.stop()}catch{w.onstop=null}}else C.length&&Gh(t,n,T,C,S);b.close().catch(()=>{}),(E.readyState===WebSocket.OPEN||E.readyState===WebSocket.CONNECTING)&&E.close()}},xe=async e=>{let t=i[e.name];if(!t)return d?.({tool_name:e.name}),{error:`Unknown tool ${e.name}`};let n={};try{n=JSON.parse(e.arguments||`{}`)}catch{}try{return await t(n)}catch(e){return{error:e?.message||`Tool execution failed`}}},Se=async e=>{for(let t of e.functions||[]){if(!t.client_side)continue;let e=await xe(t);if(O||E.readyState!==WebSocket.OPEN)return;E.send(JSON.stringify({type:`FunctionCallResponse`,id:t.id,name:t.name,content:typeof e==`string`?e:JSON.stringify(e??{})}))}},Ce=e=>{switch(e.type){case`Welcome`:Number.isFinite(e.barge_in_rms)&&e.barge_in_rms>0&&(fe=e.barge_in_rms),Number.isFinite(e.barge_in_frames)&&e.barge_in_frames>0&&e.barge_in_frames,T=e.session_id||r||n||null,a?.({conversationId:T});break;case`ConversationText`:{let t=String(e.content||``);if(e.role===`user`){let e=t.trim();if(ee.has(e)){ee.delete(e);break}if(/^\[SYSTEM:/i.test(e)||/^Continue (now )?to the next section/i.test(e)||/^That was the last section/i.test(e)){console.debug(`[FlowEngage] widget instruction hidden from transcript`);break}}re(e.role===`user`?`user`:`agent`,t,e.debug),e.role!==`user`&&e.debug&&c?.({text:t,tools:e.debug.tools||[]});break}case`UserStartedSpeaking`:k&&!ue&&console.log(`[FlowEngage] interrupted by the server, not the widget: loudest speech ${A.toFixed(3)} (needs ${fe}), longest run ${pe} frames, echo cancellation ${ge?`on`:`off`}, speech model ${F?`on`:`off`}`),ne(),N.stop(),de=!1,se=!1,k=!1,oe=!1,j&&!me&&(clearTimeout(j),j=null),he=!1,l?.({mode:`listening`});break;case`AgentStartedSpeaking`:se=!0,k=!0,ue=!1,A=0,pe=0,l?.({mode:`speaking`});break;case`AgentAudioDone`:de=!1,ne(),M(),N.isPlaying()||(k=!1,l?.({mode:oe?`thinking`:`listening`}));break;case`FunctionCallRequest`:Se(e);break;case`AgentPreparing`:de=!0;break;case`AgentTurnComplete`:oe=!1,he=!0,M();break;case`SessionEnding`:console.debug(`[FlowEngage] server is ending the session:`,e.reason||`unspecified`),me=!0;break;case`StartWalkthrough`:g?.();break;case`AgentThinking`:oe=!0,l?.({mode:`thinking`});break;case`PromptUpdated`:break;case`AgentPanel`:console.log(`[FlowEngage] AgentPanel received:`,e.panel,(e.items||[]).length,`items`),h?.({panel:e.panel||null,title:e.title||null,items:e.items||[]});break;case`Error`:console.error(`[FlowEngage:Voice]`,e.code||``,e.description||e),u?.(Error(e.description||`Voice service error`));break;case`Warning`:console.warn(`[FlowEngage:Voice]`,e.code||``,e.description||``);break;default:break}};return E.onopen=()=>E.send(JSON.stringify(v)),E.onmessage=e=>{if(e.data instanceof ArrayBuffer){se&&N.enqueue(new Int16Array(e.data));return}let t;try{t=JSON.parse(e.data)}catch{return}try{Ce(t)}catch(e){console.error(`[FlowEngage] voice event handler failed:`,t?.type,e)}},E.onerror=()=>u?.(Error(`Voice connection failed`)),E.onclose=()=>{I(),o?.()},{endSession:async()=>I(),sendContextualUpdate:e=>{O||E.readyState!==WebSocket.OPEN||!e||E.send(JSON.stringify({type:`UpdatePrompt`,prompt:e}))},reportPage:(e,t)=>{O||E.readyState!==WebSocket.OPEN||!e||E.send(JSON.stringify({type:`PageChanged`,path:e,title:t||null}))},sendUserMessage:(e,{silent:t=!0,suppressQuestion:n=!1}={})=>{O||E.readyState!==WebSocket.OPEN||!e||(t&&ee.add(e.trim()),E.send(JSON.stringify({type:`InjectUserMessage`,content:e,suppress_question:n})))},injectAgentSpeech:(e,t=`interrupt`)=>{O||E.readyState!==WebSocket.OPEN||!e||E.send(JSON.stringify({type:`InjectAgentMessage`,message:e,behavior:t}))},setWalkthroughActive:e=>{O||E.readyState!==WebSocket.OPEN||E.send(JSON.stringify({type:`WalkthroughActive`,active:!!e}))},setMicMuted:e=>{ie=!!e,!O&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:`MicHeld`,held:ie}))},get status(){return O?`disconnected`:`connected`}}}var Xh={startSession:Yh},Q=`fe-vv`;function Zh(){if(typeof document>`u`||document.getElementById(`${Q}-styles`))return;let e=`
28
+ `,document.head.appendChild(e)};function rr(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1.h2.h3.h4.h5.h6.[data-section].section[id].[id].main li.article li.[role='main'] li.[class*='card'].[class*='Card'].[class*='feature'].[class*='Feature'].[class*='tier'].[class*='Tier'].[class*='plan'].[class*='Plan'].[class*='pricing'].[class*='Pricing'].[class*='testimonial'].[class*='Testimonial'].[class*='team'].[class*='Team'].[class*='service'].[class*='Service'].[class*='block'].[role='listitem'].[role='article'].[role='region'].dt.dd`.split(`.`).join(`, `))).filter(e=>{if(Tn(e))return!1;let t=e.textContent.trim();return!(t.length<3||t.length>5e3||e.closest(`nav, footer, header, aside, .nav, .footer, .header`))});for(let e of i)if(En(e).toLowerCase()===n)return e;for(let e of i){let t=En(e).toLowerCase();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=En(e).toLowerCase();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=En(e).toLowerCase();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=En(n).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!Tn(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(Tn(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(Tn(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(Tn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!Tn(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(Tn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function ir(){return document.querySelector(`[itemprop='articleBody'], .article-body, .post-content, .entry-content, .field--name-body, .field--body, .node__content, article .content, .prose, article .prose`)||document.querySelector(`main article, main, [role='main'], article`)||document.body}var ar=new Set(`the.and.for.are.but.not.you.all.can.her.was.one.our.out.day.get.has.him.his.how.its.may.new.now.old.see.two.way.who.did.let.put.say.she.too.use.has.have.this.that.with.from.they.will.your.about.into.than.then.some.very.when.come.here.just.like.also.back.after.over.such.take.only.know.think.each.made.look.more.most.other.well`.split(`.`)),or=`section, article, li, a, [class*='card']`,sr=`h1, h2, h3, h4, h5, h6`,cr={january:`jan`,february:`feb`,march:`mar`,april:`apr`,june:`jun`,july:`jul`,august:`aug`,september:`sep`,sept:`sep`,october:`oct`,november:`nov`,december:`dec`},lr=3,ur=2,dr=.8,fr=.6,pr=.6,mr=.5;function hr(e){return new Set(String(e||``).toLowerCase().replace(/(\d),(?=\d{3})/g,`$1`).replace(/[^\p{L}\p{N}\s]/gu,` `).split(/\s+/).map(e=>cr[e]||e).filter(e=>(/^\d+$/.test(e)?e.length>=2:e.length>=3)&&!ar.has(e)))}function gr(e){if(typeof document>`u`)return null;let t=hr(e);if(t.size<lr)return null;let n=ir(),r=n.textContent.length||1,i=[],a=new Set(n.querySelectorAll(or));for(let e of n.querySelectorAll(sr))e.parentElement&&!e.closest(`li, a, [class*='card']`)&&a.add(e.parentElement);for(let e of a)Tn(e)||e.closest(`nav, header, footer, aside, [role='navigation']`)||!/^(SECTION|ARTICLE)$/.test(e.tagName)&&!e.querySelector(sr)||e.textContent.length>r*mr||i.push({el:e,length:e.textContent.length,terms:hr(e.innerText)});if(!i.length)return null;let o=i.filter(e=>!i.some(t=>t!==e&&e.el.contains(t.el))),s=new Map;for(let e of o)for(let n of e.terms)t.has(n)&&s.set(n,(s.get(n)||0)+1);let c=[];for(let e of i){let n=0,r=0,i=0;for(let a of t){if(!e.terms.has(a))continue;let t=Math.max(1,s.get(a)||0);r+=1,n+=1/t,t<=2&&(i+=1)}r>=lr&&i>=ur&&c.push({...e,score:n})}if(!c.length)return null;c.sort((e,t)=>t.score-e.score);let[l]=c,u=c.find(e=>!l.el.contains(e.el)&&!e.el.contains(l.el));if(u&&u.score>=l.score*fr)return null;let d=c.filter(e=>e.score>=l.score*dr).sort((e,t)=>e.length-t.length)[0],f=[...t].filter(e=>i.some(t=>t.terms.has(e)));return f.filter(e=>d.terms.has(e)).length>=f.length*pr?d.el:null}function _r(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;nr(),Cn();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function vr(){typeof document>`u`||(document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`)),Cn())}function yr(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function br(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href),n=t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href;return(await fetch(n,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok}catch{return!1}}async function xr(e,{siteId:t,apiBaseUrl:n}){if(!e)return{allowed:!1,correctedUrl:null};let r=!1;try{r=!!Hn()}catch{r=!1}let i=async()=>({allowed:r?!1:await br(e),correctedUrl:null});if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),i();let a=String(n).replace(/\/$/,``),o=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let e=await(await fetch(`${a}/api/widget/navigate-allowed?${o.toString()}`)).json().catch(()=>({}));return e.success&&e.allowed?{allowed:!0,correctedUrl:e.correctedUrl||null}:i()}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),i()}}function Sr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Dn,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function Cr(e,{skipPushState:t=!1,isBack:n=!1}={}){if(typeof window>`u`||typeof document>`u`)return!1;try{if(new URL(e,window.location.href).origin!==window.location.origin)return!1}catch{return!1}$n();let r=new AbortController,i=setTimeout(()=>r.abort(),8e3);try{let a=await fetch(e,{credentials:`same-origin`,cache:`no-store`,signal:r.signal});if(clearTimeout(i),!a.ok)return er(),!1;let o=await a.text(),s=new DOMParser().parseFromString(o,`text/html`),c=document.getElementById(`flowengage-root`);if(!c)return er(),!1;try{typeof window.Drupal?.detachBehaviors==`function`&&window.Drupal.detachBehaviors(document.body,window.drupalSettings)}catch{}document.querySelectorAll(`script`).forEach(e=>{e.setAttribute(`data-fe-original`,`true`)}),Array.from(document.body.children).forEach(e=>{if(e===c)return;let t=e.tagName?.toUpperCase();t===`AUDIO`||t===`VIDEO`||e.remove()}),Wn();let l=new Set(Array.from(document.querySelectorAll(`link[rel='stylesheet']`)).map(e=>{try{return new URL(e.getAttribute(`href`)||``,window.location.href).href}catch{return``}}));for(let t of Array.from(s.head.querySelectorAll(`link[rel='stylesheet']`))){let n=t.getAttribute(`href`);if(!n)continue;let r;try{r=new URL(n,e).href}catch{continue}if(l.has(r))continue;let i=document.createElement(`link`);i.rel=`stylesheet`,i.href=r,i.setAttribute(Un,`true`),t.media&&(i.media=t.media),document.head.appendChild(i)}for(let e of Array.from(s.head.querySelectorAll(`style`))){if(!e.textContent.trim())continue;let t=e.textContent.trim().slice(0,120);if(Array.from(document.head.querySelectorAll(`style:not([data-fe-swap-css])`)).some(e=>e.textContent.trim().slice(0,120)===t))continue;let n=document.createElement(`style`);n.textContent=e.textContent,n.setAttribute(Un,`true`),document.head.appendChild(n)}Array.from(s.body.children).forEach(e=>{e.tagName?.toUpperCase()!==`SCRIPT`&&document.body.insertBefore(document.importNode(e,!0),c)});let u=document.querySelectorAll(`script:not([data-fe-replayed])`);for(let e of u){if(e.closest(`#flowengage-root, .flowengage-shell`)||e.hasAttribute(`data-fe-original`)||e.hasAttribute(`data-fe-replayed`))continue;let t=e.getAttribute(`src`),n=e.getAttribute(`type`)||``;if(!(n&&n!==`text/javascript`&&n!==``&&!n.includes(`drupal-ajax`))){if(n.includes(`drupal-ajax`)){e.setAttribute(`data-fe-replayed`,`true`);try{let t=JSON.parse(e.textContent);if(Array.isArray(t))for(let e of t){if((e.command===`insert`||e.command===`insert_new_content`)&&e.selector&&e.data){let t=document.querySelector(e.selector);t&&(e.method===`replaceWith`?t.outerHTML=e.data:e.method===`html`||e.method===`replace`?t.innerHTML=e.data:e.method===`append`?t.insertAdjacentHTML(`beforeend`,e.data):e.method===`prepend`?t.insertAdjacentHTML(`afterbegin`,e.data):t.innerHTML=e.data,q(`trySpaNavigate: BigPipe replacement →`,e.selector))}if(e.command===`settings`&&e.settings)try{window.drupalSettings&&typeof window.drupalSettings==`object`&&Object.assign(window.drupalSettings,e.settings)}catch{}}}catch(e){q(`trySpaNavigate: BigPipe parse error:`,e.message)}continue}if(!t&&e.textContent.trim()){let t=e.textContent;if(/window\.location\s*[.=]|location\s*\.\s*(href|assign|replace|reload)\s*[=(]/i.test(t)){e.setAttribute(`data-fe-replayed`,`true`);continue}let n=document.createElement(`script`);n.textContent=t,n.setAttribute(`data-fe-replayed`,`true`),e.parentNode.replaceChild(n,e)}}}try{for(let e of Array.from(s.querySelectorAll(`script`))){let t=(e.textContent||``).match(/drupalSettings\s*[,=]\s*(\{[\s\S]*?\})\s*[;)]/);if(t){try{let e=JSON.parse(t[1]);window.drupalSettings&&typeof window.drupalSettings==`object`?Object.assign(window.drupalSettings,e):window.drupalSettings=e,q(`trySpaNavigate: updated drupalSettings from new page`)}catch{}break}}}catch{}let d=window.location.assign.bind(window.location),f=window.location.replace.bind(window.location),p=!0;window.location.assign=e=>{if(p){q(`trySpaNavigate: blocked location.assign from replayed script:`,e);return}return d(e)},window.location.replace=e=>{if(p){q(`trySpaNavigate: blocked location.replace from replayed script:`,e);return}return f(e)};function m(e){let t=e.toLowerCase();return!!(/\/jquery[.\-\/]/.test(t)||/\/jquery\.min\.js/.test(t)||/\/jquery-once/.test(t)||/\/jquery\.once/.test(t)||/\/jquery\.ui[\./]/.test(t)||/\/jqueryui/.test(t)||/\/core\/misc\//.test(t)||/\/core\/modules\//.test(t)||/\/misc\/drupal\.js/.test(t)||/\/lodash[.\-\/]/.test(t)||/\/underscore[.\-\/]/.test(t)||/\/backbone[.\-\/]/.test(t)||/\/modernizr[.\-\/]/.test(t)||/\/popper[.\-\/]/.test(t)||/\/bootstrap\.min\.js/.test(t)||/\/bootstrap\.bundle/.test(t))}let h=new Set(Array.from(document.querySelectorAll(`script[src]`)).map(e=>{try{return new URL(e.getAttribute(`src`)||``,window.location.href).href}catch{return``}}));function g(t,n){let r=t.getAttribute(`src`)||``;if(r.includes(`flowengage`))return;let i=document.createElement(`script`);if(r){let n;try{n=new URL(r,e).href}catch{return}if(h.has(n)){if(m(n))return;q(`trySpaNavigate: re-running theme/custom script:`,n)}h.add(n),i.src=n,i.async=t.async,i.defer=t.defer}else if(t.textContent.trim()){let e=t.textContent;if(/window\.location\s*[.=]|location\s*\.\s*(href|assign|replace|reload)\s*[=(]/i.test(e)){q(`trySpaNavigate: skipping inline script with navigation:`,e.slice(0,120));return}if(/^\s*\(?\s*(?:window\.)?drupalSettings\s*[,=]/.test(e))return;i.textContent=e}else return;let a=t.getAttribute(`type`);a&&a!==`text/javascript`&&a!==``&&(i.type=a),n.parentNode.insertBefore(i,n)}for(let e of Array.from(s.head.querySelectorAll(`script`)))g(e,c);for(let e of Array.from(s.body.querySelectorAll(`script`)))g(e,c);try{typeof window.Drupal?.attachBehaviors==`function`&&window.Drupal.attachBehaviors(document.body,window.drupalSettings)}catch{}try{typeof window.jQuery==`function`&&(window.jQuery(document).trigger(`ready`),window.dispatchEvent(new Event(`resize`)))}catch{}try{document.dispatchEvent(new Event(`DOMContentLoaded`,{bubbles:!0,cancelable:!1}))}catch{}try{window.dispatchEvent(new Event(`load`))}catch{}try{let e=document.querySelectorAll(`iframe:not([data-fe-skip-reload])`);for(let t of e){if(t.closest(`#flowengage-root, .flowengage-shell`))continue;let e=t.getAttribute(`src`)||t.src;e&&e!==`about:blank`&&!e.startsWith(`javascript:`)&&(q(`trySpaNavigate: reloading iframe:`,e),t.src=e)}}catch{}try{let e=document.querySelectorAll(`.g-recaptcha, [data-sitekey]`);if(e.length>0){if(typeof window.grecaptcha?.render==`function`){for(let t of e)if(!t.closest(`#flowengage-root`)){t.innerHTML=``;try{window.grecaptcha.render(t,{sitekey:t.getAttribute(`data-sitekey`)||``}),q(`trySpaNavigate: re-rendered reCAPTCHA`)}catch{}}}else if(!document.querySelector(`script[src*='recaptcha']`)){let e=document.createElement(`script`);e.src=`https://www.google.com/recaptcha/api.js?render=explicit`,e.async=!0,document.head.appendChild(e),q(`trySpaNavigate: injected reCAPTCHA script`)}}}catch{}if(setTimeout(()=>{p=!1,window.location.assign=d,window.location.replace=f},2e3),s.title&&(document.title=s.title),!t)try{history.pushState({flowengageSpa:!0},``,e)}catch{}if(Ln(),zn(),n){try{qn()}catch{}try{Xn()}catch{}}else window.scrollTo(0,0);er(),Zn(e);try{sessionStorage.removeItem(Dn)}catch{}try{sessionStorage.removeItem(kn)}catch{}try{In=new URL(e,window.location.origin).pathname}catch{}return q(`trySpaNavigate: succeeded →`,e),!0}catch{return clearTimeout(i),er(),!1}}function wr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(kn,JSON.stringify({voiceWasActive:!0,targetUrl:String(e),ts:Date.now()}))}catch{}}function Tr(){if(!(typeof sessionStorage>`u`))try{sessionStorage.removeItem(kn)}catch{}}function Er(){if(typeof window>`u`||typeof sessionStorage>`u`)return{shouldResumeVoice:!1,targetUrl:null};let e;try{e=JSON.parse(sessionStorage.getItem(kn)||`null`)}catch{return{shouldResumeVoice:!1,targetUrl:null}}if(!e)return{shouldResumeVoice:!1,targetUrl:null};try{sessionStorage.removeItem(kn)}catch{}return e.voiceWasActive?Date.now()-e.ts>An?(q(`initVoiceNavResume: state expired, skipping`),{shouldResumeVoice:!1,targetUrl:null}):(q(`initVoiceNavResume: voice was active during navigation to`,e.targetUrl),{shouldResumeVoice:!0,targetUrl:e.targetUrl||null}):{shouldResumeVoice:!1,targetUrl:null}}function Dr(){if(typeof document>`u`)return!1;let e=/(^|\W)(404|page not found|not found|page (?:doesn'?t|does not) exist|no longer exists|couldn'?t find (?:this|that|the) page|error 404|oops[!,. ].*(?:not found|doesn'?t exist))(\W|$)/i,t=(document.title||``).trim();if(t&&e.test(t))return!0;let n=document.querySelector(`main, [role="main"], #content, .content`)||document.body;if(n){let t=n.querySelectorAll(`h1, h2`);for(let n of t){let t=(n.textContent||``).replace(/\s+/g,` `).trim();if(t&&t.length<80&&e.test(t))return!0}}return!1}var Or=6e3,kr=250,Ar=700;async function jr(){if(typeof window>`u`)return;let e=window.__fe_agentAudioPlaying;if(typeof e!=`function`){await new Promise(e=>setTimeout(e,Ar));return}let t=Date.now()+Or;for(;Date.now()<t;){let t=!1;try{t=e()}catch{t=!1}if(!t)break;await new Promise(e=>setTimeout(e,100))}await new Promise(e=>setTimeout(e,kr))}async function Mr(e,t={}){if(typeof window>`u`)return{navigated:!1};let{sectionText:n,voiceActive:r=!1}=t;try{let t=yr(e),i=new URL(t,window.location.origin);if(i.hash&&i.pathname===window.location.pathname){let e=document.getElementById(i.hash.slice(1));if(e)return e.scrollIntoView({behavior:`smooth`,block:`start`}),{navigated:!0}}if(i.pathname===window.location.pathname&&i.search===window.location.search&&!i.hash)return{navigated:!1,reason:`already-on-page`};let a=i.pathname+i.search+i.hash;if(window.Shopify)return n&&Sr(n),r||xe(),r?jr().then(()=>window.location.assign(i.href)):window.location.assign(i.href),{navigated:!0};let o=window.next?.router;if(o?.push)return new Promise(e=>{let t=()=>{o.events?.off(`routeChangeComplete`,t),e({navigated:!0})};o.events?.on(`routeChangeComplete`,t),o.push(a),setTimeout(t,5e3)});if(window.__NEXT_ROUTER__?.push)return window.__NEXT_ROUTER__.push(a),{navigated:!0};if(Hn()){n&&Sr(n);let e=window.location.href;try{window.history.pushState({},``,i.href),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}}))}catch{}if(await new Promise(e=>setTimeout(e,400)),Dr()){try{window.history.pushState({},``,e),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}}))}catch{}return n&&Sr(n),r||xe(),window.location.assign(i.href),{navigated:!0}}return{navigated:!0}}return n&&Sr(n),r||xe(),window.location.assign(i.href),{navigated:!0}}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&Sr(n);try{window.location.href=yr(e)}catch{window.location.href=e}return{navigated:!0}}}var Nr=!1,Pr=null;function Fr(e){Pr=e,typeof window<`u`&&(window.__fe_triggerVoiceNavHooks=()=>{try{e.onBeforeNavigate()}catch{}}),!Nr&&(Nr=!0,!(typeof document>`u`)&&(document.addEventListener(`click`,e=>{if(!Pr)return;let t=e.target.closest?.(`a[href]`);if(!t||t.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`))return;let n=t.getAttribute(`href`)||``;if(!n||n===`#`||n.startsWith(`javascript:`)||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||t.hasAttribute(`download`)||t.target===`_blank`||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;let r;try{if(r=new URL(n,window.location.href),r.origin!==window.location.origin)return}catch{return}if(!(r.pathname===window.location.pathname&&r.hash)&&!(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)){q(`voice-link-hook: saving state before navigation →`,r.href);try{Pr.onBeforeNavigate()}catch{}}},!0),document.addEventListener(`submit`,e=>{if(Pr&&!e.target?.closest?.(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)){q(`voice-form-hook: saving state before form submit`);try{Pr.onBeforeNavigate()}catch{}}},!0)))}function Ir(){Pr=null,q(`voice-nav-hooks: deactivated`)}var Lr=4e3,Rr=null;function zr(){let e=typeof window<`u`&&window.Shopify?.routes?.root||`/`;return e.endsWith(`/`)?e:`${e}/`}async function Br(e,t={}){let n=new AbortController,r=setTimeout(()=>n.abort(),Lr);try{let r=await fetch(e,{credentials:`same-origin`,signal:n.signal,...t,headers:{Accept:`application/json`,...t.body?{"Content-Type":`application/json`}:{},...t.headers||{}}}),i=await r.json().catch(()=>({}));if(!r.ok){let e=Error(i.description||i.message||`Cart request failed (${r.status})`);throw e.status=r.status,r.status===422&&i.description&&(e.userMessage=i.description),e}return i}finally{clearTimeout(r)}}async function Vr(){if(Rr!==null)return Rr;if(typeof window>`u`)return Rr=!1;if(window.Shopify)return Rr=!0;try{let e=await Br(`${zr()}cart.js`);Rr=e&&typeof e.item_count==`number`}catch{Rr=!1}return Rr}async function Hr(){return Br(`${zr()}cart.js`)}function Ur(){return typeof window>`u`?null:window.__flowengageCustomer?.id||null}function Wr(e){return typeof e!=`number`||Number.isNaN(e)?null:(e/100).toFixed(2)}async function Gr(){try{if(!await Vr())return null;let e=await Hr();return{itemCount:e.item_count,subtotal:Wr(e.items_subtotal_price),currency:e.currency||null,items:(e.items||[]).map(e=>({title:e.product_title||e.title,variantTitle:e.variant_title||null,quantity:e.quantity,linePrice:Wr(e.final_line_price??e.line_price),handle:e.handle||null}))}}catch{return null}}async function Kr(e,t=null){let n=await Br(`${zr()}products/${encodeURIComponent(e)}.js`),r=n.variants||[];if(!r.length){let t=Error(`No variants for ${e}`);throw t.userMessage=`"${n.title||e}" has no purchasable options right now.`,t}let i=null;if(t){let e=t.toLowerCase();if(i=r.find(t=>(t.title||``).toLowerCase()===e)||r.find(t=>{let n=[t.title,...t.options||[]].join(` `).toLowerCase();return e.split(/[\s/,-]+/).filter(Boolean).every(e=>n.includes(e))}),!i){let e=Error(`Variant not found: ${t}`);throw e.userMessage=`I couldn't find a "${t}" option for ${n.title}. Available: ${r.map(e=>e.title).slice(0,6).join(`, `)}.`,e}}else i=r.find(e=>e.available)||r[0];if(!i.available){let e=Error(`Variant unavailable: ${i.title}`);throw e.userMessage=`Sorry — ${n.title}${i.title&&i.title!==`Default Title`?` (${i.title})`:``} is currently sold out.`,e}return{variant:i,product:n}}async function qr(e,t=1){return Br(`${zr()}cart/add.js`,{method:`POST`,body:JSON.stringify({items:[{id:e,quantity:t}]})})}async function Jr(e,t){return Br(`${zr()}cart/change.js`,{method:`POST`,body:JSON.stringify({line:e,quantity:t})})}function Yr(){return`${zr()}cart`}function Xr(){return`${zr()}checkout`}function Zr(e){return`${zr()}products/${encodeURIComponent(e)}`}async function Qr(e,t=6){let n=new URLSearchParams({q:e,"resources[type]":`product`,"resources[limit]":String(t)});try{return((await Br(`${zr()}search/suggest.json?${n.toString()}`))?.resources?.results?.products||[]).map(e=>({title:e.title,handle:e.handle,price:e.price||null,url:e.url||(e.handle?Zr(e.handle):null),image:e.featured_image?.url||e.image||e.images?.[0]||null,type:e.type||e.product_type||null,vendor:e.vendor||null}))}catch{return[]}}function $r(){return typeof window>`u`?!1:/\/cart\/?$/.test(window.location.pathname)}var ei=[`form[action*="/cart"]`,`cart-items`,`cart-drawer-items`,`.cart-items`,`.cart__items`,`#main-cart-items`,`[data-cart-items]`].join(`, `);function ti(e){if(/cart/i.test(e.id))return!0;try{return!!e.querySelector(ei)}catch{return!1}}async function ni(){if(typeof document>`u`)return!1;let e=Array.from(document.querySelectorAll(`[id^="shopify-section-"]`)).filter(ti);if(!e.length)return!1;let t=e.map(e=>e.id.replace(/^shopify-section-/,``));try{let e=await Br(`${window.location.pathname}?sections=${encodeURIComponent(t.join(`,`))}`),n=!1;for(let[t,r]of Object.entries(e||{})){if(!r||typeof r!=`string`)continue;let e=document.getElementById(`shopify-section-${t}`);if(!e)continue;let i=document.createElement(`div`);i.innerHTML=r;let a=i.querySelector(`#shopify-section-${t}`)||i.firstElementChild;a&&(e.innerHTML=a.innerHTML,n=!0)}return n}catch{return!1}}var ri=[`[data-cart-count]`,`.cart-count-bubble`,`.cart-count`,`#CartCount`,`.cart-link__bubble`,`.site-header__cart-count`,`#cart-icon-bubble`];function ii(e){if(typeof document>`u`)return;let t=String(e);for(let e of ri)document.querySelectorAll(e).forEach(e=>{e.hasAttribute(`data-cart-count`)&&e.setAttribute(`data-cart-count`,t),e.querySelectorAll(`span, div, sup`).forEach(e=>{e.children.length===0&&/\d/.test(e.textContent||``)&&(e.textContent=(e.textContent||``).replace(/\d+/,t))}),e.children.length===0&&/^\s*\d+\s*$/.test(e.textContent||``)&&(e.textContent=t)})}function ai(e){if(typeof document>`u`)return;let t={cart:e,source:`flowengage`};[`cart:updated`,`cart:refresh`,`cart:change`,`cart-drawer:refresh`].forEach(e=>{try{document.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0}))}catch{}});try{window.dispatchEvent(new CustomEvent(`cart:refresh`,{detail:t}))}catch{}}async function oi(e){let t=await ni();return!t&&$r()&&(await new Promise(e=>setTimeout(e,600)),t=await ni()),e&&typeof e.item_count==`number`&&ii(e.item_count),ai(e||null),{sectionsSwapped:t}}async function si(e){try{let{sectionsSwapped:t}=await oi(e);if(!t&&$r())return` (The list on this page may need a quick refresh to show it.)`}catch{}return``}function ci(e){let t=Wr(e.items_subtotal_price),n=e.item_count;return t==null?``:` Your cart now has ${n} item${n===1?``:`s`} — subtotal ${t}${e.currency?` ${e.currency}`:``}.`}function li(e,t){let n=t.title&&t.title!==`Default Title`;return`${e.title}${n?` (${t.title})`:``}`}function ui(e,t){return e?.userMessage||t}var di={async add(e){let{variant:t,product:n}=await Kr(e.productHandle,e.variantTitle||null);await qr(t.id,e.quantity||1);let r=await Hr(),i=await si(r);return{message:`✅ Added ${e.quantity||1} × ${li(n,t)} to your cart.${ci(r)}${i}`}},async update(e){let t=(await Hr()).items?.[e.line-1];if(!t)return{message:`⚠️ I couldn't find item #${e.line} in your cart — it may have changed. Ask me "what's in my cart?" to see the current list.`};let n=await Jr(e.line,e.quantity),r=await si(n);return{message:`✅ Updated ${t.product_title||t.title} to quantity ${e.quantity}.${ci(n)}${r}`}},async remove(e){let t=(await Hr()).items?.[e.line-1];if(!t)return{message:`⚠️ I couldn't find item #${e.line} in your cart — it may have changed. Ask me "what's in my cart?" to see the current list.`};let n=await Jr(e.line,0),r=await si(n);return{message:`🗑️ Removed ${t.product_title||t.title} from your cart.${ci(n)}${r}`}},async view_cart(){return{message:`Opening your cart…`,navigateTo:Yr()}},async checkout(){return(await Hr()).item_count?{message:`Taking you to checkout…`,navigateTo:Xr()}:{message:`Your cart is empty — add something first and I'll take you straight to checkout.`}},async view_product(e){return{message:`Opening the product page…`,navigateTo:Zr(e.productHandle)}}},fi={add:`⚠️ I couldn't add that to your cart — please try from the product page.`,update:`⚠️ I couldn't update that cart item — please try again.`,remove:`⚠️ I couldn't remove that cart item — please try again.`,view_cart:`⚠️ I couldn't open the cart page.`,checkout:`⚠️ I couldn't start checkout — you can open the cart and check out from there.`,view_product:`⚠️ I couldn't open that product page.`};async function pi(e){let t={messages:[],navigateTo:null};if(!Array.isArray(e)||e.length===0)return t;if(!await Vr())return t.messages.push(`⚠️ Cart actions only work on the store's own website — please try from the shop page.`),t;for(let n of e){let e=di[n?.type];if(e)try{let r=await e(n);r.message&&t.messages.push(r.message),r.navigateTo&&(t.navigateTo=r.navigateTo)}catch(e){console.warn(`[FlowEngage:Cart] ${n.type} failed:`,e),t.messages.push(ui(e,fi[n.type]))}}return t}var mi=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request[^>]*>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),hi=(e=[])=>e.filter(e=>e.type!==`call_recording`&&!(typeof e.message==`string`&&e.message.includes(`AI chat recording`))).map(e=>({...e,message:mi(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),gi=50,_i=(e,t)=>{let n=t[0]?.timestamp;if(!n)return t;let r=new Set(t.map(e=>e.id)),i=e.filter(e=>!e.isPending&&e.timestamp&&e.timestamp<n&&!r.has(e.id));return i.length?[...i,...t]:t};function vi(e){if(!e||typeof e!=`string`)return null;let t=e.match(/<navigate([^>]*?)(?:\/>|>[\s\S]*?<\/navigate>)/i);if(!t)return null;let n=t[1],r=n.match(/url=["']([^"']+)["']/i);if(!r)return null;let i=n.match(/section=["']([^"']+)["']/i)||n.match(/highlight=["']([^"']+)["']/i);return{url:r[1].trim(),section:i?.[1]?.trim()||null}}var yi=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,bi=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},xi=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},Si=(e=[],t,n=6)=>!t?.message||e.slice(-n).some(e=>e.sender===`system`&&e.message===t.message)?e:[...e,t];function Ci({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,d.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),[a,o]=(0,d.useState)(0),[s,c]=(0,d.useState)(`booting`),[l,u]=(0,d.useState)(null),[m,h]=(0,d.useState)(null),[g,_]=(0,d.useState)(``),[x,S]=(0,d.useState)([]),[E,ee]=(0,d.useState)(!1),D=(0,d.useRef)(!1),te=(0,d.useCallback)(()=>{S(e=>[...e,{id:`nav-fail-${e.length}-${Math.random().toString(36).slice(2,8)}`,sender:`bot`,message:`I couldn't find that page on our site — could you tell me more about what you're looking for?`,timestamp:new Date().toISOString()}])},[]),ne=(0,d.useCallback)(e=>{pi(e).then(({messages:e,navigateTo:t})=>{e.length&&S(t=>[...t,...e.map((e,n)=>({id:`cart-${t.length+n}-${Math.random().toString(36).slice(2,8)}`,sender:`bot`,message:e,timestamp:new Date().toISOString()}))]),t&&setTimeout(()=>{window.location.assign(t)},900)})},[]),O=(0,d.useCallback)(()=>{S(e=>e.slice(-3).some(e=>(e.sender===`bot`||e.sender===`assistant`)&&/already on (that|this|the)\b/i.test(String(e.message||``)))?e:[...e,{id:`nav-already-${e.length}-${Math.random().toString(36).slice(2,8)}`,sender:`bot`,message:`Looks like you're already on this page!`,timestamp:new Date().toISOString()}])},[]),[k,A]=(0,d.useState)(le().isOpen),[pe,j]=(0,d.useState)(le().activeScreen),[he,M]=(0,d.useState)(le().isHumanHandled),[N,ge]=(0,d.useState)(le().agentName),[_e,ve]=(0,d.useState)(le().agentHeadshot),[ye,P]=(0,d.useState)(()=>de(i?.siteId)),[be,I]=(0,d.useState)(!1),[xe,Se]=(0,d.useState)(!1),[Ce,L]=(0,d.useState)(`idle`),[we,Te]=(0,d.useState)(!1),[Ee,De]=(0,d.useState)(!1),[R,je]=(0,d.useState)(``),[Me,Ne]=(0,d.useState)(!1),[Pe,Fe]=(0,d.useState)(0),[Ie,Le]=(0,d.useState)(0),[Re,ze]=(0,d.useState)(!1),[z,Be]=(0,d.useState)(null),[B,Ve]=(0,d.useState)(null),[He,Ue]=(0,d.useState)(`idle`),[We,Ge]=(0,d.useState)(null),[Ke,qe]=(0,d.useState)(!1),[Je,Ye]=(0,d.useState)(``),[Xe,V]=(0,d.useState)(!1),H=(0,d.useRef)(null),U=(0,d.useRef)(null),W=(0,d.useRef)(``),Ze=(0,d.useRef)(!1),Qe=(0,d.useRef)(null),$e=(0,d.useRef)(null),et=(0,d.useRef)(null),tt=(0,d.useRef)(null),nt=(0,d.useRef)(null),rt=(0,d.useRef)(null),it=(0,d.useRef)(null),at=(0,d.useRef)(!1),ot=(0,d.useRef)({url:null,at:0}),st=(0,d.useCallback)((e,t)=>{Nn(6e3);let n=e;try{n=new URL(e,window.location.origin).href}catch{}let r=ot.current;return r.url===n&&Date.now()-r.at<4e3?Promise.resolve({navigated:!0,deduped:!0}):(ot.current={url:n,at:Date.now()},Mr(e,t))},[]),ct=(0,d.useRef)([]),G=(0,d.useRef)(null),lt=(0,d.useRef)(null),ut=(0,d.useRef)(null),dt=(0,d.useRef)(!1),ft=(0,d.useRef)(!1),pt=(0,d.useRef)(``),mt=(0,d.useRef)(null),ht=(0,d.useRef)(null),gt=(0,d.useRef)([]),_t=(0,d.useRef)(0),vt=(0,d.useRef)(N),yt=(0,d.useRef)([]),bt=(0,d.useRef)(!1),xt=(0,d.useRef)(!1),St=(0,d.useRef)(i),Ct=(0,d.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),wt=(0,d.useCallback)((e={})=>{let t=!!e.is_human_handled;return M(t),t?(j(`agent`),e.agent_info?.name&&ge(e.agent_info.name),e.agent_info?.headshot&&ve(e.agent_info.headshot),t):(j(`ai`),t)},[]),Tt=(0,d.useMemo)(()=>{let e=m?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:y},[i,m]);(0,d.useEffect)(()=>{$e.current=z},[z]),(0,d.useEffect)(()=>{vt.current=N},[N]),(0,d.useEffect)(()=>{xt.current=Me},[Me]),(0,d.useEffect)(()=>{St.current=i},[i]);let Et=()=>{Ye(``)},Dt=(0,d.useCallback)(()=>{ut.current&&=(window.clearTimeout(ut.current),null)},[]),Ot=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return P(t),fe(t,i?.siteId),t};(0,d.useEffect)(()=>{let e=i?.siteId;if(!e)return;let t=de(e);if(t){P(t);return}P(t=>(t&&fe(t,e),t))},[i?.siteId]);let kt=(e=`unspecified`)=>{let t=G.current||rt.current?.callId,n=_t.current,r=mt.current;if(mt.current=null,_t.current=0,r&&r.state!==`inactive`){r.onstop=()=>{let e=gt.current;if(gt.current=[],e.length>0&&t&&U.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;U.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}};try{r.stop()}catch{r.onstop=null,gt.current=[]}}else if(r&&r.state===`inactive`){let e=gt.current;if(gt.current=[],e.length>0&&t&&U.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;U.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}}else gt.current=[];if(ht.current){try{ht.current.close()}catch{}ht.current=null}et.current&&=(et.current.close(),null),tt.current&&=(tt.current.getTracks().forEach(e=>e.stop()),null),nt.current&&=(nt.current.srcObject=null,nt.current.remove(),null),Dt(),rt.current=null,ct.current=[],G.current=null,lt.current=null,dt.current=!1,qe(!1),Be(null),Ve(null),Ue(`idle`),Ge(null)},At=(e=new Date().toISOString())=>{let t=H.current,n=G.current||rt.current?.callId;if(!(!t?.connected||!n||dt.current)){dt.current=!0,t.emit(`call:connected`,{callId:n,chatId:W.current,connectedAt:e});try{let e=tt.current,t=nt.current?.srcObject;if(e&&t&&!mt.current){gt.current=[];let n=new(window.AudioContext||window.webkitAudioContext);ht.current=n;let r=n.createMediaStreamDestination();n.createMediaStreamSource(e).connect(r),n.createMediaStreamSource(t).connect(r);let i=window.MediaRecorder.isTypeSupported(`audio/webm`)?`audio/webm`:`audio/mp4`,a=new window.MediaRecorder(r.stream,{mimeType:i});a.ondataavailable=e=>{e.data&&e.data.size>0&&gt.current.push(e.data)},mt.current=a,_t.current=Date.now(),a.start(1e3),setTimeout(()=>{try{if(!window.speechSynthesis)return;let e=new SpeechSynthesisUtterance(`This call is being recorded for quality and training purposes.`);if(e.rate=.95,e.pitch=1,e.volume=1,window.MediaStreamTrackGenerator||window.AudioContext)try{let t=n.createMediaStreamDestination();e.onstart=()=>{try{let i=document.createElement(`audio`);i.style.display=`none`,i.srcObject=t.stream,document.body.appendChild(i),i.play().catch(()=>{});let a=n.createMediaStreamSource(t.stream);a.connect(r),e.onend=()=>{try{a.disconnect()}catch{}try{i.remove()}catch{}}}catch{}}}catch{}window.speechSynthesis.speak(e)}catch{}},200)}}catch{}}},jt=(e={})=>{if(!e.callId)return;let t=lt.current===e.callId,n=G.current===e.callId,r=$e.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(Dt(),Be(null),t||n){G.current=e.callId,Ve(e.callId),Ue(e=>e===`connected`?e:`connecting`),A(!0);return}Ue(`idle`)}},Mt=(e={})=>{if(!e.callId)return;let t=lt.current===e.callId,n=G.current===e.callId,r=$e.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(Dt(),n){kt();return}lt.current=null,rt.current=null,ct.current=[],Be(null),Ue(`idle`)}},Nt=async(e={})=>{let t=et.current,n=H.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:W.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),rt.current=e;return}if(await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),ct.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:W.current,queuedCount:ct.current.length});for(let e of ct.current)await t.addIceCandidate(new RTCIceCandidate(e));ct.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:W.current})};(0,d.useEffect)(()=>{ue({isOpen:k,activeScreen:pe,isHumanHandled:he,agentName:N,agentHeadshot:_e})},[k,pe,he,N,_e]),(0,d.useEffect)(()=>{let e=!0;return(async()=>{V(!0);try{let t=p(i),n=await ke(t);if(!e)return;let a=t.siteId,o=oe(a),s=me(a),l=``;try{let e=Ze.current,r=Qe.current;if(Ze.current=!1,Qe.current=null,l=(await Oe({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:a,priorChatId:e||r?null:o||C(),forceNew:e,resumeChatId:r,visitorId:s}))?.data?.chatId,!l)throw Error(`resolve-session returned no chatId`);w(),ce(a,l)}catch(e){console.warn(`[FlowEngageProvider] resolve-session failed, reusing persisted or ephemeral chat id`,e?.message||e),l=o||T(),ce(a,l)}W.current=l;let u=Ae({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId,visitorId:s});U.current=u,h({...n,apiBaseUrl:t.apiBaseUrl}),_(l);let d=n?.widgetSettings?.branding?.fallbackAgentName||`Agent`,f=pn({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:l,siteId:t.siteId});H.current=f,f.on(`connect`,async()=>{L(`connected`);let e=W.current;if(e&&U.current)try{wt(await U.current.checkHumanHandled(e))}catch{}}),f.on(`disconnect`,()=>{L(`disconnected`)}),f.on(`aiTyping`,()=>{Se(!0)}),f.on(`ai:typing`,()=>{Se(!0)}),f.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:mi(t.message)};Se(!1),I(!1),!(n.type===`call_recording`||typeof n.message==`string`&&n.message.includes(`AI chat recording`))&&S(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),f.on(`conversationStarted`,e=>{e?.message&&S(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),f.on(`message:new`,e=>{let t=e.message||e,n={...t,message:mi(t.message)};Se(!1),!(n.type===`call_recording`||typeof n.message==`string`&&n.message.includes(`AI chat recording`))&&((n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&I(!1),S(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(M(!0),j(`agent`),ge(xi([n.agent_name,n.agentName,n.metadata?.agentName],d)),n.sender_headshot&&ve(n.sender_headshot),A(!0),Fe(e=>e+1)))});let m=(e={})=>{let t=xi([e.agent?.name,e.agentName,e.agent_name,vt.current],d);M(!0),j(`agent`),ge(t),ve(e.agent?.headshot||null),A(!0),Fe(e=>e+1),S(e=>Si(e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}))},g=(e={})=>{let t=xi([e.agent?.name,e.agentName,e.agent_name,vt.current],d);M(!1),j(`ai`),S(e=>Si(e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}))};f.on(`agent:joined`,m),f.on(`agentJoined`,m),f.on(`agent:left`,g),f.on(`agentLeft`,g),f.on(`conversationEnded`,e=>{ze(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;S(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),f.on(`chat:history_update`,e=>{let t=hi(e.chat_history||[]);S(e=>_i(e,t)),t.length===0&&(ze(!1),M(!1),j(`ai`),Se(!1),I(!1))}),f.on(`conversation:reset`,()=>{S([]),ze(!1),M(!1),j(`ai`),Se(!1),I(!1)}),f.on(`voice:end_session`,(e={})=>{console.log(`[FlowEngageProvider] voice:end_session received — ending voice session`),Le(e=>e+1),A(!0),Fe(e=>e+1)}),f.on(`typing:start`,e=>{e.sender===`agent`&&I(!0)}),f.on(`typing:stop`,e=>{e.sender===`agent`&&I(!1)}),f.on(`call:incoming`,(e={})=>{let t=xi([e.agentName,e.ownerName,e.agent?.name,vt.current],`Agent`);Et(),Dt(),dt.current=!1,Be({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ge(e=>xi([t,e],`Agent`)),Ue(`incoming`),Ge(null),A(!0)}),f.on(`call:offer`,async(e={})=>{rt.current=e;try{await Nt(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),f.on(`call:ice-candidate-from-agent`,async(e={})=>{if(e.candidate)try{let t=bi(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(!et.current||!et.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||W.current,queueSize:ct.current.length+1}),ct.current.push(t);return}await et.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),f.on(`call:ended`,()=>{Et(),kt(`socket:call_ended`)}),f.on(`call:accepted`,(e={})=>{jt(e)}),f.on(`call:accepted_by_other`,(e={})=>{jt(e)}),f.on(`call:rejected`,(e={})=>{Mt(e)}),f.on(`call:missed`,(e={})=>{Mt(e)}),f.on(`call:failed`,(e={})=>{Mt(e)}),f.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=lt.current===e.callId,n=G.current===e.callId,r=rt.current?.callId===e.callId,i=$e.current?.callId===e.callId;if(!t&&!n&&!r){i&&(Be(null),Ue(`idle`));return}dt.current=!0,lt.current=null,G.current=e.callId,Ve(e.callId),Be(null),Ue(`connected`),Ge(e.connectedAt||new Date().toISOString()),A(!0)}),f.on(`call:unavailable`,(e={})=>{kt(`socket:call_unavailable`),Ye(yi(e,`This visitor is not available for a call right now.`)),A(!0)}),f.on(`call:error`,(e={})=>{kt(`socket:call_error`),Ye(yi(e,`We couldn't connect the call right now.`)),A(!0)}),f.on(`visitor:navigate`,async({url:e,section:t,highlight:n}={})=>{e&&st(e,{voiceActive:xt.current}).then(({navigated:e,reason:r})=>{if(!e){r===`not-found`?te():r===`already-on-page`&&O();return}let i=t||n;i&&setTimeout(()=>{let e=rr(null,i);e&&_r(e)},300)})}),f.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;let n=rr(e||null,t||null);n&&_r(n)}),f.on(`visitor:clear_highlight`,()=>{vr()}),Ct.current=mn({socket:f,chatId:l});let v=await u.loadHistory(l,r);if(!e)return;S(hi(v.chat_history||[])),ee((v.chat_history||[]).length>=gi),M(!!v.is_human_handled),j(v.is_human_handled?`agent`:pe);let y=v?.visitor_email||v?.visitorEmail;if(y&&String(y).trim()&&Ot(String(y).trim()),await new Promise(e=>setTimeout(e,500)),!e)return;c(`ready`)}catch(t){if(!e)return;u(t),c(`error`)}finally{e&&V(!1)}})(),()=>{e=!1,Ct.current?.cleanup?.(),kt(),H.current?.disconnect()}},[i,r,a]),(0,d.useEffect)(()=>()=>{if(Me&&!bt.current&&yt.current.length>0){let e=W.current,t=yt.current,n=U.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),bt.current=!0)}},[Me,m]);let Pt=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e=U.current;!e||!g||Pt.current!==k&&(k&&Pt.current!==null?e.updateChatStatus(g,`open`).catch(()=>{}):Pt.current===!0&&e.updateChatStatus(g,`widget_closed`).catch(()=>{}),Pt.current=k)},[k,g]),(0,d.useEffect)(()=>{let e=()=>{let e=W.current,t=U.current;!e||!t||typeof navigator>`u`||t.beaconWidgetClosed?.(e)||t.updateChatStatus(e,`widget_closed`).catch(()=>{})};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[]);let Ft=async()=>{if(!(!z?.callId||!U.current||!H.current||!g)){Et(),lt.current=z.callId,Dt();try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});tt.current=e;let t=[{urls:`stun:stun.l.google.com:19302`}];try{let e=await U.current.getIceServersConfig();e?.data?.iceServers?.length&&(t=e.data.iceServers)}catch(e){console.warn(`[FlowEngageProvider] ice-config fetch failed, using STUN default`,e)}let n=new RTCPeerConnection({iceServers:t});et.current=n,n.onconnectionstatechange=()=>{let e=n.connectionState;if(e===`connected`){let e=new Date().toISOString();Ue(`connected`),Ge(t=>t||e),At(e);return}if(e===`connecting`){Ue(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&kt(`peer:connection_${e}`)},n.oniceconnectionstatechange=()=>{let e=n.iceConnectionState;if(e===`connected`||e===`completed`){let e=new Date().toISOString();Ue(`connected`),Ge(t=>t||e),At(e);return}if(e===`checking`||e===`new`){Ue(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&kt(`peer:ice_${e}`)},n.onsignalingstatechange=()=>{},n.onicegatheringstatechange=()=>{},e.getTracks().forEach(t=>{n.addTrack(t,e)}),n.onicecandidate=e=>{if(!e.candidate||!H.current?.connected)return;let t=e.candidate;H.current.emit(`call:ice-candidate`,{callId:z.callId,candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,chatId:g,from:`customer`})},n.ontrack=e=>{let[t]=e.streams||[],[n]=t?.getAudioTracks?.()||[];if(!nt.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,e.playsInline=!0,e.onplay=()=>{},e.onpause=()=>{},e.onended=()=>{},e.onerror=e=>{},nt.current=e,document.body.appendChild(e)}nt.current.srcObject=e.streams[0];let r=z?.callId,i=r&&(lt.current===r||G.current===r);if(!dt.current&&i){let e=new Date().toISOString();Ue(`connected`),Ge(t=>t||e),G.current=r,Ve(r),At(e)}nt.current.srcObject=t||null;let a=nt.current.play?.();a?.catch&&a.catch(e=>{})};let r=rt.current;r&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:r.callId||z.callId,chatId:g}),await Nt({...r,callId:r.callId||z.callId})),await U.current.acceptCall(z.callId,g),H.current?.emit(`call:accepted`,{callId:z.callId,chatId:g}),G.current=z.callId,Ve(z.callId),Ue(e=>e===`connected`||dt.current?`connected`:`connecting`),Be(null),A(!0)}catch(e){if(lt.current=null,kt(`accept_call_failed`),e?.status===404||e?.status===409||e?.status===422){Ye(yi(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await U.current.rejectCall(z.callId,g)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Ye(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Ye(`We couldn't connect the call right now. Please try again.`)}}},It=async()=>{if(!z?.callId||!U.current||!g){kt(`reject_call_without_server_context`);return}let e=z.callId;Dt(),Et(),H.current?.emit(`call:rejected`,{callId:e,chatId:g,reason:`visitor_declined`});try{await U.current.rejectCall(e,g)}catch(e){Ye(yi(e,`We couldn't decline the call cleanly.`))}finally{kt(`reject_call_finally`)}},Lt=(0,d.useRef)(It);Lt.current=It,(0,d.useEffect)(()=>{if(!z?.callId||B){Dt();return}let e=z.callId;return Dt(),ut.current=window.setTimeout(()=>{$e.current?.callId===e&&lt.current!==e&&G.current!==e&&Lt.current()},b),()=>{ut.current&&=(window.clearTimeout(ut.current),null)}},[B,Dt,z?.callId]);let Rt=async()=>{if(!B||!U.current||!g){kt(`end_call_without_server_context`);return}Et();try{await U.current.endWebRTCCall(B,g)}catch(e){Ye(yi(e,`The call ended locally, but the server could not be updated.`))}finally{kt(`end_call_finally`)}},zt=()=>{let e=tt.current?.getAudioTracks?.()||[],t=et.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0)return;let r=!Ke;n.forEach(e=>{e.enabled=!r}),qe(r)},Bt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(A(!0),!(!t||!U.current||!g||typeof window>`u`)){try{await U.current.trackVisitor({chatId:g,currentPagePath:window.location.pathname||`/`})}catch{}try{await U.current.updateChatStatus(g,`open`)}catch{}}},Vt=async e=>{let t=Ot(e);if(!t||!U.current||!W.current)return t;try{await U.current.trackVisitor({chatId:W.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Ht=()=>{!g||!H.current?.connected||ft.current||(ft.current=!0,H.current.emit(`typing:start`,{chatId:g,sender:`user`}))},Ut=()=>{!g||!H.current?.connected||!ft.current||(ft.current=!1,H.current.emit(`typing:stop`,{chatId:g,sender:`user`}))},Wt=(e=``)=>{let t=typeof e==`string`?e:``;!g||!H.current?.connected||t!==``&&pt.current===t||(pt.current=t,H.current.emit(`typing:update`,{chatId:g,sender:`user`,text:t}))};function Gt(){if(typeof document>`u`)return null;try{let e=(document.querySelector(`main`)||document.querySelector(`[role='main']`)||document.querySelector(`article`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);e.querySelectorAll(`nav, footer, header, aside, script, style, noscript, #flowengage-root, .flowengage-shell, .flowengage-widget-root, [id*='flowengage'], [class*='flowengage']`).forEach(e=>e.remove());let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>0?t.substring(0,3e3):null}catch{return null}}let Kt=async(e,t=``,n=null,a={})=>{let o=typeof e==`string`?e.trim():``;if(!o||!U.current||!g||s!==`ready`||Re)return;Ut(),at.current=!1;let c=/^\s*(yes|yeah|sure|ok|okay|go ahead|take me(?: there)?(?!\s+\w)|navigate(?!\s+(?:me\s+)?to\s+\w)|yep|absolutely|please do|do it|let'?s go|go there|show me(?!\s+(?:the|a|an)\s+\w)|go to it|bring me there|navigate me there)\b/i,l=/^\s*(?:yes|yeah|sure|ok|okay|yep|absolutely)\s+(?!(?:please|do\s+it|let'?s|that|this|there|it|thanks|go|cool|great|perfect|sounds|alright|proceed)\b)\w/i,d=/\b(take me|navigate|go to|show me|bring me|open|go there|navigate to|take me to|let'?s go to)\b/i;if(it.current&&c.test(o)&&!l.test(o)){let{url:e,section:t}=it.current;it.current=null,at.current=!0,console.log(`[FWH Nav] Client-side nav firing →`,e),st(e,{voiceActive:xt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?te():n===`already-on-page`&&O();return}!t||!xt.current||setTimeout(()=>{let e=rr(null,t);e&&_r(e)},300)})}else c.test(o)||(it.current=null);let f=`pending-user-${Date.now()}`,p={id:f,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,type:a?.type||`text`,metadata:a?.metadata||void 0,...n||{}};S(e=>[...e,p]);let m=he;if(m)try{m=wt(await U.current.checkHumanHandled(g))}catch{}if(m&&H.current?.connected){H.current.emit(`customer:message`,{chatId:g,content:e,sender:`user`,email:ye||void 0,type:a?.type||`text`,metadata:a?.metadata||{},...n||{}});return}Te(!0);try{let s=await Gr(),c=Ur(),l=`stream-preview-${Date.now().toString(36)}`,u=e=>{Se(!1),S(t=>{let n=t.findIndex(e=>e.id===l);if(n===-1)return[...t,{id:l,sender:`bot`,message:e,timestamp:new Date().toISOString(),isStreaming:!0}];let r=[...t];return r[n]={...r[n],message:r[n].message+e},r})},f=await U.current.sendAiMessage(g,e,r,t,{...n||{},...ye?{email:ye}:{}},{...a,currentPageUrl:typeof window<`u`?window.location.href:void 0,currentPageTitle:typeof window<`u`?document.title:void 0,currentPagePath:typeof window<`u`?window.location.pathname:void 0,currentPageContent:Gt()||void 0,navPreference:re(i?.siteId)||void 0,...s?{shopifyCart:s}:{},...c?{shopifyCustomerId:c}:{}},u),p=f.chat_history||[];if(console.log(`[FWH Nav Debug] API response fields:`,{has_navigate:!!f.navigate,navigate:f.navigate,has_pending_navigate:!!f.pending_navigate,pending_navigate:f.pending_navigate,last_bot_msg:[...p].reverse().find(e=>e.sender===`bot`)?.message?.substring(0,80)}),f.pending_navigate?.url){let e={url:f.pending_navigate.url,section:f.pending_navigate.section||null};d.test(o)?(console.log(`[FWH Nav] Auto-navigating (intent detected) →`,e.url),st(e.url,{voiceActive:xt.current}).then(({navigated:t,reason:n})=>{if(!t){n===`not-found`?te():n===`already-on-page`&&O();return}e.section&&setTimeout(()=>{let t=rr(null,e.section);t&&_r(t)},300)})):(it.current=e,console.log(`[FWH Nav] Stored pending nav →`,it.current));let t=i?.siteId;t&&!ie(t)&&(ae(t),S(e=>[...e,{id:`nav-pref-${Date.now()}`,type:`nav_pref_choice`,sender:`system`,message:``,timestamp:new Date().toISOString()}]))}if(f.navigate?.url)if(at.current)at.current=!1;else{let{url:e,section:t}=f.navigate;st(e,{voiceActive:xt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?te():n===`already-on-page`&&O();return}t&&setTimeout(()=>{let e=rr(null,t);e&&_r(e)},300)})}else if(f.highlight?.section){let e=f.highlight.section;setTimeout(()=>{let t=rr(null,e);t&&_r(t)},150)}else{let e=[...p].reverse().find(e=>e.sender===`bot`||e.sender===`assistant`);if(e?.message){let t=vi(e.message);t&&xr(t.url,{siteId:St.current?.siteId,apiBaseUrl:St.current?.apiBaseUrl}).then(({allowed:e,correctedUrl:n})=>{if(!e){te();return}st(n||t.url,{voiceActive:xt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?te():n===`already-on-page`&&O();return}!t.section||!xt.current||setTimeout(()=>{let e=rr(null,t.section);e&&_r(e)},300)})})}}S(e=>_i(e,hi(p))),Array.isArray(f.cart_actions)&&f.cart_actions.length&&ne(f.cart_actions),M(!!f.is_human_handled),j(f.is_human_handled?`agent`:`ai`),Se(!1),Te(!1),await U.current.updateChatStatus(g,`messageSent`)}catch(e){S(e=>e.filter(e=>!e.isStreaming).map(e=>e.id===f?{...e,isPending:!1,failed:!0}:e)),Se(!1),Te(!1),e.status===429?(De(!0),je(e.message),window.setTimeout(()=>{De(!1),je(``)},v)):u(e)}},qt=async e=>{if(!U.current||!e)throw Error(`Upload is unavailable right now.`);return U.current.uploadChatFile(e)},Jt=async e=>{if(!(!U.current||!g)){try{let t=e?`voice`:`text`;await U.current.setChatMode(g,t)}catch{}Ne(e),e&&(bt.current=!1)}},Yt=async e=>{if(bt.current)return;if(bt.current=!0,!U.current||!g||!e?.length){Ne(!1);return}let t=()=>{let t=hi(e);S(e=>{if(!e.length)return t;let n=e[e.length-1],r=t[0];return n&&r&&n.sender===r.sender&&n.message===r.message?e:[...e,...t]})};try{let n=await U.current.syncVoice(g,e);if(n?.chat_history?.length)S(e=>_i(e,hi(n.chat_history)));else if(n?.success)try{let e=await U.current.loadHistory(g,r);e?.chat_history?.length?S(t=>_i(t,hi(e.chat_history))):t()}catch{t()}else t()}catch{t()}finally{Ne(!1)}},K=async()=>{if(!(!U.current||!g)){Me&&!bt.current&&yt.current.length>0&&await Yt(yt.current);try{await U.current.endConversation(g)}catch{try{await U.current.updateChatStatus(g,`ended`)}catch{}}ze(!0),S(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,d.useEffect)(()=>{if(He!==`connected`||!B||!g||!We||!Tt)return;let e=new Date(We).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,Tt*1e3-t),r=window.setTimeout(()=>{Ye(`The call ended because it reached the time limit.`),Rt()},n);return()=>window.clearTimeout(r)},[B,We,He,g,Rt,Tt]),(0,d.useEffect)(()=>{let e=()=>{let e=W.current,t=U.current;if(!t||!e)return;if(xt.current&&yt.current.length>0&&F(),!bt.current&&yt.current.length>0&&(t.beaconSyncVoice(e,yt.current)||t.syncVoice(e,yt.current).catch(()=>{}),bt.current=!0),G.current){t.beaconEndWebRTCCall(G.current,e);return}let n=lt.current||$e.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let Xt=(0,d.useCallback)(async e=>{let t=W.current;if(!t||!e||!U.current||D.current)return 0;D.current=!0;try{let n=await U.current.getOlderMessages(t,e);if(W.current!==t)return 0;let r=hi(n?.history||[]);return ee(!!n?.hasMore),r.length?(S(e=>{let t=new Set(e.map(e=>e.id));return[...r.filter(e=>!t.has(e.id)),...e]}),r.length):0}catch{return 0}finally{D.current=!1}},[]),Zt=(0,d.useCallback)(()=>{let e=i?.siteId;se(e),Ze.current=!0,Qe.current=null,H.current?.disconnect(),S([]),_(``),W.current=``,ze(!1),M(!1),ge(null),ve(null),V(!0),o(e=>e+1)},[i?.siteId]),Qt=(0,d.useCallback)(e=>{i?.siteId,Ze.current=!1,Qe.current=e,H.current?.disconnect(),S([]),_(``),W.current=``,ze(!1),M(!1),ge(null),ve(null),V(!0),o(e=>e+1)},[i?.siteId]),$t=(0,d.useMemo)(()=>({status:s,error:l,runtimeConfig:m,resolvedConfig:i,chatId:g,chatHistory:x,isOpen:k,activeScreen:pe,isHumanHandled:he,agentName:N,agentHeadshot:_e,visitorEmail:ye,isAgentTyping:be,isAiTyping:xe,connectionStatus:Ce,isLoading:we,isVoiceMode:Me,isRateLimited:Ee,rateLimitMessage:R,isConversationEnded:Re,isSessionRestoring:Xe,openToChatCounter:Pe,voiceEndCounter:Ie,incomingCall:z,activeCallId:B,callConnectionState:He,callConnectedAt:We,isCallMuted:Ke,webRTCError:Je,language:r,historyRef:yt,hasSyncedRef:bt,dismissCallError:Et,captureVisitorEmail:Vt,startTyping:Ht,stopTyping:Ut,updateTypingDraft:Wt,notifyRouteChange:()=>Ct.current?.notifyRouteChange?.(),openWidget:Bt,closeWidget:()=>A(!1),toggleWidget:()=>{if(k){A(!1);return}Bt({notifyChatInitiated:!0})},sendMessage:Kt,uploadChatFile:qt,setVoiceMode:Jt,onMessageSync:Yt,beaconSyncVoiceTranscript:e=>{let t=U.current,n=W.current;return!t||!n||!Array.isArray(e)||!e.length?!1:(t.beaconSyncVoice(n,e)||t.syncVoice(n,e).catch(()=>{}),!0)},endConversation:K,startNewChat:Zt,resumeChat:Qt,getVisitorChatHistory:()=>U.current?.getVisitorChatHistory?.(),getVisitorChatThread:e=>U.current?.getVisitorChatThread?.(e),hasOlderMessages:E,loadOlderMessages:Xt,acceptCall:Ft,rejectCall:It,endWebRTCCall:Rt,toggleCallMute:zt}),[s,l,m,i,g,x,k,pe,he,N,_e,ye,be,xe,Ce,we,Me,Ee,R,Re,Xe,Pe,Ie,z,B,He,We,Ke,Je,r,Vt,Ht,Ut,Wt,Ft,It,Rt,zt,Bt,Kt,qt,Jt,Yt,K,Zt,Et,E,Xt]);return(0,f.jsx)(hn.Provider,{value:$t,children:n})}var wi=(0,d.createContext)({});function Ti(e){let t=(0,d.useRef)(null);return t.current===null&&(t.current=e()),t.current}var Ei=typeof window<`u`?d.useLayoutEffect:d.useEffect,Di=(0,d.createContext)(null);function Oi(e,t){e.indexOf(t)===-1&&e.push(t)}function ki(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var Ai=(e,t,n)=>n>t?t:n<e?e:n;function ji(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}var Mi=()=>{},Ni=()=>{};typeof process<`u`&&process.env.NODE_ENV!==`production`&&(Mi=(e,t,n)=>{!e&&typeof console<`u`&&console.warn(ji(t,n))},Ni=(e,t,n)=>{if(!e)throw Error(ji(t,n))});var Pi={},Fi=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Ii(e){return typeof e==`object`&&!!e}var Li=e=>/^0[^.\s]+$/u.test(e);function Ri(e){let t;return()=>(t===void 0&&(t=e()),t)}var zi=e=>e,Bi=(e,t)=>n=>t(e(n)),Vi=(...e)=>e.reduce(Bi),Hi=(e,t,n)=>{let r=t-e;return r===0?1:(n-e)/r},Ui=class{constructor(){this.subscriptions=[]}add(e){return Oi(this.subscriptions,e),()=>ki(this.subscriptions,e)}notify(e,t,n){let r=this.subscriptions.length;if(r)if(r===1)this.subscriptions[0](e,t,n);else for(let i=0;i<r;i++){let r=this.subscriptions[i];r&&r(e,t,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}},Wi=e=>e*1e3,Gi=e=>e/1e3;function Ki(e,t){return t?1e3/t*e:0}var qi=new Set;function Ji(e,t,n){e||qi.has(t)||(console.warn(ji(t,n)),qi.add(t))}var Yi=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Xi=1e-7,Zi=12;function Qi(e,t,n,r,i){let a,o,s=0;do o=t+(n-t)/2,a=Yi(o,r,i)-e,a>0?n=o:t=o;while(Math.abs(a)>Xi&&++s<Zi);return o}function $i(e,t,n,r){if(e===t&&n===r)return zi;let i=t=>Qi(t,0,1,e,n);return e=>e===0||e===1?e:Yi(i(e),t,r)}var ea=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,ta=e=>t=>1-e(1-t),na=$i(.33,1.53,.69,.99),ra=ta(na),ia=ea(ra),aa=e=>e>=1?1:(e*=2)<1?.5*ra(e):.5*(2-2**(-10*(e-1))),oa=e=>1-Math.sin(Math.acos(e)),sa=ta(oa),ca=ea(oa),la=$i(.42,0,1,1),ua=$i(0,0,.58,1),da=$i(.42,0,.58,1),fa=e=>Array.isArray(e)&&typeof e[0]!=`number`,pa=e=>Array.isArray(e)&&typeof e[0]==`number`,ma={linear:zi,easeIn:la,easeInOut:da,easeOut:ua,circIn:oa,circInOut:ca,circOut:sa,backIn:ra,backInOut:ia,backOut:na,anticipate:aa},ha=e=>typeof e==`string`,ga=e=>{if(pa(e)){Ni(e.length===4,`Cubic bezier arrays must contain four numerical values.`,`cubic-bezier-length`);let[t,n,r,i]=e;return $i(t,n,r,i)}else if(ha(e))return Ni(ma[e]!==void 0,`Invalid easing type '${e}'`,`invalid-easing-type`),ma[e];return e},_a=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`],va={value:null,addProjectionMetrics:null};function ya(e,t){let n=new Set,r=new Set,i=!1,a=!1,o=new WeakSet,s={delta:0,timestamp:0,isProcessing:!1},c=0;function l(t){o.has(t)&&(u.schedule(t),e()),c++,t(s)}let u={schedule:(e,t=!1,a=!1)=>{let s=a&&i?n:r;return t&&o.add(e),s.add(e),e},cancel:e=>{r.delete(e),o.delete(e)},process:e=>{if(s=e,i){a=!0;return}i=!0;let o=n;n=r,r=o,n.forEach(l),t&&va.value&&va.value.frameloop[t].push(c),c=0,n.clear(),i=!1,a&&(a=!1,u.process(e))}};return u}var ba=40;function xa(e,t){let n=!1,r=!0,i={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,o=_a.reduce((e,n)=>(e[n]=ya(a,t?n:void 0),e),{}),{setup:s,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:f,render:p,postRender:m}=o,h=()=>{let a=Pi.useManualTiming,o=a?i.timestamp:performance.now();n=!1,a||(i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,ba),1)),i.timestamp=o,i.isProcessing=!0,s.process(i),c.process(i),l.process(i),u.process(i),d.process(i),f.process(i),p.process(i),m.process(i),i.isProcessing=!1,n&&t&&(r=!1,e(h))},g=()=>{n=!0,r=!0,i.isProcessing||e(h)};return{schedule:_a.reduce((e,t)=>{let r=o[t];return e[t]=(e,t=!1,i=!1)=>(n||g(),r.schedule(e,t,i)),e},{}),cancel:e=>{for(let t=0;t<_a.length;t++)o[_a[t]].cancel(e)},state:i,steps:o}}var{schedule:J,cancel:Sa,state:Ca,steps:wa}=xa(typeof requestAnimationFrame<`u`?requestAnimationFrame:zi,!0),Ta;function Ea(){Ta=void 0}var Da={now:()=>(Ta===void 0&&Da.set(Ca.isProcessing||Pi.useManualTiming?Ca.timestamp:performance.now()),Ta),set:e=>{Ta=e,queueMicrotask(Ea)}},Oa={layout:0,mainThread:0,waapi:0},ka=e=>t=>typeof t==`string`&&t.startsWith(e),Aa=ka(`--`),ja=ka(`var(--`),Ma=e=>ja(e)?Na.test(e.split(`/*`)[0].trim()):!1,Na=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Pa(e){return typeof e==`string`?e.split(`/*`)[0].includes(`var(--`):!1}var Fa={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},Ia={...Fa,transform:e=>Ai(0,1,e)},La={...Fa,default:1},Ra=e=>Math.round(e*1e5)/1e5,za=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Ba(e){return e==null}var Va=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Ha=(e,t)=>n=>!!(typeof n==`string`&&Va.test(n)&&n.startsWith(e)||t&&!Ba(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ua=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(za);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},Wa=e=>Ai(0,255,e),Ga={...Fa,transform:e=>Math.round(Wa(e))},Ka={test:Ha(`rgb`,`red`),parse:Ua(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Ga.transform(e)+`, `+Ga.transform(t)+`, `+Ga.transform(n)+`, `+Ra(Ia.transform(r))+`)`};function qa(e){let t=``,n=``,r=``,i=``;return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}var Ja={test:Ha(`#`),parse:qa,transform:Ka.transform},Ya=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Xa=Ya(`deg`),Za=Ya(`%`),Y=Ya(`px`),Qa=Ya(`vh`),$a=Ya(`vw`),eo={...Za,parse:e=>Za.parse(e)/100,transform:e=>Za.transform(e*100)},to={test:Ha(`hsl`,`hue`),parse:Ua(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+Za.transform(Ra(t))+`, `+Za.transform(Ra(n))+`, `+Ra(Ia.transform(r))+`)`},no={test:e=>Ka.test(e)||Ja.test(e)||to.test(e),parse:e=>Ka.test(e)?Ka.parse(e):to.test(e)?to.parse(e):Ja.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?Ka.transform(e):to.transform(e),getAnimatableNone:e=>{let t=no.parse(e);return t.alpha=0,no.transform(t)}},ro=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function io(e){return isNaN(e)&&typeof e==`string`&&(e.match(za)?.length||0)+(e.match(ro)?.length||0)>0}var ao=`number`,oo=`color`,so=`var`,co=`var(`,lo="${}",uo=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function fo(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(uo,e=>(no.test(e)?(r.color.push(a),i.push(oo),n.push(no.parse(e))):e.startsWith(co)?(r.var.push(a),i.push(so),n.push(e)):(r.number.push(a),i.push(ao),n.push(parseFloat(e))),++a,lo)).split(lo),indexes:r,types:i}}function po(e){return fo(e).values}function mo({split:e,types:t}){let n=e.length;return r=>{let i=``;for(let a=0;a<n;a++)if(i+=e[a],r[a]!==void 0){let e=t[a];e===ao?i+=Ra(r[a]):e===oo?i+=no.transform(r[a]):i+=r[a]}return i}}function ho(e){return mo(fo(e))}var go=e=>typeof e==`number`?0:no.test(e)?no.getAnimatableNone(e):e,_o=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:go(e);function vo(e){let t=fo(e);return mo(t)(t.values.map((e,n)=>_o(e,t.split[n])))}var yo={test:io,parse:po,createTransformer:ho,getAnimatableNone:vo};function bo(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function xo({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let i=0,a=0,o=0;if(!t)i=a=o=n;else{let r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=bo(s,r,e+1/3),a=bo(s,r,e),o=bo(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function So(e,t){return n=>n>0?t:e}var X=(e,t,n)=>e+(t-e)*n,Co=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},wo=[Ja,Ka,to],To=e=>wo.find(t=>t.test(e));function Eo(e){let t=To(e);if(Mi(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`,`color-not-animatable`),!t)return!1;let n=t.parse(e);return t===to&&(n=xo(n)),n}var Do=(e,t)=>{let n=Eo(e),r=Eo(t);if(!n||!r)return So(e,t);let i={...n};return e=>(i.red=Co(n.red,r.red,e),i.green=Co(n.green,r.green,e),i.blue=Co(n.blue,r.blue,e),i.alpha=X(n.alpha,r.alpha,e),Ka.transform(i))},Oo=new Set([`none`,`hidden`]);function ko(e,t){return Oo.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function Ao(e,t){return n=>X(e,t,n)}function jo(e){return typeof e==`number`?Ao:typeof e==`string`?Ma(e)?So:no.test(e)?Do:Fo:Array.isArray(e)?Mo:typeof e==`object`?no.test(e)?Do:No:So}function Mo(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>jo(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function No(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=jo(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function Po(e,t){let n=[],r={color:0,var:0,number:0};for(let i=0;i<t.values.length;i++){let a=t.types[i],o=e.indexes[a][r[a]];n[i]=e.values[o]??0,r[a]++}return n}var Fo=(e,t)=>{let n=yo.createTransformer(t),r=fo(e),i=fo(t);return r.indexes.var.length===i.indexes.var.length&&r.indexes.color.length===i.indexes.color.length&&r.indexes.number.length>=i.indexes.number.length?Oo.has(e)&&!i.values.length||Oo.has(t)&&!r.values.length?ko(e,t):Vi(Mo(Po(r,i),i.values),n):(Mi(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,`complex-values-different`),So(e,t))};function Io(e,t,n){return typeof e==`number`&&typeof t==`number`&&typeof n==`number`?X(e,t,n):jo(e)(e,t)}var Lo=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>J.update(t,e),stop:()=>Sa(t),now:()=>Ca.isProcessing?Ca.timestamp:Da.now()}},Ro=(e,t,n=10)=>{let r=``,i=Math.max(Math.round(t/n),2);for(let t=0;t<i;t++)r+=Math.round(e(t/(i-1))*1e4)/1e4+`, `;return`linear(${r.substring(0,r.length-2)})`},zo=2e4;function Bo(e){let t=0,n=e.next(t);for(;!n.done&&t<2e4;)t+=50,n=e.next(t);return t>=2e4?1/0:t}function Vo(e,t=100,n){let r=n({...e,keyframes:[0,t]}),i=Math.min(Bo(r),zo);return{type:`keyframes`,ease:e=>r.next(i*e).value/t,duration:Gi(i)}}var Z={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function Ho(e,t){return e*Math.sqrt(1-t*t)}var Uo=12;function Wo(e,t,n){let r=n;for(let n=1;n<Uo;n++)r-=e(r)/t(r);return r}var Go=.001;function Ko({duration:e=Z.duration,bounce:t=Z.bounce,velocity:n=Z.velocity,mass:r=Z.mass}){let i,a;Mi(e<=Wi(Z.maxDuration),`Spring duration must be 10 seconds or less`,`spring-duration-limit`);let o=1-t;o=Ai(Z.minDamping,Z.maxDamping,o),e=Ai(Z.minDuration,Z.maxDuration,Gi(e)),o<1?(i=t=>{let r=t*o,i=r*e,a=r-n,s=Ho(t,o),c=Math.exp(-i);return Go-a/s*c},a=t=>{let r=t*o*e,a=r*n+n,s=o**2*t**2*e,c=Math.exp(-r),l=Ho(t**2,o);return(-i(t)+Go>0?-1:1)*((a-s)*c)/l}):(i=t=>{let r=Math.exp(-t*e),i=(t-n)*e+1;return-Go+r*i},a=t=>Math.exp(-t*e)*((n-t)*(e*e)));let s=5/e,c=Wo(i,a,s);if(e=Wi(e),isNaN(c))return{stiffness:Z.stiffness,damping:Z.damping,duration:e};{let t=c**2*r;return{stiffness:t,damping:o*2*Math.sqrt(r*t),duration:e}}}var qo=[`duration`,`bounce`],Jo=[`stiffness`,`damping`,`mass`];function Yo(e,t){return t.some(t=>e[t]!==void 0)}function Xo(e){let t={velocity:Z.velocity,stiffness:Z.stiffness,damping:Z.damping,mass:Z.mass,isResolvedFromDuration:!1,...e};if(!Yo(e,Jo)&&Yo(e,qo))if(t.velocity=0,e.visualDuration){let n=e.visualDuration,r=2*Math.PI/(n*1.2),i=r*r,a=2*Ai(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:Z.mass,stiffness:i,damping:a}}else{let n=Ko({...e,velocity:0});t={...t,...n,mass:Z.mass},t.isResolvedFromDuration=!0}return t}function Zo(e=Z.visualDuration,t=Z.bounce){let n=typeof e==`object`?e:{visualDuration:e,keyframes:[0,1],bounce:t},{restSpeed:r,restDelta:i}=n,a=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],s={done:!1,value:a},{stiffness:c,damping:l,mass:u,duration:d,velocity:f,isResolvedFromDuration:p}=Xo({...n,velocity:-Gi(n.velocity||0)}),m=f||0,h=l/(2*Math.sqrt(c*u)),g=o-a,_=Gi(Math.sqrt(c/u)),v=Math.abs(g)<5;r||=v?Z.restSpeed.granular:Z.restSpeed.default,i||=v?Z.restDelta.granular:Z.restDelta.default;let y,b,x,S,C,w;if(h<1)x=Ho(_,h),S=(m+h*_*g)/x,y=e=>o-Math.exp(-h*_*e)*(S*Math.sin(x*e)+g*Math.cos(x*e)),C=h*_*S+g*x,w=h*_*g-S*x,b=e=>Math.exp(-h*_*e)*(C*Math.sin(x*e)+w*Math.cos(x*e));else if(h===1){y=e=>o-Math.exp(-_*e)*(g+(m+_*g)*e);let e=m+_*g;b=t=>Math.exp(-_*t)*(_*e*t-m)}else{let e=_*Math.sqrt(h*h-1);y=t=>{let n=Math.exp(-h*_*t),r=Math.min(e*t,300);return o-n*((m+h*_*g)*Math.sinh(r)+e*g*Math.cosh(r))/e};let t=(m+h*_*g)/e,n=h*_*t-g*e,r=h*_*g-t*e;b=t=>{let i=Math.exp(-h*_*t),a=Math.min(e*t,300);return i*(n*Math.sinh(a)+r*Math.cosh(a))}}let T={calculatedDuration:p&&d||null,velocity:e=>Wi(b(e)),next:e=>{if(!p&&h<1){let t=Math.exp(-h*_*e),n=Math.sin(x*e),a=Math.cos(x*e),c=o-t*(S*n+g*a),l=Wi(t*(C*n+w*a));return s.done=Math.abs(l)<=r&&Math.abs(o-c)<=i,s.value=s.done?o:c,s}let t=y(e);if(p)s.done=e>=d;else{let n=Wi(b(e));s.done=Math.abs(n)<=r&&Math.abs(o-t)<=i}return s.value=s.done?o:t,s},toString:()=>{let e=Math.min(Bo(T),zo),t=Ro(t=>T.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return T}Zo.applyToOptions=e=>{let t=Vo(e,100,Zo);return e.ease=t.ease,e.duration=Wi(t.duration),e.type=`keyframes`,e};var Qo=5;function $o(e,t,n){let r=Math.max(t-Qo,0);return Ki(n-e(r),t-r)}function es({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:a=500,modifyTarget:o,min:s,max:c,restDelta:l=.5,restSpeed:u}){let d=e[0],f={done:!1,value:d},p=e=>s!==void 0&&e<s||c!==void 0&&e>c,m=e=>s===void 0?c:c===void 0||Math.abs(s-e)<Math.abs(c-e)?s:c,h=n*t,g=d+h,_=o===void 0?g:o(g);_!==g&&(h=_-d);let v=e=>-h*Math.exp(-e/r),y=e=>_+v(e),b=e=>{let t=v(e),n=y(e);f.done=Math.abs(t)<=l,f.value=f.done?_:n},x,S,C=e=>{p(f.value)&&(x=e,S=Zo({keyframes:[f.value,m(f.value)],velocity:$o(y,e,f.value),damping:i,stiffness:a,restDelta:l,restSpeed:u}))};return C(0),{calculatedDuration:null,next:e=>{let t=!1;return!S&&x===void 0&&(t=!0,b(e),C(e)),x!==void 0&&e>=x?S.next(e-x):(!t&&b(e),f)}}}function ts(e,t,n){let r=[],i=n||Pi.mix||Io,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=Vi(Array.isArray(t)?t[n]||zi:t,a)),r.push(a)}return r}function ns(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(Ni(a===t.length,`Both input and output ranges must be the same length`,`range-length`),a===1)return()=>t[0];if(a===2&&t[0]===t[1])return()=>t[1];let o=e[0]===e[1];e[0]>e[a-1]&&(e=[...e].reverse(),t=[...t].reverse());let s=ts(t,r,i),c=s.length,l=n=>{if(o&&n<e[0])return t[0];let r=0;if(c>1)for(;r<e.length-2&&!(n<e[r+1]);r++);let i=Hi(e[r],e[r+1],n);return s[r](i)};return n?t=>l(Ai(e[0],e[a-1],t)):l}function rs(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=Hi(0,t,r);e.push(X(n,1,i))}}function is(e){let t=[0];return rs(t,e.length-1),t}function as(e,t){return e.map(e=>e*t)}function os(e,t){return e.map(()=>t||da).splice(0,e.length-1)}function ss({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=fa(r)?r.map(ga):ga(r),a={done:!1,value:t[0]},o=ns(as(n&&n.length===t.length?n:is(t),e),t,{ease:Array.isArray(i)?i:os(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var cs=e=>e!==null;function ls(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(cs),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var us={decay:es,inertia:es,tween:ss,keyframes:ss,spring:Zo};function ds(e){typeof e.type==`string`&&(e.type=us[e.type])}var fs=class{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,t){return this.finished.then(e,t)}},ps=e=>e/100,ms=class extends fs{constructor(e){super(),this.state=`idle`,this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{let{motionValue:e}=this.options;e&&e.updatedAt!==Da.now()&&this.tick(Da.now()),this.isStopped=!0,this.state!==`idle`&&(this.teardown(),this.options.onStop?.())},Oa.mainThread++,this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){let{options:e}=this;ds(e);let{type:t=ss,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||ss;process.env.NODE_ENV!==`production`&&s!==ss&&Ni(o.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${o}`,`spring-two-frames`),s!==ss&&typeof o[0]!=`number`&&(this.mixKeyframes=Vi(ps,Io(o[0],o[1])),o=[0,100]);let c=s({...e,keyframes:o});i===`mirror`&&(this.mirroredGenerator=s({...e,keyframes:[...o].reverse(),velocity:-a})),c.calculatedDuration===null&&(c.calculatedDuration=Bo(c));let{calculatedDuration:l}=c;this.calculatedDuration=l,this.resolvedDuration=l+r,this.totalDuration=this.resolvedDuration*(n+1)-r,this.generator=c}updateTime(e){let t=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime===null?this.currentTime=t:this.currentTime=this.holdTime}tick(e,t=!1){let{generator:n,totalDuration:r,mixKeyframes:i,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:s}=this;if(this.startTime===null)return n.next(0);let{delay:c=0,keyframes:l,repeat:u,repeatType:d,repeatDelay:f,type:p,onUpdate:m,finalKeyframe:h}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-r/this.speed,this.startTime)),t?this.currentTime=e:this.updateTime(e);let g=this.currentTime-c*(this.playbackSpeed>=0?1:-1),_=this.playbackSpeed>=0?g<0:g>r;this.currentTime=Math.max(g,0),this.state===`finished`&&this.holdTime===null&&(this.currentTime=r);let v=this.currentTime,y=n;if(u){let e=Math.min(this.currentTime,r)/o,t=Math.floor(e),n=e%1;!n&&e>=1&&(n=1),n===1&&t--,t=Math.min(t,u+1),t%2&&(d===`reverse`?(n=1-n,f&&(n-=f/o)):d===`mirror`&&(y=a)),v=Ai(0,1,n)*o}let b;_?(this.delayState.value=l[0],b=this.delayState):b=y.next(v),i&&!_&&(b.value=i(b.value));let{done:x}=b;!_&&s!==null&&(x=this.playbackSpeed>=0?this.currentTime>=r:this.currentTime<=0);let S=this.holdTime===null&&(this.state===`finished`||this.state===`running`&&x);return S&&p!==es&&(b.value=ls(l,this.options,h,this.speed)),m&&m(b.value),S&&this.finish(),b}then(e,t){return this.finished.then(e,t)}get duration(){return Gi(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Gi(e)}get time(){return Gi(this.currentTime)}set time(e){e=Wi(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state=`paused`,this.holdTime=e,this.tick(e))}getGeneratorVelocity(){let e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);let t=this.generator.next(e).value;return $o(e=>this.generator.next(e).value,e,t)}get speed(){return this.playbackSpeed}set speed(e){let t=this.playbackSpeed!==e;t&&this.driver&&this.updateTime(Da.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=Gi(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=Lo,startTime:t}=this.options;this.driver||=e(e=>this.tick(e)),this.options.onPlay?.();let n=this.driver.now();this.state===`finished`?(this.updateFinished(),this.startTime=n):this.holdTime===null?this.startTime||=t??n:this.startTime=n-this.holdTime,this.state===`finished`&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state=`running`,this.driver.start()}pause(){this.state=`paused`,this.updateTime(Da.now()),this.holdTime=this.currentTime}complete(){this.state!==`running`&&this.play(),this.state=`finished`,this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state=`finished`,this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state=`idle`,this.stopDriver(),this.startTime=this.holdTime=null,Oa.mainThread--}stopDriver(){this.driver&&=(this.driver.stop(),void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){return this.options.allowFlatten&&(this.options.type=`keyframes`,this.options.ease=`linear`,this.initAnimation()),this.driver?.stop(),e.observe(this)}};function hs(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var gs=e=>e*180/Math.PI,_s=e=>ys(gs(Math.atan2(e[1],e[0]))),vs={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:_s,rotateZ:_s,skewX:e=>gs(Math.atan(e[1])),skewY:e=>gs(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},ys=e=>(e%=360,e<0&&(e+=360),e),bs=_s,xs=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),Ss=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),Cs={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:xs,scaleY:Ss,scale:e=>(xs(e)+Ss(e))/2,rotateX:e=>ys(gs(Math.atan2(e[6],e[5]))),rotateY:e=>ys(gs(Math.atan2(-e[2],e[0]))),rotateZ:bs,rotate:bs,skewX:e=>gs(Math.atan(e[4])),skewY:e=>gs(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function ws(e){return e.includes(`scale`)?1:0}function Ts(e,t){if(!e||e===`none`)return ws(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=Cs,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=vs,i=t}if(!i)return ws(t);let a=r[t],o=i[1].split(`,`).map(Ds);return typeof a==`function`?a(o):o[a]}var Es=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return Ts(n,t)};function Ds(e){return parseFloat(e.trim())}var Os=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],ks=new Set(Os),As=e=>e===Fa||e===Y,js=new Set([`x`,`y`,`z`]),Ms=Os.filter(e=>!js.has(e));function Ns(e){let t=[];return Ms.forEach(n=>{let r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith(`scale`)?1:0))}),t}var Ps={width:({x:e},{paddingLeft:t=`0`,paddingRight:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},height:({y:e},{paddingTop:t=`0`,paddingBottom:n=`0`,boxSizing:r})=>{let i=e.max-e.min;return r===`border-box`?i:i-parseFloat(t)-parseFloat(n)},top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>Ts(t,`x`),y:(e,{transform:t})=>Ts(t,`y`)};Ps.translateX=Ps.x,Ps.translateY=Ps.y;var Fs=new Set,Is=!1,Ls=!1,Rs=!1;function zs(){if(Ls){let e=Array.from(Fs).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),n=new Map;t.forEach(e=>{let t=Ns(e);t.length&&(n.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();let t=n.get(e);t&&t.forEach(([t,n])=>{e.getValue(t)?.set(n)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{e.suspendedScrollY!==void 0&&window.scrollTo(0,e.suspendedScrollY)})}Ls=!1,Is=!1,Fs.forEach(e=>e.complete(Rs)),Fs.clear()}function Bs(){Fs.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Ls=!0)})}function Vs(){Rs=!0,Bs(),zs(),Rs=!1}var Hs=class{constructor(e,t,n,r,i,a=!1){this.state=`pending`,this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=n,this.motionValue=r,this.element=i,this.isAsync=a}scheduleResolve(){this.state=`scheduled`,this.isAsync?(Fs.add(this),Is||(Is=!0,J.read(Bs),J.resolveKeyframes(zs))):(this.readKeyframes(),this.complete())}readKeyframes(){let{unresolvedKeyframes:e,name:t,element:n,motionValue:r}=this;if(e[0]===null){let i=r?.get(),a=e[e.length-1];if(i!==void 0)e[0]=i;else if(n&&t){let r=n.readValue(t,a);r!=null&&(e[0]=r)}e[0]===void 0&&(e[0]=a),r&&i===void 0&&r.set(e[0])}hs(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Fs.delete(this)}cancel(){this.state===`scheduled`&&(Fs.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},Us=e=>e.startsWith(`--`);function Ws(e,t,n){Us(t)?e.style.setProperty(t,n):e.style[t]=n}var Gs={};function Ks(e,t){let n=Ri(e);return()=>Gs[t]??n()}var qs=Ks(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),Js=Ks(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),Ys=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,Xs={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:Ys([0,.65,.55,1]),circOut:Ys([.55,0,1,.45]),backIn:Ys([.31,.01,.66,-.59]),backOut:Ys([.33,1.53,.69,.99])};function Zs(e,t){if(e)return typeof e==`function`?Js()?Ro(e,t):`ease-out`:pa(e)?Ys(e):Array.isArray(e)?e.map(e=>Zs(e,t)||Xs.easeOut):Xs[e]}function Qs(e,t,n,{delay:r=0,duration:i=300,repeat:a=0,repeatType:o=`loop`,ease:s=`easeOut`,times:c}={},l=void 0){let u={[t]:n};c&&(u.offset=c);let d=Zs(s,i);Array.isArray(d)&&(u.easing=d),va.value&&Oa.waapi++;let f={delay:r,duration:i,easing:Array.isArray(d)?`linear`:d,fill:`both`,iterations:a+1,direction:o===`reverse`?`alternate`:`normal`};l&&(f.pseudoElement=l);let p=e.animate(u,f);return va.value&&p.finished.finally(()=>{Oa.waapi--}),p}function $s(e){return typeof e==`function`&&`applyToOptions`in e}function ec({type:e,...t}){return $s(e)&&Js()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var tc=class extends fs{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;let{element:t,name:n,keyframes:r,pseudoElement:i,allowFlatten:a=!1,finalKeyframe:o,onComplete:s}=e;this.isPseudoElement=!!i,this.allowFlatten=a,this.options=e,Ni(typeof e.type!=`string`,`Mini animate() doesn't support "type" as a string.`,`mini-spring`);let c=ec(e);this.animation=Qs(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=ls(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),Ws(t,n,e),this.animation.cancel()}s?.(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state===`finished`&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;let{state:e}=this;e===`idle`||e===`finished`||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){let e=this.options?.element;!this.isPseudoElement&&e?.isConnected&&this.animation.commitStyles?.()}get duration(){let e=this.animation.effect?.getComputedTiming?.().duration||0;return Gi(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Gi(e)}get time(){return Gi(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Wi(e),t&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime===null?this.animation.playState:`finished`}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:t,rangeEnd:n,observe:r}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:`linear`}),this.animation.onfinish=null,e&&qs()?(this.animation.timeline=e,t&&(this.animation.rangeStart=t),n&&(this.animation.rangeEnd=n),zi):r(this)}},nc={anticipate:aa,backInOut:ia,circInOut:ca};function rc(e){return e in nc}function ic(e){typeof e.ease==`string`&&rc(e.ease)&&(e.ease=nc[e.ease])}var ac=10,oc=class extends tc{constructor(e){ic(e),ds(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){let{motionValue:t,onUpdate:n,onComplete:r,element:i,...a}=this.options;if(!t)return;if(e!==void 0){t.set(e);return}let o=new ms({...a,autoplay:!1}),s=Math.max(ac,Da.now()-this.startTime),c=Ai(0,ac,s-ac),l=o.sample(s).value,{name:u}=this.options;i&&u&&Ws(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},sc=(e,t)=>t===`zIndex`?!1:!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(yo.test(e)||e===`0`)&&!e.startsWith(`url(`));function cc(e){let t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function lc(e,t,n,r){let i=e[0];if(i===null)return!1;if(t===`display`||t===`visibility`)return!0;let a=e[e.length-1],o=sc(i,t),s=sc(a,t);return Mi(o===s,`You are trying to animate ${t} from "${i}" to "${a}". "${o?a:i}" is not an animatable value.`,`value-not-animatable`),!o||!s?!1:cc(e)||(n===`spring`||$s(n))&&r}function uc(e){e.duration=0,e.type=`keyframes`}var dc=new Set([`opacity`,`clipPath`,`filter`,`transform`]),fc=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function pc(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&fc.test(e[t]))return!0;return!1}var mc=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),hc=Ri(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function gc(e){let{motionValue:t,name:n,repeatDelay:r,repeatType:i,damping:a,type:o,keyframes:s}=e;if(!(t?.owner?.current instanceof HTMLElement))return!1;let{onUpdate:c,transformTemplate:l}=t.owner.getProps();return hc()&&n&&(dc.has(n)||mc.has(n)&&pc(s))&&(n!==`transform`||!l)&&!c&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var _c=40,vc=class extends fs{constructor({autoplay:e=!0,delay:t=0,type:n=`keyframes`,repeat:r=0,repeatDelay:i=0,repeatType:a=`loop`,keyframes:o,name:s,motionValue:c,element:l,...u}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Da.now();let d={autoplay:e,delay:t,type:n,repeat:r,repeatDelay:i,repeatType:a,name:s,motionValue:c,element:l,...u};this.keyframeResolver=new(l?.KeyframeResolver||Hs)(o,(e,t,n)=>this.onKeyframesResolved(e,t,d,!n),s,c,l),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(e,t,n,r){this.keyframeResolver=void 0;let{name:i,type:a,velocity:o,delay:s,isHandoff:c,onUpdate:l}=n;this.resolvedAt=Da.now();let u=!0;lc(e,i,a,o)||(u=!1,(Pi.instantAnimations||!s)&&l?.(ls(e,n,t)),e[0]=e[e.length-1],uc(n),n.repeat=0);let d={startTime:r?this.resolvedAt&&this.resolvedAt-this.createdAt>_c?this.resolvedAt:this.createdAt:void 0,finalKeyframe:t,...n,keyframes:e},f=u&&!c&&gc(d),p=d.motionValue?.owner?.current,m;if(f)try{m=new oc({...d,element:p})}catch{m=new ms(d)}else m=new ms(d);m.finished.then(()=>{this.notifyFinished()}).catch(zi),this.pendingTimeline&&=(this.stopTimeline=m.attachTimeline(this.pendingTimeline),void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,t){return this.finished.finally(e).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),Vs()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}};function yc(e,t,n,r=0,i=1){let a=Array.from(e).sort((e,t)=>e.sortNodePosition(t)).indexOf(t),o=e.size,s=(o-1)*r;return typeof n==`function`?n(a,o):i===1?a*r:s-a*r}var bc=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function xc(e){let t=bc.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}var Sc=4;function Cc(e,t,n=1){Ni(n<=Sc,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,`max-css-var-depth`);let[r,i]=xc(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return Fi(e)?parseFloat(e):e}return Ma(i)?Cc(i,t,n+1):i}var wc={type:`spring`,stiffness:500,damping:25,restSpeed:10},Tc=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),Ec={type:`keyframes`,duration:.8},Dc={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},Oc=(e,{keyframes:t})=>t.length>2?Ec:ks.has(e)?e.startsWith(`scale`)?Tc(t[1]):wc:Dc;function kc(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function Ac(e,t){let n=e?.[t]??e?.default??e;return n===e?n:kc(n,e)}var jc=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function Mc(e){for(let t in e)if(!jc.has(t))return!0;return!1}var Nc=(e,t,n,r={},i,a)=>o=>{let s=Ac(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=Wi(c);let u={keyframes:Array.isArray(n)?n:[null,n],ease:`easeOut`,velocity:t.getVelocity(),...s,delay:-l,onUpdate:e=>{t.set(e),s.onUpdate&&s.onUpdate(e)},onComplete:()=>{o(),s.onComplete&&s.onComplete()},name:e,motionValue:t,element:a?void 0:i};Mc(s)||Object.assign(u,Oc(e,u)),u.duration&&=Wi(u.duration),u.repeatDelay&&=Wi(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(uc(u),u.delay===0&&(d=!0)),(Pi.instantAnimations||Pi.skipAnimations||i?.shouldSkipAnimations)&&(d=!0,uc(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=ls(u.keyframes,s);if(e!==void 0){J.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new ms(u):new vc(u)};function Pc(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function Fc(e,t,n,r){if(typeof t==`function`){let[i,a]=Pc(r);t=t(n===void 0?e.custom:n,i,a)}if(typeof t==`string`&&(t=e.variants&&e.variants[t]),typeof t==`function`){let[i,a]=Pc(r);t=t(n===void 0?e.custom:n,i,a)}return t}function Ic(e,t,n){let r=e.getProps();return Fc(r,t,n===void 0?r.custom:n,e)}var Lc=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...Os]),Rc=30,zc=e=>!isNaN(parseFloat(e)),Bc={current:void 0},Vc=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=Da.now();if(this.updatedAt!==t&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(let e of this.dependents)e.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=Da.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=zc(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!==`production`&&Ji(!1,`value.onChange(callback) is deprecated. Switch to value.on("change", callback).`),this.on(`change`,e)}on(e,t){this.events[e]||(this.events[e]=new Ui);let n=this.events[e].add(t);return e===`change`?()=>{n(),J.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(let e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,t,n){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(e){this.dependents||=new Set,this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return Bc.current&&Bc.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=Da.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Rc)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,Rc);return Ki(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=e(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}};function Hc(e,t){return new Vc(e,t)}var Uc=e=>Array.isArray(e);function Wc(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Hc(n))}function Gc(e){return Uc(e)?e[e.length-1]||0:e}function Kc(e,t){let{transitionEnd:n={},transition:r={},...i}=Ic(e,t)||{};i={...i,...n};for(let t in i)Wc(e,t,Gc(i[t]))}var qc=e=>!!(e&&e.getVelocity);function Jc(e){return!!(qc(e)&&e.add)}function Yc(e,t){let n=e.getValue(`willChange`);if(Jc(n))return n.add(t);if(!n&&Pi.WillChange){let n=new Pi.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function Xc(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var Zc=`data-`+Xc(`framerAppearId`);function Qc(e){return e.props[Zc]}function $c({protectedKeys:e,needsAnimating:t},n){let r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function el(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:a,transitionEnd:o,...s}=t,c=e.getDefaultTransition();a=a?kc(a,c):c;let l=a?.reduceMotion;r&&(a=r);let u=[],d=i&&e.animationState&&e.animationState.getState()[i];for(let t in s){let r=e.getValue(t,e.latestValues[t]??null),i=s[t];if(i===void 0||d&&$c(d,t))continue;let o={delay:n,...Ac(a||{},t)},c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){J.update(()=>r.set(i));continue}let f=!1;if(window.MotionHandoffAnimation){let n=Qc(e);if(n){let e=window.MotionHandoffAnimation(n,t,J);e!==null&&(o.startTime=e,f=!0)}}Yc(e,t);let p=l??e.shouldReduceMotion;r.start(Nc(t,r,i,p&&Lc.has(t)?{type:!1}:o,e,f));let m=r.animation;m&&u.push(m)}if(o){let t=()=>J.update(()=>{o&&Kc(e,o)});u.length?Promise.all(u).then(t):t()}return u}function tl(e,t,n={}){let r=Ic(e,t,n.type===`exit`?e.presenceContext?.custom:void 0),{transition:i=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(i=n.transitionOverride);let a=r?()=>Promise.all(el(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{let{delayChildren:a=0,staggerChildren:o,staggerDirection:s}=i;return nl(e,t,r,a,o,s,n)}:()=>Promise.resolve(),{when:s}=i;if(s){let[e,t]=s===`beforeChildren`?[a,o]:[o,a];return e().then(()=>t())}else return Promise.all([a(),o(n.delay)])}function nl(e,t,n=0,r=0,i=0,a=1,o){let s=[];for(let c of e.variantChildren)c.notify(`AnimationStart`,t),s.push(tl(c,t,{...o,delay:n+(typeof r==`function`?0:r)+yc(e.variantChildren,c,r,i,a)}).then(()=>c.notify(`AnimationComplete`,t)));return Promise.all(s)}function rl(e,t,n={}){e.notify(`AnimationStart`,t);let r;if(Array.isArray(t)){let i=t.map(t=>tl(e,t,n));r=Promise.all(i)}else if(typeof t==`string`)r=tl(e,t,n);else{let i=typeof t==`function`?Ic(e,t,n.custom):t;r=Promise.all(el(e,i,n))}return r.then(()=>{e.notify(`AnimationComplete`,t)})}var il={test:e=>e===`auto`,parse:e=>e},al=e=>t=>t.test(e),ol=[Fa,Y,Za,Xa,$a,Qa,il],sl=e=>ol.find(al(e));function cl(e){return typeof e==`number`?e===0:e===null?!0:e===`none`||e===`0`||Li(e)}var ll=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function ul(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(za)||[];if(!r)return e;let i=n.replace(r,``),a=ll.has(t)?1:0;return r!==n&&(a*=100),t+`(`+a+i+`)`}var dl=/\b([a-z-]*)\(.*?\)/gu,fl={...yo,getAnimatableNone:e=>{let t=e.match(dl);return t?t.map(ul).join(` `):e}},pl={...yo,getAnimatableNone:e=>{let t=yo.parse(e);return yo.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},ml={...Fa,transform:Math.round},hl={borderWidth:Y,borderTopWidth:Y,borderRightWidth:Y,borderBottomWidth:Y,borderLeftWidth:Y,borderRadius:Y,borderTopLeftRadius:Y,borderTopRightRadius:Y,borderBottomRightRadius:Y,borderBottomLeftRadius:Y,width:Y,maxWidth:Y,height:Y,maxHeight:Y,top:Y,right:Y,bottom:Y,left:Y,inset:Y,insetBlock:Y,insetBlockStart:Y,insetBlockEnd:Y,insetInline:Y,insetInlineStart:Y,insetInlineEnd:Y,padding:Y,paddingTop:Y,paddingRight:Y,paddingBottom:Y,paddingLeft:Y,paddingBlock:Y,paddingBlockStart:Y,paddingBlockEnd:Y,paddingInline:Y,paddingInlineStart:Y,paddingInlineEnd:Y,margin:Y,marginTop:Y,marginRight:Y,marginBottom:Y,marginLeft:Y,marginBlock:Y,marginBlockStart:Y,marginBlockEnd:Y,marginInline:Y,marginInlineStart:Y,marginInlineEnd:Y,fontSize:Y,backgroundPositionX:Y,backgroundPositionY:Y,rotate:Xa,rotateX:Xa,rotateY:Xa,rotateZ:Xa,scale:La,scaleX:La,scaleY:La,scaleZ:La,skew:Xa,skewX:Xa,skewY:Xa,distance:Y,translateX:Y,translateY:Y,translateZ:Y,x:Y,y:Y,z:Y,perspective:Y,transformPerspective:Y,opacity:Ia,originX:eo,originY:eo,originZ:Y,zIndex:ml,fillOpacity:Ia,strokeOpacity:Ia,numOctaves:ml},gl={...hl,color:no,backgroundColor:no,outlineColor:no,fill:no,stroke:no,borderColor:no,borderTopColor:no,borderRightColor:no,borderBottomColor:no,borderLeftColor:no,filter:fl,WebkitFilter:fl,mask:pl,WebkitMask:pl},_l=e=>gl[e],vl=new Set([fl,pl]);function yl(e,t){let n=_l(e);return vl.has(n)||(n=yo),n.getAnimatableNone?n.getAnimatableNone(t):void 0}var bl=new Set([`auto`,`none`,`0`]);function xl(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!bl.has(t)&&fo(t).values.length&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]=yl(n,i)}var Sl=class extends Hs{constructor(e,t,n,r,i){super(e,t,n,r,i,!0)}readKeyframes(){let{unresolvedKeyframes:e,element:t,name:n}=this;if(!t||!t.current)return;super.readKeyframes();for(let n=0;n<e.length;n++){let r=e[n];if(typeof r==`string`&&(r=r.trim(),Ma(r))){let i=Cc(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!Lc.has(n)||e.length!==2)return;let[r,i]=e,a=sl(r),o=sl(i);if(Pa(r)!==Pa(i)&&Ps[n]){this.needsMeasurement=!0;return}if(a!==o)if(As(a)&&As(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else Ps[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||cl(e[t]))&&n.push(t);n.length&&xl(e,n,t)}measureInitialState(){let{element:e,unresolvedKeyframes:t,name:n}=this;if(!e||!e.current)return;n===`height`&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Ps[n](e.measureViewportBox(),window.getComputedStyle(e.current)),t[0]=this.measuredOrigin;let r=t[t.length-1];r!==void 0&&e.getValue(n,r).jump(r,!1)}measureEndState(){let{element:e,name:t,unresolvedKeyframes:n}=this;if(!e||!e.current)return;let r=e.getValue(t);r&&r.jump(this.measuredOrigin,!1);let i=n.length-1,a=n[i];n[i]=Ps[t](e.measureViewportBox(),window.getComputedStyle(e.current)),a!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=a),this.removedTransforms?.length&&this.removedTransforms.forEach(([t,n])=>{e.getValue(t).set(n)}),this.resolveNoneKeyframes()}};function Cl(e,t,n){if(e==null)return[];if(e instanceof EventTarget)return[e];if(typeof e==`string`){let r=document;t&&(r=t.current);let i=n?.[e]??r.querySelectorAll(e);return i?Array.from(i):[]}return Array.from(e).filter(e=>e!=null)}var wl=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function Tl(e){return Ii(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}var{schedule:El,cancel:Dl}=xa(queueMicrotask,!1),Ol={x:!1,y:!1};function kl(){return Ol.x||Ol.y}function Al(e){return e===`x`||e===`y`?Ol[e]?null:(Ol[e]=!0,()=>{Ol[e]=!1}):Ol.x||Ol.y?null:(Ol.x=Ol.y=!0,()=>{Ol.x=Ol.y=!1})}function jl(e,t){let n=Cl(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function Ml(e){return!(e.pointerType===`touch`||kl())}function Nl(e,t,n={}){let[r,i,a]=jl(e,n);return r.forEach(e=>{let n=!1,r=!1,a,o=()=>{e.removeEventListener(`pointerleave`,u)},s=e=>{a&&=(a(e),void 0),o()},c=e=>{n=!1,window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),r&&(r=!1,s(e))},l=()=>{n=!0,window.addEventListener(`pointerup`,c,i),window.addEventListener(`pointercancel`,c,i)},u=e=>{if(e.pointerType!==`touch`){if(n){r=!0;return}s(e)}};e.addEventListener(`pointerenter`,n=>{if(!Ml(n))return;r=!1;let o=t(e,n);typeof o==`function`&&(a=o,e.addEventListener(`pointerleave`,u,i))},i),e.addEventListener(`pointerdown`,l,i)}),a}var Pl=(e,t)=>t?e===t?!0:Pl(e,t.parentElement):!1,Fl=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,Il=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function Ll(e){return Il.has(e.tagName)||e.isContentEditable===!0}var Rl=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function zl(e){return Rl.has(e.tagName)||e.isContentEditable===!0}var Bl=new WeakSet;function Vl(e){return t=>{t.key===`Enter`&&e(t)}}function Hl(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var Ul=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=Vl(()=>{if(Bl.has(n))return;Hl(n,`down`);let e=Vl(()=>{Hl(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>Hl(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function Wl(e){return Fl(e)&&!kl()}var Gl=new WeakSet;function Kl(e,t,n={}){let[r,i,a]=jl(e,n),o=e=>{let r=e.currentTarget;if(!Wl(e)||Gl.has(e))return;Bl.add(r),n.stopPropagation&&Gl.add(e);let a=t(r,e),o=(e,t)=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c),Bl.has(r)&&Bl.delete(r),Wl(e)&&typeof a==`function`&&a(e,{success:t})},s=e=>{o(e,r===window||r===document||n.useGlobalTarget||Pl(r,e.target))},c=e=>{o(e,!1)};window.addEventListener(`pointerup`,s,i),window.addEventListener(`pointercancel`,c,i)};return r.forEach(e=>{(n.useGlobalTarget?window:e).addEventListener(`pointerdown`,o,i),Tl(e)&&(e.addEventListener(`focus`,e=>Ul(e,i)),!Ll(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}function ql(e){return Ii(e)&&`ownerSVGElement`in e}var Jl=new WeakMap,Yl,Xl=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:ql(r)&&`getBBox`in r?r.getBBox()[t]:r[n],Zl=Xl(`inline`,`width`,`offsetWidth`),Ql=Xl(`block`,`height`,`offsetHeight`);function $l({target:e,borderBoxSize:t}){Jl.get(e)?.forEach(n=>{n(e,{get width(){return Zl(e,t)},get height(){return Ql(e,t)}})})}function eu(e){e.forEach($l)}function tu(){typeof ResizeObserver>`u`||(Yl=new ResizeObserver(eu))}function nu(e,t){Yl||tu();let n=Cl(e);return n.forEach(e=>{let n=Jl.get(e);n||(n=new Set,Jl.set(e,n)),n.add(t),Yl?.observe(e)}),()=>{n.forEach(e=>{let n=Jl.get(e);n?.delete(t),n?.size||Yl?.unobserve(e)})}}var ru=new Set,iu;function au(){iu=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};ru.forEach(t=>t(e))},window.addEventListener(`resize`,iu)}function ou(e){return ru.add(e),iu||au(),()=>{ru.delete(e),!ru.size&&typeof iu==`function`&&(window.removeEventListener(`resize`,iu),iu=void 0)}}function su(e,t){return typeof e==`function`?ou(e):nu(e,t)}function cu(e){return ql(e)&&e.tagName===`svg`}var lu=[...ol,no,yo],uu=e=>lu.find(al(e)),du=()=>({translate:0,scale:1,origin:0,originPoint:0}),fu=()=>({x:du(),y:du()}),pu=()=>({min:0,max:0}),mu=()=>({x:pu(),y:pu()}),hu=new WeakMap;function gu(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function _u(e){return typeof e==`string`||Array.isArray(e)}var vu=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],yu=[`initial`,...vu];function bu(e){return gu(e.animate)||yu.some(t=>_u(e[t]))}function xu(e){return!!(bu(e)||e.variants)}function Su(e,t,n){for(let r in t){let i=t[r],a=n[r];if(qc(i))e.addValue(r,i);else if(qc(a))e.addValue(r,Hc(i,{owner:e}));else if(a!==i)if(e.hasValue(r)){let t=e.getValue(r);t.liveStyle===!0?t.jump(i):t.hasAnimated||t.set(i)}else{let t=e.getStaticValue(r);e.addValue(r,Hc(t===void 0?i:t,{owner:e}))}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var Cu={current:null},wu={current:!1},Tu=typeof window<`u`;function Eu(){if(wu.current=!0,Tu)if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>Cu.current=e.matches;e.addEventListener(`change`,t),t()}else Cu.current=!1}var Du=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],Ou={};function ku(e){Ou=e}function Au(){return Ou}var ju=class{scrapeMotionValuesFromProps(e,t,n){return{}}constructor({parent:e,props:t,presenceContext:n,reducedMotionConfig:r,skipAnimations:i,blockInitialAnimation:a,visualState:o},s={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=Hs,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify(`Update`,this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{let e=Da.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,J.render(this.render,!1,!0))};let{latestValues:c,renderState:l}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=t.initial?{...c}:{},this.renderState=l,this.parent=e,this.props=t,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=r,this.skipAnimationsConfig=i,this.options=s,this.blockInitialAnimation=!!a,this.isControllingVariants=bu(t),this.isVariantNode=xu(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);let{willChange:u,...d}=this.scrapeMotionValuesFromProps(t,{},this);for(let e in d){let t=d[e];c[e]!==void 0&&qc(t)&&t.set(c[e])}}mount(e){if(this.hasBeenMounted)for(let e in this.initialValues)this.values.get(e)?.jump(this.initialValues[e]),this.latestValues[e]=this.initialValues[e];this.current=e,hu.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((e,t)=>this.bindToMotionValue(t,e)),this.reducedMotionConfig===`never`?this.shouldReduceMotion=!1:this.reducedMotionConfig===`always`?this.shouldReduceMotion=!0:(wu.current||Eu(),this.shouldReduceMotion=Cu.current),process.env.NODE_ENV!==`production`&&Ji(this.shouldReduceMotion!==!0,`You have Reduced Motion enabled on your device. Animations may not appear as expected.`,`reduced-motion-disabled`),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),Sa(this.notifyUpdate),Sa(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(let e in this.events)this.events[e].clear();for(let e in this.features){let t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??=new Set,this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,t){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),t.accelerate&&dc.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new tc({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:Wi(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=ks.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&J.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()}),i;typeof window<`u`&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i&&i(),t.owner&&t.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e=`animation`;for(e in Ou){let t=Ou[e];if(!t)continue;let{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(this)),this.features[e]){let t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):mu()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let t=0;t<Du.length;t++){let n=Du[t];this.propEventSubscriptions[n]&&(this.propEventSubscriptions[n](),delete this.propEventSubscriptions[n]);let r=e[`on`+n];r&&(this.propEventSubscriptions[n]=this.on(n,r))}this.prevMotionValues=Su(this,this.scrapeMotionValuesFromProps(e,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){let t=this.getClosestVariantNode();if(t)return t.variantChildren&&t.variantChildren.add(e),()=>t.variantChildren.delete(e)}addValue(e,t){let n=this.values.get(e);t!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t),this.latestValues[e]=t.get())}removeValue(e){this.values.delete(e);let t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&t!==void 0&&(n=Hc(t===null?void 0:t,{owner:this}),this.addValue(e,n)),n}readValue(e,t){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n==`string`&&(Fi(n)||Li(n))?n=parseFloat(n):!uu(n)&&yo.test(t)&&(n=yl(e,t)),this.setBaseTarget(e,qc(n)?n.get():n)),qc(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){let{initial:t}=this.props,n;if(typeof t==`string`||typeof t==`object`){let r=Fc(this.props,t,this.presenceContext?.custom);r&&(n=r[e])}if(t&&n!==void 0)return n;let r=this.getBaseTargetFromProps(this.props,e);return r!==void 0&&!qc(r)?r:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,t){return this.events[e]||(this.events[e]=new Ui),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){El.render(this.render)}},Mu=class extends ju{constructor(){super(...arguments),this.KeyframeResolver=Sl}sortInstanceNodePosition(e,t){return e.compareDocumentPosition(t)&2?1:-1}getBaseTargetFromProps(e,t){let n=e.style;return n?n[t]:void 0}removeValueFromRenderState(e,{vars:t,style:n}){delete t[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);let{children:e}=this.props;qc(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},Nu=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function Pu({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function Fu({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function Iu(e,t){if(!t)return e;let n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function Lu(e){return e===void 0||e===1}function Ru({scale:e,scaleX:t,scaleY:n}){return!Lu(e)||!Lu(t)||!Lu(n)}function zu(e){return Ru(e)||Bu(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Bu(e){return Vu(e.x)||Vu(e.y)}function Vu(e){return e&&e!==`0%`}function Hu(e,t,n){return n+t*(e-n)}function Uu(e,t,n,r,i){return i!==void 0&&(e=Hu(e,i,r)),Hu(e,n,r)+t}function Wu(e,t=0,n=1,r,i){e.min=Uu(e.min,t,n,r,i),e.max=Uu(e.max,t,n,r,i)}function Gu(e,{x:t,y:n}){Wu(e.x,t.translate,t.scale,t.originPoint),Wu(e.y,n.translate,n.scale,n.originPoint)}var Ku=.999999999999,qu=1.0000000000001;function Ju(e,t,n,r=!1){let i=n.length;if(!i)return;t.x=t.y=1;let a,o;for(let s=0;s<i;s++){a=n[s],o=a.projectionDelta;let{visualElement:i}=a.options;i&&i.props.style&&i.props.style.display===`contents`||(r&&a.options.layoutScroll&&a.scroll&&a!==a.root&&(Yu(e.x,-a.scroll.offset.x),Yu(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Gu(e,o)),r&&zu(a.latestValues)&&Qu(e,a.latestValues,a.layout?.layoutBox))}t.x<qu&&t.x>Ku&&(t.x=1),t.y<qu&&t.y>Ku&&(t.y=1)}function Yu(e,t){e.min+=t,e.max+=t}function Xu(e,t,n,r,i=.5){Wu(e,t,n,X(e.min,e.max,i),r)}function Zu(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function Qu(e,t,n){let r=n??e;Xu(e.x,Zu(t.x,r.x),t.scaleX,t.scale,t.originX),Xu(e.y,Zu(t.y,r.y),t.scaleY,t.scale,t.originY)}function $u(e,t){return Pu(Iu(e.getBoundingClientRect(),t))}function ed(e,t,n){let r=$u(e,n),{scroll:i}=t;return i&&(Yu(r.x,i.offset.x),Yu(r.y,i.offset.y)),r}var td={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},nd=Os.length;function rd(e,t,n){let r=``,i=!0;for(let a=0;a<nd;a++){let o=Os[a],s=e[o];if(s===void 0)continue;let c=!0;if(typeof s==`number`)c=s===(o.startsWith(`scale`)?1:0);else{let e=parseFloat(s);c=o.startsWith(`scale`)?e===1:e===0}if(!c||n){let e=wl(s,hl[o]);if(!c){i=!1;let t=td[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}return r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function id(e,t,n){let{style:r,vars:i,transformOrigin:a}=e,o=!1,s=!1;for(let e in t){let n=t[e];if(ks.has(e)){o=!0;continue}else if(Aa(e)){i[e]=n;continue}else{let t=wl(n,hl[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=rd(t,e.transform,n):r.transform&&=`none`),s){let{originX:e=`50%`,originY:t=`50%`,originZ:n=0}=a;r.transformOrigin=`${e} ${t} ${n}`}}function ad(e,{style:t,vars:n},r,i){let a=e.style,o;for(o in t)a[o]=t[o];for(o in i?.applyProjectionStyles(a,r),n)a.setProperty(o,n[o])}function od(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var sd={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`)if(Y.test(e))e=parseFloat(e);else return e;return`${od(e,t.target.x)}% ${od(e,t.target.y)}%`}},cd={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=yo.parse(e);if(i.length>5)return r;let a=yo.createTransformer(e),o=typeof i[0]==`number`?0:1,s=n.x.scale*t.x,c=n.y.scale*t.y;i[0+o]/=s,i[1+o]/=c;let l=X(s,c,.5);return typeof i[2+o]==`number`&&(i[2+o]/=l),typeof i[3+o]==`number`&&(i[3+o]/=l),a(i)}},ld={borderRadius:{...sd,applyTo:[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`]},borderTopLeftRadius:sd,borderTopRightRadius:sd,borderBottomLeftRadius:sd,borderBottomRightRadius:sd,boxShadow:cd};function ud(e,{layout:t,layoutId:n}){return ks.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!ld[e]||e===`opacity`)}function dd(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(qc(r[t])||i&&qc(i[t])||ud(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function fd(e){return window.getComputedStyle(e)}var pd=class extends Mu{constructor(){super(...arguments),this.type=`html`,this.renderInstance=ad}readValueFromInstance(e,t){if(ks.has(t))return this.projection?.isProjecting?ws(t):Es(e,t);{let n=fd(e),r=(Aa(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return $u(e,t)}build(e,t,n){id(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return dd(e,t,n)}},md={offset:`stroke-dashoffset`,array:`stroke-dasharray`},hd={offset:`strokeDashoffset`,array:`strokeDasharray`};function gd(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?md:hd;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var _d=[`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function vd(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(id(e,s,l),c){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};let{attrs:d,style:f}=e;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??`50% 50%`,delete d.transformOrigin),f.transform&&(f.transformBox=u?.transformBox??`fill-box`,delete d.transformBox);for(let e of _d)d[e]!==void 0&&(f[e]=d[e],delete d[e]);t!==void 0&&(d.x=t),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&gd(d,i,a,o,!1)}var yd=new Set([`baseFrequency`,`diffuseConstant`,`kernelMatrix`,`kernelUnitLength`,`keySplines`,`keyTimes`,`limitingConeAngle`,`markerHeight`,`markerWidth`,`numOctaves`,`targetX`,`targetY`,`surfaceScale`,`specularConstant`,`specularExponent`,`stdDeviation`,`tableValues`,`viewBox`,`gradientTransform`,`pathLength`,`startOffset`,`textLength`,`lengthAdjust`]),bd=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function xd(e,t,n,r){ad(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(yd.has(n)?n:Xc(n),t.attrs[n])}function Sd(e,t,n){let r=dd(e,t,n);for(let n in e)if(qc(e[n])||qc(t[n])){let t=Os.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var Cd=class extends Mu{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=mu}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(ks.has(t)){let e=_l(t);return e&&e.default||0}return t=yd.has(t)?t:Xc(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return Sd(e,t,n)}build(e,t,n){vd(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){xd(e,t,n,r)}mount(e){this.isSVGTag=bd(e.tagName),super.mount(e)}},wd=yu.length;function Td(e){if(!e)return;if(!e.isControllingVariants){let t=e.parent&&Td(e.parent)||{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}let t={};for(let n=0;n<wd;n++){let r=yu[n],i=e.props[r];(_u(i)||i===!1)&&(t[r]=i)}return t}function Ed(e,t){if(!Array.isArray(t))return!1;let n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}var Dd=[...vu].reverse(),Od=vu.length;function kd(e){return t=>Promise.all(t.map(({animation:t,options:n})=>rl(e,t,n)))}function Ad(e){let t=kd(e),n=Nd(),r=!0,i=!1,a=t=>(n,r)=>{let i=Ic(e,r,t===`exit`?e.presenceContext?.custom:void 0);if(i){let{transition:e,transitionEnd:t,...r}=i;n={...n,...r,...t}}return n};function o(n){t=n(e)}function s(o){let{props:s}=e,c=Td(e.parent)||{},l=[],u=new Set,d={},f=1/0;for(let t=0;t<Od;t++){let p=Dd[t],m=n[p],h=s[p]===void 0?c[p]:s[p],g=_u(h),_=p===o?m.isActive:null;_===!1&&(f=t);let v=h===c[p]&&h!==s[p]&&g;if(v&&(r||i)&&e.manuallyAnimateOnMount&&(v=!1),m.protectedKeys={...d},!m.isActive&&_===null||!h&&!m.prevProp||gu(h)||typeof h==`boolean`)continue;if(p===`exit`&&m.isActive&&_!==!0){m.prevResolvedValues&&(d={...d,...m.prevResolvedValues});continue}let y=jd(m.prevProp,h),b=y||p===o&&m.isActive&&!v&&g||t>f&&g,x=!1,S=Array.isArray(h)?h:[h],C=S.reduce(a(p),{});_===!1&&(C={});let{prevResolvedValues:w={}}=m,T={...w,...C},E=t=>{b=!0,u.has(t)&&(x=!0,u.delete(t)),m.needsAnimating[t]=!0;let n=e.getValue(t);n&&(n.liveStyle=!1)};for(let e in T){let t=C[e],n=w[e];if(d.hasOwnProperty(e))continue;let r=!1;r=Uc(t)&&Uc(n)?!Ed(t,n):t!==n,r?t==null?u.add(e):E(e):t!==void 0&&u.has(e)?E(e):m.protectedKeys[e]=!0}m.prevProp=h,m.prevResolvedValues=C,m.isActive&&(d={...d,...C}),(r||i)&&e.blockInitialAnimation&&(b=!1);let ee=v&&y;b&&(!ee||x)&&l.push(...S.map(t=>{let n={type:p};if(typeof t==`string`&&(r||i)&&!ee&&e.manuallyAnimateOnMount&&e.parent){let{parent:r}=e,i=Ic(r,t);if(r.enteringChildren&&i){let{delayChildren:t}=i.transition||{};n.delay=yc(r.enteringChildren,e,t)}}return{animation:t,options:n}}))}if(u.size){let t={};if(typeof s.initial!=`boolean`){let n=Ic(e,Array.isArray(s.initial)?s.initial[0]:s.initial);n&&n.transition&&(t.transition=n.transition)}u.forEach(n=>{let r=e.getBaseTarget(n),i=e.getValue(n);i&&(i.liveStyle=!0),t[n]=r??null}),l.push({animation:t})}let p=!!l.length;return r&&(s.initial===!1||s.initial===s.animate)&&!e.manuallyAnimateOnMount&&(p=!1),r=!1,i=!1,p?t(l):Promise.resolve()}function c(t,r){if(n[t].isActive===r)return Promise.resolve();e.variantChildren?.forEach(e=>e.animationState?.setActive(t,r)),n[t].isActive=r;let i=s(t);for(let e in n)n[e].protectedKeys={};return i}return{animateChanges:s,setActive:c,setAnimateFunction:o,getState:()=>n,reset:()=>{n=Nd(),i=!0}}}function jd(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!Ed(t,e):!1}function Md(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Nd(){return{animate:Md(!0),whileInView:Md(),whileHover:Md(),whileTap:Md(),whileDrag:Md(),whileFocus:Md(),exit:Md()}}function Pd(e,t){e.min=t.min,e.max=t.max}function Fd(e,t){Pd(e.x,t.x),Pd(e.y,t.y)}function Id(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var Ld=1e-4,Rd=1-Ld,zd=1+Ld,Bd=.01,Vd=0-Bd,Hd=0+Bd;function Ud(e){return e.max-e.min}function Wd(e,t,n){return Math.abs(e-t)<=n}function Gd(e,t,n,r=.5){e.origin=r,e.originPoint=X(t.min,t.max,e.origin),e.scale=Ud(n)/Ud(t),e.translate=X(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Rd&&e.scale<=zd||isNaN(e.scale))&&(e.scale=1),(e.translate>=Vd&&e.translate<=Hd||isNaN(e.translate))&&(e.translate=0)}function Kd(e,t,n,r){Gd(e.x,t.x,n.x,r?r.originX:void 0),Gd(e.y,t.y,n.y,r?r.originY:void 0)}function qd(e,t,n,r=0){e.min=(r?X(n.min,n.max,r):n.min)+t.min,e.max=e.min+Ud(t)}function Jd(e,t,n,r){qd(e.x,t.x,n.x,r?.x),qd(e.y,t.y,n.y,r?.y)}function Yd(e,t,n,r=0){let i=r?X(n.min,n.max,r):n.min;e.min=t.min-i,e.max=e.min+Ud(t)}function Xd(e,t,n,r){Yd(e.x,t.x,n.x,r?.x),Yd(e.y,t.y,n.y,r?.y)}function Zd(e,t,n,r,i){return e-=t,e=Hu(e,1/n,r),i!==void 0&&(e=Hu(e,1/i,r)),e}function Qd(e,t=0,n=1,r=.5,i,a=e,o=e){if(Za.test(t)&&(t=parseFloat(t),t=X(o.min,o.max,t/100)-o.min),typeof t!=`number`)return;let s=X(a.min,a.max,r);e===a&&(s-=t),e.min=Zd(e.min,t,n,s,i),e.max=Zd(e.max,t,n,s,i)}function $d(e,t,[n,r,i],a,o){Qd(e,t[n],t[r],t[i],t.scale,a,o)}var ef=[`x`,`scaleX`,`originX`],tf=[`y`,`scaleY`,`originY`];function nf(e,t,n,r){$d(e.x,t,ef,n?n.x:void 0,r?r.x:void 0),$d(e.y,t,tf,n?n.y:void 0,r?r.y:void 0)}function rf(e){return e.translate===0&&e.scale===1}function af(e){return rf(e.x)&&rf(e.y)}function of(e,t){return e.min===t.min&&e.max===t.max}function sf(e,t){return of(e.x,t.x)&&of(e.y,t.y)}function cf(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function lf(e,t){return cf(e.x,t.x)&&cf(e.y,t.y)}function uf(e){return Ud(e.x)/Ud(e.y)}function df(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function ff(e){return[e(`x`),e(`y`)]}function pf(e,t,n){let r=``,i=e.x.translate/t.x,a=e.y.translate/t.y,o=n?.z||0;if((i||a||o)&&(r=`translate3d(${i}px, ${a}px, ${o}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){let{transformPerspective:e,rotate:t,rotateX:i,rotateY:a,skewX:o,skewY:s}=n;e&&(r=`perspective(${e}px) ${r}`),t&&(r+=`rotate(${t}deg) `),i&&(r+=`rotateX(${i}deg) `),a&&(r+=`rotateY(${a}deg) `),o&&(r+=`skewX(${o}deg) `),s&&(r+=`skewY(${s}deg) `)}let s=e.x.scale*t.x,c=e.y.scale*t.y;return(s!==1||c!==1)&&(r+=`scale(${s}, ${c})`),r||`none`}var mf=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`],hf=mf.length,gf=e=>typeof e==`string`?parseFloat(e):e,_f=e=>typeof e==`number`||Y.test(e);function vf(e,t,n,r,i,a){i?(e.opacity=X(0,n.opacity??1,bf(r)),e.opacityExit=X(t.opacity??1,0,xf(r))):a&&(e.opacity=X(t.opacity??1,n.opacity??1,r));for(let i=0;i<hf;i++){let a=mf[i],o=yf(t,a),s=yf(n,a);o===void 0&&s===void 0||(o||=0,s||=0,o===0||s===0||_f(o)===_f(s)?(e[a]=Math.max(X(gf(o),gf(s),r),0),(Za.test(s)||Za.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=X(t.rotate||0,n.rotate||0,r))}function yf(e,t){return e[t]===void 0?e.borderRadius:e[t]}var bf=Sf(0,.5,sa),xf=Sf(.5,.95,zi);function Sf(e,t,n){return r=>r<e?0:r>t?1:n(Hi(e,t,r))}function Cf(e,t,n){let r=qc(e)?e:Hc(e);return r.start(Nc(``,r,t,n)),r.animation}function wf(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}var Tf=(e,t)=>e.depth-t.depth,Ef=class{constructor(){this.children=[],this.isDirty=!1}add(e){Oi(this.children,e),this.isDirty=!0}remove(e){ki(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Tf),this.isDirty=!1,this.children.forEach(e)}};function Df(e,t){let n=Da.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(Sa(r),e(a-t))};return J.setup(r,!0),()=>Sa(r)}function Of(e){return qc(e)?e.get():e}var kf=class{constructor(){this.members=[]}add(e){Oi(this.members,e);for(let t=this.members.length-1;t>=0;t--){let n=this.members[t];if(n===e||n===this.lead||n===this.prevLead)continue;let r=n.instance;(!r||r.isConnected===!1)&&!n.snapshot&&(ki(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(ki(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){let e=this.members[this.members.length-1];e&&this.promote(e)}}relegate(e){for(let t=this.members.indexOf(e)-1;t>=0;t--){let e=this.members[t];if(e.isPresent!==!1&&e.instance?.isConnected!==!1)return this.promote(e),!0}return!1}promote(e,t){let n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.updateSnapshot(),e.scheduleRender();let{layoutDependency:r}=n.options,{layoutDependency:i}=e.options;(r===void 0||r!==i)&&(e.resumeFrom=n,t&&(n.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root?.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{e.options.onExitComplete?.(),e.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}},Af={hasAnimatedSinceResize:!0,hasEverUpdated:!1},jf={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},Mf=[``,`X`,`Y`,`Z`],Nf=1e3,Pf=0;function Ff(e,t,n,r){let{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function If(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=Qc(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,J,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&If(r)}function Lf({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=Pf++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,va.value&&(jf.nodes=jf.calculatedTargetDeltas=jf.calculatedProjections=0),this.nodes.forEach(Bf),this.nodes.forEach(Yf),this.nodes.forEach(Xf),this.nodes.forEach(Vf),va.addProjectionMetrics&&va.addProjectionMetrics(jf)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let e=0;e<this.path.length;e++)this.path[e].shouldResetTransform=!0;this.root===this&&(this.nodes=new Ef)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new Ui),this.eventHandlers.get(e).add(t)}notifyListeners(e,...t){let n=this.eventHandlers.get(e);n&&n.notify(...t)}hasListeners(e){return this.eventHandlers.has(e)}mount(t){if(this.instance)return;this.isSVG=ql(t)&&!cu(t),this.instance=t;let{layoutId:n,layout:r,visualElement:i}=this.options;if(i&&!i.current&&i.mount(t),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(r||n)&&(this.isLayoutDirty=!0),e){let n,r=0,i=()=>this.root.updateBlockedByResize=!1;J.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=Df(i,250),Af.hasAnimatedSinceResize&&(Af.hasAnimatedSinceResize=!1,this.nodes.forEach(Jf)))})}n&&this.root.registerSharedNode(n,this),this.options.animate!==!1&&i&&(n||r)&&this.addEventListener(`didUpdate`,({delta:e,hasLayoutChanged:t,hasRelativeLayoutChanged:n,layout:r})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}let a=this.options.transition||i.getDefaultTransition()||rp,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!lf(this.targetLayout,r),l=!t&&n;if(this.options.layoutRoot||this.resumeFrom||l||t&&(c||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);let t={...Ac(a,`layout`),onPlay:o,onComplete:s};(i.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t),this.setAnimationOrigin(e,l)}else t||Jf(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=r})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);let e=this.getStack();e&&e.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Sa(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Zf),this.animationId++)}getTransformTemplate(){let{visualElement:e}=this.options;return e&&e.getProps().transformTemplate}willUpdate(e=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&If(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let e=0;e<this.path.length;e++){let t=this.path[e];t.shouldResetTransform=!0,(typeof t.latestValues.x==`string`||typeof t.latestValues.y==`string`)&&(t.isLayoutDirty=!0),t.updateScroll(`snapshot`),t.options.layoutRoot&&t.willUpdate(!1)}let{layoutId:t,layout:n}=this.options;if(t===void 0&&!n)return;let r=this.getTransformTemplate();this.prevTransformTemplateValue=r?r(this.latestValues,``):void 0,this.updateSnapshot(),e&&this.notifyListeners(`willUpdate`)}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){let e=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),e&&this.nodes.forEach(Wf),this.nodes.forEach(Uf);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Gf);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Kf),this.nodes.forEach(qf),this.nodes.forEach(Rf),this.nodes.forEach(zf)):this.nodes.forEach(Gf),this.clearAllSnapshots();let e=Da.now();Ca.delta=Ai(0,1e3/60,e-Ca.timestamp),Ca.timestamp=e,Ca.isProcessing=!0,wa.update.process(Ca),wa.preRender.process(Ca),wa.render.process(Ca),Ca.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,El.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Hf),this.sharedNodes.forEach(Qf)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,J.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){J.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ud(this.snapshot.measuredBox.x)&&!Ud(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let e=0;e<this.path.length;e++)this.path[e].updateScroll();let e=this.layout;this.layout=this.measure(!1),this.layoutVersion++,this.layoutCorrected||=mu(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners(`measure`,this.layout.layoutBox);let{visualElement:t}=this.options;t&&t.notify(`LayoutMeasure`,this.layout.layoutBox,e?e.layoutBox:void 0)}updateScroll(e=`measure`){let t=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===e&&(t=!1),t&&this.instance){let t=r(this.instance);this.scroll={animationId:this.root.animationId,phase:e,isRoot:t,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:t}}}resetTransform(){if(!i)return;let e=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,t=this.projectionDelta&&!af(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||zu(this.latestValues)||a)&&(i(this.instance,r),this.shouldResetTransform=!1,this.scheduleRender())}measure(e=!0){let t=this.measurePageBox(),n=this.removeElementScroll(t);return e&&(n=this.removeTransform(n)),sp(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return mu();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(lp))){let{scroll:e}=this.root;e&&(Yu(t.x,e.offset.x),Yu(t.y,e.offset.y))}return t}removeElementScroll(e){let t=mu();if(Fd(t,e),this.scroll?.wasRoot)return t;for(let n=0;n<this.path.length;n++){let r=this.path[n],{scroll:i,options:a}=r;r!==this.root&&i&&a.layoutScroll&&(i.wasRoot&&Fd(t,e),Yu(t.x,i.offset.x),Yu(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||mu();Fd(r,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];!t&&n.options.layoutScroll&&n.scroll&&n!==n.root&&(Yu(r.x,-n.scroll.offset.x),Yu(r.y,-n.scroll.offset.y)),zu(n.latestValues)&&Qu(r,n.latestValues,n.layout?.layoutBox)}return zu(this.latestValues)&&Qu(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=mu();Fd(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!zu(n.latestValues))continue;let r;n.instance&&(Ru(n.latestValues)&&n.updateSnapshot(),r=mu(),Fd(r,n.measurePageBox())),nf(t,n.latestValues,n.snapshot?.layoutBox,r)}return zu(this.latestValues)&&nf(t,this.latestValues),t}setTargetDelta(e){this.targetDelta=e,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(e){this.options={...this.options,...e,crossfade:e.crossfade===void 0?!0:e.crossfade}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Ca.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(e=!1){let t=this.getLead();this.isProjectionDirty||=t.isProjectionDirty,this.isTransformDirty||=t.isTransformDirty,this.isSharedProjectionDirty||=t.isSharedProjectionDirty;let n=!!this.resumingFrom||this!==t;if(!(e||n&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;let{layout:r,layoutId:i}=this.options;if(!this.layout||!(r||i))return;this.resolvedRelativeTargetAt=Ca.timestamp;let a=this.getClosestProjectingParent();a&&this.linkedParentVersion!==a.layoutVersion&&!a.options.layoutRoot&&this.removeRelativeTarget(),!this.targetDelta&&!this.relativeTarget&&(this.options.layoutAnchor!==!1&&a&&a.layout?this.createRelativeTarget(a,this.layout.layoutBox,a.layout.layoutBox):this.removeRelativeTarget()),!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=mu(),this.targetWithTransforms=mu()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Jd(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):Fd(this.target,this.layout.layoutBox),Gu(this.target,this.targetDelta)):Fd(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget&&(this.attemptToResolveRelativeTarget=!1,this.options.layoutAnchor!==!1&&a&&!!a.resumingFrom==!!this.resumingFrom&&!a.options.layoutScroll&&a.target&&this.animationProgress!==1?this.createRelativeTarget(a,this.target,a.target):this.relativeParent=this.relativeTarget=void 0),va.value&&jf.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||Ru(this.parent.latestValues)||Bu(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}createRelativeTarget(e,t,n){this.relativeParent=e,this.linkedParentVersion=e.layoutVersion,this.forceRelativeParentToResolveTarget(),this.relativeTarget=mu(),this.relativeTargetOrigin=mu(),Xd(this.relativeTargetOrigin,t,n,this.options.layoutAnchor||void 0),Fd(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){let e=this.getLead(),t=!!this.resumingFrom||this!==e,n=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(n=!1),t&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(n=!1),this.resolvedRelativeTargetAt===Ca.timestamp&&(n=!1),n)return;let{layout:r,layoutId:i}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(r||i))return;Fd(this.layoutCorrected,this.layout.layoutBox);let a=this.treeScale.x,o=this.treeScale.y;Ju(this.layoutCorrected,this.treeScale,this.path,t),e.layout&&!e.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(e.target=e.layout.layoutBox,e.targetWithTransforms=mu());let{target:s}=e;if(!s){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Id(this.prevProjectionDelta.x,this.projectionDelta.x),Id(this.prevProjectionDelta.y,this.projectionDelta.y)),Kd(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!df(this.projectionDelta.x,this.prevProjectionDelta.x)||!df(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),va.value&&jf.calculatedProjections++}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){if(this.options.visualElement?.scheduleRender(),e){let e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=fu(),this.projectionDelta=fu(),this.projectionDeltaWithTransform=fu()}setAnimationOrigin(e,t=!1){let n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},a=fu();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let o=mu(),s=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),c=this.getStack(),l=!c||c.members.length<=1,u=!!(s&&!l&&this.options.crossfade===!0&&!this.path.some(np));this.animationProgress=0;let d;this.mixTargetDelta=t=>{let n=t/1e3;$f(a.x,e.x,n),$f(a.y,e.y,n),this.setTargetDelta(a),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Xd(o,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),tp(this.relativeTarget,this.relativeTargetOrigin,o,n),d&&sf(this.relativeTarget,d)&&(this.isProjectionDirty=!1),d||=mu(),Fd(d,this.relativeTarget)),s&&(this.animationValues=i,vf(i,r,this.latestValues,n,u,l)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=n},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(e){this.notifyListeners(`animationStart`),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&=(Sa(this.pendingAnimation),void 0),this.pendingAnimation=J.update(()=>{Af.hasAnimatedSinceResize=!0,Oa.layout++,this.motionValue||=Hc(0),this.motionValue.jump(0,!1),this.currentAnimation=Cf(this.motionValue,[0,1e3],{...e,velocity:0,isSync:!0,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onStop:()=>{Oa.layout--},onComplete:()=>{Oa.layout--,e.onComplete&&e.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);let e=this.getStack();e&&e.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners(`animationComplete`)}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Nf),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){let e=this.getLead(),{targetWithTransforms:t,target:n,layout:r,latestValues:i}=e;if(!(!t||!n||!r)){if(this!==e&&this.layout&&r&&cp(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||mu();let t=Ud(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;let r=Ud(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}Fd(t,n),Qu(t,i),Kd(this.projectionDeltaWithTransform,this.layoutCorrected,t,i)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new kf),this.sharedNodes.get(e).add(t);let n=t.options.initialPromotionConfig;t.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(t):void 0})}isLead(){let e=this.getStack();return e?e.lead===this:!0}getLead(){let{layoutId:e}=this.options;return e&&this.getStack()?.lead||this}getPrevLead(){let{layoutId:e}=this.options;return e?this.getStack()?.prevLead:void 0}getStack(){let{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:n}={}){let r=this.getStack();r&&r.promote(this,n),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){let e=this.getStack();return e?e.relegate(this):!1}resetSkewAndRotation(){let{visualElement:e}=this.options;if(!e)return;let t=!1,{latestValues:n}=e;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(t=!0),!t)return;let r={};n.z&&Ff(`z`,e,r,this.animationValues);for(let t=0;t<Mf.length;t++)Ff(`rotate${Mf[t]}`,e,r,this.animationValues),Ff(`skew${Mf[t]}`,e,r,this.animationValues);e.render();for(let t in r)e.setStaticValue(t,r[t]),this.animationValues&&(this.animationValues[t]=r[t]);e.scheduleRender()}applyProjectionStyles(e,t){if(!this.instance||this.isSVG)return;if(!this.isVisible){e.visibility=`hidden`;return}let n=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,e.visibility=``,e.opacity=``,e.pointerEvents=Of(t?.pointerEvents)||``,e.transform=n?n(this.latestValues,``):`none`;return}let r=this.getLead();if(!this.projectionDelta||!this.layout||!r.target){this.options.layoutId&&(e.opacity=this.latestValues.opacity===void 0?1:this.latestValues.opacity,e.pointerEvents=Of(t?.pointerEvents)||``),this.hasProjected&&!zu(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=pf(this.projectionDeltaWithTransform,this.treeScale,i);n&&(a=n(i,a)),e.transform=a;let{x:o,y:s}=this.projectionDelta;e.transformOrigin=`${o.origin*100}% ${s.origin*100}% 0`,r.animationValues?e.opacity=r===this?i.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:i.opacityExit:e.opacity=r===this?i.opacity===void 0?``:i.opacity:i.opacityExit===void 0?0:i.opacityExit;for(let t in ld){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=ld[t],c=a===`none`?i[t]:n(i[t],r);if(o){let t=o.length;for(let n=0;n<t;n++)e[o[n]]=c}else s?this.options.visualElement.renderState.vars[t]=c:e[t]=c}this.options.layoutId&&(e.pointerEvents=r===this?Of(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(Uf),this.root.sharedNodes.clear()}}}function Rf(e){e.updateLayout()}function zf(e){let t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners(`didUpdate`)){let{layoutBox:n,measuredBox:r}=e.layout,{animationType:i}=e.options,a=t.source!==e.layout.source;if(i===`size`)ff(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=Ud(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;Pd(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else cp(i,t.layoutBox,n)&&ff(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=Ud(n[r]);i.max=i.min+o,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[r].max=e.relativeTarget[r].min+o)});let o=fu();Kd(o,n,t.layoutBox);let s=fu();a?Kd(s,e.applyTransform(r,!0),t.measuredBox):Kd(s,n,t.layoutBox);let c=!af(o),l=!1;if(!e.resumeFrom){let r=e.getClosestProjectingParent();if(r&&!r.resumeFrom){let{snapshot:i,layout:a}=r;if(i&&a){let o=e.options.layoutAnchor||void 0,s=mu();Xd(s,t.layoutBox,i.layoutBox,o);let c=mu();Xd(c,n,a.layoutBox,o),lf(s,c)||(l=!0),r.options.layoutRoot&&(e.relativeTarget=c,e.relativeTargetOrigin=s,e.relativeParent=r)}}}e.notifyListeners(`didUpdate`,{layout:n,snapshot:t,delta:s,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:l})}else if(e.isLead()){let{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function Bf(e){va.value&&jf.nodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty),e.isTransformDirty||=e.parent.isTransformDirty)}function Vf(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Hf(e){e.clearSnapshot()}function Uf(e){e.clearMeasurements()}function Wf(e){e.isLayoutDirty=!0,e.updateLayout()}function Gf(e){e.isLayoutDirty=!1}function Kf(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function qf(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function Jf(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Yf(e){e.resolveTargetDelta()}function Xf(e){e.calcProjection()}function Zf(e){e.resetSkewAndRotation()}function Qf(e){e.removeLeadSnapshot()}function $f(e,t,n){e.translate=X(t.translate,0,n),e.scale=X(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function ep(e,t,n,r){e.min=X(t.min,n.min,r),e.max=X(t.max,n.max,r)}function tp(e,t,n,r){ep(e.x,t.x,n.x,r),ep(e.y,t.y,n.y,r)}function np(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var rp={duration:.45,ease:[.4,0,.1,1]},ip=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),ap=ip(`applewebkit/`)&&!ip(`chrome/`)?Math.round:zi;function op(e){e.min=ap(e.min),e.max=ap(e.max)}function sp(e){op(e.x),op(e.y)}function cp(e,t,n){return e===`position`||e===`preserve-aspect`&&!Wd(uf(t),uf(n),.2)}function lp(e){return e!==e.root&&e.scroll?.wasRoot}var up=Lf({attachResizeListener:(e,t)=>wf(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),dp={current:void 0},fp=Lf({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!dp.current){let e=new up({});e.mount(window),e.setOptions({layoutScroll:!0}),dp.current=e}return dp.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),pp=(0,d.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function mp(e=!0){let t=(0,d.useContext)(Di);if(t===null)return[!0,null];let{isPresent:n,onExitComplete:r,register:i}=t,a=(0,d.useId)();(0,d.useEffect)(()=>{if(e)return i(a)},[e]);let o=(0,d.useCallback)(()=>e&&r&&r(a),[a,r,e]);return!n&&r?[!1,o]:[!0]}var hp=(0,d.createContext)({strict:!1}),gp={animation:[`animate`,`variants`,`whileHover`,`whileTap`,`exit`,`whileInView`,`whileFocus`,`whileDrag`],exit:[`exit`],drag:[`drag`,`dragControls`],focus:[`whileFocus`],hover:[`whileHover`,`onHoverStart`,`onHoverEnd`],tap:[`whileTap`,`onTap`,`onTapStart`,`onTapCancel`],pan:[`onPan`,`onPanStart`,`onPanSessionStart`,`onPanEnd`],inView:[`whileInView`,`onViewportEnter`,`onViewportLeave`],layout:[`layout`,`layoutId`]},_p=!1;function vp(){if(_p)return;let e={};for(let t in gp)e[t]={isEnabled:e=>gp[t].some(t=>!!e[t])};ku(e),_p=!0}function yp(){return vp(),Au()}function bp(e){let t=yp();for(let n in e)t[n]={...t[n],...e[n]};ku(t)}var xp=new Set(`animate.exit.variants.initial.style.values.variants.transition.transformTemplate.custom.inherit.onBeforeLayoutMeasure.onAnimationStart.onAnimationComplete.onUpdate.onDragStart.onDrag.onDragEnd.onMeasureDragConstraints.onDirectionLock.onDragTransitionEnd._dragX._dragY.onHoverStart.onHoverEnd.onViewportEnter.onViewportLeave.globalTapTarget.propagate.ignoreStrict.viewport`.split(`.`));function Sp(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||xp.has(e)}var Cp=s({default:()=>wp}),wp,Tp=o((()=>{throw wp={},Error(`Could not resolve "@emotion/is-prop-valid" imported by "framer-motion". Is it installed?`)})),Ep=e=>!Sp(e);function Dp(e){typeof e==`function`&&(Ep=t=>t.startsWith(`on`)?!Sp(t):e(t))}try{Dp((Tp(),u(Cp)).default)}catch{}function Op(e,t,n){let r={};for(let i in e)i===`values`&&typeof e.values==`object`||qc(e[i])||(Ep(i)||n===!0&&Sp(i)||!t&&!Sp(i)||e.draggable&&i.startsWith(`onDrag`))&&(r[i]=e[i]);return r}var kp=(0,d.createContext)({});function Ap(e,t){if(bu(e)){let{initial:t,animate:n}=e;return{initial:t===!1||_u(t)?t:void 0,animate:_u(n)?n:void 0}}return e.inherit===!1?{}:t}function jp(e){let{initial:t,animate:n}=Ap(e,(0,d.useContext)(kp));return(0,d.useMemo)(()=>({initial:t,animate:n}),[Mp(t),Mp(n)])}function Mp(e){return Array.isArray(e)?e.join(` `):e}var Np=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Pp(e,t,n){for(let r in t)!qc(t[r])&&!ud(r,n)&&(e[r]=t[r])}function Fp({transformTemplate:e},t){return(0,d.useMemo)(()=>{let n=Np();return id(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Ip(e,t){let n=e.style||{},r={};return Pp(r,n,e),Object.assign(r,Fp(e,t)),r}function Lp(e,t){let n={},r=Ip(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout=`none`,r.touchAction=e.drag===!0?`none`:`pan-${e.drag===`x`?`y`:`x`}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=r,n}var Rp=()=>({...Np(),attrs:{}});function zp(e,t,n,r){let i=(0,d.useMemo)(()=>{let n=Rp();return vd(n,t,bd(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};Pp(t,e.style,e),i.style={...t,...i.style}}return i}var Bp=[`animate`,`circle`,`defs`,`desc`,`ellipse`,`g`,`image`,`line`,`filter`,`marker`,`mask`,`metadata`,`path`,`pattern`,`polygon`,`polyline`,`rect`,`stop`,`switch`,`symbol`,`svg`,`text`,`tspan`,`use`,`view`];function Vp(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(Bp.indexOf(e)>-1||/[A-Z]/u.test(e))}function Hp(e,t,n,{latestValues:r},i,a=!1,o){let s=(o??Vp(e)?zp:Lp)(t,r,i,e),c=Op(t,typeof e==`string`,a),l=e===d.Fragment?{}:{...c,...s,ref:n},{children:u}=t,f=(0,d.useMemo)(()=>qc(u)?u.get():u,[u]);return(0,d.createElement)(e,{...l,children:f})}function Up({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:Wp(n,r,i,e),renderState:t()}}function Wp(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=Of(a[e]);let{initial:o,animate:s}=e,c=bu(e),l=xu(e);t&&l&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),s===void 0&&(s=t.animate));let u=n?n.initial===!1:!1;u||=o===!1;let d=u?s:o;if(d&&typeof d!=`boolean`&&!gu(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=Fc(e,t[n]);if(r){let{transitionEnd:e,transition:t,...n}=r;for(let e in n){let t=n[e];if(Array.isArray(t)){let e=u?t.length-1:0;t=t[e]}t!==null&&(i[e]=t)}for(let t in e)i[t]=e[t]}}}return i}var Gp=e=>(t,n)=>{let r=(0,d.useContext)(kp),i=(0,d.useContext)(Di),a=()=>Up(e,t,r,i);return n?a():Ti(a)},Kp=Gp({scrapeMotionValuesFromProps:dd,createRenderState:Np}),qp=Gp({scrapeMotionValuesFromProps:Sd,createRenderState:Rp}),Jp=Symbol.for(`motionComponentSymbol`);function Yp(e,t,n){let r=(0,d.useRef)(n);(0,d.useInsertionEffect)(()=>{r.current=n});let i=(0,d.useRef)(null);return(0,d.useCallback)(n=>{n&&e.onMount?.(n);let a=r.current;if(typeof a==`function`)if(n){let e=a(n);typeof e==`function`&&(i.current=e)}else i.current?(i.current(),i.current=null):a(n);else a&&(a.current=n);t&&(n?t.mount(n):t.unmount())},[t])}var Xp=(0,d.createContext)({});function Zp(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function Qp(e,t,n,r,i,a){let{visualElement:o}=(0,d.useContext)(kp),s=(0,d.useContext)(hp),c=(0,d.useContext)(Di),l=(0,d.useContext)(pp),u=l.reducedMotion,f=l.skipAnimations,p=(0,d.useRef)(null),m=(0,d.useRef)(!1);r||=s.renderer,!p.current&&r&&(p.current=r(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:f,isSVG:a}),m.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));let h=p.current,g=(0,d.useContext)(Xp);h&&!h.projection&&i&&(h.type===`html`||h.type===`svg`)&&$p(p.current,n,i,g);let _=(0,d.useRef)(!1);(0,d.useInsertionEffect)(()=>{h&&_.current&&h.update(n,c)});let v=n[Zc],y=(0,d.useRef)(!!v&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(v)&&window.MotionHasOptimisedAnimation?.(v));return Ei(()=>{m.current=!0,h&&(_.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),h.scheduleRenderMicrotask(),y.current&&h.animationState&&h.animationState.animateChanges())}),(0,d.useEffect)(()=>{h&&(!y.current&&h.animationState&&h.animationState.animateChanges(),y.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(v)}),!1),h.enteringChildren=void 0)}),h}function $p(e,t,n,r){let{layoutId:i,layout:a,drag:o,dragConstraints:s,layoutScroll:c,layoutRoot:l,layoutAnchor:u,layoutCrossfade:d}=t;e.projection=new n(e.latestValues,t[`data-framer-portal-id`]?void 0:em(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&Zp(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function em(e){if(e)return e.options.allowProjection===!1?em(e.parent):e.projection}function tm(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&bp(r);let a=n?n===`svg`:Vp(e),o=a?qp:Kp;function s(n,s){let c,l={...(0,d.useContext)(pp),...n,layoutId:nm(n)},{isStatic:u}=l,p=jp(n),m=o(n,u);if(!u&&typeof window<`u`){rm(l,r);let t=im(l);c=t.MeasureLayout,p.visualElement=Qp(e,m,l,i,t.ProjectionNode,a)}return(0,f.jsxs)(kp.Provider,{value:p,children:[c&&p.visualElement?(0,f.jsx)(c,{visualElement:p.visualElement,...l}):null,Hp(e,n,Yp(m,p.visualElement,s),m,u,t,a)]})}s.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let c=(0,d.forwardRef)(s);return c[Jp]=e,c}function nm({layoutId:e}){let t=(0,d.useContext)(wi).id;return t&&e!==void 0?t+`-`+e:e}function rm(e,t){let n=(0,d.useContext)(hp).strict;if(process.env.NODE_ENV!==`production`&&t&&n){let t="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?Mi(!1,t,`lazy-strict-mode`):Ni(!1,t,`lazy-strict-mode`)}}function im(e){let{drag:t,layout:n}=yp();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function am(e,t){if(typeof Proxy>`u`)return tm;let n=new Map,r=(n,r)=>tm(n,r,e,t);return new Proxy((e,t)=>(process.env.NODE_ENV!==`production`&&Ji(!1,`motion() is deprecated. Use motion.create() instead.`),r(e,t)),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,tm(a,void 0,e,t)),n.get(a))})}var om=(e,t)=>t.isSVG??Vp(e)?new Cd(t):new pd(t,{allowProjection:e!==d.Fragment}),sm=class extends Nu{constructor(e){super(e),e.animationState||=Ad(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();gu(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){let{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}},cm=0,lm={animation:{Feature:sm},exit:{Feature:class extends Nu{constructor(){super(...arguments),this.id=cm++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;let{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;if(e&&n===!1){if(this.isExitComplete){let{initial:e,custom:t}=this.node.getProps();if(typeof e==`string`){let n=Ic(this.node,e,t);if(n){let{transition:e,transitionEnd:t,...r}=n;for(let e in r)this.node.getValue(e)?.jump(r[e])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive(`exit`,!1);this.isExitComplete=!1;return}let r=this.node.animationState.setActive(`exit`,!e);t&&!e&&r.then(()=>{this.isExitComplete=!0,t(this.id)})}mount(){let{register:e,onExitComplete:t}=this.node.presenceContext||{};t&&t(this.id),e&&(this.unmount=e(this.id))}unmount(){}}}};function um(e){return{point:{x:e.pageX,y:e.pageY}}}var dm=e=>t=>Fl(t)&&e(t,um(t));function fm(e,t,n,r){return wf(e,t,dm(n),r)}var pm=({current:e})=>e?e.ownerDocument.defaultView:null,mm=(e,t)=>Math.abs(e-t);function hm(e,t){let n=mm(e.x,t.x),r=mm(e.y,t.y);return Math.sqrt(n**2+r**2)}var gm=new Set([`auto`,`scroll`]),_m=class{constructor(e,t,{transformPagePoint:n,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:a=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=e=>{this.handleScroll(e.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=vm(this.lastRawMoveEventInfo,this.transformPagePoint));let e=bm(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=hm(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e,{timestamp:i}=Ca;this.history.push({...r,timestamp:i});let{onStart:a,onMove:o}=this.handlers;t||(a&&a(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),o&&o(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastRawMoveEventInfo=t,this.lastMoveEventInfo=vm(t,this.transformPagePoint),J.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.end();let{onEnd:n,onSessionEnd:r,resumeAnimation:i}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&i&&i(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let a=bm(e.type===`pointercancel`?this.lastMoveEventInfo:vm(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,a),r&&r(e,a)},!Fl(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.distanceThreshold=a,this.contextWindow=r||window;let s=vm(um(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=Ca;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,bm(s,this.history)),this.removeListeners=Vi(fm(this.contextWindow,`pointermove`,this.handlePointerMove),fm(this.contextWindow,`pointerup`,this.handlePointerUp),fm(this.contextWindow,`pointercancel`,this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let t=e.parentElement;for(;t;){let e=getComputedStyle(t);(gm.has(e.overflowX)||gm.has(e.overflowY))&&this.scrollPositions.set(t,{x:t.scrollLeft,y:t.scrollTop}),t=t.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.addEventListener(`scroll`,this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener(`scroll`,this.onElementScroll,{capture:!0}),window.removeEventListener(`scroll`,this.onWindowScroll)}}handleScroll(e){let t=this.scrollPositions.get(e);if(!t)return;let n=e===window,r=n?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},i={x:r.x-t.x,y:r.y-t.y};i.x===0&&i.y===0||(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(e,r),J.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Sa(this.updatePoint)}};function vm(e,t){return t?{point:t(e.point)}:e}function ym(e,t){return{x:e.x-t.x,y:e.y-t.y}}function bm({point:e},t){return{point:e,delta:ym(e,Sm(t)),offset:ym(e,xm(t)),velocity:Cm(t,.1)}}function xm(e){return e[0]}function Sm(e){return e[e.length-1]}function Cm(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=Sm(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>Wi(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>Wi(t)*2&&(r=e[1]);let a=Gi(i.timestamp-r.timestamp);if(a===0)return{x:0,y:0};let o={x:(i.x-r.x)/a,y:(i.y-r.y)/a};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function wm(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?X(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?X(n,e,r.max):Math.min(e,n)),e}function Tm(e,t,n){return{min:t===void 0?void 0:e.min+t,max:n===void 0?void 0:e.max+n-(e.max-e.min)}}function Em(e,{top:t,left:n,bottom:r,right:i}){return{x:Tm(e.x,n,i),y:Tm(e.y,t,r)}}function Dm(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,r]=[r,n]),{min:n,max:r}}function Om(e,t){return{x:Dm(e.x,t.x),y:Dm(e.y,t.y)}}function km(e,t){let n=.5,r=Ud(e),i=Ud(t);return i>r?n=Hi(t.min,t.max-r,e.min):r>i&&(n=Hi(e.min,e.max-i,t.min)),Ai(0,1,n)}function Am(e,t){let n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}var jm=.35;function Mm(e=jm){return e===!1?e=0:e===!0&&(e=jm),{x:Nm(e,`left`,`right`),y:Nm(e,`top`,`bottom`)}}function Nm(e,t,n){return{min:Pm(e,t),max:Pm(e,n)}}function Pm(e,t){return typeof e==`number`?e:e[t]||0}var Fm=new WeakMap,Im=class{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=mu(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:t=!1,distanceThreshold:n}={}){let{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;let i=e=>{t&&this.snapToCursor(um(e).point),this.stopAnimation()},a=(e,t)=>{let{drag:n,dragPropagation:r,onDragStart:i}=this.getProps();if(n&&!r&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Al(n),!this.openDragLock))return;this.latestPointerEvent=e,this.latestPanInfo=t,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ff(e=>{let t=this.getAxisMotionValue(e).get()||0;if(Za.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=Ud(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&J.update(()=>i(e,t),!1,!0),Yc(this.visualElement,`transform`);let{animationState:a}=this.visualElement;a&&a.setActive(`whileDrag`,!0)},o=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t;let{dragPropagation:n,dragDirectionLock:r,onDirectionLock:i,onDrag:a}=this.getProps();if(!n&&!this.openDragLock)return;let{offset:o}=t;if(r&&this.currentDirection===null){this.currentDirection=Bm(o),this.currentDirection!==null&&i&&i(this.currentDirection);return}this.updateAxis(`x`,t.point,o),this.updateAxis(`y`,t.point,o),this.visualElement.render(),a&&J.update(()=>a(e,t),!1,!0)},s=(e,t)=>{this.latestPointerEvent=e,this.latestPanInfo=t,this.stop(e,t),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>{let{dragSnapToOrigin:e}=this.getProps();(e||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:l}=this.getProps();this.panSession=new _m(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:pm(this.visualElement),element:this.visualElement.current})}stop(e,t){let n=e||this.latestPointerEvent,r=t||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!r||!n)return;let{velocity:a}=r;this.startAnimation(a);let{onDragEnd:o}=this.getProps();o&&J.postRender(()=>o(n,r))}cancel(){this.isDragging=!1;let{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();let{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive(`whileDrag`,!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,t,n){let{drag:r}=this.getProps();if(!n||!zm(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=wm(a,this.constraints[e],this.elastic[e])),i.set(a)}resolveConstraints(){let{dragConstraints:e,dragElastic:t}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;e&&Zp(e)?this.constraints||=this.resolveRefConstraints():e&&n?this.constraints=Em(n.layoutBox,e):this.constraints=!1,this.elastic=Mm(t),r!==this.constraints&&!Zp(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&ff(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=Am(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Zp(e))return!1;let n=e.current;Ni(n!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.",`drag-constraints-ref`);let{projection:r}=this.visualElement;if(!r||!r.layout)return!1;let i=ed(n,r.root,this.visualElement.getTransformPagePoint()),a=Om(r.layout.layoutBox,i);if(t){let e=t(Fu(a));this.hasMutatedConstraints=!!e,e&&(a=Pu(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=ff(o=>{if(!zm(o,t,this.currentDirection))return;let c=s&&s[o]||{};(a===!0||a===o)&&(c={min:0,max:0});let l=r?200:1e6,u=r?40:1e7,d={type:`inertia`,velocity:n?e[o]:0,bounceStiffness:l,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...c};return this.startAxisValueAnimation(o,d)});return Promise.all(c).then(o)}startAxisValueAnimation(e,t){let n=this.getAxisMotionValue(e);return Yc(this.visualElement,e),n.start(Nc(e,n,0,t,this.visualElement,!1))}stopAnimation(){ff(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){let t=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps();return n[t]||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){ff(t=>{let{drag:n}=this.getProps();if(!zm(t,n,this.currentDirection))return;let{projection:r}=this.visualElement,i=this.getAxisMotionValue(t);if(r&&r.layout){let{min:n,max:a}=r.layout.layoutBox[t],o=i.get()||0;i.set(e[t]-X(n,a,.5)+o)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!Zp(t)||!n||!this.constraints)return;this.stopAnimation();let r={x:0,y:0};ff(e=>{let t=this.getAxisMotionValue(e);if(t&&this.constraints!==!1){let n=t.get();r[e]=km({min:n,max:n},this.constraints[e])}});let{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},``):`none`,n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),ff(t=>{if(!zm(t,e,null))return;let n=this.getAxisMotionValue(t),{min:i,max:a}=this.constraints[t];n.set(X(i,a,r[t]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;Fm.set(this.visualElement,this);let e=this.visualElement.current,t=fm(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&zl(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();Zp(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=Rm(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),J.read(r);let o=wf(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(ff(t=>{let n=this.getAxisMotionValue(t);n&&(this.originPoint[t]+=e[t].translate,n.set(n.get()+e[t].translate))}),this.visualElement.render())}));return()=>{o(),t(),a(),s&&s(),n&&n()}}getProps(){let e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:n=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:a=jm,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function Lm(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function Rm(e,t,n){let r=su(e,Lm(n)),i=su(t,Lm(n));return()=>{r(),i()}}function zm(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Bm(e,t=10){let n=null;return Math.abs(e.y)>t?n=`y`:Math.abs(e.x)>t&&(n=`x`),n}var Vm=class extends Nu{constructor(e){super(e),this.removeGroupControls=zi,this.removeListeners=zi,this.controls=new Im(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||zi}update(){let{dragControls:e}=this.node.getProps(),{dragControls:t}=this.node.prevProps||{};e!==t&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}},Hm=e=>(t,n)=>{e&&J.update(()=>e(t,n),!1,!0)},Um=class extends Nu{constructor(){super(...arguments),this.removePointerDownListener=zi}onPointerDown(e){this.session=new _m(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:pm(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:Hm(e),onStart:Hm(t),onMove:Hm(n),onEnd:(e,t)=>{delete this.session,r&&J.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=fm(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},Wm=!1,Gm=class extends d.Component{componentDidMount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n,layoutId:r}=this.props,{projection:i}=e;i&&(t.group&&t.group.add(i),n&&n.register&&r&&n.register(i),Wm&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Af.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){let{layoutDependency:t,visualElement:n,drag:r,isPresent:i}=this.props,{projection:a}=n;return a?(a.isPresent=i,e.layoutDependency!==t&&a.setOptions({...a.options,layoutDependency:t}),Wm=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||J.postRender(()=>{let e=a.getStack();(!e||!e.members.length)&&this.safeToRemove()})),null):null}componentDidUpdate(){let{visualElement:e,layoutAnchor:t}=this.props,{projection:n}=e;n&&(n.options.layoutAnchor=t,n.root.didUpdate(),El.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;Wm=!0,r&&(r.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(r),n&&n.deregister&&n.deregister(r))}safeToRemove(){let{safeToRemove:e}=this.props;e&&e()}render(){return null}};function Km(e){let[t,n]=mp(),r=(0,d.useContext)(wi);return(0,f.jsx)(Gm,{...e,layoutGroup:r,switchLayoutGroup:(0,d.useContext)(Xp),isPresent:t,safeToRemove:n})}var qm={pan:{Feature:Um},drag:{Feature:Vm,ProjectionNode:fp,MeasureLayout:Km}};function Jm(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&J.postRender(()=>i(t,um(t)))}var Ym=class extends Nu{mount(){let{current:e}=this.node;e&&(this.unmount=Nl(e,(e,t)=>(Jm(this.node,t,`Start`),e=>Jm(this.node,e,`End`))))}unmount(){}},Xm=class extends Nu{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(`:focus-visible`)}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive(`whileFocus`,!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive(`whileFocus`,!1),this.isActive=!1)}mount(){this.unmount=Vi(wf(this.node.current,`focus`,()=>this.onFocus()),wf(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function Zm(e,t,n){let{props:r}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&r.whileTap&&e.animationState.setActive(`whileTap`,n===`Start`);let i=r[`onTap`+(n===`End`?``:n)];i&&J.postRender(()=>i(t,um(t)))}var Qm=class extends Nu{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=Kl(e,(e,t)=>(Zm(this.node,t,`Start`),(e,{success:t})=>Zm(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},$m=new WeakMap,eh=new WeakMap,th=e=>{let t=$m.get(e.target);t&&t(e)},nh=e=>{e.forEach(th)};function rh({root:e,...t}){let n=e||document;eh.has(n)||eh.set(n,{});let r=eh.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(nh,{root:e,...t})),r[i]}function ih(e,t,n){let r=rh(t);return $m.set(e,n),r.observe(e),()=>{$m.delete(e),r.unobserve(e)}}var ah={some:0,all:1},oh=class extends Nu{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();let{viewport:e={}}=this.node.getProps(),{root:t,margin:n,amount:r=`some`,once:i}=e,a={root:t?t.current:void 0,rootMargin:n,threshold:typeof r==`number`?r:ah[r]};this.stopObserver=ih(this.node.current,a,e=>{let{isIntersecting:t}=e;if(this.isInView===t||(this.isInView=t,i&&!t&&this.hasEnteredView))return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive(`whileInView`,t);let{onViewportEnter:n,onViewportLeave:r}=this.node.getProps(),a=t?n:r;a&&a(e)})}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>`u`)return;let{props:e,prevProps:t}=this.node;[`amount`,`margin`,`root`].some(sh(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function sh({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var ch={inView:{Feature:oh},tap:{Feature:Qm},focus:{Feature:Xm},hover:{Feature:Ym}},lh={layout:{ProjectionNode:fp,MeasureLayout:Km}},uh=am({...lm,...ch,...qm,...lh},om),dh=16e3,fh=512,ph=64,mh=`silero_vad_v6.onnx`,hh=`ort.wasm.min.js`,gh=null;function _h(e){return typeof window<`u`&&window.ort?Promise.resolve(window.ort):(gh||=new Promise((t,n)=>{let r=document.createElement(`script`);r.src=`${e}/${hh}`,r.async=!0,r.onload=()=>window.ort?t(window.ort):n(Error(`speech model runtime did not initialise`)),r.onerror=()=>n(Error(`speech model runtime failed to load`)),document.head.appendChild(r)}).catch(e=>{throw gh=null,e}),gh)}function vh(e,t=dh){let n=e/t,r=0,i=0;return e=>{let t=[];for(;r<e.length-1;){let a=Math.floor(r),o=a<0?i:e[a];t.push(o+(e[a+1]-o)*(r-a)),r+=n}return r-=e.length,i=e[e.length-1],t}}async function yh({ort:e,modelUrl:t,inputRate:n}){let r=await e.InferenceSession.create(t,{executionProviders:[`wasm`]}),i=new e.Tensor(`int64`,BigInt64Array.from([BigInt(dh)]),[]),a=vh(n),o=new e.Tensor(`float32`,new Float32Array(256),[2,1,128]),s=new Float32Array(ph),c=[],l=!1,u=!1,d=0,f=async()=>{if(!l){l=!0;try{for(;!u&&c.length>=fh;){let t=Float32Array.from(c.slice(0,fh));c=c.slice(fh);let n=new Float32Array(ph+fh);n.set(s,0),n.set(t,ph);let a=await r.run({input:new e.Tensor(`float32`,n,[1,n.length]),state:o,sr:i});o=a.stateN,s=t.slice(fh-ph),d=a.output.data[0]}}finally{l=!1}}};return{push(e){u||(c=c.concat(a(e)),f().catch(()=>{}))},get speechProbability(){return d},close(){u=!0,r.release?.().catch?.(()=>{})}}}async function bh({assetBase:e,inputRate:t}){let n=await _h(e);return n.env.wasm.wasmPaths=`${e}/`,n.env.wasm.numThreads=1,yh({ort:n,modelUrl:`${e}/${mh}`,inputRate:t})}var xh=1500,Sh=128e3,Ch=(e,t,n)=>Promise.race([e,new Promise((e,r)=>setTimeout(()=>r(Error(`${n} timed out`)),t))]),wh=e=>e.iceGatheringState===`complete`?Promise.resolve():new Promise(t=>{e.addEventListener(`icegatheringstatechange`,()=>e.iceGatheringState===`complete`&&t())}),Th=e=>new Promise((t,n)=>{let r=()=>{e.connectionState===`connected`?t():(e.connectionState===`failed`||e.connectionState===`closed`)&&n(Error(`loopback ${e.connectionState}`))};e.addEventListener(`connectionstatechange`,r),r()});async function Eh(e,t){return await e.setLocalDescription(t),await Ch(wh(e),xh,`candidate gathering`),e.localDescription}async function Dh(e){if(typeof RTCPeerConnection>`u`)throw Error(`WebRTC unavailable`);let t=e.createMediaStreamDestination(),n=new RTCPeerConnection,r=new RTCPeerConnection,i=new Audio,a=()=>{i.pause(),i.srcObject=null,n.close(),r.close()};try{let e=new Promise(e=>{r.ontrack=t=>e(t.streams[0]||new MediaStream([t.track]))}),o=n.addTrack(t.stream.getAudioTracks()[0],t.stream);await r.setRemoteDescription(await Eh(n,await n.createOffer())),await n.setRemoteDescription(await Eh(r,await r.createAnswer())),await Ch(Promise.all([Th(n),Th(r)]),xh,`loopback connection`);let s=o.getParameters();return s.encodings?.length&&(s.encodings[0].maxBitrate=Sh,await o.setParameters(s).catch(()=>{})),i.srcObject=await Ch(e,xh,`loopback track`),await Ch(i.play(),xh,`loopback playback`),{node:t,close:a}}catch(e){throw a(),e}}var Oh=24e3,kh=2048,Ah=1200,jh=.05,Mh=.005,Nh=.35,Ph=3,Fh=3,Ih=5,Lh=1.6,Rh=.5;function zh(e){let t=0;for(let n=1;n<e.length;n++)e[n-1]>=0!=e[n]>=0&&(t+=1);return t/(e.length-1)}function Bh(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}function Vh(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++){let r=Math.max(-1,Math.min(1,e[n]));t[n]=r<0?r*32768:r*32767}return t}function Hh(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]/32768;return t}var Uh=.13,Wh=[`audio/webm`,`audio/mp4`];function Gh(){return typeof window>`u`||window.MediaRecorder===void 0?null:Wh.find(e=>window.MediaRecorder.isTypeSupported(e))||null}function Kh(e,t,n,r,i){if(!r.length||!n||!e)return;let a=new Blob(r,{type:i}),o=new FormData;o.append(`audio`,a,`aichat-${n}.webm`),o.append(`voiceSessionId`,n),o.append(`siteId`,t||``),fetch(`${e}/api/voice/upload-chat-recording`,{method:`POST`,body:o}).then(e=>{if(!e.ok)throw Error(`HTTP ${e.status}`)}).catch(e=>console.warn(`[FlowEngage] voice recording upload failed:`,e.message))}var qh=.02;function Jh(e,t,n){let r=e.destination,i=0,a=0,o=[],s=()=>{let t=e.currentTime;o.forEach(({source:e,gain:n})=>{try{n.gain.cancelScheduledValues(t),n.gain.setValueAtTime(n.gain.value,t),n.gain.linearRampToValueAtTime(0,t+qh),e.stop(t+qh)}catch{}}),o=[],i=0,a=0},c=()=>i>e.currentTime;return{enqueue:s=>{let l=Hh(s),u=e.createBuffer(1,l.length,Oh);u.copyToChannel(l,0);let d=e.createBufferSource();d.buffer=u;let f=e.createGain();d.connect(f),f.connect(r),n&&f.connect(n);let p=c()?i:e.currentTime+Uh;a||=p,d.start(p),i=p+u.duration;let m={source:d,gain:f};o.push(m),d.onended=()=>{o=o.filter(e=>e!==m),!o.length&&!c()&&t?.()}},stop:s,isPlaying:c,playedMs:()=>Math.max(0,(e.currentTime-a)*1e3),useOutput:e=>(r=e,i)}}async function Yh(e,t,n){let r=new URLSearchParams({siteId:t||``});n&&r.set(`chatId`,n);let i=Ur();i&&r.set(`shopifyCustomerId`,String(i)),re(t)===`auto`&&r.set(`navPreference`,`auto`);let a=await fetch(`${e}/api/voice/session?${r.toString()}`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(a.status===429){let e=await a.json().catch(()=>({}));throw Error(e.message||`Too many voice sessions started. Please wait a minute before trying again.`)}if(!a.ok)throw Error(`Could not start a voice session.`);let o=await a.json();if(!o?.success||!o.wsUrl)throw Error(o?.error||`Voice session was refused.`);return o}async function Xh(e){let{apiBaseUrl:t,siteId:n,chatId:r,clientTools:i={},onConnect:a,onDisconnect:o,onMessage:s,onAgentAnswer:c,onModeChange:l,onError:u,onUnhandledClientToolCall:d,onAgentTurnEnd:f,onSessionInfo:p,onSessionEnding:m,onPanel:h,onStartWalkthrough:g}=e,_=await Yh(t,n,r);p?.({emailOnFile:!!_.emailOnFile});let v={type:`Start`};e.greeting!==void 0&&(v.greeting=e.greeting||null);let y=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),b=new(window.AudioContext||window.webkitAudioContext)({sampleRate:Oh});b.state===`suspended`&&await b.resume();let x=b.createMediaStreamDestination(),S=Gh(),C=[],w=null,T=r||n||null;S&&(w=new window.MediaRecorder(x.stream,{mimeType:S}),w.ondataavailable=e=>{e.data&&e.data.size>0&&C.push(e.data)},w.start());let E=new WebSocket(_.wsUrl);E.binaryType=`arraybuffer`;let ee=new Set,D={role:null,text:``,timer:null,debug:null},te=``,ne=()=>{D.timer&&=(clearTimeout(D.timer),null);let e=D.text.trim(),t=D.role,n=D.debug;if(D.text=``,D.role=null,D.debug=null,!(!e||!t)){if(t===`agent`){if(e===te){console.debug(`[FlowEngage] duplicate agent turn suppressed`);return}te=e}s?.({role:t,message:e,debug:n})}},re=(e,t,n)=>{t&&(D.role&&D.role!==e&&ne(),D.role=e,D.text=D.text?`${D.text} ${t}`.replace(/\s+/g,` `):t,n&&(D.debug=n),D.timer&&clearTimeout(D.timer),D.timer=setTimeout(ne,Ah))},O=!1,ie=!1,ae=!1,k=!1,oe=!1,se=!0,ce=0,le=0,ue=!1,de=!1,fe=jh,A=0,pe=0,j=null,me=!1,he=!1,M=()=>{j&&clearTimeout(j);let e=()=>{if(!O){if(N.isPlaying()){j=setTimeout(e,150);return}if(j=null,me){m?.();return}!O&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:`PlaybackDrained`})),he&&(he=!1,f?.())}};j=setTimeout(e,150)},N=Jh(b,()=>{k&&(k=!1,l?.({mode:oe?`thinking`:`listening`}))},x);typeof window<`u`&&(window.__fe_agentAudioPlaying=()=>N.isPlaying());let ge=null,_e=1/0;Dh(b).then(e=>{if(O)return e.close();ge=e,_e=N.useOutput(e.node),console.log(`[FlowEngage] agent audio routed through echo cancellation`)}).catch(e=>console.warn(`[FlowEngage] agent audio is not echo-cancelled, using the cautious interruption check:`,e?.message));let ve=b.createMediaStreamSource(y);ve.connect(x);let ye=b.createScriptProcessor(kh,1,1),P=!1,F=null,be=!1;bh({assetBase:`${t}/vad`,inputRate:Oh}).then(e=>{if(O)return e.close();F=e,console.log(`[FlowEngage] speech model ready`)}).catch(e=>console.warn(`[FlowEngage] speech model unavailable, using the basic speech check:`,e?.message)),ye.onaudioprocess=e=>{if(O||E.readyState!==WebSocket.OPEN)return;let t=e.inputBuffer.getChannelData(0),n=()=>E.send(new Int16Array(t.length).buffer);if(ie){ae||(ae=!0,console.debug(`[FlowEngage] mic held — streaming silence to keep socket alive`)),P=!1,ce=0,le=0,n();return}let r=Bh(t),i=zh(t),a=N.isPlaying()||de,o=a&&!(F&&b.currentTime>=_e),s=o?fe*Lh:fe,c=o?Ih:Ph;F?.push(t),(F?r>=s&&F.speechProbability>=Rh:r>=s&&i>=Mh&&i<=Nh)?(le=0,ce+=1):++le>=Fh&&(ce=0),a&&F?.speechProbability>=Rh&&(A=Math.max(A,r)),a&&(pe=Math.max(pe,ce));let u=ce>=Ph;if(F&&u!==be&&(be=u,E.send(JSON.stringify({type:`VisitorSpeech`,active:u}))),a?P=!1:!P&&ce>=Ph?(P=!0,l?.({mode:`user-speaking`})):P&&ce===0&&(P=!1),a&&!ue&&!me&&ce>=c){ue=!0,oe=!1;let e=N.playedMs();N.stop(),se=!1,de=!1,j&&!me&&(clearTimeout(j),j=null),he=!1,E.send(JSON.stringify({type:`VisitorInterrupted`,played_ms:Math.round(e)})),console.log(`[FlowEngage] barge-in — visitor spoke over the agent`)}E.send(Vh(t).buffer)},ve.connect(ye),ye.connect(b.destination);let I=()=>{if(!O){O=!0,F?.close(),ge?.close(),j&&=(clearTimeout(j),null),ne(),N.stop(),typeof window<`u`&&delete window.__fe_agentAudioPlaying;try{ye.disconnect(),ve.disconnect()}catch{}if(y.getTracks().forEach(e=>e.stop()),w&&w.state!==`inactive`){w.onstop=()=>Kh(t,n,T,C,S);try{w.stop()}catch{w.onstop=null}}else C.length&&Kh(t,n,T,C,S);b.close().catch(()=>{}),(E.readyState===WebSocket.OPEN||E.readyState===WebSocket.CONNECTING)&&E.close()}},xe=async e=>{let t=i[e.name];if(!t)return d?.({tool_name:e.name}),{error:`Unknown tool ${e.name}`};let n={};try{n=JSON.parse(e.arguments||`{}`)}catch{}try{return await t(n)}catch(e){return{error:e?.message||`Tool execution failed`}}},Se=async e=>{for(let t of e.functions||[]){if(!t.client_side)continue;let e=await xe(t);if(O||E.readyState!==WebSocket.OPEN)return;E.send(JSON.stringify({type:`FunctionCallResponse`,id:t.id,name:t.name,content:typeof e==`string`?e:JSON.stringify(e??{})}))}},Ce=e=>{switch(e.type){case`Welcome`:Number.isFinite(e.barge_in_rms)&&e.barge_in_rms>0&&(fe=e.barge_in_rms),Number.isFinite(e.barge_in_frames)&&e.barge_in_frames>0&&e.barge_in_frames,T=e.session_id||r||n||null,a?.({conversationId:T});break;case`ConversationText`:{let t=String(e.content||``);if(e.role===`user`){let e=t.trim();if(ee.has(e)){ee.delete(e);break}if(/^\[SYSTEM:/i.test(e)||/^Continue (now )?to the next section/i.test(e)||/^That was the last section/i.test(e)){console.debug(`[FlowEngage] widget instruction hidden from transcript`);break}}re(e.role===`user`?`user`:`agent`,t,e.debug),e.role!==`user`&&e.debug&&c?.({text:t,tools:e.debug.tools||[]});break}case`UserStartedSpeaking`:k&&!ue&&console.log(`[FlowEngage] interrupted by the server, not the widget: loudest speech ${A.toFixed(3)} (needs ${fe}), longest run ${pe} frames, echo cancellation ${ge?`on`:`off`}, speech model ${F?`on`:`off`}`),ne(),N.stop(),de=!1,se=!1,k=!1,oe=!1,j&&!me&&(clearTimeout(j),j=null),he=!1,l?.({mode:`listening`});break;case`AgentStartedSpeaking`:se=!0,k=!0,ue=!1,A=0,pe=0,l?.({mode:`speaking`});break;case`AgentAudioDone`:de=!1,ne(),M(),N.isPlaying()||(k=!1,l?.({mode:oe?`thinking`:`listening`}));break;case`FunctionCallRequest`:Se(e);break;case`AgentPreparing`:de=!0;break;case`AgentTurnComplete`:oe=!1,he=!0,M();break;case`SessionEnding`:console.debug(`[FlowEngage] server is ending the session:`,e.reason||`unspecified`),me=!0;break;case`StartWalkthrough`:g?.();break;case`AgentThinking`:oe=!0,l?.({mode:`thinking`});break;case`PromptUpdated`:break;case`AgentPanel`:console.log(`[FlowEngage] AgentPanel received:`,e.panel,(e.items||[]).length,`items`),h?.({panel:e.panel||null,title:e.title||null,items:e.items||[]});break;case`Error`:console.error(`[FlowEngage:Voice]`,e.code||``,e.description||e),u?.(Error(e.description||`Voice service error`));break;case`Warning`:console.warn(`[FlowEngage:Voice]`,e.code||``,e.description||``);break;default:break}};return E.onopen=()=>E.send(JSON.stringify(v)),E.onmessage=e=>{if(e.data instanceof ArrayBuffer){se&&N.enqueue(new Int16Array(e.data));return}let t;try{t=JSON.parse(e.data)}catch{return}try{Ce(t)}catch(e){console.error(`[FlowEngage] voice event handler failed:`,t?.type,e)}},E.onerror=()=>u?.(Error(`Voice connection failed`)),E.onclose=()=>{I(),o?.()},{endSession:async()=>I(),sendContextualUpdate:e=>{O||E.readyState!==WebSocket.OPEN||!e||E.send(JSON.stringify({type:`UpdatePrompt`,prompt:e}))},reportPage:(e,t)=>{O||E.readyState!==WebSocket.OPEN||!e||E.send(JSON.stringify({type:`PageChanged`,path:e,title:t||null}))},sendUserMessage:(e,{silent:t=!0,suppressQuestion:n=!1}={})=>{O||E.readyState!==WebSocket.OPEN||!e||(t&&ee.add(e.trim()),E.send(JSON.stringify({type:`InjectUserMessage`,content:e,suppress_question:n})))},injectAgentSpeech:(e,t=`interrupt`)=>{O||E.readyState!==WebSocket.OPEN||!e||E.send(JSON.stringify({type:`InjectAgentMessage`,message:e,behavior:t}))},setWalkthroughActive:e=>{O||E.readyState!==WebSocket.OPEN||E.send(JSON.stringify({type:`WalkthroughActive`,active:!!e}))},setMicMuted:e=>{ie=!!e,!O&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:`MicHeld`,held:ie}))},get status(){return O?`disconnected`:`connected`}}}var Zh={startSession:Xh},Q=`fe-vv`;function Qh(){if(typeof document>`u`||document.getElementById(`${Q}-styles`))return;let e=`
29
29
  /* ── Action toast ───────────────────────────────────────────────────────────── */
30
30
  #${Q}-toast {
31
31
  position: fixed;
@@ -247,25 +247,25 @@
247
247
  50% { transform: translate(-4px,-4px) scale(0.82); }
248
248
  100% { transform: translate(-4px,-4px) scale(1); }
249
249
  }
250
- `,t=document.createElement(`style`);t.id=`${Q}-styles`,t.textContent=e,(document.head||document.documentElement).appendChild(t)}var Qh=null,$h=null;function eg(){return(!Qh||!Qh.isConnected)&&(Qh=document.createElement(`div`),Qh.id=`${Q}-toast`,document.body.appendChild(Qh)),Qh}function tg(e,{spinner:t=!0,icon:n=null,duration:r=0}={}){if(typeof document>`u`)return;Zh(),$h&&=(clearTimeout($h),null);let i=eg();if(i.innerHTML=``,n){let e=document.createElement(`span`);e.className=`${Q}-icon`,e.textContent=n,i.appendChild(e)}else if(t){let e=document.createElement(`span`);e.className=`${Q}-spin`,i.appendChild(e)}let a=document.createElement(`span`);a.textContent=e,i.appendChild(a),i.classList.remove(`${Q}-show`),i.offsetHeight,i.classList.add(`${Q}-show`),r>0&&($h=setTimeout(()=>ng(),r))}function ng(e=0){Qh&&(e>0?$h=setTimeout(()=>{Qh&&Qh.classList.remove(`${Q}-show`)},e):Qh&&Qh.classList.remove(`${Q}-show`))}var rg=null;function ig(){return(!rg||!rg.isConnected)&&(rg=document.createElement(`div`),rg.id=`${Q}-panel`,document.body.appendChild(rg)),rg}var ag=12,og=320,sg=130,cg=`right`,lg=!1;function ug(e,t){let n=()=>{e.style.left=``,e.style.right=``,e.style.bottom=`1.5rem`,t===`left`?e.style.left=`${sg}px`:e.style.right=`${sg}px`};e.style.left=``,e.style.right=``,e.style.bottom=``;let r=window.innerWidth,i=window.innerHeight;if(!(r<=900))try{let a=(document.getElementById(`flowengage-root`)?.shadowRoot?.querySelector(`.flowengage-widget-root`)||document.querySelector(`.flowengage-widget-root`))?.getBoundingClientRect();if(!(a&&a.width>0&&a.width<r*.55&&a.height>0))return n();if(t===`left`){let t=Math.round(a.right+ag);if(t+og>r-12)return n();e.style.left=`${t}px`}else{let t=Math.round(r-a.left+ag);if(t+og>r-12)return n();e.style.right=`${t}px`}e.style.bottom=`${Math.min(Math.max(12,Math.round(i-a.bottom)),i-200)}px`}catch{n()}}function dg(e,t){let n=Number(e);if(!Number.isFinite(n))return null;let r=n.toLocaleString(void 0,{minimumFractionDigits:n%1==0?0:2,maximumFractionDigits:2});return t?`${t} ${r}`:r}function fg(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString(void 0,{day:`numeric`,month:`short`,year:`numeric`})}function pg(e,t={}){try{mg(e,t)}catch(e){console.error(`[FlowEngage] product panel render failed:`,e),hg()}}function mg(e,{title:t=`Products`,side:n=`right`,productUrl:r=null}={}){if(typeof document>`u`)return;let i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return console.log(`[FlowEngage] product panel: nothing to show`),hg();Zh();let a=ig();cg=n===`left`?`left`:`right`,ug(a,cg),lg||(lg=!0,window.addEventListener(`resize`,()=>{rg?.classList.contains(`${Q}-show`)&&ug(rg,cg)}));let o=document.createDocumentFragment(),s=document.createElement(`div`);s.id=`${Q}-panel-head`;let c=document.createElement(`div`);c.id=`${Q}-panel-title`,c.textContent=t;let l=document.createElement(`span`);l.id=`${Q}-panel-count`,l.textContent=String(i.length);let u=document.createElement(`button`);u.id=`${Q}-panel-close`,u.type=`button`,u.setAttribute(`aria-label`,`Close product panel`),u.textContent=`×`,u.addEventListener(`click`,()=>hg()),s.append(c,l,u);let d=document.createElement(`div`);d.id=`${Q}-panel-list`;for(let e of i){let t=typeof r==`function`?r(e):null,n=document.createElement(t?`a`:`div`);if(n.className=`${Q}-card`,t&&(n.href=t,n.rel=`noopener`),e.image){let t=document.createElement(`img`);t.className=`${Q}-card-thumb`,t.src=e.image,t.alt=``,t.loading=`lazy`,t.addEventListener(`error`,()=>{let e=document.createElement(`div`);e.className=`${Q}-card-thumb-ph`,e.textContent=`🛍`,t.replaceWith(e)}),n.appendChild(t)}else{let e=document.createElement(`div`);e.className=`${Q}-card-thumb-ph`,e.textContent=`🛍`,n.appendChild(e)}let i=document.createElement(`div`);i.className=`${Q}-card-body`;let a=document.createElement(`div`);a.className=`${Q}-card-title`,a.textContent=e.title||`Item`,i.appendChild(a);let o=[];e.quantity>1&&o.push(`Qty ${e.quantity}`);let s=fg(e.orderedAt);if(s&&o.push(s),e.fulfillmentStatus&&o.push(e.fulfillmentStatus),o.length||e.productType){let t=document.createElement(`div`);if(t.className=`${Q}-card-meta`,e.productType){let n=document.createElement(`span`);n.className=`${Q}-chip`,n.textContent=e.productType,t.appendChild(n)}t.appendChild(document.createTextNode(o.join(` · `))),i.appendChild(t)}let c=dg(e.price,e.currency);if(c){let e=document.createElement(`div`);e.className=`${Q}-card-price`,e.textContent=c,i.appendChild(e)}n.appendChild(i),d.appendChild(n)}o.append(s,d),a.innerHTML=``,a.append(o),a.classList.remove(`${Q}-show`),a.offsetHeight,a.classList.add(`${Q}-show`),console.log(`[FlowEngage] product panel shown:`,i.length,`items`,{left:a.style.left,right:a.style.right,bottom:a.style.bottom,rect:a.getBoundingClientRect()})}function hg(){rg&&rg.classList.remove(`${Q}-show`)}var gg=null,_g=[];function vg(){return(!gg||!gg.isConnected)&&(gg=document.createElement(`div`),gg.id=`${Q}-bar`,document.body.appendChild(gg)),gg}function yg(){if(typeof document>`u`)return;Zh(),_g.forEach(clearTimeout),_g=[];let e=vg();e.style.transition=`none`,e.style.width=`0%`,e.classList.add(`${Q}-bar-active`),e.offsetHeight,e.style.transition=`width 0.35s ease, opacity 0.25s ease`;let t=[[80,`width 0.6s ease`],[92,`width 1.2s ease`]],n=50;for(let[e,r]of t){let t=n,i=e,a=r;_g.push(setTimeout(()=>{gg&&(gg.style.transition=a,gg.style.width=`${i}%`)},t)),n+=800}}function bg(){gg&&(_g.forEach(clearTimeout),_g=[],gg.style.transition=`width 0.2s ease`,gg.style.width=`100%`,_g.push(setTimeout(()=>{gg&&(gg.style.transition=`opacity 0.35s ease`,gg.style.opacity=`0`,_g.push(setTimeout(()=>{gg&&(gg.style.width=`0%`,gg.classList.remove(`${Q}-bar-active`))},380)))},220)))}var xg=`<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 22 22" fill="none">
250
+ `,t=document.createElement(`style`);t.id=`${Q}-styles`,t.textContent=e,(document.head||document.documentElement).appendChild(t)}var $h=null,eg=null;function tg(){return(!$h||!$h.isConnected)&&($h=document.createElement(`div`),$h.id=`${Q}-toast`,document.body.appendChild($h)),$h}function ng(e,{spinner:t=!0,icon:n=null,duration:r=0}={}){if(typeof document>`u`)return;Qh(),eg&&=(clearTimeout(eg),null);let i=tg();if(i.innerHTML=``,n){let e=document.createElement(`span`);e.className=`${Q}-icon`,e.textContent=n,i.appendChild(e)}else if(t){let e=document.createElement(`span`);e.className=`${Q}-spin`,i.appendChild(e)}let a=document.createElement(`span`);a.textContent=e,i.appendChild(a),i.classList.remove(`${Q}-show`),i.offsetHeight,i.classList.add(`${Q}-show`),r>0&&(eg=setTimeout(()=>rg(),r))}function rg(e=0){$h&&(e>0?eg=setTimeout(()=>{$h&&$h.classList.remove(`${Q}-show`)},e):$h&&$h.classList.remove(`${Q}-show`))}var ig=null;function ag(){return(!ig||!ig.isConnected)&&(ig=document.createElement(`div`),ig.id=`${Q}-panel`,document.body.appendChild(ig)),ig}var og=12,sg=320,cg=130,lg=`right`,ug=!1;function dg(e,t){let n=()=>{e.style.left=``,e.style.right=``,e.style.bottom=`1.5rem`,t===`left`?e.style.left=`${cg}px`:e.style.right=`${cg}px`};e.style.left=``,e.style.right=``,e.style.bottom=``;let r=window.innerWidth,i=window.innerHeight;if(!(r<=900))try{let a=(document.getElementById(`flowengage-root`)?.shadowRoot?.querySelector(`.flowengage-widget-root`)||document.querySelector(`.flowengage-widget-root`))?.getBoundingClientRect();if(!(a&&a.width>0&&a.width<r*.55&&a.height>0))return n();if(t===`left`){let t=Math.round(a.right+og);if(t+sg>r-12)return n();e.style.left=`${t}px`}else{let t=Math.round(r-a.left+og);if(t+sg>r-12)return n();e.style.right=`${t}px`}e.style.bottom=`${Math.min(Math.max(12,Math.round(i-a.bottom)),i-200)}px`}catch{n()}}function fg(e,t){let n=Number(e);if(!Number.isFinite(n))return null;let r=n.toLocaleString(void 0,{minimumFractionDigits:n%1==0?0:2,maximumFractionDigits:2});return t?`${t} ${r}`:r}function pg(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString(void 0,{day:`numeric`,month:`short`,year:`numeric`})}function mg(e,t={}){try{hg(e,t)}catch(e){console.error(`[FlowEngage] product panel render failed:`,e),gg()}}function hg(e,{title:t=`Products`,side:n=`right`,productUrl:r=null}={}){if(typeof document>`u`)return;let i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return console.log(`[FlowEngage] product panel: nothing to show`),gg();Qh();let a=ag();lg=n===`left`?`left`:`right`,dg(a,lg),ug||(ug=!0,window.addEventListener(`resize`,()=>{ig?.classList.contains(`${Q}-show`)&&dg(ig,lg)}));let o=document.createDocumentFragment(),s=document.createElement(`div`);s.id=`${Q}-panel-head`;let c=document.createElement(`div`);c.id=`${Q}-panel-title`,c.textContent=t;let l=document.createElement(`span`);l.id=`${Q}-panel-count`,l.textContent=String(i.length);let u=document.createElement(`button`);u.id=`${Q}-panel-close`,u.type=`button`,u.setAttribute(`aria-label`,`Close product panel`),u.textContent=`×`,u.addEventListener(`click`,()=>gg()),s.append(c,l,u);let d=document.createElement(`div`);d.id=`${Q}-panel-list`;for(let e of i){let t=typeof r==`function`?r(e):null,n=document.createElement(t?`a`:`div`);if(n.className=`${Q}-card`,t&&(n.href=t,n.rel=`noopener`),e.image){let t=document.createElement(`img`);t.className=`${Q}-card-thumb`,t.src=e.image,t.alt=``,t.loading=`lazy`,t.addEventListener(`error`,()=>{let e=document.createElement(`div`);e.className=`${Q}-card-thumb-ph`,e.textContent=`🛍`,t.replaceWith(e)}),n.appendChild(t)}else{let e=document.createElement(`div`);e.className=`${Q}-card-thumb-ph`,e.textContent=`🛍`,n.appendChild(e)}let i=document.createElement(`div`);i.className=`${Q}-card-body`;let a=document.createElement(`div`);a.className=`${Q}-card-title`,a.textContent=e.title||`Item`,i.appendChild(a);let o=[];e.quantity>1&&o.push(`Qty ${e.quantity}`);let s=pg(e.orderedAt);if(s&&o.push(s),e.fulfillmentStatus&&o.push(e.fulfillmentStatus),o.length||e.productType){let t=document.createElement(`div`);if(t.className=`${Q}-card-meta`,e.productType){let n=document.createElement(`span`);n.className=`${Q}-chip`,n.textContent=e.productType,t.appendChild(n)}t.appendChild(document.createTextNode(o.join(` · `))),i.appendChild(t)}let c=fg(e.price,e.currency);if(c){let e=document.createElement(`div`);e.className=`${Q}-card-price`,e.textContent=c,i.appendChild(e)}n.appendChild(i),d.appendChild(n)}o.append(s,d),a.innerHTML=``,a.append(o),a.classList.remove(`${Q}-show`),a.offsetHeight,a.classList.add(`${Q}-show`),console.log(`[FlowEngage] product panel shown:`,i.length,`items`,{left:a.style.left,right:a.style.right,bottom:a.style.bottom,rect:a.getBoundingClientRect()})}function gg(){ig&&ig.classList.remove(`${Q}-show`)}var _g=null,vg=[];function yg(){return(!_g||!_g.isConnected)&&(_g=document.createElement(`div`),_g.id=`${Q}-bar`,document.body.appendChild(_g)),_g}function bg(){if(typeof document>`u`)return;Qh(),vg.forEach(clearTimeout),vg=[];let e=yg();e.style.transition=`none`,e.style.width=`0%`,e.classList.add(`${Q}-bar-active`),e.offsetHeight,e.style.transition=`width 0.35s ease, opacity 0.25s ease`;let t=[[80,`width 0.6s ease`],[92,`width 1.2s ease`]],n=50;for(let[e,r]of t){let t=n,i=e,a=r;vg.push(setTimeout(()=>{_g&&(_g.style.transition=a,_g.style.width=`${i}%`)},t)),n+=800}}function xg(){_g&&(vg.forEach(clearTimeout),vg=[],_g.style.transition=`width 0.2s ease`,_g.style.width=`100%`,vg.push(setTimeout(()=>{_g&&(_g.style.transition=`opacity 0.35s ease`,_g.style.opacity=`0`,vg.push(setTimeout(()=>{_g&&(_g.style.width=`0%`,_g.classList.remove(`${Q}-bar-active`))},380)))},220)))}var Sg=`<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 22 22" fill="none">
251
251
  <filter id="${Q}-csh">
252
252
  <feDropShadow dx="1" dy="2" stdDeviation="1.5" flood-color="#00000060"/>
253
253
  </filter>
254
254
  <path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
255
255
  fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
256
256
  filter="url(#${Q}-csh)"/>
257
- </svg>`,Sg=null,Cg=!1;function wg(){return(!Sg||!Sg.isConnected)&&(Sg=document.createElement(`div`),Sg.id=`${Q}-cursor`,Sg.innerHTML=xg,document.body.appendChild(Sg),Cg=!1),Sg}async function Tg(e){if(typeof document>`u`||!e)return;Zh();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=wg();Cg||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await kg(360)}function Eg(e=!1){Sg&&(e?(Sg.classList.remove(`${Q}-cursor-visible`),Cg=!1):(Sg.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{Cg=!1},250)))}async function Dg(e){Sg&&(Sg.classList.add(`${Q}-cursor-click`),await kg(280),Sg.classList.remove(`${Q}-cursor-click`))}function Og(e){if(!e||typeof document>`u`)return;Zh();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function kg(e){return new Promise(t=>setTimeout(t,e))}var Ag=({size:e=18,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),jg=({size:e=20})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Mg=({size:e=18})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,f.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),Ng=()=>(0,f.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,f.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),Pg=()=>(0,f.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),Fg=({className:e=``})=>(0,f.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),Ig=({size:e=14})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 8V4H8`}),(0,f.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,f.jsx)(`path`,{d:`M2 14h2`}),(0,f.jsx)(`path`,{d:`M20 14h2`}),(0,f.jsx)(`path`,{d:`M15 13v2`}),(0,f.jsx)(`path`,{d:`M9 13v2`})]}),Lg=({size:e=20,strokeWidth:t=2,color:n=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:n,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`5`,x2:`12`,y2:`19`}),(0,f.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`})]}),Rg=({size:e=20,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`,fill:t}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`,fill:t}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`,fill:t})]}),zg=({size:e=20,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`path`,{d:`M22 11.5667C22 16.8499 17.5222 21.1334 12 21.1334C11.3507 21.1343 10.7032 21.0742 10.0654 20.9545C9.60633 20.8682 9.37678 20.8251 9.21653 20.8496C9.05627 20.8741 8.82918 20.9948 8.37499 21.2364C7.09014 21.9197 5.59195 22.161 4.15111 21.893C4.69874 21.2194 5.07275 20.4112 5.23778 19.5448C5.33778 19.0148 5.09 18.5 4.71889 18.1231C3.03333 16.4115 2 14.1051 2 11.5667C2 6.28357 6.47778 2 12 2C17.5222 2 22 6.28357 22 11.5667Z`,stroke:`white`,"stroke-width":`1.5`,"stroke-linejoin":`round`}),(0,f.jsx)(`path`,{d:`M11.9955 12H12.0045M15.991 12H16M8 12H8.00897`,stroke:`white`,"stroke-width":`2`,"stroke-linecap":`round`,"stroke-linejoin":`round`})]}),Bg=()=>(0,f.jsx)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,f.jsx)(`path`,{d:`M16.7133 8.59374C18.1939 8.98463 19.2229 9.47922 20.1589 10.0848C21.5432 10.9804 22.1367 12.5944 21.9737 14.1517C21.9049 14.8099 21.3744 15.1246 20.7592 14.9544L19.3705 14.57C18.2697 14.2653 17.7193 14.1129 17.3837 13.71C17.0481 13.307 17.0086 12.751 16.9296 11.6391L16.7133 8.59374ZM16.7133 8.59374C13.7164 7.80255 10.2871 7.80163 7.28669 8.59374M7.28669 8.59374C5.80606 8.98463 4.77711 9.47923 3.84113 10.0848C2.45683 10.9804 1.86334 12.5944 2.02628 14.1517C2.09514 14.8099 2.62563 15.1246 3.24078 14.9544L4.62954 14.57C5.73032 14.2653 6.28071 14.1129 6.61631 13.71C6.95191 13.307 6.9914 12.751 7.07038 11.6391L7.28669 8.59374Z`,stroke:`#E30C12`,"stroke-width":`1.5`,"stroke-linejoin":`round`})}),Vg=({size:e=24})=>(0,f.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 19v3`}),(0,f.jsx)(`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`}),(0,f.jsx)(`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`}),(0,f.jsx)(`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`}),(0,f.jsx)(`path`,{d:`m2 2 20 20`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`})]}),Hg=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Ug=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),Wg=new Set([`p`,`br`,`ul`,`ol`,`li`,`strong`,`em`,`b`,`i`,`a`]),Gg=/^https?:\/\//i;function Kg(e){let t=Array.from(e.childNodes);for(let n of t)if(n.nodeType===Node.ELEMENT_NODE){let t=n.tagName.toLowerCase();if(!Wg.has(t)){e.replaceChild(document.createTextNode(n.textContent),n);continue}let r={};if(t===`a`){let e=n.getAttribute(`href`)||``;Gg.test(e)&&(r.href=e),r.target=`_blank`,r.rel=`noopener noreferrer`}for(;n.attributes.length>0;)n.removeAttribute(n.attributes[0].name);for(let[e,t]of Object.entries(r))n.setAttribute(e,t);Kg(n)}else n.nodeType!==Node.TEXT_NODE&&e.removeChild(n)}function qg(e){let t=document.createElement(`div`);return t.innerHTML=e,Kg(t),t.innerHTML}function Jg(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var Yg=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return Jg(qg(t));let n=t.replace(/\r\n/g,`
257
+ </svg>`,Cg=null,wg=!1;function Tg(){return(!Cg||!Cg.isConnected)&&(Cg=document.createElement(`div`),Cg.id=`${Q}-cursor`,Cg.innerHTML=Sg,document.body.appendChild(Cg),wg=!1),Cg}async function Eg(e){if(typeof document>`u`||!e)return;Qh();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=Tg();wg||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await Ag(360)}function Dg(e=!1){Cg&&(e?(Cg.classList.remove(`${Q}-cursor-visible`),wg=!1):(Cg.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{wg=!1},250)))}async function Og(e){Cg&&(Cg.classList.add(`${Q}-cursor-click`),await Ag(280),Cg.classList.remove(`${Q}-cursor-click`))}function kg(e){if(!e||typeof document>`u`)return;Qh();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function Ag(e){return new Promise(t=>setTimeout(t,e))}var jg=({size:e=18,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),Mg=({size:e=20})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Ng=({size:e=18})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,f.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),Pg=()=>(0,f.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,f.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),Fg=()=>(0,f.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),Ig=({className:e=``})=>(0,f.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),Lg=({size:e=14})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 8V4H8`}),(0,f.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,f.jsx)(`path`,{d:`M2 14h2`}),(0,f.jsx)(`path`,{d:`M20 14h2`}),(0,f.jsx)(`path`,{d:`M15 13v2`}),(0,f.jsx)(`path`,{d:`M9 13v2`})]}),Rg=({size:e=20,strokeWidth:t=2,color:n=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:n,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`12`,y1:`5`,x2:`12`,y2:`19`}),(0,f.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`})]}),zg=({size:e=20,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`,fill:t}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`,fill:t}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`,fill:t})]}),Bg=({size:e=20,color:t=`currentColor`})=>(0,f.jsxs)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`path`,{d:`M22 11.5667C22 16.8499 17.5222 21.1334 12 21.1334C11.3507 21.1343 10.7032 21.0742 10.0654 20.9545C9.60633 20.8682 9.37678 20.8251 9.21653 20.8496C9.05627 20.8741 8.82918 20.9948 8.37499 21.2364C7.09014 21.9197 5.59195 22.161 4.15111 21.893C4.69874 21.2194 5.07275 20.4112 5.23778 19.5448C5.33778 19.0148 5.09 18.5 4.71889 18.1231C3.03333 16.4115 2 14.1051 2 11.5667C2 6.28357 6.47778 2 12 2C17.5222 2 22 6.28357 22 11.5667Z`,stroke:`white`,"stroke-width":`1.5`,"stroke-linejoin":`round`}),(0,f.jsx)(`path`,{d:`M11.9955 12H12.0045M15.991 12H16M8 12H8.00897`,stroke:`white`,"stroke-width":`2`,"stroke-linecap":`round`,"stroke-linejoin":`round`})]}),Vg=()=>(0,f.jsx)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,f.jsx)(`path`,{d:`M16.7133 8.59374C18.1939 8.98463 19.2229 9.47922 20.1589 10.0848C21.5432 10.9804 22.1367 12.5944 21.9737 14.1517C21.9049 14.8099 21.3744 15.1246 20.7592 14.9544L19.3705 14.57C18.2697 14.2653 17.7193 14.1129 17.3837 13.71C17.0481 13.307 17.0086 12.751 16.9296 11.6391L16.7133 8.59374ZM16.7133 8.59374C13.7164 7.80255 10.2871 7.80163 7.28669 8.59374M7.28669 8.59374C5.80606 8.98463 4.77711 9.47923 3.84113 10.0848C2.45683 10.9804 1.86334 12.5944 2.02628 14.1517C2.09514 14.8099 2.62563 15.1246 3.24078 14.9544L4.62954 14.57C5.73032 14.2653 6.28071 14.1129 6.61631 13.71C6.95191 13.307 6.9914 12.751 7.07038 11.6391L7.28669 8.59374Z`,stroke:`#E30C12`,"stroke-width":`1.5`,"stroke-linejoin":`round`})}),Hg=({size:e=24})=>(0,f.jsxs)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 19v3`}),(0,f.jsx)(`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`}),(0,f.jsx)(`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`}),(0,f.jsx)(`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`}),(0,f.jsx)(`path`,{d:`m2 2 20 20`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`})]}),Ug=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Wg=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),Gg=new Set([`p`,`br`,`ul`,`ol`,`li`,`strong`,`em`,`b`,`i`,`a`]),Kg=/^https?:\/\//i;function qg(e){let t=Array.from(e.childNodes);for(let n of t)if(n.nodeType===Node.ELEMENT_NODE){let t=n.tagName.toLowerCase();if(!Gg.has(t)){e.replaceChild(document.createTextNode(n.textContent),n);continue}let r={};if(t===`a`){let e=n.getAttribute(`href`)||``;Kg.test(e)&&(r.href=e),r.target=`_blank`,r.rel=`noopener noreferrer`}for(;n.attributes.length>0;)n.removeAttribute(n.attributes[0].name);for(let[e,t]of Object.entries(r))n.setAttribute(e,t);qg(n)}else n.nodeType!==Node.TEXT_NODE&&e.removeChild(n)}function Jg(e){let t=document.createElement(`div`);return t.innerHTML=e,qg(t),t.innerHTML}function Yg(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var Xg=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return Yg(Jg(t));let n=t.replace(/\r\n/g,`
258
258
  `).replace(/\n{3,}/g,`
259
259
 
260
- `).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>Ug(e).replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*\n]+)\*/g,`<em>$1</em>`);return Jg(n.map(e=>{let t=e.split(`
261
- `).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``))},Xg=new Set([`application/pdf`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`]),Zg=new Set([`.pdf`,`.docx`,`.png`,`.jpg`,`.jpeg`]),Qg=`image/png,image/jpeg,.pdf,.docx`;function $g(e){if(!e)return!1;let t=typeof e.name==`string`?e.name.toLowerCase():``,n=t.includes(`.`)?`.${t.split(`.`).pop()}`:``,r=typeof e.type==`string`?e.type.toLowerCase():``;return r===`image/png`||r===`image/jpeg`||Xg.has(r)||Zg.has(n)}function e_(e){return e?$g(e)?e.size>2097152?`File must be 2 MB or smaller.`:``:`Only PNG, JPEG, PDF, and DOCX files are allowed.`:`No file selected.`}function t_(e=0){if(!Number.isFinite(e)||e<=0)return``;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=n>=10||r===0?0:1;return`${n.toFixed(i)} ${t[r]}`}function n_(e){return e?e.name||`Attachment`:``}function r_(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function i_({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,d.useState)(null),o=typeof e==`string`?e.trim():``;return(0,d.useEffect)(()=>{if(!o){a(null);return}a(null);let e=!1,t=new window.Image;return t.onload=()=>{e||a(o)},t.onerror=()=>{e||a(null)},t.src=o,()=>{e=!0}},[o]),i?(0,f.jsx)(`img`,{src:i,alt:``,style:n,onError:()=>a(null)}):(0,f.jsx)(`span`,{style:r,children:r_(t)})}function a_({siteId:e,onChoose:t}){let[n,r]=(0,d.useState)(null),i=n=>{O(e,n),r(n),t?.(n)};return(0,f.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`4px 0 10px`},children:(0,f.jsxs)(`div`,{style:{maxWidth:`88%`,borderRadius:`14px`,border:`1px solid #e5e7eb`,background:`#f9fafb`,padding:`12px 14px`},children:[(0,f.jsx)(`p`,{style:{margin:`0 0 10px`,fontSize:`12.5px`,color:`#4b5563`,lineHeight:1.45},children:`When I offer to take you to a page, should I ask first each time, or just take you there?`}),n?(0,f.jsx)(`p`,{style:{margin:0,fontSize:`12.5px`,fontWeight:600,color:`#111827`},children:n===`auto`?`Got it — I'll navigate automatically.`:`Got it — I'll ask each time.`}):(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`8px`,flexWrap:`wrap`},children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>i(`auto`),style:{padding:`7px 14px`,borderRadius:`999px`,border:`1px solid #d1d5db`,background:`white`,color:`#111827`,fontSize:`12.5px`,fontWeight:600,cursor:`pointer`},children:`Just take me there`}),(0,f.jsx)(`button`,{type:`button`,onClick:()=>i(`ask`),style:{padding:`7px 14px`,borderRadius:`999px`,border:`1px solid #d1d5db`,background:`white`,color:`#111827`,fontSize:`12.5px`,fontWeight:600,cursor:`pointer`},children:`Ask me each time`})]})]})})}function o_({chatHistory:e,isAiTyping:t,isLoading:n,isAgentTyping:r,setReplyContext:i,primaryColor:a=`#3B82F6`,agentHeadshot:o=null,agentDisplayName:s=`Agent`,botAvatarNode:c=null}){let{resolvedConfig:l,hasOlderMessages:u,loadOlderMessages:p}=gn(),m=(0,d.useRef)(null),[h,g]=(0,d.useState)(null),[_,v]=(0,d.useState)(null),y=e[0]?.id,b=e[e.length-1]?.id,x=(0,d.useRef)(b),S=(0,d.useRef)(!0),C=(0,d.useRef)(null),w=(0,d.useRef)(null),[T,E]=(0,d.useState)(!1),ee=()=>{let t=C.current;if(!t||t.scrollTop>80||!u||w.current||!p)return;let n=e.find(e=>e.messageId&&!e.isPending);n&&(w.current={height:t.scrollHeight,top:t.scrollTop},E(!0),p(n.messageId).then(e=>{e||(w.current=null)}).finally(()=>E(!1)))};(0,d.useLayoutEffect)(()=>{let e=w.current,t=C.current;!e||!t||(w.current=null,t.scrollTop=t.scrollHeight-e.height+e.top)},[y]);let D=(0,d.useCallback)(e=>{let t=e.target.closest(`a[href]`);if(!t)return;let n=t.getAttribute(`href`)||``;if(!(!n||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||n.startsWith(`javascript:`)))try{let t=new URL(n,window.location.href);if(t.origin!==window.location.origin){e.preventDefault(),window.open(t.href,`_blank`,`noopener,noreferrer`);return}e.preventDefault(),br(t.href,{siteId:l?.siteId,apiBaseUrl:l?.apiBaseUrl}).then(({allowed:e,correctedUrl:n})=>{e&&jr(n||t.href)})}catch{}},[l]),te=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i} min${i>1?`s`:``} ago`;let a=Math.floor(i/60);if(a<24)return`${a} hr${a>1?`s`:``} ago`;let o=Math.floor(a/24);return`${o} day${o>1?`s`:``} ago`};return(0,d.useEffect)(()=>{if(S.current){S.current=!1,x.current=b,C.current&&(C.current.scrollTop=C.current.scrollHeight);return}let e=!!b&&b!==x.current;x.current=b,(e||t||r)&&m.current?.scrollIntoView({behavior:`smooth`})},[b,t,n,r]),(0,f.jsxs)(`div`,{ref:C,onScroll:ee,style:{flex:1,overflowY:`auto`,overscrollBehavior:`contain`,padding:`10px 16px 20px`,display:`flex`,flexDirection:`column`,background:`transparent`},children:[T&&(0,f.jsxs)(`div`,{style:{position:`sticky`,top:0,height:0,flexShrink:0,zIndex:1,display:`flex`,justifyContent:`center`,overflow:`visible`},children:[(0,f.jsx)(`style`,{children:`@keyframes fe-older-spin { to { transform: rotate(360deg); } }`}),(0,f.jsxs)(`div`,{role:`status`,style:{display:`flex`,alignItems:`center`,gap:`8px`,height:`28px`,padding:`0 12px`,borderRadius:`9999px`,background:`white`,boxShadow:`0 1px 4px rgba(0,0,0,0.12)`,color:`#6b7280`,fontSize:`12px`,fontWeight:500,whiteSpace:`nowrap`},children:[(0,f.jsx)(`span`,{style:{width:`12px`,height:`12px`,border:`2px solid #e5e7eb`,borderTopColor:a,borderRadius:`50%`,animation:`fe-older-spin 0.8s linear infinite`}}),`Loading earlier messages…`]})]}),e.map(e=>{if(e.type===`call_recording`||typeof e.message==`string`&&e.message.includes(`AI chat recording`))return null;if(e.type===`nav_pref_choice`)return(0,f.jsx)(a_,{siteId:l?.siteId},e.id||e.messageId);let t=e.sender===`system`,n=e.sender===`user`,r=e.sender===`ai`||e.sender===`bot`,u=e.sender===`agent`,d=e.isPending,p=e.failed,m=e.type===`file`&&e.metadata?.fileUrl,h=e.agent_name||e.agentName||e.metadata?.agentName||s,y=typeof e.sender_headshot==`string`&&e.sender_headshot.trim()||typeof o==`string`&&o.trim()||null,b=Hg(e.replyToContent||e.replyContext?.message||``),x=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,f.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`8px 0`},children:(0,f.jsx)(`div`,{style:{padding:`6px 12px`,borderRadius:`9999px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,fontWeight:500},children:e.message})},e.id):(0,f.jsxs)(`div`,{style:{display:`flex`,justifyContent:n?`flex-end`:`flex-start`,alignItems:`flex-start`,marginBottom:`16px`,gap:`8px`,flexDirection:`row`},children:[!n&&(r||u)&&(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:u?`#f3f4f6`:c&&r?`transparent`:`var(--flowengage-primary)`,color:u?a:`#fff`,boxShadow:u?`0 2px 8px rgba(0,0,0,0.06)`:c&&r?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`,border:u?`1px solid ${a}22`:`none`,fontSize:`12px`,fontWeight:800,marginTop:!d&&(r||u)?`22px`:`0px`},children:r?c||(0,f.jsx)(Ig,{size:16}):(0,f.jsx)(i_,{src:y||``,name:h,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`75%`,minWidth:0},children:[!d&&u&&(0,f.jsxs)(`button`,{type:`button`,onClick:()=>i(e),style:{opacity:1,marginBottom:`4px`,display:`flex`,alignItems:`center`,gap:`4px`,fontSize:`11px`,color:`#9ca3af`,background:`transparent`,border:0,cursor:`pointer`,padding:0,marginLeft:`2px`},onMouseEnter:e=>{e.currentTarget.style.color=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:[(0,f.jsx)(Ng,{}),`Reply`]}),(0,f.jsxs)(`div`,{style:{padding:`8px 16px`,borderRadius:n?`20px 6px 20px 20px`:`6px 20px 20px 20px`,lineHeight:1.8,letterSpacing:0,boxShadow:`0 2px 8px rgba(0,0,0,0.06)`,background:n?`var(--flowengage-primary)`:`rgba(255,255,255,0.92)`,color:n?`#fff`:`#111827`,fontSize:`14px`,fontWeight:400,opacity:d||e.failed?.55:1,transition:`opacity 0.3s ease`,wordBreak:`break-word`,width:`fit-content`},children:[b&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,borderRadius:`14px`,borderLeft:n?`2px solid rgba(255,255,255,0.8)`:`2px solid var(--flowengage-primary)`,padding:`8px 12px`,fontSize:`12px`,background:n?`rgba(255,255,255,0.15)`:`#f9fafb`,color:n?`rgba(255,255,255,0.9)`:`#6b7280`},children:[(0,f.jsx)(`div`,{style:{marginBottom:`2px`,fontWeight:600},children:x}),(0,f.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:b})]}),m?(()=>{let t=e.metadata.fileType||``,r=e.metadata.fileName||e.message||`File`,i=t_(e.metadata.fileSize),a=t.startsWith(`image/`),o=`shared file: ${r}`.toLowerCase(),s=(e.message||``).trim(),c=s&&s.toLowerCase()!==o&&!s.toLowerCase().startsWith(`shared file:`),l=t===`application/pdf`?{color:`#ef4444`,label:`PDF`}:t.includes(`word`)||t.includes(`docx`)?{color:`#3b82f6`,label:`DOCX`}:t.includes(`excel`)||t.includes(`sheet`)||t===`text/csv`?{color:`#10b981`,label:`XLSX`}:{color:`#6b7280`,label:`FILE`};return(0,f.jsxs)(`div`,{style:{minWidth:`200px`,maxWidth:`240px`},children:[c&&(0,f.jsx)(`div`,{style:{marginBottom:`6px`,fontSize:`14px`,color:n?`#fff`:`#111827`,whiteSpace:`normal`,wordBreak:`break-word`},children:s}),a?(0,f.jsx)(`button`,{type:`button`,onClick:()=>g({url:e.metadata.fileUrl,name:r}),onMouseEnter:()=>v(e.id),onMouseLeave:()=>v(null),style:{display:`block`,width:`100%`,background:`transparent`,border:0,padding:0,margin:0,textAlign:`left`,cursor:`pointer`},children:(0,f.jsxs)(`div`,{style:{position:`relative`},children:[(0,f.jsx)(`img`,{src:e.metadata.fileUrl,alt:r,style:{width:`100%`,borderRadius:`10px`,display:`block`,maxHeight:`180px`,objectFit:`cover`}}),(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,borderRadius:`10px`,background:_===e.id?`rgba(17,24,39,0.32)`:`rgba(17,24,39,0)`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#fff`,fontSize:`13px`,fontWeight:700,letterSpacing:`0.02em`,opacity:_===e.id?1:0,transition:`background 0.18s ease, opacity 0.18s ease`,pointerEvents:`none`},children:`Preview`})]})}):(0,f.jsx)(`a`,{href:e.metadata.fileUrl,target:`_blank`,rel:`noopener noreferrer`,style:{textDecoration:`none`,display:`block`},children:(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`10px`,background:n?`rgba(255,255,255,0.15)`:`#f3f4f6`,borderRadius:`12px`,padding:`10px 12px`},children:[(0,f.jsxs)(`div`,{style:{width:`38px`,height:`46px`,borderRadius:`8px`,background:n?`rgba(255,255,255,0.22)`:`#fff`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 1px 4px rgba(0,0,0,0.1)`,gap:`3px`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`#fff`:l.color,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`}),(0,f.jsx)(`polyline`,{points:`14 2 14 8 20 8`})]}),(0,f.jsx)(`span`,{style:{fontSize:`7px`,fontWeight:800,letterSpacing:`0.04em`,color:n?`#fff`:l.color,lineHeight:1},children:l.label})]}),(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:n?`#fff`:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:r}),i&&(0,f.jsx)(`div`,{style:{fontSize:`11px`,marginTop:`3px`,color:n?`rgba(255,255,255,0.6)`:`#9ca3af`},children:i})]}),(0,f.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`rgba(255,255,255,0.65)`:`#9ca3af`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,f.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,f.jsx)(`polyline`,{points:`7 10 12 15 17 10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`15`,x2:`12`,y2:`3`})]})]})})]})})():r?(0,f.jsx)(`div`,{className:`flowengage-message-content fe-bot-message`,dangerouslySetInnerHTML:{__html:Yg(e.message)},onClick:D}):(0,f.jsx)(`div`,{style:{whiteSpace:`pre-wrap`},children:e.message})]}),(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,marginTop:`4px`,padding:`0 4px`,alignSelf:n?`flex-end`:`flex-start`},children:d?(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500,fontStyle:`italic`},children:`sending…`}):p?(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#dc2626`,fontWeight:500},children:`Not sent — tap send to try again`}):(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500},children:te(e.timestamp||e.createdAt)}),(0,f.jsx)(`span`,{style:{fontSize:`10px`,fontWeight:700,color:n?`var(--flowengage-primary)`:`#9ca3af`},children:`✓`})]})})]})]},e.id)}),(t||n)&&(0,f.jsxs)(`div`,{style:{marginBottom:`16px`,display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:c?`transparent`:`var(--flowengage-primary)`,color:`#fff`,boxShadow:c?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`},children:c||(0,f.jsx)(Ig,{size:16})}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`2px`,color:`#374151`,fontSize:`13px`,fontWeight:500,fontStyle:`italic`},children:[`Analysing`,[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`},children:`.`},e))]})]}),r&&(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:`8px`,marginBottom:`12px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,overflow:`hidden`},children:(0,f.jsx)(i_,{src:o||``,name:s,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})]}),(0,f.jsx)(`div`,{ref:m}),h&&(0,f.jsx)(`button`,{type:`button`,onClick:()=>g(null),style:{position:`fixed`,inset:0,zIndex:1e4,border:0,padding:`16px`,margin:0,background:`rgba(2,6,23,0.88)`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`default`},children:(0,f.jsxs)(`div`,{style:{position:`relative`,maxWidth:`min(96vw, 1100px)`,maxHeight:`96vh`,width:`100%`,display:`flex`,flexDirection:`column`,gap:`10px`,alignItems:`center`},children:[(0,f.jsx)(`img`,{src:h.url,alt:h.name,style:{width:`100%`,maxHeight:`calc(96vh - 72px)`,objectFit:`contain`,borderRadius:`16px`,boxShadow:`0 30px 80px rgba(0,0,0,0.42)`}}),(0,f.jsx)(`div`,{style:{maxWidth:`100%`,padding:`8px 14px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.92)`,color:`#0f172a`,fontSize:`12px`,fontWeight:600,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:h.name})]})})]})}var s_=typeof window<`u`&&(window.matchMedia?.(`(pointer: coarse)`).matches||navigator.maxTouchPoints>0);function c_({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:u,emailInput:p,setEmailInput:m,emailError:h,showVoiceToggle:g=!1,voiceEnabled:_=!0,onFileSelect:v,selectedFile:y=null,onRemoveSelectedFile:b,attachmentError:x=``,isUploadingAttachment:S=!1,inputPlaceholder:C=`Type your message`}){let w=(0,d.useRef)(null),T=(0,d.useRef)(null),E=e=>{e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)};(0,d.useEffect)(()=>{u||E(T.current)},[e,u]),(0,d.useEffect)(()=>{u||s_||e||s||T.current?.focus()},[e,u,s]);let ee=e=>{e.key===`Enter`&&(s_||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||(e.preventDefault(),e.currentTarget.form?.requestSubmit()))},D=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`,te=u?!!p?.trim():!!e?.trim()||!!y,ne=s||S||!te,re=!u&&_&&g;return(0,f.jsxs)(`div`,{style:{padding:`0 16px`,background:`transparent`},children:[c&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,D]}),(0,f.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),u&&(0,f.jsx)(`div`,{style:{marginBottom:`8px`,padding:`0 8px`},children:(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,f.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,f.jsx)(Ig,{size:13})}),(0,f.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),y&&!u&&(0,f.jsxs)(`div`,{style:{marginBottom:`10px`,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.06)`,background:`#fff`,padding:`12px 14px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1},children:[(0,f.jsx)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`,marginBottom:`2px`},children:`Attachment ready`}),(0,f.jsx)(`div`,{style:{fontSize:`13px`,color:`#111827`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`},children:n_(y)}),(0,f.jsx)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginTop:`2px`},children:t_(y.size)})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`,flexShrink:0},onClick:b,"aria-label":`Remove attachment`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),(0,f.jsxs)(`form`,{style:{display:`flex`,alignItems:`flex-end`,gap:`8px`,minHeight:`40px`,padding:`4px`,border:`1px solid rgba(0,0,0,0.06)`,borderRadius:`20px`,background:`#fff`,boxShadow:`0 4px 14px rgba(0,0,0,0.04)`,opacity:1},onSubmit:n,children:[re?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`input`,{ref:w,type:`file`,accept:Qg,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];t&&v?.(t),e.target.value=``}}),(0,f.jsx)(`button`,{type:`button`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`#f3f4f8`,color:`var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, opacity 0.2s ease`,border:0,cursor:`pointer`,flexShrink:0},onClick:()=>w.current?.click(),title:`Attach file`,"aria-label":`Attach file`,disabled:S,onMouseEnter:e=>{e.currentTarget.style.opacity=`0.8`},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(Lg,{size:16,color:`currentColor`})})]}):null,u?(0,f.jsx)(`input`,{className:`flowengage-chat-text-input`,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:0,paddingLeft:re?`0`:`8px`,color:`#111827`,background:`transparent`,cursor:`text`,alignSelf:`center`},value:p,onChange:e=>m(e.target.value),placeholder:`Enter your Email`,disabled:s,type:`email`,autoComplete:`email`}):(0,f.jsx)(`textarea`,{ref:T,className:`flowengage-chat-text-input`,rows:1,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,lineHeight:`20px`,outline:`none`,padding:`6px 0`,paddingLeft:re?`0`:`8px`,color:`#111827`,background:`transparent`,cursor:`text`,resize:`none`,maxHeight:`120px`,overflowY:`auto`},value:e,onChange:e=>{t(e.target.value),E(e.target)},onKeyDown:ee,placeholder:o===`agent`?`Message the agent…`:C,disabled:s,autoComplete:`off`}),(0,f.jsx)(`button`,{type:`submit`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`var(--flowengage-primary)`,color:`#fff`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`opacity 0.2s ease`,cursor:ne?`not-allowed`:`pointer`,opacity:ne?.45:1,flexShrink:0},disabled:ne,onMouseEnter:e=>{ne||(e.currentTarget.style.opacity=`0.85`)},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(Mg,{size:16})})]}),!u&&x&&(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`7px 4px 0`},children:[(0,f.jsxs)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#dc2626`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),(0,f.jsx)(`span`,{style:{fontSize:`11px`,color:`#dc2626`,fontWeight:500},children:x})]}),u&&h&&(0,f.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:h})]})}function l_({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,isRateLimited:i,rateLimitMessage:a}){return(0,f.jsxs)(f.Fragment,{children:[(e||t)&&(0,f.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,f.jsx)(Fg,{className:``}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,f.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),i&&(0,f.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:a})]})}var u_=[`#135bd8`,`#ef334b`,`#ffbd2e`];function d_(e){return!Array.isArray(e)||e.length===0?u_:e.length===1?[e[0],e[0],e[0]]:e.length===2?[e[0],e[1],e[0]]:[e[0],e[1],e[2]]}var f_={idle:3,listening:.75,thinking:1,speaking:1.4,muted:.75,error:.08};function p_(e){if(!e||typeof e!=`string`)return[0,0,0];let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}function m_(e,t){if(!e||typeof e!=`string`)return`rgba(0,0,0,${t})`;if(e.startsWith(`rgb`))return e.replace(/[\d.]+\)$/,`${t})`);let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n;return`rgba(${parseInt(r.slice(0,2),16)},${parseInt(r.slice(2,4),16)},${parseInt(r.slice(4,6),16)},${t})`}var h_=`
260
+ `).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>Wg(e).replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*\n]+)\*/g,`<em>$1</em>`);return Yg(n.map(e=>{let t=e.split(`
261
+ `).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``))},Zg=new Set([`application/pdf`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`]),Qg=new Set([`.pdf`,`.docx`,`.png`,`.jpg`,`.jpeg`]),$g=`image/png,image/jpeg,.pdf,.docx`;function e_(e){if(!e)return!1;let t=typeof e.name==`string`?e.name.toLowerCase():``,n=t.includes(`.`)?`.${t.split(`.`).pop()}`:``,r=typeof e.type==`string`?e.type.toLowerCase():``;return r===`image/png`||r===`image/jpeg`||Zg.has(r)||Qg.has(n)}function t_(e){return e?e_(e)?e.size>2097152?`File must be 2 MB or smaller.`:``:`Only PNG, JPEG, PDF, and DOCX files are allowed.`:`No file selected.`}function n_(e=0){if(!Number.isFinite(e)||e<=0)return``;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=n>=10||r===0?0:1;return`${n.toFixed(i)} ${t[r]}`}function r_(e){return e?e.name||`Attachment`:``}function i_(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function a_({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,d.useState)(null),o=typeof e==`string`?e.trim():``;return(0,d.useEffect)(()=>{if(!o){a(null);return}a(null);let e=!1,t=new window.Image;return t.onload=()=>{e||a(o)},t.onerror=()=>{e||a(null)},t.src=o,()=>{e=!0}},[o]),i?(0,f.jsx)(`img`,{src:i,alt:``,style:n,onError:()=>a(null)}):(0,f.jsx)(`span`,{style:r,children:i_(t)})}function o_({siteId:e,onChoose:t}){let[n,r]=(0,d.useState)(null),i=n=>{O(e,n),r(n),t?.(n)};return(0,f.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`4px 0 10px`},children:(0,f.jsxs)(`div`,{style:{maxWidth:`88%`,borderRadius:`14px`,border:`1px solid #e5e7eb`,background:`#f9fafb`,padding:`12px 14px`},children:[(0,f.jsx)(`p`,{style:{margin:`0 0 10px`,fontSize:`12.5px`,color:`#4b5563`,lineHeight:1.45},children:`When I offer to take you to a page, should I ask first each time, or just take you there?`}),n?(0,f.jsx)(`p`,{style:{margin:0,fontSize:`12.5px`,fontWeight:600,color:`#111827`},children:n===`auto`?`Got it — I'll navigate automatically.`:`Got it — I'll ask each time.`}):(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`8px`,flexWrap:`wrap`},children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>i(`auto`),style:{padding:`7px 14px`,borderRadius:`999px`,border:`1px solid #d1d5db`,background:`white`,color:`#111827`,fontSize:`12.5px`,fontWeight:600,cursor:`pointer`},children:`Just take me there`}),(0,f.jsx)(`button`,{type:`button`,onClick:()=>i(`ask`),style:{padding:`7px 14px`,borderRadius:`999px`,border:`1px solid #d1d5db`,background:`white`,color:`#111827`,fontSize:`12.5px`,fontWeight:600,cursor:`pointer`},children:`Ask me each time`})]})]})})}function s_({chatHistory:e,isAiTyping:t,isLoading:n,isAgentTyping:r,setReplyContext:i,primaryColor:a=`#3B82F6`,agentHeadshot:o=null,agentDisplayName:s=`Agent`,botAvatarNode:c=null}){let{resolvedConfig:l,hasOlderMessages:u,loadOlderMessages:p}=gn(),m=(0,d.useRef)(null),[h,g]=(0,d.useState)(null),[_,v]=(0,d.useState)(null),y=e[0]?.id,b=e[e.length-1]?.id,x=(0,d.useRef)(b),S=(0,d.useRef)(!0),C=(0,d.useRef)(null),w=(0,d.useRef)(null),[T,E]=(0,d.useState)(!1),ee=()=>{let t=C.current;if(!t||t.scrollTop>80||!u||w.current||!p)return;let n=e.find(e=>e.messageId&&!e.isPending);n&&(w.current={height:t.scrollHeight,top:t.scrollTop},E(!0),p(n.messageId).then(e=>{e||(w.current=null)}).finally(()=>E(!1)))};(0,d.useLayoutEffect)(()=>{let e=w.current,t=C.current;!e||!t||(w.current=null,t.scrollTop=t.scrollHeight-e.height+e.top)},[y]);let D=(0,d.useCallback)(e=>{let t=e.target.closest(`a[href]`);if(!t)return;let n=t.getAttribute(`href`)||``;if(!(!n||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||n.startsWith(`javascript:`)))try{let t=new URL(n,window.location.href);if(t.origin!==window.location.origin){e.preventDefault(),window.open(t.href,`_blank`,`noopener,noreferrer`);return}e.preventDefault(),xr(t.href,{siteId:l?.siteId,apiBaseUrl:l?.apiBaseUrl}).then(({allowed:e,correctedUrl:n})=>{e&&Mr(n||t.href)})}catch{}},[l]),te=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i} min${i>1?`s`:``} ago`;let a=Math.floor(i/60);if(a<24)return`${a} hr${a>1?`s`:``} ago`;let o=Math.floor(a/24);return`${o} day${o>1?`s`:``} ago`};return(0,d.useEffect)(()=>{if(S.current){S.current=!1,x.current=b,C.current&&(C.current.scrollTop=C.current.scrollHeight);return}let e=!!b&&b!==x.current;x.current=b,(e||t||r)&&m.current?.scrollIntoView({behavior:`smooth`})},[b,t,n,r]),(0,f.jsxs)(`div`,{ref:C,onScroll:ee,style:{flex:1,overflowY:`auto`,overscrollBehavior:`contain`,padding:`10px 16px 20px`,display:`flex`,flexDirection:`column`,background:`transparent`},children:[T&&(0,f.jsxs)(`div`,{style:{position:`sticky`,top:0,height:0,flexShrink:0,zIndex:1,display:`flex`,justifyContent:`center`,overflow:`visible`},children:[(0,f.jsx)(`style`,{children:`@keyframes fe-older-spin { to { transform: rotate(360deg); } }`}),(0,f.jsxs)(`div`,{role:`status`,style:{display:`flex`,alignItems:`center`,gap:`8px`,height:`28px`,padding:`0 12px`,borderRadius:`9999px`,background:`white`,boxShadow:`0 1px 4px rgba(0,0,0,0.12)`,color:`#6b7280`,fontSize:`12px`,fontWeight:500,whiteSpace:`nowrap`},children:[(0,f.jsx)(`span`,{style:{width:`12px`,height:`12px`,border:`2px solid #e5e7eb`,borderTopColor:a,borderRadius:`50%`,animation:`fe-older-spin 0.8s linear infinite`}}),`Loading earlier messages…`]})]}),e.map(e=>{if(e.type===`call_recording`||typeof e.message==`string`&&e.message.includes(`AI chat recording`))return null;if(e.type===`nav_pref_choice`)return(0,f.jsx)(o_,{siteId:l?.siteId},e.id||e.messageId);let t=e.sender===`system`,n=e.sender===`user`,r=e.sender===`ai`||e.sender===`bot`,u=e.sender===`agent`,d=e.isPending,p=e.failed,m=e.type===`file`&&e.metadata?.fileUrl,h=e.agent_name||e.agentName||e.metadata?.agentName||s,y=typeof e.sender_headshot==`string`&&e.sender_headshot.trim()||typeof o==`string`&&o.trim()||null,b=Ug(e.replyToContent||e.replyContext?.message||``),x=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,f.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`8px 0`},children:(0,f.jsx)(`div`,{style:{padding:`6px 12px`,borderRadius:`9999px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,fontWeight:500},children:e.message})},e.id):(0,f.jsxs)(`div`,{style:{display:`flex`,justifyContent:n?`flex-end`:`flex-start`,alignItems:`flex-start`,marginBottom:`16px`,gap:`8px`,flexDirection:`row`},children:[!n&&(r||u)&&(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:u?`#f3f4f6`:c&&r?`transparent`:`var(--flowengage-primary)`,color:u?a:`#fff`,boxShadow:u?`0 2px 8px rgba(0,0,0,0.06)`:c&&r?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`,border:u?`1px solid ${a}22`:`none`,fontSize:`12px`,fontWeight:800,marginTop:!d&&(r||u)?`22px`:`0px`},children:r?c||(0,f.jsx)(Lg,{size:16}):(0,f.jsx)(a_,{src:y||``,name:h,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`75%`,minWidth:0},children:[!d&&u&&(0,f.jsxs)(`button`,{type:`button`,onClick:()=>i(e),style:{opacity:1,marginBottom:`4px`,display:`flex`,alignItems:`center`,gap:`4px`,fontSize:`11px`,color:`#9ca3af`,background:`transparent`,border:0,cursor:`pointer`,padding:0,marginLeft:`2px`},onMouseEnter:e=>{e.currentTarget.style.color=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:[(0,f.jsx)(Pg,{}),`Reply`]}),(0,f.jsxs)(`div`,{style:{padding:`8px 16px`,borderRadius:n?`20px 6px 20px 20px`:`6px 20px 20px 20px`,lineHeight:1.8,letterSpacing:0,boxShadow:`0 2px 8px rgba(0,0,0,0.06)`,background:n?`var(--flowengage-primary)`:`rgba(255,255,255,0.92)`,color:n?`#fff`:`#111827`,fontSize:`14px`,fontWeight:400,opacity:d||e.failed?.55:1,transition:`opacity 0.3s ease`,wordBreak:`break-word`,width:`fit-content`},children:[b&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,borderRadius:`14px`,borderLeft:n?`2px solid rgba(255,255,255,0.8)`:`2px solid var(--flowengage-primary)`,padding:`8px 12px`,fontSize:`12px`,background:n?`rgba(255,255,255,0.15)`:`#f9fafb`,color:n?`rgba(255,255,255,0.9)`:`#6b7280`},children:[(0,f.jsx)(`div`,{style:{marginBottom:`2px`,fontWeight:600},children:x}),(0,f.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:b})]}),m?(()=>{let t=e.metadata.fileType||``,r=e.metadata.fileName||e.message||`File`,i=n_(e.metadata.fileSize),a=t.startsWith(`image/`),o=`shared file: ${r}`.toLowerCase(),s=(e.message||``).trim(),c=s&&s.toLowerCase()!==o&&!s.toLowerCase().startsWith(`shared file:`),l=t===`application/pdf`?{color:`#ef4444`,label:`PDF`}:t.includes(`word`)||t.includes(`docx`)?{color:`#3b82f6`,label:`DOCX`}:t.includes(`excel`)||t.includes(`sheet`)||t===`text/csv`?{color:`#10b981`,label:`XLSX`}:{color:`#6b7280`,label:`FILE`};return(0,f.jsxs)(`div`,{style:{minWidth:`200px`,maxWidth:`240px`},children:[c&&(0,f.jsx)(`div`,{style:{marginBottom:`6px`,fontSize:`14px`,color:n?`#fff`:`#111827`,whiteSpace:`normal`,wordBreak:`break-word`},children:s}),a?(0,f.jsx)(`button`,{type:`button`,onClick:()=>g({url:e.metadata.fileUrl,name:r}),onMouseEnter:()=>v(e.id),onMouseLeave:()=>v(null),style:{display:`block`,width:`100%`,background:`transparent`,border:0,padding:0,margin:0,textAlign:`left`,cursor:`pointer`},children:(0,f.jsxs)(`div`,{style:{position:`relative`},children:[(0,f.jsx)(`img`,{src:e.metadata.fileUrl,alt:r,style:{width:`100%`,borderRadius:`10px`,display:`block`,maxHeight:`180px`,objectFit:`cover`}}),(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,borderRadius:`10px`,background:_===e.id?`rgba(17,24,39,0.32)`:`rgba(17,24,39,0)`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#fff`,fontSize:`13px`,fontWeight:700,letterSpacing:`0.02em`,opacity:_===e.id?1:0,transition:`background 0.18s ease, opacity 0.18s ease`,pointerEvents:`none`},children:`Preview`})]})}):(0,f.jsx)(`a`,{href:e.metadata.fileUrl,target:`_blank`,rel:`noopener noreferrer`,style:{textDecoration:`none`,display:`block`},children:(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`10px`,background:n?`rgba(255,255,255,0.15)`:`#f3f4f6`,borderRadius:`12px`,padding:`10px 12px`},children:[(0,f.jsxs)(`div`,{style:{width:`38px`,height:`46px`,borderRadius:`8px`,background:n?`rgba(255,255,255,0.22)`:`#fff`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 1px 4px rgba(0,0,0,0.1)`,gap:`3px`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`#fff`:l.color,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`}),(0,f.jsx)(`polyline`,{points:`14 2 14 8 20 8`})]}),(0,f.jsx)(`span`,{style:{fontSize:`7px`,fontWeight:800,letterSpacing:`0.04em`,color:n?`#fff`:l.color,lineHeight:1},children:l.label})]}),(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:n?`#fff`:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:r}),i&&(0,f.jsx)(`div`,{style:{fontSize:`11px`,marginTop:`3px`,color:n?`rgba(255,255,255,0.6)`:`#9ca3af`},children:i})]}),(0,f.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`rgba(255,255,255,0.65)`:`#9ca3af`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,f.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,f.jsx)(`polyline`,{points:`7 10 12 15 17 10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`15`,x2:`12`,y2:`3`})]})]})})]})})():r?(0,f.jsx)(`div`,{className:`flowengage-message-content fe-bot-message`,dangerouslySetInnerHTML:{__html:Xg(e.message)},onClick:D}):(0,f.jsx)(`div`,{style:{whiteSpace:`pre-wrap`},children:e.message})]}),(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,marginTop:`4px`,padding:`0 4px`,alignSelf:n?`flex-end`:`flex-start`},children:d?(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500,fontStyle:`italic`},children:`sending…`}):p?(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#dc2626`,fontWeight:500},children:`Not sent — tap send to try again`}):(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500},children:te(e.timestamp||e.createdAt)}),(0,f.jsx)(`span`,{style:{fontSize:`10px`,fontWeight:700,color:n?`var(--flowengage-primary)`:`#9ca3af`},children:`✓`})]})})]})]},e.id)}),(t||n)&&(0,f.jsxs)(`div`,{style:{marginBottom:`16px`,display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:c?`transparent`:`var(--flowengage-primary)`,color:`#fff`,boxShadow:c?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`},children:c||(0,f.jsx)(Lg,{size:16})}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`2px`,color:`#374151`,fontSize:`13px`,fontWeight:500,fontStyle:`italic`},children:[`Analysing`,[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`},children:`.`},e))]})]}),r&&(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:`8px`,marginBottom:`12px`},children:[(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,overflow:`hidden`},children:(0,f.jsx)(a_,{src:o||``,name:s,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})]}),(0,f.jsx)(`div`,{ref:m}),h&&(0,f.jsx)(`button`,{type:`button`,onClick:()=>g(null),style:{position:`fixed`,inset:0,zIndex:1e4,border:0,padding:`16px`,margin:0,background:`rgba(2,6,23,0.88)`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`default`},children:(0,f.jsxs)(`div`,{style:{position:`relative`,maxWidth:`min(96vw, 1100px)`,maxHeight:`96vh`,width:`100%`,display:`flex`,flexDirection:`column`,gap:`10px`,alignItems:`center`},children:[(0,f.jsx)(`img`,{src:h.url,alt:h.name,style:{width:`100%`,maxHeight:`calc(96vh - 72px)`,objectFit:`contain`,borderRadius:`16px`,boxShadow:`0 30px 80px rgba(0,0,0,0.42)`}}),(0,f.jsx)(`div`,{style:{maxWidth:`100%`,padding:`8px 14px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.92)`,color:`#0f172a`,fontSize:`12px`,fontWeight:600,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:h.name})]})})]})}var c_=typeof window<`u`&&(window.matchMedia?.(`(pointer: coarse)`).matches||navigator.maxTouchPoints>0);function l_({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:u,emailInput:p,setEmailInput:m,emailError:h,showVoiceToggle:g=!1,voiceEnabled:_=!0,onFileSelect:v,selectedFile:y=null,onRemoveSelectedFile:b,attachmentError:x=``,isUploadingAttachment:S=!1,inputPlaceholder:C=`Type your message`}){let w=(0,d.useRef)(null),T=(0,d.useRef)(null),E=e=>{e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)};(0,d.useEffect)(()=>{u||E(T.current)},[e,u]),(0,d.useEffect)(()=>{u||c_||e||s||T.current?.focus()},[e,u,s]);let ee=e=>{e.key===`Enter`&&(c_||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||(e.preventDefault(),e.currentTarget.form?.requestSubmit()))},D=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`,te=u?!!p?.trim():!!e?.trim()||!!y,ne=s||S||!te,re=!u&&_&&g;return(0,f.jsxs)(`div`,{style:{padding:`0 16px`,background:`transparent`},children:[c&&(0,f.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,D]}),(0,f.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),u&&(0,f.jsx)(`div`,{style:{marginBottom:`8px`,padding:`0 8px`},children:(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,f.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,f.jsx)(Lg,{size:13})}),(0,f.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),y&&!u&&(0,f.jsxs)(`div`,{style:{marginBottom:`10px`,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.06)`,background:`#fff`,padding:`12px 14px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,f.jsxs)(`div`,{style:{minWidth:0,flex:1},children:[(0,f.jsx)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`,marginBottom:`2px`},children:`Attachment ready`}),(0,f.jsx)(`div`,{style:{fontSize:`13px`,color:`#111827`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`},children:r_(y)}),(0,f.jsx)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginTop:`2px`},children:n_(y.size)})]}),(0,f.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`,flexShrink:0},onClick:b,"aria-label":`Remove attachment`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),(0,f.jsxs)(`form`,{style:{display:`flex`,alignItems:`flex-end`,gap:`8px`,minHeight:`40px`,padding:`4px`,border:`1px solid rgba(0,0,0,0.06)`,borderRadius:`20px`,background:`#fff`,boxShadow:`0 4px 14px rgba(0,0,0,0.04)`,opacity:1},onSubmit:n,children:[re?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`input`,{ref:w,type:`file`,accept:$g,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];t&&v?.(t),e.target.value=``}}),(0,f.jsx)(`button`,{type:`button`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`#f3f4f8`,color:`var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, opacity 0.2s ease`,border:0,cursor:`pointer`,flexShrink:0},onClick:()=>w.current?.click(),title:`Attach file`,"aria-label":`Attach file`,disabled:S,onMouseEnter:e=>{e.currentTarget.style.opacity=`0.8`},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(Rg,{size:16,color:`currentColor`})})]}):null,u?(0,f.jsx)(`input`,{className:`flowengage-chat-text-input`,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:0,paddingLeft:re?`0`:`8px`,color:`#111827`,background:`transparent`,cursor:`text`,alignSelf:`center`},value:p,onChange:e=>m(e.target.value),placeholder:`Enter your Email`,disabled:s,type:`email`,autoComplete:`email`}):(0,f.jsx)(`textarea`,{ref:T,className:`flowengage-chat-text-input`,rows:1,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,lineHeight:`20px`,outline:`none`,padding:`6px 0`,paddingLeft:re?`0`:`8px`,color:`#111827`,background:`transparent`,cursor:`text`,resize:`none`,maxHeight:`120px`,overflowY:`auto`},value:e,onChange:e=>{t(e.target.value),E(e.target)},onKeyDown:ee,placeholder:o===`agent`?`Message the agent…`:C,disabled:s,autoComplete:`off`}),(0,f.jsx)(`button`,{type:`submit`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`var(--flowengage-primary)`,color:`#fff`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`opacity 0.2s ease`,cursor:ne?`not-allowed`:`pointer`,opacity:ne?.45:1,flexShrink:0},disabled:ne,onMouseEnter:e=>{ne||(e.currentTarget.style.opacity=`0.85`)},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,f.jsx)(Ng,{size:16})})]}),!u&&x&&(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`7px 4px 0`},children:[(0,f.jsxs)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#dc2626`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,f.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),(0,f.jsx)(`span`,{style:{fontSize:`11px`,color:`#dc2626`,fontWeight:500},children:x})]}),u&&h&&(0,f.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:h})]})}function u_({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,isRateLimited:i,rateLimitMessage:a}){return(0,f.jsxs)(f.Fragment,{children:[(e||t)&&(0,f.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,f.jsx)(Ig,{className:``}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,f.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),i&&(0,f.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:a})]})}var d_=[`#135bd8`,`#ef334b`,`#ffbd2e`];function f_(e){return!Array.isArray(e)||e.length===0?d_:e.length===1?[e[0],e[0],e[0]]:e.length===2?[e[0],e[1],e[0]]:[e[0],e[1],e[2]]}var p_={idle:3,listening:.75,thinking:1,speaking:1.4,muted:.75,error:.08};function m_(e){if(!e||typeof e!=`string`)return[0,0,0];let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}function h_(e,t){if(!e||typeof e!=`string`)return`rgba(0,0,0,${t})`;if(e.startsWith(`rgb`))return e.replace(/[\d.]+\)$/,`${t})`);let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n;return`rgba(${parseInt(r.slice(0,2),16)},${parseInt(r.slice(2,4),16)},${parseInt(r.slice(4,6),16)},${t})`}var g_=`
262
262
  attribute vec2 a_pos;
263
263
  varying vec2 v_uv;
264
264
  void main() {
265
265
  v_uv = a_pos * 0.5 + 0.5;
266
266
  gl_Position = vec4(a_pos, 0.0, 1.0);
267
267
  }
268
- `,g_=`
268
+ `,__=`
269
269
  precision highp float;
270
270
 
271
271
  varying vec2 v_uv;
@@ -380,7 +380,7 @@
380
380
 
381
381
  gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
382
382
  }
383
- `;function __(e,t,n){let r=(t,n)=>{let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(console.error(`[AnimatedOrb shader]`,e.getShaderInfoLog(r)),null)},i=r(e.VERTEX_SHADER,t),a=r(e.FRAGMENT_SHADER,n);if(!i||!a)return null;let o=e.createProgram();return e.attachShader(o,i),e.attachShader(o,a),e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)?o:(console.error(`[AnimatedOrb link]`,e.getProgramInfoLog(o)),null)}function v_({size:e=94,voiceState:t=`idle`,isMuted:n=!1,colors:r,onClick:i,style:a,className:o}){let[s,c,l]=d_(r),u=t===`speaking`,p=e<=50,m=(0,d.useRef)(null),h=(0,d.useRef)(f_[t]??.35);(0,d.useEffect)(()=>{h.current=f_[t]??.35},[t]),(0,d.useEffect)(()=>{let t=m.current;if(!t)return;let n=Math.min(window.devicePixelRatio||1,2);t.width=e*n,t.height=e*n;let r=t.getContext(`webgl`,{alpha:!0,antialias:!0})||t.getContext(`experimental-webgl`,{alpha:!0,antialias:!0});if(!r){console.warn(`[AnimatedOrb] WebGL unavailable.`);return}let i=__(r,h_,g_);if(!i){console.error(`[AnimatedOrb] WebGL program failed to compile/link`);return}r.useProgram(i);let a=r.createBuffer();r.bindBuffer(r.ARRAY_BUFFER,a),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW);let o=r.getAttribLocation(i,`a_pos`);r.enableVertexAttribArray(o),r.vertexAttribPointer(o,2,r.FLOAT,!1,0,0);let u={time:r.getUniformLocation(i,`u_time`),speed:r.getUniformLocation(i,`u_speed`),c1:r.getUniformLocation(i,`u_c1`),c2:r.getUniformLocation(i,`u_c2`),c3:r.getUniformLocation(i,`u_c3`)};r.uniform3fv(u.c1,p_(s)),r.uniform3fv(u.c2,p_(c)),r.uniform3fv(u.c3,p_(l)),r.viewport(0,0,t.width,t.height);let d=performance.now(),f,p=e=>{r.uniform1f(u.time,(e-d)/1e3),r.uniform1f(u.speed,h.current),r.drawArrays(r.TRIANGLES,0,6),f=requestAnimationFrame(p)};return f=requestAnimationFrame(p),()=>{cancelAnimationFrame(f),r.deleteProgram(i),r.deleteBuffer(a)}},[s,c,l,e]);let g=n?`saturate(0.3) brightness(1.1)`:t===`error`?`saturate(0.4) hue-rotate(28deg)`:`none`;return(0,f.jsxs)(`div`,{style:{position:`relative`,width:e,height:e,flexShrink:0,cursor:i?`pointer`:`default`,...a},className:o,onClick:i,children:[u&&!p&&(0,f.jsx)(lh.div,{style:{position:`absolute`,inset:-10,borderRadius:`50%`,background:`radial-gradient(circle, ${m_(s,.18)} 0%, transparent 70%)`,pointerEvents:`none`},animate:{opacity:[.3,.75]},transition:{duration:1,repeat:1/0,repeatType:`mirror`,ease:`easeInOut`}}),(0,f.jsx)(`div`,{style:{width:e,height:e,borderRadius:`50%`,overflow:`hidden`,WebkitMaskImage:`-webkit-radial-gradient(white, black)`,filter:g,transition:`filter 1.2s ease`},children:(0,f.jsx)(`canvas`,{ref:m,style:{width:`100%`,height:`100%`,display:`block`}})}),u&&(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,pointerEvents:`none`,zIndex:1},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`3px`},children:[4,8,12,8,4].map((e,t)=>(0,f.jsx)(lh.div,{style:{width:`3px`,borderRadius:`3px`,background:`rgba(255,255,255,0.85)`},animate:{height:[4,e+8,4]},transition:{duration:.48,delay:t*.08,repeat:1/0,ease:`easeInOut`}},t))})})]})}var y_=`
383
+ `;function v_(e,t,n){let r=(t,n)=>{let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(console.error(`[AnimatedOrb shader]`,e.getShaderInfoLog(r)),null)},i=r(e.VERTEX_SHADER,t),a=r(e.FRAGMENT_SHADER,n);if(!i||!a)return null;let o=e.createProgram();return e.attachShader(o,i),e.attachShader(o,a),e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)?o:(console.error(`[AnimatedOrb link]`,e.getProgramInfoLog(o)),null)}function y_({size:e=94,voiceState:t=`idle`,isMuted:n=!1,colors:r,onClick:i,style:a,className:o}){let[s,c,l]=f_(r),u=t===`speaking`,p=e<=50,m=(0,d.useRef)(null),h=(0,d.useRef)(p_[t]??.35);(0,d.useEffect)(()=>{h.current=p_[t]??.35},[t]),(0,d.useEffect)(()=>{let t=m.current;if(!t)return;let n=Math.min(window.devicePixelRatio||1,2);t.width=e*n,t.height=e*n;let r=t.getContext(`webgl`,{alpha:!0,antialias:!0})||t.getContext(`experimental-webgl`,{alpha:!0,antialias:!0});if(!r){console.warn(`[AnimatedOrb] WebGL unavailable.`);return}let i=v_(r,g_,__);if(!i){console.error(`[AnimatedOrb] WebGL program failed to compile/link`);return}r.useProgram(i);let a=r.createBuffer();r.bindBuffer(r.ARRAY_BUFFER,a),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW);let o=r.getAttribLocation(i,`a_pos`);r.enableVertexAttribArray(o),r.vertexAttribPointer(o,2,r.FLOAT,!1,0,0);let u={time:r.getUniformLocation(i,`u_time`),speed:r.getUniformLocation(i,`u_speed`),c1:r.getUniformLocation(i,`u_c1`),c2:r.getUniformLocation(i,`u_c2`),c3:r.getUniformLocation(i,`u_c3`)};r.uniform3fv(u.c1,m_(s)),r.uniform3fv(u.c2,m_(c)),r.uniform3fv(u.c3,m_(l)),r.viewport(0,0,t.width,t.height);let d=performance.now(),f,p=e=>{r.uniform1f(u.time,(e-d)/1e3),r.uniform1f(u.speed,h.current),r.drawArrays(r.TRIANGLES,0,6),f=requestAnimationFrame(p)};return f=requestAnimationFrame(p),()=>{cancelAnimationFrame(f),r.deleteProgram(i),r.deleteBuffer(a)}},[s,c,l,e]);let g=n?`saturate(0.3) brightness(1.1)`:t===`error`?`saturate(0.4) hue-rotate(28deg)`:`none`;return(0,f.jsxs)(`div`,{style:{position:`relative`,width:e,height:e,flexShrink:0,cursor:i?`pointer`:`default`,...a},className:o,onClick:i,children:[u&&!p&&(0,f.jsx)(uh.div,{style:{position:`absolute`,inset:-10,borderRadius:`50%`,background:`radial-gradient(circle, ${h_(s,.18)} 0%, transparent 70%)`,pointerEvents:`none`},animate:{opacity:[.3,.75]},transition:{duration:1,repeat:1/0,repeatType:`mirror`,ease:`easeInOut`}}),(0,f.jsx)(`div`,{style:{width:e,height:e,borderRadius:`50%`,overflow:`hidden`,WebkitMaskImage:`-webkit-radial-gradient(white, black)`,filter:g,transition:`filter 1.2s ease`},children:(0,f.jsx)(`canvas`,{ref:m,style:{width:`100%`,height:`100%`,display:`block`}})}),u&&(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,pointerEvents:`none`,zIndex:1},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`3px`},children:[4,8,12,8,4].map((e,t)=>(0,f.jsx)(uh.div,{style:{width:`3px`,borderRadius:`3px`,background:`rgba(255,255,255,0.85)`},animate:{height:[4,e+8,4]},transition:{duration:.48,delay:t*.08,repeat:1/0,ease:`easeInOut`}},t))})})]})}var b_=`
384
384
  @keyframes fe-call-ring-pulse {
385
385
  0% { transform: scale(1); opacity: 0.55; }
386
386
  70% { transform: scale(1.85); opacity: 0; }
@@ -409,22 +409,22 @@
409
409
  0%, 100% { opacity: 0.5; transform: scale(1); }
410
410
  50% { opacity: 0.9; transform: scale(1.12); }
411
411
  }
412
- `;function b_(e){let t=(e||``).replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return`${parseInt(n.slice(0,2),16)},${parseInt(n.slice(2,4),16)},${parseInt(n.slice(4,6),16)}`}function x_(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function S_(e,t){let n=Array.isArray(e)&&e.length>0?e:[t||`#3B82F6`],[r,i,a]=n;return n.length===1?[`radial-gradient(ellipse 110% 65% at 50% -5%, ${r}28 0%, transparent 68%)`,`radial-gradient(ellipse 90% 55% at 50% 108%, ${r}1a 0%, transparent 65%)`,`#f7f8fa`].join(`, `):n.length===2?[`radial-gradient(ellipse 80% 100% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${i}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 70% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${i}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${a}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function C_({headshot:e,name:t,size:n=80,primaryColor:r=`#3B82F6`}){let i=(t||`A`)[0].toUpperCase(),a=x_(r),o=n>48?{boxShadow:`0 0 0 3px ${r}44`,border:`3px solid rgba(255,255,255,0.15)`}:{border:`1.5px solid ${r}55`};return e?(0,f.jsx)(`img`,{src:e,alt:t||`Agent`,style:{width:n,height:n,borderRadius:`50%`,objectFit:`cover`,position:`relative`,zIndex:1,flexShrink:0,...o}}):(0,f.jsx)(`div`,{style:{width:n,height:n,borderRadius:`50%`,background:`linear-gradient(135deg, ${r}, ${r}99)`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:Math.round(n*.36)+`px`,fontWeight:700,color:a,position:`relative`,zIndex:1,flexShrink:0,...o},children:i})}function w_(e){let t=(0,d.useRef)(null),n=(0,d.useCallback)(()=>{if(!t.current)return;let{audioContext:e,oscillator:n,interval:r,toneTimeout:i}=t.current;window.clearInterval(r),window.clearTimeout(i);try{n.stop()}catch{}try{e.close()}catch{}t.current=null},[]),r=(0,d.useCallback)(()=>{if(t.current||typeof window>`u`)return;let e=window.AudioContext||window.webkitAudioContext||null;if(e)try{let n=new e,r=n.createOscillator(),i=n.createGain();r.connect(i),i.connect(n.destination),r.frequency.value=0,r.type=`sine`,i.gain.value=.3;let a=()=>{t.current&&(window.clearTimeout(t.current.toneTimeout),r.frequency.value=440,t.current.toneTimeout=window.setTimeout(()=>{r.frequency.value=0},400))};n.state===`suspended`&&n.resume().catch(e=>{console.warn(`[FlowEngage] ringtone autoplay blocked`,e)}),r.start(),t.current={audioContext:n,oscillator:r,interval:null,toneTimeout:null},a(),t.current.interval=window.setInterval(a,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);return(0,d.useEffect)(()=>{if(e){r();return}n()},[e,r,n]),(0,d.useEffect)(()=>()=>n(),[n]),n}function T_({incomingCall:e,activeCallId:t,callConnectionState:n,callDurationSeconds:r,isCallMuted:i,agentName:a,agentHeadshot:o,fallbackAgentName:s,acceptCall:c,rejectCall:l,endWebRTCCall:u,toggleCallMute:d,formatCallDuration:p,onMinimize:m,primaryColor:h=`#3B82F6`,orbColors:g,chatHistory:_=[]}){let v=a||s||`Agent`,y=e?`incoming`:n===`connecting`?`connecting`:`ongoing`,b=w_(!!e),x=async()=>{b(),await c()},S=async()=>{b(),await l()},C=i?`muted`:n===`connecting`?`idle`:`listening`,w=y===`ongoing`,T={position:`absolute`,inset:0,zIndex:10,display:`flex`,flexDirection:`column`,borderRadius:`inherit`,overflow:`hidden`,background:S_(g,h),animation:w?`fe-call-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`:`fe-call-fade-in 0.32s ease`};if(y===`incoming`){let e=Array.isArray(g)&&g.length>0?g:[h];return(0,f.jsxs)(`div`,{style:T,children:[(0,f.jsx)(`style`,{children:y_}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,padding:`60px 32px 56px`},children:[(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`22px`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`,width:`96px`,height:`96px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,f.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,background:`radial-gradient(circle, rgba(${b_(e[0])},0.2) 0%, transparent 70%)`,filter:`blur(10px)`,zIndex:0}}),[0,.5,1].map((t,n)=>(0,f.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,border:`1.5px solid ${e[n%e.length]}`,animation:`fe-call-ring-pulse 2.6s cubic-bezier(0.215,0.61,0.355,1) ${t}s infinite`,zIndex:1}},n)),(0,f.jsx)(C_,{headshot:o,name:v,size:82,primaryColor:h})]}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`div`,{style:{fontSize:`22px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.015em`,lineHeight:1.2},children:v}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`6px`,marginTop:`8px`},children:[(0,f.jsx)(`div`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:e[0],boxShadow:`0 0 5px ${e[0]}88`,animation:`fe-call-dot-blink 1.4s ease-in-out infinite`}}),(0,f.jsx)(`span`,{style:{fontSize:`13px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Incoming call`})]})]})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`56px`,alignItems:`flex-end`},children:[(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,f.jsx)(`button`,{type:`button`,onClick:S,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(239,68,68,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(239,68,68,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(239,68,68,0.5)`},"aria-label":`Decline call`,children:(0,f.jsx)(jg,{size:26})}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Decline`})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,f.jsx)(`button`,{type:`button`,onClick:x,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#22c55e`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(34,197,94,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(34,197,94,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(34,197,94,0.5)`},"aria-label":`Accept call`,children:(0,f.jsx)(Pg,{})}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Accept`})]})]})]})]})}return y===`connecting`?(0,f.jsxs)(`div`,{style:T,children:[(0,f.jsx)(`style`,{children:y_}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`24px`},children:[(0,f.jsx)(C_,{headshot:o,name:v,size:64,primaryColor:h}),(0,f.jsx)(`div`,{style:{width:`48px`,height:`48px`,borderRadius:`50%`,border:`3px solid rgba(255,255,255,0.12)`,borderTopColor:Array.isArray(g)&&g[0]||h,animation:`fe-call-spin 0.9s linear infinite`}}),(0,f.jsx)(`span`,{style:{fontSize:`15px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Connecting…`})]})]}):(0,f.jsxs)(`div`,{style:T,children:[(0,f.jsx)(`style`,{children:y_}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px 16px 10px`,gap:`10px`,flexShrink:0},children:[(0,f.jsx)(`button`,{type:`button`,onClick:m,style:{width:`40px`,height:`40px`,borderRadius:`50%`,background:`rgba(0,0,0,0.06)`,border:`1px solid rgba(0,0,0,0.1)`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#374151`,transition:`background 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.11)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.06)`},"aria-label":`Minimize call`,children:(0,f.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`15 18 9 12 15 6`})})}),(0,f.jsx)(v_,{colors:g,size:36,voiceState:C}),(0,f.jsx)(`div`,{style:{flex:1,minWidth:0,fontSize:`15px`,fontWeight:600,color:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:v}),(0,f.jsx)(`div`,{style:{flexShrink:0,padding:`3px 10px`,borderRadius:`999px`,background:`${h}18`,border:`1px solid ${h}44`,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`11px`,fontWeight:600,color:h,letterSpacing:`0.02em`,lineHeight:1},children:`On Call`})})]}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`,padding:`0 24px 16px`},children:[(0,f.jsx)(C_,{headshot:o,name:v,size:116,primaryColor:h}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`div`,{style:{fontSize:`20px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.01em`},children:v}),(0,f.jsx)(`div`,{style:{marginTop:`8px`,fontSize:`24px`,fontWeight:300,color:`#9ca3af`,letterSpacing:`0.06em`,fontVariantNumeric:`tabular-nums`},children:p(r)})]})]}),(0,f.jsxs)(`div`,{style:{flexShrink:0,display:`flex`,gap:`12px`,padding:`16px 24px 40px`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:d,style:{flex:1,height:`54px`,borderRadius:`14px`,background:i?`rgba(239,68,68,0.1)`:`rgba(0,0,0,0.06)`,border:i?`1.5px solid rgba(239,68,68,0.4)`:`1.5px solid rgba(0,0,0,0.1)`,cursor:`pointer`,color:i?`#ef4444`:`#374151`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,fontSize:`14px`,fontWeight:600,transition:`all 0.2s ease`},"aria-label":i?`Unmute`:`Mute`,children:[i?(0,f.jsx)(Vg,{size:18}):(0,f.jsx)(Ag,{size:18}),i?`Unmute`:`Mute`]}),(0,f.jsxs)(`button`,{type:`button`,onClick:u,style:{flex:1,height:`54px`,borderRadius:`14px`,background:`rgba(239,68,68,0.9)`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`white`,fontSize:`14px`,fontWeight:600,boxShadow:`0 4px 20px rgba(239,68,68,0.38)`,transition:`transform 0.15s ease, background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#ef4444`,e.currentTarget.style.transform=`scale(1.02)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(239,68,68,0.9)`,e.currentTarget.style.transform=`scale(1)`},"aria-label":`End call`,children:[(0,f.jsx)(jg,{size:18}),`End Call`]})]})]})}function E_({agentName:e,agentHeadshot:t,fallbackAgentName:n,callDurationSeconds:r,isCallMuted:i,formatCallDuration:a,toggleCallMute:o,endWebRTCCall:s,onExpand:c,primaryColor:l=`#3B82F6`}){let u=e||n||`Agent`;return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`style`,{children:y_}),(0,f.jsxs)(`div`,{role:`button`,tabIndex:0,onClick:c,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&c?.()},onMouseEnter:e=>{e.currentTarget.style.boxShadow=`0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08), inset 0 1px 0 rgba(255,255,255,0.95)`,e.currentTarget.style.transform=`translateY(-2px)`},onMouseLeave:e=>{e.currentTarget.style.boxShadow=`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,e.currentTarget.style.transform=`translateY(0)`},style:{display:`flex`,alignItems:`center`,gap:`12px`,padding:`10px 12px 10px 10px`,margin:`0 12px 8px`,borderRadius:`18px`,background:`rgba(255,255,255,0.88)`,backdropFilter:`blur(20px)`,WebkitBackdropFilter:`blur(20px)`,border:`1px solid rgba(255,255,255,0.65)`,boxShadow:`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,cursor:`pointer`,animation:`fe-call-bar-slide-in 0.3s cubic-bezier(0.16,1,0.3,1)`,flexShrink:0,userSelect:`none`,outline:`none`,transition:`box-shadow 0.22s ease, transform 0.18s ease`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`,flexShrink:0,width:`42px`,height:`42px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,f.jsx)(`div`,{style:{position:`absolute`,inset:`-4px`,borderRadius:`50%`,background:`${l}28`,animation:`fe-call-avatar-breathe 2.8s ease-in-out infinite`}}),(0,f.jsx)(`div`,{style:{position:`absolute`,inset:`-2px`,borderRadius:`50%`,border:`1.5px solid ${l}55`}}),(0,f.jsx)(C_,{headshot:t,name:u,size:38,primaryColor:l})]}),(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:`#111827`,lineHeight:1.3,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:u}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,marginTop:`3px`},children:[(0,f.jsx)(`div`,{style:{width:`6px`,height:`6px`,borderRadius:`50%`,background:`#22c55e`,flexShrink:0,boxShadow:`0 0 4px rgba(34,197,94,0.6)`,animation:`fe-call-dot-blink 1.6s ease-in-out infinite`}}),(0,f.jsxs)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontVariantNumeric:`tabular-nums`,letterSpacing:`0.01em`},children:[`On Call\xA0•\xA0`,a(r)]})]})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`,flexShrink:0},children:[(0,f.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:i?`${l}18`:`rgba(0,0,0,0.05)`,border:i?`1.5px solid ${l}55`:`1.5px solid rgba(0,0,0,0.08)`,cursor:`pointer`,color:i?l:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,transition:`all 0.18s ease`,boxShadow:i?`0 0 0 3px ${l}12`:`none`},"aria-label":i?`Unmute`:`Mute`,children:i?(0,f.jsx)(Vg,{size:15}):(0,f.jsx)(Ag,{size:15})}),(0,f.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),s()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`,e.currentTarget.style.boxShadow=`0 4px 16px rgba(239,68,68,0.55)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 2px 10px rgba(239,68,68,0.35)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,color:`white`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 2px 10px rgba(239,68,68,0.35)`,transition:`all 0.18s ease`},"aria-label":`End call`,children:(0,f.jsx)(jg,{size:16})})]})]})]})}function D_(e,t={}){let n=t.maxChars??4500;if(!Array.isArray(e)||e.length===0)return``;let r=[];for(let t of e){if(!t||t.isPending)continue;let e=String(t.sender||``).toLowerCase(),n=null;if(e===`user`?n=`Visitor`:(e===`bot`||e===`ai`||e===`agent`)&&(n=`Assistant`),!n)continue;let i=String(t.message||``).replace(/<[^>]+>/g,` `).replace(/\s+/g,` `).trim().slice(0,1200);i&&r.push(`${n}: ${i}`)}if(r.length===0)return``;let i=r.join(`
412
+ `;function x_(e){let t=(e||``).replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return`${parseInt(n.slice(0,2),16)},${parseInt(n.slice(2,4),16)},${parseInt(n.slice(4,6),16)}`}function S_(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function C_(e,t){let n=Array.isArray(e)&&e.length>0?e:[t||`#3B82F6`],[r,i,a]=n;return n.length===1?[`radial-gradient(ellipse 110% 65% at 50% -5%, ${r}28 0%, transparent 68%)`,`radial-gradient(ellipse 90% 55% at 50% 108%, ${r}1a 0%, transparent 65%)`,`#f7f8fa`].join(`, `):n.length===2?[`radial-gradient(ellipse 80% 100% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${i}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 70% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${i}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${a}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function w_({headshot:e,name:t,size:n=80,primaryColor:r=`#3B82F6`}){let i=(t||`A`)[0].toUpperCase(),a=S_(r),o=n>48?{boxShadow:`0 0 0 3px ${r}44`,border:`3px solid rgba(255,255,255,0.15)`}:{border:`1.5px solid ${r}55`};return e?(0,f.jsx)(`img`,{src:e,alt:t||`Agent`,style:{width:n,height:n,borderRadius:`50%`,objectFit:`cover`,position:`relative`,zIndex:1,flexShrink:0,...o}}):(0,f.jsx)(`div`,{style:{width:n,height:n,borderRadius:`50%`,background:`linear-gradient(135deg, ${r}, ${r}99)`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:Math.round(n*.36)+`px`,fontWeight:700,color:a,position:`relative`,zIndex:1,flexShrink:0,...o},children:i})}function T_(e){let t=(0,d.useRef)(null),n=(0,d.useCallback)(()=>{if(!t.current)return;let{audioContext:e,oscillator:n,interval:r,toneTimeout:i}=t.current;window.clearInterval(r),window.clearTimeout(i);try{n.stop()}catch{}try{e.close()}catch{}t.current=null},[]),r=(0,d.useCallback)(()=>{if(t.current||typeof window>`u`)return;let e=window.AudioContext||window.webkitAudioContext||null;if(e)try{let n=new e,r=n.createOscillator(),i=n.createGain();r.connect(i),i.connect(n.destination),r.frequency.value=0,r.type=`sine`,i.gain.value=.3;let a=()=>{t.current&&(window.clearTimeout(t.current.toneTimeout),r.frequency.value=440,t.current.toneTimeout=window.setTimeout(()=>{r.frequency.value=0},400))};n.state===`suspended`&&n.resume().catch(e=>{console.warn(`[FlowEngage] ringtone autoplay blocked`,e)}),r.start(),t.current={audioContext:n,oscillator:r,interval:null,toneTimeout:null},a(),t.current.interval=window.setInterval(a,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);return(0,d.useEffect)(()=>{if(e){r();return}n()},[e,r,n]),(0,d.useEffect)(()=>()=>n(),[n]),n}function E_({incomingCall:e,activeCallId:t,callConnectionState:n,callDurationSeconds:r,isCallMuted:i,agentName:a,agentHeadshot:o,fallbackAgentName:s,acceptCall:c,rejectCall:l,endWebRTCCall:u,toggleCallMute:d,formatCallDuration:p,onMinimize:m,primaryColor:h=`#3B82F6`,orbColors:g,chatHistory:_=[]}){let v=a||s||`Agent`,y=e?`incoming`:n===`connecting`?`connecting`:`ongoing`,b=T_(!!e),x=async()=>{b(),await c()},S=async()=>{b(),await l()},C=i?`muted`:n===`connecting`?`idle`:`listening`,w=y===`ongoing`,T={position:`absolute`,inset:0,zIndex:10,display:`flex`,flexDirection:`column`,borderRadius:`inherit`,overflow:`hidden`,background:C_(g,h),animation:w?`fe-call-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`:`fe-call-fade-in 0.32s ease`};if(y===`incoming`){let e=Array.isArray(g)&&g.length>0?g:[h];return(0,f.jsxs)(`div`,{style:T,children:[(0,f.jsx)(`style`,{children:b_}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,padding:`60px 32px 56px`},children:[(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`22px`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`,width:`96px`,height:`96px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,f.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,background:`radial-gradient(circle, rgba(${x_(e[0])},0.2) 0%, transparent 70%)`,filter:`blur(10px)`,zIndex:0}}),[0,.5,1].map((t,n)=>(0,f.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,border:`1.5px solid ${e[n%e.length]}`,animation:`fe-call-ring-pulse 2.6s cubic-bezier(0.215,0.61,0.355,1) ${t}s infinite`,zIndex:1}},n)),(0,f.jsx)(w_,{headshot:o,name:v,size:82,primaryColor:h})]}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`div`,{style:{fontSize:`22px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.015em`,lineHeight:1.2},children:v}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`6px`,marginTop:`8px`},children:[(0,f.jsx)(`div`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:e[0],boxShadow:`0 0 5px ${e[0]}88`,animation:`fe-call-dot-blink 1.4s ease-in-out infinite`}}),(0,f.jsx)(`span`,{style:{fontSize:`13px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Incoming call`})]})]})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`56px`,alignItems:`flex-end`},children:[(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,f.jsx)(`button`,{type:`button`,onClick:S,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(239,68,68,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(239,68,68,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(239,68,68,0.5)`},"aria-label":`Decline call`,children:(0,f.jsx)(Mg,{size:26})}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Decline`})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,f.jsx)(`button`,{type:`button`,onClick:x,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#22c55e`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(34,197,94,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(34,197,94,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(34,197,94,0.5)`},"aria-label":`Accept call`,children:(0,f.jsx)(Fg,{})}),(0,f.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Accept`})]})]})]})]})}return y===`connecting`?(0,f.jsxs)(`div`,{style:T,children:[(0,f.jsx)(`style`,{children:b_}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`24px`},children:[(0,f.jsx)(w_,{headshot:o,name:v,size:64,primaryColor:h}),(0,f.jsx)(`div`,{style:{width:`48px`,height:`48px`,borderRadius:`50%`,border:`3px solid rgba(255,255,255,0.12)`,borderTopColor:Array.isArray(g)&&g[0]||h,animation:`fe-call-spin 0.9s linear infinite`}}),(0,f.jsx)(`span`,{style:{fontSize:`15px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Connecting…`})]})]}):(0,f.jsxs)(`div`,{style:T,children:[(0,f.jsx)(`style`,{children:b_}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px 16px 10px`,gap:`10px`,flexShrink:0},children:[(0,f.jsx)(`button`,{type:`button`,onClick:m,style:{width:`40px`,height:`40px`,borderRadius:`50%`,background:`rgba(0,0,0,0.06)`,border:`1px solid rgba(0,0,0,0.1)`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#374151`,transition:`background 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.11)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.06)`},"aria-label":`Minimize call`,children:(0,f.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`15 18 9 12 15 6`})})}),(0,f.jsx)(y_,{colors:g,size:36,voiceState:C}),(0,f.jsx)(`div`,{style:{flex:1,minWidth:0,fontSize:`15px`,fontWeight:600,color:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:v}),(0,f.jsx)(`div`,{style:{flexShrink:0,padding:`3px 10px`,borderRadius:`999px`,background:`${h}18`,border:`1px solid ${h}44`,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`11px`,fontWeight:600,color:h,letterSpacing:`0.02em`,lineHeight:1},children:`On Call`})})]}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`,padding:`0 24px 16px`},children:[(0,f.jsx)(w_,{headshot:o,name:v,size:116,primaryColor:h}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`div`,{style:{fontSize:`20px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.01em`},children:v}),(0,f.jsx)(`div`,{style:{marginTop:`8px`,fontSize:`24px`,fontWeight:300,color:`#9ca3af`,letterSpacing:`0.06em`,fontVariantNumeric:`tabular-nums`},children:p(r)})]})]}),(0,f.jsxs)(`div`,{style:{flexShrink:0,display:`flex`,gap:`12px`,padding:`16px 24px 40px`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:d,style:{flex:1,height:`54px`,borderRadius:`14px`,background:i?`rgba(239,68,68,0.1)`:`rgba(0,0,0,0.06)`,border:i?`1.5px solid rgba(239,68,68,0.4)`:`1.5px solid rgba(0,0,0,0.1)`,cursor:`pointer`,color:i?`#ef4444`:`#374151`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,fontSize:`14px`,fontWeight:600,transition:`all 0.2s ease`},"aria-label":i?`Unmute`:`Mute`,children:[i?(0,f.jsx)(Hg,{size:18}):(0,f.jsx)(jg,{size:18}),i?`Unmute`:`Mute`]}),(0,f.jsxs)(`button`,{type:`button`,onClick:u,style:{flex:1,height:`54px`,borderRadius:`14px`,background:`rgba(239,68,68,0.9)`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`white`,fontSize:`14px`,fontWeight:600,boxShadow:`0 4px 20px rgba(239,68,68,0.38)`,transition:`transform 0.15s ease, background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#ef4444`,e.currentTarget.style.transform=`scale(1.02)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(239,68,68,0.9)`,e.currentTarget.style.transform=`scale(1)`},"aria-label":`End call`,children:[(0,f.jsx)(Mg,{size:18}),`End Call`]})]})]})}function D_({agentName:e,agentHeadshot:t,fallbackAgentName:n,callDurationSeconds:r,isCallMuted:i,formatCallDuration:a,toggleCallMute:o,endWebRTCCall:s,onExpand:c,primaryColor:l=`#3B82F6`}){let u=e||n||`Agent`;return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`style`,{children:b_}),(0,f.jsxs)(`div`,{role:`button`,tabIndex:0,onClick:c,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&c?.()},onMouseEnter:e=>{e.currentTarget.style.boxShadow=`0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08), inset 0 1px 0 rgba(255,255,255,0.95)`,e.currentTarget.style.transform=`translateY(-2px)`},onMouseLeave:e=>{e.currentTarget.style.boxShadow=`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,e.currentTarget.style.transform=`translateY(0)`},style:{display:`flex`,alignItems:`center`,gap:`12px`,padding:`10px 12px 10px 10px`,margin:`0 12px 8px`,borderRadius:`18px`,background:`rgba(255,255,255,0.88)`,backdropFilter:`blur(20px)`,WebkitBackdropFilter:`blur(20px)`,border:`1px solid rgba(255,255,255,0.65)`,boxShadow:`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,cursor:`pointer`,animation:`fe-call-bar-slide-in 0.3s cubic-bezier(0.16,1,0.3,1)`,flexShrink:0,userSelect:`none`,outline:`none`,transition:`box-shadow 0.22s ease, transform 0.18s ease`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`,flexShrink:0,width:`42px`,height:`42px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,f.jsx)(`div`,{style:{position:`absolute`,inset:`-4px`,borderRadius:`50%`,background:`${l}28`,animation:`fe-call-avatar-breathe 2.8s ease-in-out infinite`}}),(0,f.jsx)(`div`,{style:{position:`absolute`,inset:`-2px`,borderRadius:`50%`,border:`1.5px solid ${l}55`}}),(0,f.jsx)(w_,{headshot:t,name:u,size:38,primaryColor:l})]}),(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:`#111827`,lineHeight:1.3,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:u}),(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,marginTop:`3px`},children:[(0,f.jsx)(`div`,{style:{width:`6px`,height:`6px`,borderRadius:`50%`,background:`#22c55e`,flexShrink:0,boxShadow:`0 0 4px rgba(34,197,94,0.6)`,animation:`fe-call-dot-blink 1.6s ease-in-out infinite`}}),(0,f.jsxs)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontVariantNumeric:`tabular-nums`,letterSpacing:`0.01em`},children:[`On Call\xA0•\xA0`,a(r)]})]})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`,flexShrink:0},children:[(0,f.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:i?`${l}18`:`rgba(0,0,0,0.05)`,border:i?`1.5px solid ${l}55`:`1.5px solid rgba(0,0,0,0.08)`,cursor:`pointer`,color:i?l:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,transition:`all 0.18s ease`,boxShadow:i?`0 0 0 3px ${l}12`:`none`},"aria-label":i?`Unmute`:`Mute`,children:i?(0,f.jsx)(Hg,{size:15}):(0,f.jsx)(jg,{size:15})}),(0,f.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),s()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`,e.currentTarget.style.boxShadow=`0 4px 16px rgba(239,68,68,0.55)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 2px 10px rgba(239,68,68,0.35)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,color:`white`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 2px 10px rgba(239,68,68,0.35)`,transition:`all 0.18s ease`},"aria-label":`End call`,children:(0,f.jsx)(Mg,{size:16})})]})]})]})}function O_(e,t={}){let n=t.maxChars??4500;if(!Array.isArray(e)||e.length===0)return``;let r=[];for(let t of e){if(!t||t.isPending)continue;let e=String(t.sender||``).toLowerCase(),n=null;if(e===`user`?n=`Visitor`:(e===`bot`||e===`ai`||e===`agent`)&&(n=`Assistant`),!n)continue;let i=String(t.message||``).replace(/<[^>]+>/g,` `).replace(/\s+/g,` `).trim().slice(0,1200);i&&r.push(`${n}: ${i}`)}if(r.length===0)return``;let i=r.join(`
413
413
  `);return i.length>n&&(i=`…(earlier messages omitted)
414
- `+i.slice(-n)),i}var O_=/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i;function k_(e){return String(e||``).replace(O_,``).replace(/\/+$/,``).toLowerCase()||`/`}function A_(e,t){return k_(e)===k_(t)}function $(...e){_n()&&console.log(`[FlowEngage:voice-tools]`,...e)}function j_(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function M_(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!Tn(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function N_(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function P_(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return N_(r.join(` `))}if(e.labels&&e.labels.length)return N_(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return N_(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return N_(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return N_(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=N_(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return N_(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return N_(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?N_(o):null}function F_(){let e=[];return M_(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Tn(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=j_(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function I_(){return F_().map((e,t)=>{let n={formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:P_(e),placeholder:e.placeholder||null};return e.tagName===`SELECT`&&(n.options=Array.from(e.options).filter(e=>e.value!==``&&!e.disabled).map(e=>({value:e.value,text:e.text.trim()})),n.currentValue=e.value||null),n})}function L_(){let e=[];return M_(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Tn(e)||e.disabled)return!1;try{let t=j_(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function R_(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function z_(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=(e.innerText||e.textContent||``).replace(/\s+/g,` `).trim(),i=[r,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-text`),e.getAttribute(`data-label`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(i.includes(n)||r.toLowerCase()===n)return 100;let a=n.split(/\s+/).filter(e=>e.length>1);if(!a.length)return 0;let o=0;for(let e of a)i.includes(e)&&(o+=1);return o/a.length*92}function B_(e,t,n=6){let r=String(t||``).toLowerCase().trim();if(!r)return 1/0;let i=e;for(let e=0;e<=n&&i;e++,i=i.parentElement)if((i.innerText||i.textContent||``).toLowerCase().includes(r))return e;return 1/0}function V_(e,t,n){let r=[];M_(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));r.push(...t.filter(e=>{if(Tn(e)||e.disabled)return!1;try{let t=j_(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1}catch{}return!0}))});let i=0,a=r.map(t=>({el:t,s:z_(t,e)}));for(let{s:e}of a)e>i&&(i=e);if(i<28)return null;let o=a.filter(({s:e})=>e===i).map(({el:e})=>e);if(o.length===1)return o[0];if(n){let e=o.map(e=>B_(e,n)),t=Math.min(...e);if(t!==1/0&&(o=o.filter((n,r)=>e[r]===t)),o.length===1)return o[0]}let s=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(s.length){let e=o[0],t=1/0;for(let n of o)for(let r of s){let i=R_(n,r);i<t&&(t=i,e=n)}return e}return o[0]}function H_(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function U_(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function W_(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function G_(){let e=e=>{let t=Array.from(e).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)&&!e.closest(`nav, footer, header, aside, .nav, .footer, .header, .sidebar`)),n=[],r=0;for(;r<t.length;){let e=t[r],i=En(e);if(!i||i.length<2){r++;continue}let a=i;if(i.length<40&&!/[.!?:;]$/.test(i)&&r+1<t.length){let n=t[r+1],o=En(n);o&&n.tagName===e.tagName&&o.length<60&&(e.nextElementSibling===n||e.parentElement===n.parentElement)&&(a=`${i} ${o}`,r++)}a.length>2&&a.length<200&&n.push({text:a,level:Number(e.tagName.slice(1))||6}),r++}return n},t=document.querySelector(`main, [role='main']`)||document.body,n=e(t.querySelectorAll(`h1, h2, h3, h4, h5`));n.length||(n=e(document.body.querySelectorAll(`h1, h2, h3, h4, h5`)));let r=new Set,i=[];for(let e of n)if(!(!e||r.has(e.text))&&(r.add(e.text),i.push(e),i.length>=30))break;let a=i.map(e=>e.text),o=[];for(let e=0;e<i.length;e++){let t=0;for(let n=e+1;n<i.length&&!(i[n].level<=i[e].level);n++)t+=1;t>=3&&o.push(i[e].text)}let s=Array.from(t.querySelectorAll(`h1`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)&&!e.closest(`nav, footer, header, aside, .nav, .footer, .header, .sidebar`)),c=null;if(s.length===1){let e=En(s[0]);e&&a[0]&&a[0].toLowerCase().trim()===e.toLowerCase().trim()&&(c=a[0])}let l=``;try{let e=t.querySelector(`h1, h2, h3, h4, h5`);if(e){let n=document.createRange();n.setStart(t,0),n.setEndBefore(e);let r=n.cloneContents(),i=[];r.querySelectorAll(`p, li`).forEach(e=>{let t=e.textContent.replace(/\s+/g,` `).trim();t.length>20&&i.push(t)}),l=i.join(` `).slice(0,600)}}catch{}return{headings:a,pageTitleHeading:c,introText:l,containerHeadings:o}}function K_(e){if(!e||typeof document>`u`)return``;let t=new Set([`script`,`style`,`noscript`,`svg`,`iframe`,`nav`,`footer`,`header`,`aside`]),n=parseInt(e.tagName[1],10),r=Array.from({length:n},(e,t)=>`h${t+1}`).join(`, `),i=Array.from(document.querySelectorAll(r)).filter(e=>!e.closest(wn)),a=i.indexOf(e),o=a===-1?null:i[a+1],s=document.createRange();try{if(s.setStartAfter(e),o)s.setEndBefore(o);else{let e=document.querySelector(`main, [role='main'], article`)||document.body;s.setEnd(e,e.childNodes.length)}}catch{return e.textContent.replace(/\s+/g,` `).trim()}let c;try{c=s.cloneContents()}catch{return e.textContent.replace(/\s+/g,` `).trim()}let l=[];function u(e){if(e.nodeType===Node.TEXT_NODE){let t=e.textContent.replace(/\s+/g,` `).trim();t&&l.push(t);return}if(e.nodeType!==Node.ELEMENT_NODE)return;let n=e.tagName.toLowerCase();if(!t.has(n)){if(n===`ul`||n===`ol`){let t=Array.from(e.querySelectorAll(`:scope > li`)).map(e=>{let t=e.textContent.replace(/\s+/g,` `).trim();return t?`• ${t}`:null}).filter(Boolean);t.length&&l.push(t.join(`
414
+ `+i.slice(-n)),i}var k_=/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i;function A_(e){return String(e||``).replace(k_,``).replace(/\/+$/,``).toLowerCase()||`/`}function j_(e,t){return A_(e)===A_(t)}function $(...e){_n()&&console.log(`[FlowEngage:voice-tools]`,...e)}function M_(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function N_(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!Tn(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function P_(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function F_(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return P_(r.join(` `))}if(e.labels&&e.labels.length)return P_(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return P_(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return P_(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return P_(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=P_(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return P_(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return P_(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?P_(o):null}function I_(){let e=[];return N_(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Tn(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=M_(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function L_(){return I_().map((e,t)=>{let n={formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:F_(e),placeholder:e.placeholder||null};return e.tagName===`SELECT`&&(n.options=Array.from(e.options).filter(e=>e.value!==``&&!e.disabled).map(e=>({value:e.value,text:e.text.trim()})),n.currentValue=e.value||null),n})}function R_(){let e=[];return N_(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Tn(e)||e.disabled)return!1;try{let t=M_(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function z_(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function B_(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=(e.innerText||e.textContent||``).replace(/\s+/g,` `).trim(),i=[r,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-text`),e.getAttribute(`data-label`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(i.includes(n)||r.toLowerCase()===n)return 100;let a=n.split(/\s+/).filter(e=>e.length>1);if(!a.length)return 0;let o=0;for(let e of a)i.includes(e)&&(o+=1);return o/a.length*92}function V_(e,t,n=6){let r=String(t||``).toLowerCase().trim();if(!r)return 1/0;let i=e;for(let e=0;e<=n&&i;e++,i=i.parentElement)if((i.innerText||i.textContent||``).toLowerCase().includes(r))return e;return 1/0}function H_(e,t,n){let r=[];N_(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));r.push(...t.filter(e=>{if(Tn(e)||e.disabled)return!1;try{let t=M_(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1}catch{}return!0}))});let i=0,a=r.map(t=>({el:t,s:B_(t,e)}));for(let{s:e}of a)e>i&&(i=e);if(i<28)return null;let o=a.filter(({s:e})=>e===i).map(({el:e})=>e);if(o.length===1)return o[0];if(n){let e=o.map(e=>V_(e,n)),t=Math.min(...e);if(t!==1/0&&(o=o.filter((n,r)=>e[r]===t)),o.length===1)return o[0]}let s=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(s.length){let e=o[0],t=1/0;for(let n of o)for(let r of s){let i=z_(n,r);i<t&&(t=i,e=n)}return e}return o[0]}function U_(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function W_(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function G_(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function K_(){let e=e=>{let t=Array.from(e).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)&&!e.closest(`nav, footer, header, aside, .nav, .footer, .header, .sidebar`)),n=[],r=0;for(;r<t.length;){let e=t[r],i=En(e);if(!i||i.length<2){r++;continue}let a=i;if(i.length<40&&!/[.!?:;]$/.test(i)&&r+1<t.length){let n=t[r+1],o=En(n);o&&n.tagName===e.tagName&&o.length<60&&(e.nextElementSibling===n||e.parentElement===n.parentElement)&&(a=`${i} ${o}`,r++)}a.length>2&&a.length<200&&n.push({text:a,level:Number(e.tagName.slice(1))||6}),r++}return n},t=document.querySelector(`main, [role='main']`)||document.body,n=e(t.querySelectorAll(`h1, h2, h3, h4, h5`));n.length||(n=e(document.body.querySelectorAll(`h1, h2, h3, h4, h5`)));let r=new Set,i=[];for(let e of n)if(!(!e||r.has(e.text))&&(r.add(e.text),i.push(e),i.length>=30))break;let a=i.map(e=>e.text),o=[];for(let e=0;e<i.length;e++){let t=0;for(let n=e+1;n<i.length&&!(i[n].level<=i[e].level);n++)t+=1;t>=3&&o.push(i[e].text)}let s=Array.from(t.querySelectorAll(`h1`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)&&!e.closest(`nav, footer, header, aside, .nav, .footer, .header, .sidebar`)),c=null;if(s.length===1){let e=En(s[0]);e&&a[0]&&a[0].toLowerCase().trim()===e.toLowerCase().trim()&&(c=a[0])}let l=``;try{let e=t.querySelector(`h1, h2, h3, h4, h5`);if(e){let n=document.createRange();n.setStart(t,0),n.setEndBefore(e);let r=n.cloneContents(),i=[];r.querySelectorAll(`p, li`).forEach(e=>{let t=e.textContent.replace(/\s+/g,` `).trim();t.length>20&&i.push(t)}),l=i.join(` `).slice(0,600)}}catch{}return{headings:a,pageTitleHeading:c,introText:l,containerHeadings:o}}function q_(e){if(!e||typeof document>`u`)return``;let t=new Set([`script`,`style`,`noscript`,`svg`,`iframe`,`nav`,`footer`,`header`,`aside`]),n=parseInt(e.tagName[1],10),r=Array.from({length:n},(e,t)=>`h${t+1}`).join(`, `),i=Array.from(document.querySelectorAll(r)).filter(e=>!e.closest(wn)),a=i.indexOf(e),o=a===-1?null:i[a+1],s=document.createRange();try{if(s.setStartAfter(e),o)s.setEndBefore(o);else{let e=document.querySelector(`main, [role='main'], article`)||document.body;s.setEnd(e,e.childNodes.length)}}catch{return e.textContent.replace(/\s+/g,` `).trim()}let c;try{c=s.cloneContents()}catch{return e.textContent.replace(/\s+/g,` `).trim()}let l=[];function u(e){if(e.nodeType===Node.TEXT_NODE){let t=e.textContent.replace(/\s+/g,` `).trim();t&&l.push(t);return}if(e.nodeType!==Node.ELEMENT_NODE)return;let n=e.tagName.toLowerCase();if(!t.has(n)){if(n===`ul`||n===`ol`){let t=Array.from(e.querySelectorAll(`:scope > li`)).map(e=>{let t=e.textContent.replace(/\s+/g,` `).trim();return t?`• ${t}`:null}).filter(Boolean);t.length&&l.push(t.join(`
415
415
  `));return}if(n===`table`){let t=Array.from(e.querySelectorAll(`tr`)).map(e=>Array.from(e.querySelectorAll(`td, th`)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(Boolean).join(` | `)).filter(Boolean);t.length&&l.push(t.join(`
416
416
  `));return}if(n===`form`){let t=Array.from(e.querySelectorAll(`input, textarea, select`)).map(e=>{let t=(e.getAttribute(`type`)||`text`).toLowerCase();if([`hidden`,`submit`,`button`,`reset`].includes(t))return null;let n=e.getAttribute(`placeholder`)||e.getAttribute(`aria-label`)||e.getAttribute(`name`)||t;return n?String(n).trim().slice(0,40):null}).filter(Boolean),n=e.querySelector(`button[type="submit"], input[type="submit"]`),r=n?(n.textContent||n.value||`Submit`).trim().slice(0,40):`Submit`;t.length&&l.push(`[FORM PRESENT: ${t.length} field(s) — ${t.join(`, `)}. Submit button: "${r}"]`);return}if(n===`p`||n===`blockquote`){let t=e.textContent.replace(/\s+/g,` `).trim();t.length>2&&l.push(t);return}if(/^h[1-6]$/.test(n)){let t=e.textContent.replace(/\s+/g,` `).trim();t.length>2&&l.push(t);return}for(let t of e.childNodes)u(t)}}for(let e of c.childNodes)u(e);let d=new Set;return l.filter(e=>{let t=e.substring(0,80);return d.has(t)?!1:(d.add(t),!0)}).join(`
417
417
  `).replace(/\n{3,}/g,`
418
418
 
419
- `).trim()}function q_(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=typeof e.beaconSyncFullVoiceHistory==`function`?e.beaconSyncFullVoiceHistory:null,a=[],o={"fwh-navigate-mvp":async n=>{$(`fwh-navigate-mvp ▶ raw parameters:`,n);let a=H_(n),o=U_(a),s=a.section_text??a.sectionText??a.section,c=Array.isArray(a.expected_landmarks)?a.expected_landmarks:Array.isArray(a.expectedLandmarks)?a.expectedLandmarks:[];if($(`fwh-navigate-mvp · coerced:`,{url:o,sectionText:s,expectedLandmarks:c}),!o){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`fwh-navigate-mvp ✖`,e),e}if(typeof window<`u`)try{let e=new URL(o,window.location.href);if(e.hostname===window.location.hostname&&e.origin!==window.location.origin)o=e.pathname+e.search+e.hash,$(`fwh-navigate-mvp · cross-protocol same-host URL normalized →`,o);else if(e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)){let t=e.hostname;return $(`fwh-navigate-mvp ✖ external URL blocked:`,e.href),`EXTERNAL_LINK_BLOCKED: "${o}" is on another site (${t}) and opens in a new tab, which you can't open. The visitor can click that link themselves.`}}catch{}if(typeof window<`u`){try{let e=new URL(o,window.location.href);if(e.pathname===window.location.pathname&&e.search===window.location.search)return $(`fwh-navigate-mvp ✖ already on page, skipping`),`OK_ALREADY_ON_PAGE. The visitor is already on this page, so nothing changed.`}catch{}let e=window.__fe_user_nav_during_speech;if(e&&Date.now()-e.ts<3e4)try{if(new URL(o,window.location.href).pathname===e.fromPath)return $(`flowengage_navigate ✖ blocked — would navigate back to page visitor just left`,e),`NAV_BLOCKED: the visitor just left "${e.fromPageName}" themselves and is now on "${e.toPageName}", so they were not moved back.`}catch{}}let{allowed:l,correctedUrl:u}=await br(o,{siteId:t,apiBaseUrl:e.apiBaseUrl});if(!l){let e=`PAGE_NOT_IN_SITE: "${o}" is not a page on this site, so the visitor was not moved. The real pages are in your Site Pages list, fwh-list-nav-links-mvp and fwh-search-mvp.`;return $(`fwh-navigate-mvp ✖ blocked`,e),e}u&&u!==o&&($(`fwh-navigate-mvp · corrected url:`,{requested:o,correctedUrl:u}),o=u);try{tg(`Navigating to ${o}...`,{spinner:!0}),yg(),Cn();try{i?.()}catch{}try{let e=r?r():``;if(e&&t){let n=D_([{sender:`user`,message:e}]);n&&_e(t,n)}}catch{}F();let e=o;try{e=new URL(o,typeof window<`u`?window.location.href:``).href}catch{}let n=`this`;try{let e=new URL(o,window.location.href).pathname.split(`/`).filter(Boolean).pop()||``;n=e?e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()):`Home`}catch{}t&&typeof window<`u`&&we(t,window.location.href,e,n),Cr(e);try{window.__fe_agent_nav={path:new URL(e,window.location.href).pathname,ts:Date.now()}}catch{}$(`fwh-navigate-mvp → real navigation`,o);let a=typeof window<`u`&&!window.Shopify&&!!Hn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),a&&Nn(12e3),jr(o,{voiceActive:!0}).catch(()=>{}),a)try{let e=new URL(o,window.location.origin).pathname,t=window.location.pathname,n=Date.now()+2e3;for(;Date.now()<n&&!(typeof window<`u`&&window.location.pathname===e);)await new Promise(e=>setTimeout(e,80));let r=typeof window<`u`?window.location.pathname:e,i=typeof window<`u`?window.location.href:o;(r.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),$(`fwh-navigate-mvp → SPA nav complete. target:`,e,`actual:`,r);try{typeof window<`u`&&window.scrollTo(0,0)}catch{}let a=[],s=null,c=``,l=Date.now()+12e3;for(;Date.now()<l&&(await new Promise(e=>setTimeout(e,300)),{headings:a,pageTitleHeading:s,introText:c}=G_(),!(a.length>=1)););W_(),$(`fwh-navigate-mvp → page headings collected:`,a,`titleHeading:`,s);let u=a.length?a.join(` | `):`none`,d=a.length?``:`Headings were not ready yet; fwh-get-current-page-mvp returns them.`,f=s?` "${s}" is the page title, not a section. Intro text: "${c||`none`}".`:c?` Intro text before the first section: "${c}".`:``,p=``;try{if(a.length>0){let e=a.slice(0,3),t=[];for(let n of e){let e=rr(null,n);if(e){let r=K_(e).substring(0,800);r&&t.push(`[Section: ${n}] ${r}`)}}t.length>0&&(p=` Content of the first sections: ${t.join(` | `)}.`)}}catch{}if(Er())return wr(),$(`fwh-navigate-mvp ✖ landed on a not-found/404 page:`,i),`NAVIGATION_PAGE_NOT_FOUND. ${i} shows a "not found" error — that page doesn't exist on this site.`;let m=Date.now()+4e3,h=typeof window<`u`?window.location.pathname:r;for(;Date.now()<m&&!A_(h,e)&&A_(h,t);)await new Promise(e=>setTimeout(e,120)),h=window.location.pathname;$(`fwh-navigate-mvp route settle:`,{startPath:t,targetPath:e,settledPath:h});let g=typeof window<`u`?window.location.href:i,_=(h.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,v=A_(h,e),y=!A_(h,t),b=v||y;return $(`fwh-navigate-mvp settled:`,h,`target:`,e,`match:`,b),b?(wr(),`OK_NAVIGATE_SPA. The visitor is now on ${g} (page: "${_}"). Section headings: ${u}.${f} ${d}${p}`):(wr(),`NAVIGATION_DID_NOT_HAPPEN. The page did not change; the visitor is still on ${g} (page: "${_}").`)}catch{}return`OK_NAVIGATE_RELOADING. The page is reloading; this call ends now and continues on the new page.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`fwh-navigate-mvp ✖`,t),tg(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{bg(),ng(900)}},"fwh-highlight-mvp":async e=>{$(`fwh-highlight-mvp ▶`,e);let t=H_(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(Nn(3e3),typeof window<`u`&&window.__fe_user_nav_during_speech){let e=window.__fe_user_nav_during_speech,t=window.location.pathname;if(Date.now()-e.ts>=3e4)window.__fe_user_nav_during_speech=null;else return $(`flowengage_highlight ✖ blocked — user navigated during speech`,e),`NAV_CHANGED: the visitor moved themselves from "${e.fromPageName}" to "${e.toPageName}" (${t}) while you were speaking, so nothing was highlighted.`}W_();let i=(e=>e&&e.replace(/^\d+\.\s*/,``).replace(/^["']|["']$/g,``).trim())(r),a=rr(n||null,i||null);if(!a&&i){let e=Date.now()+600;for(;!a&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),W_(),a=rr(null,i)}if(!a){$(`fwh-highlight-mvp ✖ no element for:`,i||n);let{headings:e}=G_(),t=e.length?`Headings on this page: ${e.map(e=>`"${e}"`).join(` | `)}.`:`This page has no headings to highlight.`;return`HIGHLIGHT_NOT_FOUND: "${i||n}" on the current page. ${t}`}return Sn(a),$(`fwh-highlight-mvp ✓`,i||n),`OK_HIGHLIGHT: "${i||n}" is highlighted on screen.`},"fwh-read-content-mvp":async e=>{$(`fwh-read-content-mvp ▶`,e);let t=H_(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=rr(null,n);if(!t)return`Could not find section "${n}" on the page.`;e=K_(t)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar, #flowengage-root, .flowengage-shell, .flowengage-widget-root`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`fwh-read-content-mvp ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`fwh-read-content-mvp ✖`,e.message),`Could not read page content: ${e.message}`}},"fwh-page-content-mvp":async e=>{$(`fwh-page-content-mvp ▶`,e);let r=H_(e),i=r?.url||r?.page_url||``;if($(`fwh-page-content-mvp · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`fwh-page-content-mvp ✖ missing url`),`Missing url parameter.`;if(!t)return $(`fwh-page-content-mvp ✖ no siteId`),`Site is not configured.`;if(!n)return $(`fwh-page-content-mvp ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`fwh-page-content-mvp → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`fwh-page-content-mvp · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`fwh-page-content-mvp ✖`,e),`${e} FALLBACK REQUIRED: This page is not in the search index. Call fwh-read-content-mvp (no parameters) immediately to read the live page content directly from the visitor's browser — do NOT tell the visitor you cannot access the page.`}return $(`fwh-page-content-mvp ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`fwh-page-content-mvp ✖`,t),t}},"fwh-search-mvp":async e=>{$(`fwh-search-mvp ▶`,e);let r=H_(e).query;if(!r)return $(`fwh-search-mvp ✖ missing query`),`Missing query parameter.`;if(!t)return $(`fwh-search-mvp ✖ no siteId`),`Search unavailable (no siteId configured).`;if(!n)return $(`fwh-search-mvp ✖ no api base`),`Search unavailable (no API base URL).`;try{let e=`${n}/api/site-tools/search`;$(`fwh-search-mvp → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`fwh-search-mvp · HTTP`,i.status,`success:`,a.success),!a.success||!a.results?.length)return`No results found for that query. Try rephrasing, or use fwh-read-content-mvp to read the current page.`;let o=a.results.slice(0,5).map((e,t)=>`${t+1}. ${e.title||e.url} (${e.url})${e.snippet?` — ${e.snippet}`:``}`).join(`
420
- `);return $(`fwh-search-mvp ✓`,`${a.results.length} result(s)`),`SEARCH_RESULTS:\n${o}`}catch(e){return $(`fwh-search-mvp ✖`,e.message),`Search failed. Use fwh-read-content-mvp to read the current page instead.`}},"fwh-list-nav-links-mvp":async()=>{if($(`fwh-list-nav-links-mvp ▶`),typeof window>`u`)return`Cannot read navigation (no browser context).`;let e=new Map,t=[],n=[`nav a`,`[role='navigation'] a`,`header a`,`.navbar a`,`.nav a`,`.menu a`,`.navigation a`,`.header a`,`[class*='nav'] a`,`[class*='menu'] a`,`[class*='header'] a`];if(M_(t=>{for(let r of n)try{t.querySelectorAll(r).forEach(t=>{if(Tn(t))return;let n=t.getAttribute(`href`),r=(t.textContent||``).replace(/\s+/g,` `).trim();if(!r||!n||n===`#`||n.startsWith(`javascript:`))return;try{let e=t.parentElement;if(e&&j_(e).display===`none`&&!e.closest(`nav, [role='navigation'], header, [class*='nav'], [class*='menu']`))return}catch{}let i=r.toLowerCase()+`|`+n;e.has(i)||e.set(i,{text:r,href:n})})}catch{}t.querySelectorAll(`select`).forEach(t=>{if(Tn(t))return;let n=P_(t);/nav|menu|page|section|go to/i.test(n||t.name||t.id||``)&&Array.from(t.options).forEach(r=>{if(!r.value||r.disabled)return;let i=r.text.trim();if(!i)return;let a=i.toLowerCase()+`|`+r.value;e.has(a)||e.set(a,{text:i,href:r.value,isSelectOption:!0,selectLabel:n||t.name||`dropdown`})})})}),e.forEach(e=>t.push(e)),!t.length)return`NAV_LINKS: No navigation links found on this page. Use fwh-read-content-mvp to read page content or fwh-search-mvp to search the site.`;let r=t.slice(0,50).map((e,t)=>`${t+1}. "${e.text}"${e.isSelectOption?` (dropdown option in "${e.selectLabel}")`:``} → ${e.href}`).join(`
421
- `);return $(`fwh-list-nav-links-mvp ✓`,`${t.length} links`),`NAV_LINKS (${t.length} total, showing up to 50):\n${r}`},"fwh-end-session-mvp":async()=>($(`fwh-end-session-mvp ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),"fwh-request-email-mvp":async()=>($(`fwh-request-email-mvp ▶`),typeof e.requestEmailCollection==`function`&&e.requestEmailCollection(),`EMAIL_BOX_SHOWN. A text box for their email is on screen now. EMAIL_SAVED arrives once they submit it.`),"fwh-get-current-page-mvp":async()=>{if($(`fwh-get-current-page-mvp ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``;if(Er())return $(`fwh-get-current-page-mvp ✓ 404 detected`,{url:e}),`CURRENT_PAGE_NOT_FOUND. The visitor is on a "not found" error page (${e}); there is no content here.`;let{headings:r,pageTitleHeading:i,introText:a}=G_();$(`fwh-get-current-page-mvp ✓`,{url:e,path:t,title:n}),$(`fwh-get-current-page-mvp → page headings collected:`,r,`titleHeading:`,i);let o=i?` "${i}" is the page title, not a section. Intro text: "${a||`none`}".`:a?` Intro text before the first section: "${a}".`:``;if(!r.length)return`CURRENT_PAGE. URL: ${e} | Title: ${n} |${o} This page has no section headings.`;let s=r.map(e=>`"${e}"`).join(` | `);return`CURRENT_PAGE. URL: ${e} | Title: ${n} | Page sections (${r.length} total): ${s}.${o}`},"fwh-list-forms-mvp":async()=>{let e=I_(),t=L_();$(`fwh-list-forms-mvp ✓`,`${e.length} field(s)`,`${t.length} button(s)`);let n=e.map(e=>({...e,inputCategory:e.tag===`SELECT`?`dropdown_select`:`text_input`}));return JSON.stringify({fields:n,buttons:t,hint:`field_key: use the label/placeholder/name shown above. CRITICAL: fields with inputCategory='dropdown_select' are SELECT elements — their field_key must match the SELECT's own label (e.g. 'Company Size'), NOT the option text (e.g. 'Small Business') and NOT a nearby text input label. Never fill a SELECT option value into a text input.`})},"fwh-fill-form-mvp":async()=>`FORM_FILLING_DISABLED: forms can't be filled in for the visitor; fwh-list-forms-mvp lists the fields.`,"fwh-click-button-mvp":async e=>{let t=H_(e),n=(t.button_text??t.buttonText??t.text??``).trim(),r=(t.card_context??t.cardContext??``).trim();if($(`fwh-click-button-mvp ▶`,n,r?`(card_context: ${r})`:``),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let i=V_(n,a,r);if(!i)return $(`fwh-click-button-mvp ✖ no match`),`Could not find a button matching "${n}". Call fwh-list-forms-mvp to see button texts.`;try{tg(`Clicking ${n}...`,{spinner:!0});try{i.scrollIntoView({block:`center`,inline:`nearest`})}catch{i.scrollIntoView(!0)}await Tg(i),i.focus?.(),await Dg(i),Og(i),i.click();let e=(i.innerText||i.textContent||i.value||i.getAttribute(`aria-label`)||``).replace(/\s+/g,` `).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`fwh-click-button-mvp ✓`,t),tg(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`fwh-click-button-mvp ✖`,t),tg(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{Eg(),ng(700)}},"fwh-cart-get-mvp":async()=>{$(`fwh-cart-get-mvp ▶`);try{let e=await Wr();if(!e)return`CART_UNAVAILABLE: this page is not a Shopify storefront, so there is no cart to read.`;let t=e.items.map((e,t)=>{let n=e.variantTitle&&e.variantTitle!==`Default Title`?` (${e.variantTitle})`:``;return`${t+1}. ${e.title}${n} — qty ${e.quantity} — ${e.linePrice}${e.handle?` — handle: ${e.handle}`:``}`}),n=`CART. Items: ${e.itemCount} | Subtotal: ${e.subtotal}${e.currency?` ${e.currency}`:``}${t.length?` | ${t.join(` | `)}`:` | (cart is empty)`}`;return $(`fwh-cart-get-mvp ✓`,n),n}catch(e){return $(`fwh-cart-get-mvp ✖`,e),`CART_ERROR: ${e?.userMessage||e?.message||`could not read the cart`}`}},"fwh-shop-search-mvp":async e=>{let t=String((e||{}).query||``).trim();if($(`fwh-shop-search-mvp ▶`,t),!t)return`Missing query: pass the product name or keyword to search.`;try{let e=await Zr(t);if(!e.length)return`NO_PRODUCTS_FOUND for "${t}". Tell the visitor no matching product was found — do not invent products.`;let n=e.map(e=>`"${e.title}" — handle: ${e.handle}${e.price?` — price: ${e.price}`:``}`).join(` | `);return $(`fwh-shop-search-mvp ✓`,n),`PRODUCTS_FOUND: ${n}. Use the handle with fwh-cart-add-mvp or fwh-view-product-mvp.`}catch(e){return $(`fwh-shop-search-mvp ✖`,e),`SEARCH_ERROR: ${e?.message||`product search failed`}`}},"fwh-cart-add-mvp":async e=>{let t=e||{},n=String(t.product_handle||t.productHandle||``).trim().toLowerCase(),r=String(t.variant||``).trim()||null,i=Math.min(20,Math.max(1,parseInt(t.quantity,10)||1));if($(`fwh-cart-add-mvp ▶`,{handle:n,variantText:r,quantity:i}),!n)return`Missing product_handle: search the product first with fwh-shop-search-mvp.`;try{let{variant:e,product:t}=await Gr(n,r);await Kr(e.id,i);let a=await Vr(),o=await s(a),c=e.title&&e.title!==`Default Title`?` (${e.title})`:``,l=`ADDED ${i} × ${t.title}${c}. Cart now has ${a.item_count} item(s), subtotal ${Ur(a.items_subtotal_price)}${a.currency?` ${a.currency}`:``}.${o}`;return $(`fwh-cart-add-mvp ✓`,l),l}catch(e){return $(`fwh-cart-add-mvp ✖`,e),`ADD_FAILED: ${e?.userMessage||e?.message||`could not add the item`}. Relay this reason to the visitor.`}},"fwh-cart-update-mvp":async e=>{let t=e||{},n=parseInt(t.line,10),r=Math.min(20,Math.max(0,parseInt(t.quantity,10)));if($(`fwh-cart-update-mvp ▶`,{line:n,quantity:r}),!Number.isFinite(n)||n<1)return`Missing/invalid line: call fwh-cart-get-mvp first and use the item's 1-based number.`;if(!Number.isFinite(r))return`Missing/invalid quantity.`;try{let e=await Vr(),t=e.items?.[n-1];if(!t)return`NO_SUCH_LINE: the cart has ${e.items?.length||0} item(s). Call fwh-cart-get-mvp for the current list.`;let i=await qr(n,r),a=await s(i),o=`UPDATED ${t.product_title||t.title} to qty ${r}. Cart now has ${i.item_count} item(s), subtotal ${Ur(i.items_subtotal_price)}${i.currency?` ${i.currency}`:``}.${a}`;return $(`fwh-cart-update-mvp ✓`,o),o}catch(e){return $(`fwh-cart-update-mvp ✖`,e),`UPDATE_FAILED: ${e?.userMessage||e?.message||`could not update the item`}`}},"fwh-cart-remove-mvp":async e=>{let t=parseInt((e||{}).line,10);if($(`fwh-cart-remove-mvp ▶`,{line:t}),!Number.isFinite(t)||t<1)return`Missing/invalid line: call fwh-cart-get-mvp first and use the item's 1-based number.`;try{let e=await Vr(),n=e.items?.[t-1];if(!n)return`NO_SUCH_LINE: the cart has ${e.items?.length||0} item(s). Call fwh-cart-get-mvp for the current list.`;let r=await qr(t,0),i=await s(r),a=`REMOVED ${n.product_title||n.title}. Cart now has ${r.item_count} item(s), subtotal ${Ur(r.items_subtotal_price)}${r.currency?` ${r.currency}`:``}.${i}`;return $(`fwh-cart-remove-mvp ✓`,a),a}catch(e){return $(`fwh-cart-remove-mvp ✖`,e),`REMOVE_FAILED: ${e?.userMessage||e?.message||`could not remove the item`}`}},"fwh-cart-open-mvp":async()=>($(`fwh-cart-open-mvp ▶`),c(Jr(),`Cart`)),"fwh-checkout-mvp":async()=>{$(`fwh-checkout-mvp ▶`);try{if(!(await Vr()).item_count)return`CART_EMPTY: do not go to checkout. Tell the visitor their cart is empty and offer to help find products.`}catch{}return c(Yr(),`Checkout`)},"fwh-view-product-mvp":async e=>{let t=e||{},n=String(t.product_handle||t.productHandle||``).trim().toLowerCase();return $(`fwh-view-product-mvp ▶`,{handle:n}),n?c(Xr(n),n.replace(/[-_]/g,` `)):`Missing product_handle: search the product first with fwh-shop-search-mvp.`}};async function s(e){try{let{sectionsSwapped:t}=await ai(e);if(!t&&Qr())return` NOTE: the cart list on this page could not be re-rendered — briefly tell the visitor the page may need a quick refresh to show the change.`}catch{}return``}function c(e,n){if(typeof window>`u`)return`NAV_FAILED: no browser context.`;let r=e;try{r=new URL(e,window.location.href).href}catch{}return t&&we(t,window.location.href,r,n),Cr(r),Ar().then(()=>{window.location.assign(r)}),`OK_NAVIGATING to ${n}. The page is loading.`}return{...o,highlightOnPage:o[`fwh-highlight-mvp`],getPageContent:o[`fwh-page-content-mvp`],endVoiceSession:o[`fwh-end-session-mvp`],listPageForms:o[`fwh-list-forms-mvp`],fillFormFields:o[`fwh-fill-form-mvp`],clickPageButton:o[`fwh-click-button-mvp`]}}var J_=/^(get in touch|contact us|let'?s (talk|connect)|subscribe|newsletter|follow us|quick links|company|solutions|what we do|resources|legal|sitemap|share this)/i;function Y_(){try{let{headings:e,pageTitleHeading:t,containerHeadings:n}=G_(),r=new Set((n||[]).map(e=>e.trim())),i=(e||[]).map(e=>typeof e==`string`?e:e?.text||``).filter(Boolean).filter(e=>!t||e.trim()!==t.trim()).filter(e=>!J_.test(e.trim())),a=i.filter(e=>!r.has(e.trim()));return a.length?a:i}catch{return[]}}function X_(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=_n();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var Z_=`[PAGE_CONTEXT]`;function Q_(e,t,n,r){return`${Z_} The visitor is on ${e}${r?`, having moved here themselves from the ${r} page`:``}. Approximate headings: ${t||`none`}. ${n?`Forms: ${n}. `:``}`.trim()}function $_(e,t,n,r,i){e?.sendContextualUpdate?.(Q_(t,n,r,i));try{e?.reportPage?.(new URL(t,window.location.href).pathname,document.title)}catch{}}var ev={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function tv(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function nv(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function rv(e){let[t,n]=d.default.useState(null),r=typeof e==`string`?e.trim():``;return d.default.useEffect(()=>{if(!r){n(null);return}n(null);let e=!1,t=new window.Image;return t.onload=()=>{e||n(r)},t.onerror=()=>{e||n(null)},t.src=r,()=>{e=!0}},[r]),t}function iv({logo:e,style:t}){let n=rv(typeof e==`string`?e:null);if(!e)return null;if(typeof e==`string`)return n?(0,f.jsx)(`img`,{src:n,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}}):null;let r=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return r?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:r}):null}function av({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function ov(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(i'?m|i am)\s+done\b[\s.!,]*(for\s+(today|now)|here)?[\s.!,]*$/i.test(n)||/\b(that'?s|that is)\s+(all|it)\b[\s.!,]*(for\s+(today|now))?[\s.!,]*$/i.test(n)||/\b(no\s+more|nothing\s+else)\b.*\b(questions?|thanks?|for\s+(today|now))?[\s.!,]*$/i.test(n)||e===`bot`&&(/\b(that'?s all|we'?re done)\b/i.test(n)||/\b(goodbye|bye)\b/i.test(n)||/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))):!1}function sv({orbColors:e,...t}){return(0,f.jsx)(v_,{colors:e,...t})}function cv({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||ev.green,c=nv(s),l=a?72:94,u=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(lh.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:`210px`,wordBreak:`break-word`,overflow:`hidden`,display:`-webkit-box`,WebkitLineClamp:4,WebkitBoxOrient:`vertical`},children:e.entryPrompt}),(0,f.jsxs)(lh.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${s}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(lh.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,f.jsx)(sv,{size:l,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(lh.div,{initial:{opacity:0},animate:{opacity:o?0:1},transition:{duration:.28},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,f.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`,animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u}):(0,f.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function lv({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||ev.green,l=nv(c);return(0,f.jsxs)(lh.div,{initial:{scale:50/350,borderRadius:`50%`},animate:s?{scale:50/350,opacity:0,borderRadius:`50%`}:{scale:1,borderRadius:`16px`,opacity:1},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(sv,{size:72,orbColors:t}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,lineHeight:1.4},children:e.connectionTitle}),e.connectionSubtitle&&(0,f.jsx)(`p`,{style:{margin:`6px 0 0`,fontSize:`13px`,fontWeight:400,color:`#6b7280`,lineHeight:1.4},children:e.connectionSubtitle})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:c,color:l,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${c}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function uv({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,beaconSyncVoiceTranscript:l,widgetPosition:u=`bottom-right`,voiceEndCounter:p,websiteName:m,voiceFirstMessage:h,captureVisitorEmail:g,emailRequired:_,emailCaptureEnabled:v=!0,listeningLabel:y=`Listening...`,thinkingLabel:b=`Thinking...`,enterChatModeLabel:x=`Enter Chat Mode`,endConversationLabel:S=`End Conversation`}){(0,d.useEffect)(()=>(console.log(`[FlowEngage:VoiceDebug] 🔵 VoiceMode MOUNTED`),()=>console.log(`[FlowEngage:VoiceDebug] 🔴 VoiceMode UNMOUNTED`)),[]);let[C,w]=(0,d.useState)(`idle`),[T,E]=(0,d.useState)(!1),[ee,D]=(0,d.useState)(!1),[te,ne]=(0,d.useState)(()=>re(i)===`auto`),ie=()=>{let e=te?`ask`:`auto`;O(i,e),ne(e===`auto`)},[ae,k]=(0,d.useState)(!1),[oe,se]=(0,d.useState)(``),[ce,le]=(0,d.useState)(``),ue=(0,d.useRef)(!1),de=(0,d.useRef)(!1),fe=(0,d.useRef)(null),A=(0,d.useRef)(0),pe=(0,d.useRef)(``),j=(0,d.useRef)(!1),me=(0,d.useRef)(0),he=(0,d.useRef)(!1),M=(0,d.useRef)(!1),N=(0,d.useRef)(!1),ge=(0,d.useRef)([]),P=(0,d.useRef)(null),be=(0,d.useRef)(``),I=(0,d.useRef)(null),xe=e=>{he.current=e,e||(M.current=!1),L.current?.setWalkthroughActive?.(e)};I.current=async()=>{if(M.current)return;let e=typeof window<`u`?window.location.pathname:null;if(e&&P.current&&e!==P.current){console.log(`[FlowEngage] walkthrough ended — visitor left `+P.current),P.current=null,ge.current=[],xe(!1);return}let t=ge.current;Se.current+=1;let n=Se.current,r=t[n];if(!r){if(xe(!1),t.length)L.current?.sendUserMessage?.(`That was the last section. Say so in one short sentence and ask if they want to explore any section further.`);else if(n===0){let e=``;try{let t=await we.current?.[`fwh-read-content-mvp`]?.({});typeof t==`string`&&t&&!/^Could not/i.test(t)&&(e=t.slice(0,2800))}catch{}L.current?.sendUserMessage?.(e?`Give the visitor a complete spoken overview of this page in 4-6 sentences, based ONLY on this page content:\n"""${e}"""\nThen ask which part they'd like to hear more about. Do not call any tool.`:`Give the visitor a complete spoken overview of this page in 4-6 sentences based on what you know about it, then ask which part they'd like to hear more about. Do not call any tool.`,{suppressQuestion:!0})}return}try{await we.current?.highlightOnPage?.({section_text:r})}catch(e){console.warn(`[FlowEngage] walkthrough highlight failed:`,e?.message||e)}console.debug(`[FlowEngage] walkthrough step ${n+1}/${t.length}: ${r}`);let i=``;try{let e=await we.current?.[`fwh-read-content-mvp`]?.({section_text:r});typeof e==`string`&&e&&!/^Could not/i.test(e)&&(i=e.slice(0,2500))}catch{}L.current?.sendUserMessage?.(`Describe the section titled "${r}".`+(i?` Its content:\n"""${i}"""`:``),{suppressQuestion:!0})};let Se=(0,d.useRef)(0),L=(0,d.useRef)(null),we=(0,d.useRef)(null),Ee=(0,d.useRef)(``),De=(0,d.useRef)(async()=>{}),Oe=(0,d.useRef)(!1),ke=(0,d.useRef)(!1),Ae=(0,d.useRef)(!1),R=(0,d.useRef)(!1),je=(0,d.useRef)(`minimized`),Me=(0,d.useRef)(null),Ne=(0,d.useRef)(null),Pe=(0,d.useRef)(null),Fe=(0,d.useRef)(0),Ie=(0,d.useRef)(!1),Le=(0,d.useRef)(`idle`),Re=(0,d.useRef)(null),ze=(0,d.useRef)(!1),z=(0,d.useRef)(null),Be=(0,d.useCallback)((e=`minimized`)=>{console.warn(`[FlowEngage:VoiceDebug] 🛑 requestSessionShutdown called`,{destination:e,stack:Error().stack?.split(`
422
- `).slice(1,4).join(` | `)}),je.current=e,R.current=!0,queueMicrotask(()=>{Oe.current||(Oe.current=!0,De.current?.())})},[s]),B=(0,d.useCallback)(()=>{fe.current&&=(clearTimeout(fe.current),null)},[]);(0,d.useEffect)(()=>{if(_){ue.current=!1;return}if(ue.current=!0,de.current=!1,k(!1),B(),j.current){j.current=!1,L.current?.setMicMuted?.(!1);let e=pe.current;pe.current=``,L.current?.injectAgentSpeech?.(`Thanks — I already have your email on file.`,`interrupt`),e&&L.current?.sendUserMessage?.(`The visitor's email is already on file — do not ask for it. Answer their question now: "${e}"`)}L.current?.sendContextualUpdate?.(`EMAIL REQUIREMENT SATISFIED — the visitor's email is already on file. All earlier instructions about requiring or asking for an email are VOID. Never ask for it again.`)},[_,B]);let Ve=/(that covers everything|that was all|covered everything|that(?:'|’)?s everything)/i,He=/^((uh+|um+|so|well|okay|ok|yeah)[,.\s]+)*(yes|yeah|yep|yup|sure|ok(ay)?|please|continue|go on|next|keep going|carry on|go ahead|resume|back to the tour)[\s.!,]*$/i,Ue=/navigate|highlight|click|product|cart|checkout/,We=/(would you like (me )?to take you|shall i take you|want me to take you|would you like to (go|explore|visit|see)|take you there)/i,Ge=/^((uh+|um+|oh|ah|so|well)[,.\s]+)*(cool|nice|great|awesome|wow|lovely|perfect|got it|gotcha|i see|understood|makes sense|interesting|right|alright|sounds good|mm+-?hmm+|hmm+|k)[\s.!,]*$/i,Ke=e=>String(e||``).replace(/[\s.,!?]*((uh+|um+|er+|hmm+|mm+)[\s.,!?]*)+$/i,``).trim(),qe=(0,d.useCallback)(()=>{B(),fe.current=setTimeout(()=>{if(!(!de.current||ue.current))if(A.current<3){A.current+=1;try{L.current?.injectAgentSpeech?.(`I still need your email in the box below to continue — could you enter it, please?`,`queue`)}catch{}qe()}else{try{L.current?.injectAgentSpeech?.(`Since I haven't received your email, I'll close this session for now. Feel free to come back anytime — take care!`,`queue`)}catch{}de.current=!1,k(!1),B(),Ie.current=!0}},1e4)},[B]),Je=(0,d.useCallback)(async e=>{R.current=!0;try{Cn()}catch{}try{hg()}catch{}if(i)try{Te(i)}catch{}try{await L.current?.endSession?.()}catch{}let t=Me.current,n=Ne.current;if(t&&o&&a){let e=n?Math.round((Date.now()-n)/1e3):0;fetch(`${a}/api/voice/save-chat-recording`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({chatId:o,voiceSessionId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(Me.current=null,Ne.current=null,L.current=null,w(`idle`),E(!1),Oe.current=!1,Fr(),i)try{ye(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);De.current=()=>Je(je.current===`chat`?t:n),(0,d.useEffect)(()=>{ke.current=T},[T]),(0,d.useEffect)(()=>{p&&Be(`chat`)},[p]),(0,d.useEffect)(()=>{let e=!1,d=null,f=null,p=null;return(async()=>{if(!i){w(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],Ee.current=``,Oe.current=!1,Ae.current=!1,R.current=!1,je.current=`minimized`,Pr({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=D_(s.current);e&&_e(i,e)}catch{}if(!Hn()){let e=Me.current,t=Ne.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,voiceSessionId:e,duration:n,siteId:i}),s=`${a}/api/voice/save-chat-recording`;fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:r,keepalive:!0}).catch(()=>{}),Me.current=null,Ne.current=null}catch{}}F()}});let t=X_(q_({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>Ee.current,beaconSyncFullVoiceHistory:()=>l?.(s.current),isWalkthroughActive:()=>he.current&&!M.current,requestEndSession:()=>{Ie.current=!0},requestEmailCollection:()=>{v&&(ue.current||de.current||(de.current=!0,A.current=0,k(!0),qe()))}})),n=!!(i?ve(i):null)?.transcript,r=i?Te(i):null,c=!!r,g=typeof window<`u`?window.location.pathname:`/`,y=typeof document<`u`?document.title:``,b=g.replace(/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i,``)||`/`,x=b===`/`||b===``,S={apiBaseUrl:a,siteId:i,chatId:o,clientTools:t};we.current=t;let C=(g.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),T=``;y&&y.includes(`|`)&&(T=y.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let ee=T||C||``,D=ee?`the ${ee} page`:`this page`,te=(()=>{if(!r?.targetUrl)return null;try{return new URL(r.targetUrl,window.location.href).pathname}catch{return null}})();if(c||n)S.greeting=null;else{let e=m||``;S.greeting=h||(x?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to ${D}! How may I help you?`),x||console.log(`[FlowEngage] 🏠 Page-context greeting: "${ee}" for ${g}`)}let ne=!1,re=!1,O=v&&!!_&&!N.current,ie=await Xh.startSession({...S,onConnect:({conversationId:e})=>{Me.current=e,Ne.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onSessionInfo:({emailOnFile:e})=>{N.current=!!e,e&&(ue.current=!0,de.current=!1,k(!1),B(),console.log(`[FlowEngage] email already on file per server — gate disabled`))},onAgentTurnEnd:()=>{e||he.current&&(M.current||j.current||setTimeout(()=>I.current?.(),250))},onSessionEnding:()=>{e||Be(`minimized`)},onStartWalkthrough:()=>{e||(typeof window<`u`&&(window.__fe_user_nav_during_speech=null),xe(!0),M.current=!1,me.current=0,Se.current=-1,ge.current=Y_(),P.current=typeof window<`u`?window.location.pathname:null,console.log(`[FlowEngage] walkthrough started — ${ge.current.length} sections on this page`),I.current?.())},onPanel:({title:t,items:n})=>{e||pg(n,{title:t||`Products`,side:u===`bottom-left`?`left`:`right`,productUrl:e=>e.handle?`${window.location.origin}/products/${encodeURIComponent(e.handle)}`:null})},onModeChange:({mode:t,tentative:n})=>{if(!e){if(t===`speaking`){Re.current&&=(clearTimeout(Re.current),null),z.current&&=(clearTimeout(z.current),null),w(`speaking`),Le.current=`speaking`,ze.current=!1;return}if(t===`user-speaking`){if(de.current&&!ue.current&&qe(),z.current&&=(clearTimeout(z.current),null),Le.current===`speaking`)return;try{Cn()}catch{}Re.current&&=(clearTimeout(Re.current),null),Le.current!==`listening`&&(w(`listening`),Le.current=`listening`);return}if(t===`thinking`){if(Re.current&&=(clearTimeout(Re.current),null),z.current&&=(clearTimeout(z.current),null),Le.current===`speaking`)return;w(`thinking`),Le.current=`thinking`,n&&(z.current=setTimeout(()=>{z.current=null,!(e||Le.current!==`thinking`)&&(Le.current=`listening`,w(`listening`))},4e3));return}if(Le.current=`listening`,Ie.current){Ie.current=!1,Be();return}if(O&&!re&&!ue.current&&!N.current){re=!0;try{L.current?.sendContextualUpdate?.(`The visitor hasn't given their email yet; the app will ask for it when they first speak.`)}catch{}}Re.current&&clearTimeout(Re.current),Re.current=setTimeout(()=>{e||Le.current!==`speaking`&&(ze.current||(Re.current=null,Le.current=`listening`,w(`listening`)))},1200)}},onAgentAnswer:({text:t,tools:n})=>{if(e||he.current||window.__fe_user_nav_during_speech||n.some(e=>Ue.test(e.name)))return;let r=hr(t);r&&(Nn(3e3),Sn(r))},onMessage:t=>{if(e||j.current&&t.role!==`user`&&!/email/i.test(String(t.message||``)))return;let n=t.role===`user`&&/^(Describe the section titled "|\[SYSTEM:|Give the visitor a complete spoken overview|That was the last section)/.test(String(t.message||``).trim());if(t.role===`user`&&!n)try{hg()}catch{}if(!n&&t.role===`user`&&he.current){let e=String(t.message||``).trim(),n=Ke(e),r=e=>!!e&&(He.test(e)||Ge.test(e));We.test(be.current||``)?(console.log(`[FlowEngage] walkthrough ended — visitor accepted a navigation offer`),P.current=null,ge.current=[],xe(!1)):!n||r(e)||r(n)?M.current&&(M.current=!1,console.debug(`[FlowEngage] walkthrough resumed by visitor`),setTimeout(()=>I.current?.(),300)):(console.log(`[FlowEngage] walkthrough ended — visitor moved to a new topic`),P.current=null,ge.current=[],xe(!1))}if(t.role!==`user`&&!n&&(be.current=String(t.message||``)),t.role!==`user`&&Ve.test(String(t.message||``))){let e=ge.current.length;!e||Se.current>=e-1?xe(!1):console.debug(`[FlowEngage] agent claimed completion at step ${Se.current+1}/${e} — ignoring, tour continues`)}let r=t.role===`user`?`user`:`bot`,a=t.message||t.text||t.content||``;if(a){if(r===`user`&&(Ee.current=a,typeof window<`u`&&(window.__fe_user_nav_during_speech=null),ze.current=!0,Re.current&&=(clearTimeout(Re.current),null),Le.current!==`speaking`&&(w(`thinking`),Le.current=`thinking`),O&&!ne&&!ue.current&&!N.current&&(ne=!0,pe.current=a,j.current=!0,L.current?.injectAgentSpeech?.(`Before I answer that, could you please enter your email in the text box below?`,`interrupt`),L.current?.setMicMuted?.(!0),de.current||(de.current=!0,A.current=0,k(!0),qe()))),s.current=[...s.current,{sender:r,message:a,timestamp:new Date().toISOString(),debug:t.debug}],i)try{let e=D_(s.current);e&&_e(i,e)}catch{}if(ov(r,a)){Ie.current=!0;return}ke.current&&r===`bot`&&/are you still there|still there\??|hello\?|anyone there|checking in|you there|are you available|is anyone|did you step away/i.test(a)&&(Fe.current+=1,Fe.current>=5&&Be(`minimized`))}},onError:t=>{if(!e&&!R.current&&!Ae.current&&!Ce()){Ae.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{L.current?.setMicMuted?.(!0)}catch{}E(!0),w(`error`),Be(`chat`)}},onDisconnect:t=>{if(e||R.current||Ae.current||Ce())return;let n=s.current?.length||0;console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:n,reason:t?.reason,closeCode:t?.context?.code,closeReason:t?.context?.reason||t?.message,lastUserText:Ee.current||``,wasMuted:ke.current}),Ae.current=!0;try{L.current?.setMicMuted?.(!0)}catch{}E(!0),Be(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),ie.endSession().catch(()=>{});return}d=ie,L.current=ie,w(`listening`);try{sessionStorage.setItem(`el_conv_${i}`,ie.getId())}catch{}parent.postMessage({type:`AGENT_EXPAND`},`*`);try{let e=typeof window<`u`?window.location.href:``,n=`[]`;try{n=await t[`fwh-list-forms-mvp`]()}catch{}let r=`none`;if(typeof window<`u`&&typeof document<`u`)try{let e=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`,t=document.querySelector(`main, [role='main']`)||document.body,n=Array.from(t.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200);n.length||(n=Array.from(document.body.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200)),n.length&&(r=[...new Set(n)].slice(0,15).join(` | `))}catch{}_||ie.sendContextualUpdate(`The visitor's email is already on file from an earlier session.`),$_(ie,e,r,n)}catch{}if(typeof window<`u`){let t=window.location.pathname,n=Date.now(),r=e=>{try{return(decodeURIComponent(e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}catch{return((e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}},i=()=>{if(e)return;let i=window.location.pathname;if(r(i)===r(t)){t=i;return}if(Date.now()-n<8e3){t=i;return}let a=typeof window<`u`&&window.__fe_agent_nav||null,o=te&&r(i)===r(te)||Pn()||a&&Date.now()-a.ts<15e3&&r(a.path)===r(i),s=t;t=i;let c=window.location.href,l=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.trim()})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,20):[];try{Cn()}catch{}let u=l.map(e=>e.text).join(` | `),d=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,f=d(s),p=d(i);if(o){typeof window<`u`&&(window.__fe_agent_nav=null),console.log(`[FlowEngage] agent-driven navigation settled: "${s}" → "${i}"`);try{$_(L.current,c,u)}catch{}return}typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:s,toPath:i,fromPageName:f,toPageName:p,ts:Date.now()}),console.log(`[FlowEngage] visitor navigation detected: "${s}" → "${i}" (agent target: ${te||`none`})`);try{$_(L.current,c,u,null,f)}catch{}};f=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{f(...e),setTimeout(i,50)},p=()=>setTimeout(i,50),window.addEventListener(`popstate`,p)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(w(`error`),je.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{console.warn(`[FlowEngage:VoiceDebug] ⚠️ useEffect CLEANUP fired — session will be killed`,{agentId:r,siteId:i,apiBaseUrl:a}),e=!0,R.current=!0;try{Cn()}catch{}if(i)try{Te(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Fr(),Re.current&&=(clearTimeout(Re.current),null),z.current&&=(clearTimeout(z.current),null),fe.current&&=(clearTimeout(fe.current),null),ze.current=!1,Le.current=`idle`,f&&typeof window<`u`&&(window.history.pushState=f),p&&typeof window<`u`&&window.removeEventListener(`popstate`,p);let t=d||L.current,n=Me.current,l=Ne.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=l?Math.round((Date.now()-l)/1e3):0,t=JSON.stringify({chatId:o,voiceSessionId:n,duration:e,siteId:i}),r=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(r,new Blob([t],{type:`application/json`}))||fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),Me.current=null,Ne.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Be]),(0,d.useEffect)(()=>{if(!ee)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Pe.current&&!Pe.current.contains(t)&&D(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[ee]);let Ye=async()=>{if(L.current)try{if(T){Fe.current=0,await L.current.setMicMuted?.(!1),E(!1);try{L.current.sendContextualUpdate?.(`[MIC] The visitor unmuted their microphone.`)}catch{}}else{Fe.current=0,await L.current.setMicMuted?.(!0),E(!0);try{L.current.sendContextualUpdate?.(`[MIC] The visitor muted their microphone.`)}catch{}}}catch{}},Xe=(0,d.useCallback)(async e=>{e?.preventDefault?.();let t=oe.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){le(`Please enter a valid email address.`);return}le(``),ue.current=!0,de.current=!1,B(),k(!1),se(``),j.current=!1;try{typeof g==`function`&&await g(t)}catch{}L.current?.setMicMuted?.(!1);let n=pe.current;pe.current=``;try{L.current?.injectAgentSpeech?.(`Thank you for submitting your email.`),L.current?.sendUserMessage?.(n||`The visitor's email is on file. Carry on helping them and never ask for it again.`)}catch{}},[oe,g,B]),V=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,f.jsxs)(`div`,{ref:Pe,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[ae&&(0,f.jsxs)(`form`,{onSubmit:Xe,style:{width:`270px`,maxWidth:`calc(100vw - 40px)`,boxSizing:`border-box`,background:`rgba(15,22,36,0.97)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,padding:`16px`,display:`flex`,flexDirection:`column`,gap:`10px`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsx)(`span`,{style:{color:`white`,fontSize:`13px`,fontWeight:600,lineHeight:1.4},children:`Please enter your email to continue`}),(0,f.jsx)(`input`,{type:`email`,inputMode:`email`,autoComplete:`email`,autoFocus:!0,value:oe,onChange:e=>{se(e.target.value),ce&&le(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:ce?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),ce&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:ce}),(0,f.jsx)(`button`,{type:`submit`,disabled:!oe.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:oe.trim()?V:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:oe.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,f.jsxs)(`div`,{style:{position:`relative`},children:[(C===`listening`||C===`thinking`)&&!T&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:C===`thinking`?b:y}),T&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`#f87171`,fontSize:`16px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Muted`}),(0,f.jsx)(sv,{size:72,voiceState:C,isMuted:T,orbColors:e})]}),C===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:Ye,title:T?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:T?`#7f1d1d`:`#1f2937`,border:T?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:T?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:T?(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsx)(Ag,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>D(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,f.jsx)(Rg,{size:16,color:`currentColor`})})]}),ee&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{D(!1),je.current=`chat`,Je(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(zg,{}),x]}),i&&(0,f.jsxs)(`button`,{onClick:()=>ie(),style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`8px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`span`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,minWidth:0,overflow:`hidden`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,f.jsx)(`polygon`,{points:`3 11 22 2 13 21 11 13 3 11`})}),(0,f.jsx)(`span`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:`Auto-navigate`})]}),(0,f.jsx)(`span`,{"aria-hidden":!0,style:{width:`34px`,height:`19px`,borderRadius:`999px`,background:te?`#22c55e`:`rgba(255,255,255,0.2)`,position:`relative`,flexShrink:0,transition:`background 0.15s ease`},children:(0,f.jsx)(`span`,{style:{position:`absolute`,top:`2px`,left:te?`17px`:`2px`,width:`15px`,height:`15px`,borderRadius:`50%`,background:`white`,transition:`left 0.15s ease`}})})]}),(0,f.jsxs)(`button`,{onClick:()=>{D(!1),je.current=`minimized`,Je(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(Bg,{}),S]}),(0,f.jsx)(`button`,{onClick:()=>D(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function dv({orbColors:e}){let t=Array.isArray(e)&&e.length>0?e:[`#135bd8`,`#ef334b`,`#ffbd2e`],n=t[0],r=t[1]||t[0],i=t[2]||t[0];return(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,borderRadius:`50%`,flexShrink:0,background:`
419
+ `).trim()}function J_(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=typeof e.beaconSyncFullVoiceHistory==`function`?e.beaconSyncFullVoiceHistory:null,a=[],o={"fwh-navigate-mvp":async n=>{$(`fwh-navigate-mvp ▶ raw parameters:`,n);let a=U_(n),o=W_(a),s=a.section_text??a.sectionText??a.section,c=Array.isArray(a.expected_landmarks)?a.expected_landmarks:Array.isArray(a.expectedLandmarks)?a.expectedLandmarks:[];if($(`fwh-navigate-mvp · coerced:`,{url:o,sectionText:s,expectedLandmarks:c}),!o){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`fwh-navigate-mvp ✖`,e),e}if(typeof window<`u`)try{let e=new URL(o,window.location.href);if(e.hostname===window.location.hostname&&e.origin!==window.location.origin)o=e.pathname+e.search+e.hash,$(`fwh-navigate-mvp · cross-protocol same-host URL normalized →`,o);else if(e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)){let t=e.hostname;return $(`fwh-navigate-mvp ✖ external URL blocked:`,e.href),`EXTERNAL_LINK_BLOCKED: "${o}" is on another site (${t}) and opens in a new tab, which you can't open. The visitor can click that link themselves.`}}catch{}if(typeof window<`u`){try{let e=new URL(o,window.location.href);if(e.pathname===window.location.pathname&&e.search===window.location.search)return $(`fwh-navigate-mvp ✖ already on page, skipping`),`OK_ALREADY_ON_PAGE. The visitor is already on this page, so nothing changed.`}catch{}let e=window.__fe_user_nav_during_speech;if(e&&Date.now()-e.ts<3e4)try{if(new URL(o,window.location.href).pathname===e.fromPath)return $(`flowengage_navigate ✖ blocked — would navigate back to page visitor just left`,e),`NAV_BLOCKED: the visitor just left "${e.fromPageName}" themselves and is now on "${e.toPageName}", so they were not moved back.`}catch{}}let{allowed:l,correctedUrl:u}=await xr(o,{siteId:t,apiBaseUrl:e.apiBaseUrl});if(!l){let e=`PAGE_NOT_IN_SITE: "${o}" is not a page on this site, so the visitor was not moved. The real pages are in your Site Pages list, fwh-list-nav-links-mvp and fwh-search-mvp.`;return $(`fwh-navigate-mvp ✖ blocked`,e),e}u&&u!==o&&($(`fwh-navigate-mvp · corrected url:`,{requested:o,correctedUrl:u}),o=u);try{ng(`Navigating to ${o}...`,{spinner:!0}),bg(),Cn();try{i?.()}catch{}try{let e=r?r():``;if(e&&t){let n=O_([{sender:`user`,message:e}]);n&&_e(t,n)}}catch{}F();let e=o;try{e=new URL(o,typeof window<`u`?window.location.href:``).href}catch{}let n=`this`;try{let e=new URL(o,window.location.href).pathname.split(`/`).filter(Boolean).pop()||``;n=e?e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()):`Home`}catch{}t&&typeof window<`u`&&we(t,window.location.href,e,n),wr(e);try{window.__fe_agent_nav={path:new URL(e,window.location.href).pathname,ts:Date.now()}}catch{}$(`fwh-navigate-mvp → real navigation`,o);let a=typeof window<`u`&&!window.Shopify&&!!Hn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),a&&Nn(12e3),Mr(o,{voiceActive:!0}).catch(()=>{}),a)try{let e=new URL(o,window.location.origin).pathname,t=window.location.pathname,n=Date.now()+2e3;for(;Date.now()<n&&!(typeof window<`u`&&window.location.pathname===e);)await new Promise(e=>setTimeout(e,80));let r=typeof window<`u`?window.location.pathname:e,i=typeof window<`u`?window.location.href:o;(r.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),$(`fwh-navigate-mvp → SPA nav complete. target:`,e,`actual:`,r);try{typeof window<`u`&&window.scrollTo(0,0)}catch{}let a=[],s=null,c=``,l=Date.now()+12e3;for(;Date.now()<l&&(await new Promise(e=>setTimeout(e,300)),{headings:a,pageTitleHeading:s,introText:c}=K_(),!(a.length>=1)););G_(),$(`fwh-navigate-mvp → page headings collected:`,a,`titleHeading:`,s);let u=a.length?a.join(` | `):`none`,d=a.length?``:`Headings were not ready yet; fwh-get-current-page-mvp returns them.`,f=s?` "${s}" is the page title, not a section. Intro text: "${c||`none`}".`:c?` Intro text before the first section: "${c}".`:``,p=``;try{if(a.length>0){let e=a.slice(0,3),t=[];for(let n of e){let e=rr(null,n);if(e){let r=q_(e).substring(0,800);r&&t.push(`[Section: ${n}] ${r}`)}}t.length>0&&(p=` Content of the first sections: ${t.join(` | `)}.`)}}catch{}if(Dr())return Tr(),$(`fwh-navigate-mvp ✖ landed on a not-found/404 page:`,i),`NAVIGATION_PAGE_NOT_FOUND. ${i} shows a "not found" error — that page doesn't exist on this site.`;let m=Date.now()+4e3,h=typeof window<`u`?window.location.pathname:r;for(;Date.now()<m&&!j_(h,e)&&j_(h,t);)await new Promise(e=>setTimeout(e,120)),h=window.location.pathname;$(`fwh-navigate-mvp route settle:`,{startPath:t,targetPath:e,settledPath:h});let g=typeof window<`u`?window.location.href:i,_=(h.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,v=j_(h,e),y=!j_(h,t),b=v||y;return $(`fwh-navigate-mvp settled:`,h,`target:`,e,`match:`,b),b?(Tr(),`OK_NAVIGATE_SPA. The visitor is now on ${g} (page: "${_}"). Section headings: ${u}.${f} ${d}${p}`):(Tr(),`NAVIGATION_DID_NOT_HAPPEN. The page did not change; the visitor is still on ${g} (page: "${_}").`)}catch{}return`OK_NAVIGATE_RELOADING. The page is reloading; this call ends now and continues on the new page.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`fwh-navigate-mvp ✖`,t),ng(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{xg(),rg(900)}},"fwh-highlight-mvp":async e=>{$(`fwh-highlight-mvp ▶`,e);let t=U_(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(Nn(3e3),typeof window<`u`&&window.__fe_user_nav_during_speech){let e=window.__fe_user_nav_during_speech,t=window.location.pathname;if(Date.now()-e.ts>=3e4)window.__fe_user_nav_during_speech=null;else return $(`flowengage_highlight ✖ blocked — user navigated during speech`,e),`NAV_CHANGED: the visitor moved themselves from "${e.fromPageName}" to "${e.toPageName}" (${t}) while you were speaking, so nothing was highlighted.`}G_();let i=(e=>e&&e.replace(/^\d+\.\s*/,``).replace(/^["']|["']$/g,``).trim())(r),a=rr(n||null,i||null);if(!a&&i){let e=Date.now()+600;for(;!a&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),G_(),a=rr(null,i)}if(!a){$(`fwh-highlight-mvp ✖ no element for:`,i||n);let{headings:e}=K_(),t=e.length?`Headings on this page: ${e.map(e=>`"${e}"`).join(` | `)}.`:`This page has no headings to highlight.`;return`HIGHLIGHT_NOT_FOUND: "${i||n}" on the current page. ${t}`}return Sn(a),$(`fwh-highlight-mvp ✓`,i||n),`OK_HIGHLIGHT: "${i||n}" is highlighted on screen.`},"fwh-read-content-mvp":async e=>{$(`fwh-read-content-mvp ▶`,e);let t=U_(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=rr(null,n);if(!t)return`Could not find section "${n}" on the page.`;e=q_(t)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar, #flowengage-root, .flowengage-shell, .flowengage-widget-root`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`fwh-read-content-mvp ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`fwh-read-content-mvp ✖`,e.message),`Could not read page content: ${e.message}`}},"fwh-page-content-mvp":async e=>{$(`fwh-page-content-mvp ▶`,e);let r=U_(e),i=r?.url||r?.page_url||``;if($(`fwh-page-content-mvp · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`fwh-page-content-mvp ✖ missing url`),`Missing url parameter.`;if(!t)return $(`fwh-page-content-mvp ✖ no siteId`),`Site is not configured.`;if(!n)return $(`fwh-page-content-mvp ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`fwh-page-content-mvp → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`fwh-page-content-mvp · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`fwh-page-content-mvp ✖`,e),`${e} FALLBACK REQUIRED: This page is not in the search index. Call fwh-read-content-mvp (no parameters) immediately to read the live page content directly from the visitor's browser — do NOT tell the visitor you cannot access the page.`}return $(`fwh-page-content-mvp ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`fwh-page-content-mvp ✖`,t),t}},"fwh-search-mvp":async e=>{$(`fwh-search-mvp ▶`,e);let r=U_(e).query;if(!r)return $(`fwh-search-mvp ✖ missing query`),`Missing query parameter.`;if(!t)return $(`fwh-search-mvp ✖ no siteId`),`Search unavailable (no siteId configured).`;if(!n)return $(`fwh-search-mvp ✖ no api base`),`Search unavailable (no API base URL).`;try{let e=`${n}/api/site-tools/search`;$(`fwh-search-mvp → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`fwh-search-mvp · HTTP`,i.status,`success:`,a.success),!a.success||!a.results?.length)return`No results found for that query. Try rephrasing, or use fwh-read-content-mvp to read the current page.`;let o=a.results.slice(0,5).map((e,t)=>`${t+1}. ${e.title||e.url} (${e.url})${e.snippet?` — ${e.snippet}`:``}`).join(`
420
+ `);return $(`fwh-search-mvp ✓`,`${a.results.length} result(s)`),`SEARCH_RESULTS:\n${o}`}catch(e){return $(`fwh-search-mvp ✖`,e.message),`Search failed. Use fwh-read-content-mvp to read the current page instead.`}},"fwh-list-nav-links-mvp":async()=>{if($(`fwh-list-nav-links-mvp ▶`),typeof window>`u`)return`Cannot read navigation (no browser context).`;let e=new Map,t=[],n=[`nav a`,`[role='navigation'] a`,`header a`,`.navbar a`,`.nav a`,`.menu a`,`.navigation a`,`.header a`,`[class*='nav'] a`,`[class*='menu'] a`,`[class*='header'] a`];if(N_(t=>{for(let r of n)try{t.querySelectorAll(r).forEach(t=>{if(Tn(t))return;let n=t.getAttribute(`href`),r=(t.textContent||``).replace(/\s+/g,` `).trim();if(!r||!n||n===`#`||n.startsWith(`javascript:`))return;try{let e=t.parentElement;if(e&&M_(e).display===`none`&&!e.closest(`nav, [role='navigation'], header, [class*='nav'], [class*='menu']`))return}catch{}let i=r.toLowerCase()+`|`+n;e.has(i)||e.set(i,{text:r,href:n})})}catch{}t.querySelectorAll(`select`).forEach(t=>{if(Tn(t))return;let n=F_(t);/nav|menu|page|section|go to/i.test(n||t.name||t.id||``)&&Array.from(t.options).forEach(r=>{if(!r.value||r.disabled)return;let i=r.text.trim();if(!i)return;let a=i.toLowerCase()+`|`+r.value;e.has(a)||e.set(a,{text:i,href:r.value,isSelectOption:!0,selectLabel:n||t.name||`dropdown`})})})}),e.forEach(e=>t.push(e)),!t.length)return`NAV_LINKS: No navigation links found on this page. Use fwh-read-content-mvp to read page content or fwh-search-mvp to search the site.`;let r=t.slice(0,50).map((e,t)=>`${t+1}. "${e.text}"${e.isSelectOption?` (dropdown option in "${e.selectLabel}")`:``} → ${e.href}`).join(`
421
+ `);return $(`fwh-list-nav-links-mvp ✓`,`${t.length} links`),`NAV_LINKS (${t.length} total, showing up to 50):\n${r}`},"fwh-end-session-mvp":async()=>($(`fwh-end-session-mvp ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),"fwh-request-email-mvp":async()=>($(`fwh-request-email-mvp ▶`),typeof e.requestEmailCollection==`function`&&e.requestEmailCollection(),`EMAIL_BOX_SHOWN. A text box for their email is on screen now. EMAIL_SAVED arrives once they submit it.`),"fwh-get-current-page-mvp":async()=>{if($(`fwh-get-current-page-mvp ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``;if(Dr())return $(`fwh-get-current-page-mvp ✓ 404 detected`,{url:e}),`CURRENT_PAGE_NOT_FOUND. The visitor is on a "not found" error page (${e}); there is no content here.`;let{headings:r,pageTitleHeading:i,introText:a}=K_();$(`fwh-get-current-page-mvp ✓`,{url:e,path:t,title:n}),$(`fwh-get-current-page-mvp → page headings collected:`,r,`titleHeading:`,i);let o=i?` "${i}" is the page title, not a section. Intro text: "${a||`none`}".`:a?` Intro text before the first section: "${a}".`:``;if(!r.length)return`CURRENT_PAGE. URL: ${e} | Title: ${n} |${o} This page has no section headings.`;let s=r.map(e=>`"${e}"`).join(` | `);return`CURRENT_PAGE. URL: ${e} | Title: ${n} | Page sections (${r.length} total): ${s}.${o}`},"fwh-list-forms-mvp":async()=>{let e=L_(),t=R_();$(`fwh-list-forms-mvp ✓`,`${e.length} field(s)`,`${t.length} button(s)`);let n=e.map(e=>({...e,inputCategory:e.tag===`SELECT`?`dropdown_select`:`text_input`}));return JSON.stringify({fields:n,buttons:t,hint:`field_key: use the label/placeholder/name shown above. CRITICAL: fields with inputCategory='dropdown_select' are SELECT elements — their field_key must match the SELECT's own label (e.g. 'Company Size'), NOT the option text (e.g. 'Small Business') and NOT a nearby text input label. Never fill a SELECT option value into a text input.`})},"fwh-fill-form-mvp":async()=>`FORM_FILLING_DISABLED: forms can't be filled in for the visitor; fwh-list-forms-mvp lists the fields.`,"fwh-click-button-mvp":async e=>{let t=U_(e),n=(t.button_text??t.buttonText??t.text??``).trim(),r=(t.card_context??t.cardContext??``).trim();if($(`fwh-click-button-mvp ▶`,n,r?`(card_context: ${r})`:``),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let i=H_(n,a,r);if(!i)return $(`fwh-click-button-mvp ✖ no match`),`Could not find a button matching "${n}". Call fwh-list-forms-mvp to see button texts.`;try{ng(`Clicking ${n}...`,{spinner:!0});try{i.scrollIntoView({block:`center`,inline:`nearest`})}catch{i.scrollIntoView(!0)}await Eg(i),i.focus?.(),await Og(i),kg(i),i.click();let e=(i.innerText||i.textContent||i.value||i.getAttribute(`aria-label`)||``).replace(/\s+/g,` `).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`fwh-click-button-mvp ✓`,t),ng(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`fwh-click-button-mvp ✖`,t),ng(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{Dg(),rg(700)}},"fwh-cart-get-mvp":async()=>{$(`fwh-cart-get-mvp ▶`);try{let e=await Gr();if(!e)return`CART_UNAVAILABLE: this page is not a Shopify storefront, so there is no cart to read.`;let t=e.items.map((e,t)=>{let n=e.variantTitle&&e.variantTitle!==`Default Title`?` (${e.variantTitle})`:``;return`${t+1}. ${e.title}${n} — qty ${e.quantity} — ${e.linePrice}${e.handle?` — handle: ${e.handle}`:``}`}),n=`CART. Items: ${e.itemCount} | Subtotal: ${e.subtotal}${e.currency?` ${e.currency}`:``}${t.length?` | ${t.join(` | `)}`:` | (cart is empty)`}`;return $(`fwh-cart-get-mvp ✓`,n),n}catch(e){return $(`fwh-cart-get-mvp ✖`,e),`CART_ERROR: ${e?.userMessage||e?.message||`could not read the cart`}`}},"fwh-shop-search-mvp":async e=>{let t=String((e||{}).query||``).trim();if($(`fwh-shop-search-mvp ▶`,t),!t)return`Missing query: pass the product name or keyword to search.`;try{let e=await Qr(t);if(!e.length)return`NO_PRODUCTS_FOUND for "${t}". Tell the visitor no matching product was found — do not invent products.`;let n=e.map(e=>`"${e.title}" — handle: ${e.handle}${e.price?` — price: ${e.price}`:``}`).join(` | `);return $(`fwh-shop-search-mvp ✓`,n),`PRODUCTS_FOUND: ${n}. Use the handle with fwh-cart-add-mvp or fwh-view-product-mvp.`}catch(e){return $(`fwh-shop-search-mvp ✖`,e),`SEARCH_ERROR: ${e?.message||`product search failed`}`}},"fwh-cart-add-mvp":async e=>{let t=e||{},n=String(t.product_handle||t.productHandle||``).trim().toLowerCase(),r=String(t.variant||``).trim()||null,i=Math.min(20,Math.max(1,parseInt(t.quantity,10)||1));if($(`fwh-cart-add-mvp ▶`,{handle:n,variantText:r,quantity:i}),!n)return`Missing product_handle: search the product first with fwh-shop-search-mvp.`;try{let{variant:e,product:t}=await Kr(n,r);await qr(e.id,i);let a=await Hr(),o=await s(a),c=e.title&&e.title!==`Default Title`?` (${e.title})`:``,l=`ADDED ${i} × ${t.title}${c}. Cart now has ${a.item_count} item(s), subtotal ${Wr(a.items_subtotal_price)}${a.currency?` ${a.currency}`:``}.${o}`;return $(`fwh-cart-add-mvp ✓`,l),l}catch(e){return $(`fwh-cart-add-mvp ✖`,e),`ADD_FAILED: ${e?.userMessage||e?.message||`could not add the item`}. Relay this reason to the visitor.`}},"fwh-cart-update-mvp":async e=>{let t=e||{},n=parseInt(t.line,10),r=Math.min(20,Math.max(0,parseInt(t.quantity,10)));if($(`fwh-cart-update-mvp ▶`,{line:n,quantity:r}),!Number.isFinite(n)||n<1)return`Missing/invalid line: call fwh-cart-get-mvp first and use the item's 1-based number.`;if(!Number.isFinite(r))return`Missing/invalid quantity.`;try{let e=await Hr(),t=e.items?.[n-1];if(!t)return`NO_SUCH_LINE: the cart has ${e.items?.length||0} item(s). Call fwh-cart-get-mvp for the current list.`;let i=await Jr(n,r),a=await s(i),o=`UPDATED ${t.product_title||t.title} to qty ${r}. Cart now has ${i.item_count} item(s), subtotal ${Wr(i.items_subtotal_price)}${i.currency?` ${i.currency}`:``}.${a}`;return $(`fwh-cart-update-mvp ✓`,o),o}catch(e){return $(`fwh-cart-update-mvp ✖`,e),`UPDATE_FAILED: ${e?.userMessage||e?.message||`could not update the item`}`}},"fwh-cart-remove-mvp":async e=>{let t=parseInt((e||{}).line,10);if($(`fwh-cart-remove-mvp ▶`,{line:t}),!Number.isFinite(t)||t<1)return`Missing/invalid line: call fwh-cart-get-mvp first and use the item's 1-based number.`;try{let e=await Hr(),n=e.items?.[t-1];if(!n)return`NO_SUCH_LINE: the cart has ${e.items?.length||0} item(s). Call fwh-cart-get-mvp for the current list.`;let r=await Jr(t,0),i=await s(r),a=`REMOVED ${n.product_title||n.title}. Cart now has ${r.item_count} item(s), subtotal ${Wr(r.items_subtotal_price)}${r.currency?` ${r.currency}`:``}.${i}`;return $(`fwh-cart-remove-mvp ✓`,a),a}catch(e){return $(`fwh-cart-remove-mvp ✖`,e),`REMOVE_FAILED: ${e?.userMessage||e?.message||`could not remove the item`}`}},"fwh-cart-open-mvp":async()=>($(`fwh-cart-open-mvp ▶`),c(Yr(),`Cart`)),"fwh-checkout-mvp":async()=>{$(`fwh-checkout-mvp ▶`);try{if(!(await Hr()).item_count)return`CART_EMPTY: do not go to checkout. Tell the visitor their cart is empty and offer to help find products.`}catch{}return c(Xr(),`Checkout`)},"fwh-view-product-mvp":async e=>{let t=e||{},n=String(t.product_handle||t.productHandle||``).trim().toLowerCase();return $(`fwh-view-product-mvp ▶`,{handle:n}),n?c(Zr(n),n.replace(/[-_]/g,` `)):`Missing product_handle: search the product first with fwh-shop-search-mvp.`}};async function s(e){try{let{sectionsSwapped:t}=await oi(e);if(!t&&$r())return` NOTE: the cart list on this page could not be re-rendered — briefly tell the visitor the page may need a quick refresh to show the change.`}catch{}return``}function c(e,n){if(typeof window>`u`)return`NAV_FAILED: no browser context.`;let r=e;try{r=new URL(e,window.location.href).href}catch{}return t&&we(t,window.location.href,r,n),wr(r),jr().then(()=>{window.location.assign(r)}),`OK_NAVIGATING to ${n}. The page is loading.`}return{...o,highlightOnPage:o[`fwh-highlight-mvp`],getPageContent:o[`fwh-page-content-mvp`],endVoiceSession:o[`fwh-end-session-mvp`],listPageForms:o[`fwh-list-forms-mvp`],fillFormFields:o[`fwh-fill-form-mvp`],clickPageButton:o[`fwh-click-button-mvp`]}}var Y_=/^(get in touch|contact us|let'?s (talk|connect)|subscribe|newsletter|follow us|quick links|company|solutions|what we do|resources|legal|sitemap|share this)/i;function X_(){try{let{headings:e,pageTitleHeading:t,containerHeadings:n}=K_(),r=new Set((n||[]).map(e=>e.trim())),i=(e||[]).map(e=>typeof e==`string`?e:e?.text||``).filter(Boolean).filter(e=>!t||e.trim()!==t.trim()).filter(e=>!Y_.test(e.trim())),a=i.filter(e=>!r.has(e.trim()));return a.length?a:i}catch{return[]}}function Z_(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=_n();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var Q_=`[PAGE_CONTEXT]`;function $_(e,t,n,r){return`${Q_} The visitor is on ${e}${r?`, having moved here themselves from the ${r} page`:``}. Approximate headings: ${t||`none`}. ${n?`Forms: ${n}. `:``}`.trim()}function ev(e,t,n,r,i){e?.sendContextualUpdate?.($_(t,n,r,i));try{e?.reportPage?.(new URL(t,window.location.href).pathname,document.title)}catch{}}var tv={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function nv(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function rv(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function iv(e){let[t,n]=d.default.useState(null),r=typeof e==`string`?e.trim():``;return d.default.useEffect(()=>{if(!r){n(null);return}n(null);let e=!1,t=new window.Image;return t.onload=()=>{e||n(r)},t.onerror=()=>{e||n(null)},t.src=r,()=>{e=!0}},[r]),t}function av({logo:e,style:t}){let n=iv(typeof e==`string`?e:null);if(!e)return null;if(typeof e==`string`)return n?(0,f.jsx)(`img`,{src:n,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}}):null;let r=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return r?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:r}):null}function ov({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function sv(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(i'?m|i am)\s+done\b[\s.!,]*(for\s+(today|now)|here)?[\s.!,]*$/i.test(n)||/\b(that'?s|that is)\s+(all|it)\b[\s.!,]*(for\s+(today|now))?[\s.!,]*$/i.test(n)||/\b(no\s+more|nothing\s+else)\b.*\b(questions?|thanks?|for\s+(today|now))?[\s.!,]*$/i.test(n)||e===`bot`&&(/\b(that'?s all|we'?re done)\b/i.test(n)||/\b(goodbye|bye)\b/i.test(n)||/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))):!1}function cv({orbColors:e,...t}){return(0,f.jsx)(y_,{colors:e,...t})}function lv({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||tv.green,c=rv(s),l=a?72:94,u=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(uh.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:`210px`,wordBreak:`break-word`,overflow:`hidden`,display:`-webkit-box`,WebkitLineClamp:4,WebkitBoxOrient:`vertical`},children:e.entryPrompt}),(0,f.jsxs)(uh.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${s}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(uh.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,f.jsx)(cv,{size:l,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(uh.div,{initial:{opacity:0},animate:{opacity:o?0:1},transition:{duration:.28},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,f.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`,animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u}):(0,f.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function uv({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||tv.green,l=rv(c);return(0,f.jsxs)(uh.div,{initial:{scale:50/350,borderRadius:`50%`},animate:s?{scale:50/350,opacity:0,borderRadius:`50%`}:{scale:1,borderRadius:`16px`,opacity:1},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(cv,{size:72,orbColors:t}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,lineHeight:1.4},children:e.connectionTitle}),e.connectionSubtitle&&(0,f.jsx)(`p`,{style:{margin:`6px 0 0`,fontSize:`13px`,fontWeight:400,color:`#6b7280`,lineHeight:1.4},children:e.connectionSubtitle})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:c,color:l,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${c}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function dv({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,beaconSyncVoiceTranscript:l,widgetPosition:u=`bottom-right`,voiceEndCounter:p,websiteName:m,voiceFirstMessage:h,captureVisitorEmail:g,emailRequired:_,emailCaptureEnabled:v=!0,listeningLabel:y=`Listening...`,thinkingLabel:b=`Thinking...`,enterChatModeLabel:x=`Enter Chat Mode`,endConversationLabel:S=`End Conversation`}){(0,d.useEffect)(()=>(console.log(`[FlowEngage:VoiceDebug] 🔵 VoiceMode MOUNTED`),()=>console.log(`[FlowEngage:VoiceDebug] 🔴 VoiceMode UNMOUNTED`)),[]);let[C,w]=(0,d.useState)(`idle`),[T,E]=(0,d.useState)(!1),[ee,D]=(0,d.useState)(!1),[te,ne]=(0,d.useState)(()=>re(i)===`auto`),ie=()=>{let e=te?`ask`:`auto`;O(i,e),ne(e===`auto`)},[ae,k]=(0,d.useState)(!1),[oe,se]=(0,d.useState)(``),[ce,le]=(0,d.useState)(``),ue=(0,d.useRef)(!1),de=(0,d.useRef)(!1),fe=(0,d.useRef)(null),A=(0,d.useRef)(0),pe=(0,d.useRef)(``),j=(0,d.useRef)(!1),me=(0,d.useRef)(0),he=(0,d.useRef)(!1),M=(0,d.useRef)(!1),N=(0,d.useRef)(!1),ge=(0,d.useRef)([]),P=(0,d.useRef)(null),be=(0,d.useRef)(``),I=(0,d.useRef)(null),xe=e=>{he.current=e,e||(M.current=!1),L.current?.setWalkthroughActive?.(e)};I.current=async()=>{if(M.current)return;let e=typeof window<`u`?window.location.pathname:null;if(e&&P.current&&e!==P.current){console.log(`[FlowEngage] walkthrough ended — visitor left `+P.current),P.current=null,ge.current=[],xe(!1);return}let t=ge.current;Se.current+=1;let n=Se.current,r=t[n];if(!r){if(xe(!1),t.length)L.current?.sendUserMessage?.(`That was the last section. Say so in one short sentence and ask if they want to explore any section further.`);else if(n===0){let e=``;try{let t=await we.current?.[`fwh-read-content-mvp`]?.({});typeof t==`string`&&t&&!/^Could not/i.test(t)&&(e=t.slice(0,2800))}catch{}L.current?.sendUserMessage?.(e?`Give the visitor a complete spoken overview of this page in 4-6 sentences, based ONLY on this page content:\n"""${e}"""\nThen ask which part they'd like to hear more about. Do not call any tool.`:`Give the visitor a complete spoken overview of this page in 4-6 sentences based on what you know about it, then ask which part they'd like to hear more about. Do not call any tool.`,{suppressQuestion:!0})}return}try{await we.current?.highlightOnPage?.({section_text:r})}catch(e){console.warn(`[FlowEngage] walkthrough highlight failed:`,e?.message||e)}console.debug(`[FlowEngage] walkthrough step ${n+1}/${t.length}: ${r}`);let i=``;try{let e=await we.current?.[`fwh-read-content-mvp`]?.({section_text:r});typeof e==`string`&&e&&!/^Could not/i.test(e)&&(i=e.slice(0,2500))}catch{}L.current?.sendUserMessage?.(`Describe the section titled "${r}".`+(i?` Its content:\n"""${i}"""`:``),{suppressQuestion:!0})};let Se=(0,d.useRef)(0),L=(0,d.useRef)(null),we=(0,d.useRef)(null),Ee=(0,d.useRef)(``),De=(0,d.useRef)(async()=>{}),Oe=(0,d.useRef)(!1),ke=(0,d.useRef)(!1),Ae=(0,d.useRef)(!1),R=(0,d.useRef)(!1),je=(0,d.useRef)(`minimized`),Me=(0,d.useRef)(null),Ne=(0,d.useRef)(null),Pe=(0,d.useRef)(null),Fe=(0,d.useRef)(0),Ie=(0,d.useRef)(!1),Le=(0,d.useRef)(`idle`),Re=(0,d.useRef)(null),ze=(0,d.useRef)(!1),z=(0,d.useRef)(null),Be=(0,d.useCallback)((e=`minimized`)=>{console.warn(`[FlowEngage:VoiceDebug] 🛑 requestSessionShutdown called`,{destination:e,stack:Error().stack?.split(`
422
+ `).slice(1,4).join(` | `)}),je.current=e,R.current=!0,queueMicrotask(()=>{Oe.current||(Oe.current=!0,De.current?.())})},[s]),B=(0,d.useCallback)(()=>{fe.current&&=(clearTimeout(fe.current),null)},[]);(0,d.useEffect)(()=>{if(_){ue.current=!1;return}if(ue.current=!0,de.current=!1,k(!1),B(),j.current){j.current=!1,L.current?.setMicMuted?.(!1);let e=pe.current;pe.current=``,L.current?.injectAgentSpeech?.(`Thanks — I already have your email on file.`,`interrupt`),e&&L.current?.sendUserMessage?.(`The visitor's email is already on file — do not ask for it. Answer their question now: "${e}"`)}L.current?.sendContextualUpdate?.(`EMAIL REQUIREMENT SATISFIED — the visitor's email is already on file. All earlier instructions about requiring or asking for an email are VOID. Never ask for it again.`)},[_,B]);let Ve=/(that covers everything|that was all|covered everything|that(?:'|’)?s everything)/i,He=/^((uh+|um+|so|well|okay|ok|yeah)[,.\s]+)*(yes|yeah|yep|yup|sure|ok(ay)?|please|continue|go on|next|keep going|carry on|go ahead|resume|back to the tour)[\s.!,]*$/i,Ue=/highlight|click|product|cart|checkout/,We=/(would you like (me )?to take you|shall i take you|want me to take you|would you like to (go|explore|visit|see)|take you there)/i,Ge=/^((uh+|um+|oh|ah|so|well)[,.\s]+)*(cool|nice|great|awesome|wow|lovely|perfect|got it|gotcha|i see|understood|makes sense|interesting|right|alright|sounds good|mm+-?hmm+|hmm+|k)[\s.!,]*$/i,Ke=e=>String(e||``).replace(/[\s.,!?]*((uh+|um+|er+|hmm+|mm+)[\s.,!?]*)+$/i,``).trim(),qe=(0,d.useCallback)(()=>{B(),fe.current=setTimeout(()=>{if(!(!de.current||ue.current))if(A.current<3){A.current+=1;try{L.current?.injectAgentSpeech?.(`I still need your email in the box below to continue — could you enter it, please?`,`queue`)}catch{}qe()}else{try{L.current?.injectAgentSpeech?.(`Since I haven't received your email, I'll close this session for now. Feel free to come back anytime — take care!`,`queue`)}catch{}de.current=!1,k(!1),B(),Ie.current=!0}},1e4)},[B]),Je=(0,d.useCallback)(async e=>{R.current=!0;try{Cn()}catch{}try{gg()}catch{}if(i)try{Te(i)}catch{}try{await L.current?.endSession?.()}catch{}let t=Me.current,n=Ne.current;if(t&&o&&a){let e=n?Math.round((Date.now()-n)/1e3):0;fetch(`${a}/api/voice/save-chat-recording`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({chatId:o,voiceSessionId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(Me.current=null,Ne.current=null,L.current=null,w(`idle`),E(!1),Oe.current=!1,Ir(),i)try{ye(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);De.current=()=>Je(je.current===`chat`?t:n),(0,d.useEffect)(()=>{ke.current=T},[T]),(0,d.useEffect)(()=>{p&&Be(`chat`)},[p]),(0,d.useEffect)(()=>{let e=!1,d=null,f=null,p=null;return(async()=>{if(!i){w(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],Ee.current=``,Oe.current=!1,Ae.current=!1,R.current=!1,je.current=`minimized`,Fr({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=O_(s.current);e&&_e(i,e)}catch{}if(!Hn()){let e=Me.current,t=Ne.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,voiceSessionId:e,duration:n,siteId:i}),s=`${a}/api/voice/save-chat-recording`;fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:r,keepalive:!0}).catch(()=>{}),Me.current=null,Ne.current=null}catch{}}F()}});let t=Z_(J_({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>Ee.current,beaconSyncFullVoiceHistory:()=>l?.(s.current),isWalkthroughActive:()=>he.current&&!M.current,requestEndSession:()=>{Ie.current=!0},requestEmailCollection:()=>{v&&(ue.current||de.current||(de.current=!0,A.current=0,k(!0),qe()))}})),n=!!(i?ve(i):null)?.transcript,r=i?Te(i):null,c=!!r,g=typeof window<`u`?window.location.pathname:`/`,y=typeof document<`u`?document.title:``,b=g.replace(/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i,``)||`/`,x=b===`/`||b===``,S={apiBaseUrl:a,siteId:i,chatId:o,clientTools:t};we.current=t;let C=(g.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),T=``;y&&y.includes(`|`)&&(T=y.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let ee=T||C||``,D=ee?`the ${ee} page`:`this page`,te=(()=>{if(!r?.targetUrl)return null;try{return new URL(r.targetUrl,window.location.href).pathname}catch{return null}})();if(c||n)S.greeting=null;else{let e=m||``;S.greeting=h||(x?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to ${D}! How may I help you?`),x||console.log(`[FlowEngage] 🏠 Page-context greeting: "${ee}" for ${g}`)}let ne=!1,re=!1,O=v&&!!_&&!N.current,ie=await Zh.startSession({...S,onConnect:({conversationId:e})=>{Me.current=e,Ne.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onSessionInfo:({emailOnFile:e})=>{N.current=!!e,e&&(ue.current=!0,de.current=!1,k(!1),B(),console.log(`[FlowEngage] email already on file per server — gate disabled`))},onAgentTurnEnd:()=>{e||he.current&&(M.current||j.current||setTimeout(()=>I.current?.(),250))},onSessionEnding:()=>{e||Be(`minimized`)},onStartWalkthrough:()=>{e||(typeof window<`u`&&(window.__fe_user_nav_during_speech=null),xe(!0),M.current=!1,me.current=0,Se.current=-1,ge.current=X_(),P.current=typeof window<`u`?window.location.pathname:null,console.log(`[FlowEngage] walkthrough started — ${ge.current.length} sections on this page`),I.current?.())},onPanel:({title:t,items:n})=>{e||mg(n,{title:t||`Products`,side:u===`bottom-left`?`left`:`right`,productUrl:e=>e.handle?`${window.location.origin}/products/${encodeURIComponent(e.handle)}`:null})},onModeChange:({mode:t,tentative:n})=>{if(!e){if(t===`speaking`){Re.current&&=(clearTimeout(Re.current),null),z.current&&=(clearTimeout(z.current),null),w(`speaking`),Le.current=`speaking`,ze.current=!1;return}if(t===`user-speaking`){if(de.current&&!ue.current&&qe(),z.current&&=(clearTimeout(z.current),null),Le.current===`speaking`)return;try{Cn()}catch{}Re.current&&=(clearTimeout(Re.current),null),Le.current!==`listening`&&(w(`listening`),Le.current=`listening`);return}if(t===`thinking`){if(Re.current&&=(clearTimeout(Re.current),null),z.current&&=(clearTimeout(z.current),null),Le.current===`speaking`)return;w(`thinking`),Le.current=`thinking`,n&&(z.current=setTimeout(()=>{z.current=null,!(e||Le.current!==`thinking`)&&(Le.current=`listening`,w(`listening`))},4e3));return}if(Le.current=`listening`,Ie.current){Ie.current=!1,Be();return}if(O&&!re&&!ue.current&&!N.current){re=!0;try{L.current?.sendContextualUpdate?.(`The visitor hasn't given their email yet; the app will ask for it when they first speak.`)}catch{}}Re.current&&clearTimeout(Re.current),Re.current=setTimeout(()=>{e||Le.current!==`speaking`&&(ze.current||(Re.current=null,Le.current=`listening`,w(`listening`)))},1200)}},onAgentAnswer:({text:t,tools:n})=>{if(e||he.current||window.__fe_user_nav_during_speech||n.some(e=>Ue.test(e.name)))return;let r=gr(t);r&&(Nn(3e3),Sn(r))},onMessage:t=>{if(e||j.current&&t.role!==`user`&&!/email/i.test(String(t.message||``)))return;let n=t.role===`user`&&/^(Describe the section titled "|\[SYSTEM:|Give the visitor a complete spoken overview|That was the last section)/.test(String(t.message||``).trim());if(t.role===`user`&&!n)try{gg()}catch{}if(!n&&t.role===`user`&&he.current){let e=String(t.message||``).trim(),n=Ke(e),r=e=>!!e&&(He.test(e)||Ge.test(e));We.test(be.current||``)?(console.log(`[FlowEngage] walkthrough ended — visitor accepted a navigation offer`),P.current=null,ge.current=[],xe(!1)):!n||r(e)||r(n)?M.current&&(M.current=!1,console.debug(`[FlowEngage] walkthrough resumed by visitor`),setTimeout(()=>I.current?.(),300)):(console.log(`[FlowEngage] walkthrough ended — visitor moved to a new topic`),P.current=null,ge.current=[],xe(!1))}if(t.role!==`user`&&!n&&(be.current=String(t.message||``)),t.role!==`user`&&Ve.test(String(t.message||``))){let e=ge.current.length;!e||Se.current>=e-1?xe(!1):console.debug(`[FlowEngage] agent claimed completion at step ${Se.current+1}/${e} — ignoring, tour continues`)}let r=t.role===`user`?`user`:`bot`,a=t.message||t.text||t.content||``;if(a){if(r===`user`&&(Ee.current=a,typeof window<`u`&&(window.__fe_user_nav_during_speech=null),ze.current=!0,Re.current&&=(clearTimeout(Re.current),null),Le.current!==`speaking`&&(w(`thinking`),Le.current=`thinking`),O&&!ne&&!ue.current&&!N.current&&(ne=!0,pe.current=a,j.current=!0,L.current?.injectAgentSpeech?.(`Before I answer that, could you please enter your email in the text box below?`,`interrupt`),L.current?.setMicMuted?.(!0),de.current||(de.current=!0,A.current=0,k(!0),qe()))),s.current=[...s.current,{sender:r,message:a,timestamp:new Date().toISOString(),debug:t.debug}],i)try{let e=O_(s.current);e&&_e(i,e)}catch{}if(sv(r,a)){Ie.current=!0;return}ke.current&&r===`bot`&&/are you still there|still there\??|hello\?|anyone there|checking in|you there|are you available|is anyone|did you step away/i.test(a)&&(Fe.current+=1,Fe.current>=5&&Be(`minimized`))}},onError:t=>{if(!e&&!R.current&&!Ae.current&&!Ce()){Ae.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{L.current?.setMicMuted?.(!0)}catch{}E(!0),w(`error`),Be(`chat`)}},onDisconnect:t=>{if(e||R.current||Ae.current||Ce())return;let n=s.current?.length||0;console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:n,reason:t?.reason,closeCode:t?.context?.code,closeReason:t?.context?.reason||t?.message,lastUserText:Ee.current||``,wasMuted:ke.current}),Ae.current=!0;try{L.current?.setMicMuted?.(!0)}catch{}E(!0),Be(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),ie.endSession().catch(()=>{});return}d=ie,L.current=ie,w(`listening`);try{sessionStorage.setItem(`el_conv_${i}`,ie.getId())}catch{}parent.postMessage({type:`AGENT_EXPAND`},`*`);try{let e=typeof window<`u`?window.location.href:``,n=`[]`;try{n=await t[`fwh-list-forms-mvp`]()}catch{}let r=`none`;if(typeof window<`u`&&typeof document<`u`)try{let e=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`,t=document.querySelector(`main, [role='main']`)||document.body,n=Array.from(t.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200);n.length||(n=Array.from(document.body.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200)),n.length&&(r=[...new Set(n)].slice(0,15).join(` | `))}catch{}_||ie.sendContextualUpdate(`The visitor's email is already on file from an earlier session.`),ev(ie,e,r,n)}catch{}if(typeof window<`u`){let t=window.location.pathname,n=Date.now(),r=e=>{try{return(decodeURIComponent(e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}catch{return((e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}},i=()=>{if(e)return;let i=window.location.pathname;if(r(i)===r(t)){t=i;return}if(Date.now()-n<8e3){t=i;return}let a=typeof window<`u`&&window.__fe_agent_nav||null,o=te&&r(i)===r(te)||Pn()||a&&Date.now()-a.ts<15e3&&r(a.path)===r(i),s=t;t=i;let c=window.location.href,l=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.trim()})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,20):[];try{Cn()}catch{}let u=l.map(e=>e.text).join(` | `),d=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,f=d(s),p=d(i);if(o){typeof window<`u`&&(window.__fe_agent_nav=null),console.log(`[FlowEngage] agent-driven navigation settled: "${s}" → "${i}"`);try{ev(L.current,c,u)}catch{}return}typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:s,toPath:i,fromPageName:f,toPageName:p,ts:Date.now()}),console.log(`[FlowEngage] visitor navigation detected: "${s}" → "${i}" (agent target: ${te||`none`})`);try{ev(L.current,c,u,null,f)}catch{}};f=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{f(...e),setTimeout(i,50)},p=()=>setTimeout(i,50),window.addEventListener(`popstate`,p)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(w(`error`),je.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{console.warn(`[FlowEngage:VoiceDebug] ⚠️ useEffect CLEANUP fired — session will be killed`,{agentId:r,siteId:i,apiBaseUrl:a}),e=!0,R.current=!0;try{Cn()}catch{}if(i)try{Te(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Ir(),Re.current&&=(clearTimeout(Re.current),null),z.current&&=(clearTimeout(z.current),null),fe.current&&=(clearTimeout(fe.current),null),ze.current=!1,Le.current=`idle`,f&&typeof window<`u`&&(window.history.pushState=f),p&&typeof window<`u`&&window.removeEventListener(`popstate`,p);let t=d||L.current,n=Me.current,l=Ne.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=l?Math.round((Date.now()-l)/1e3):0,t=JSON.stringify({chatId:o,voiceSessionId:n,duration:e,siteId:i}),r=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(r,new Blob([t],{type:`application/json`}))||fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),Me.current=null,Ne.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Be]),(0,d.useEffect)(()=>{if(!ee)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Pe.current&&!Pe.current.contains(t)&&D(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[ee]);let Ye=async()=>{if(L.current)try{if(T){Fe.current=0,await L.current.setMicMuted?.(!1),E(!1);try{L.current.sendContextualUpdate?.(`[MIC] The visitor unmuted their microphone.`)}catch{}}else{Fe.current=0,await L.current.setMicMuted?.(!0),E(!0);try{L.current.sendContextualUpdate?.(`[MIC] The visitor muted their microphone.`)}catch{}}}catch{}},Xe=(0,d.useCallback)(async e=>{e?.preventDefault?.();let t=oe.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){le(`Please enter a valid email address.`);return}le(``),ue.current=!0,de.current=!1,B(),k(!1),se(``),j.current=!1;try{typeof g==`function`&&await g(t)}catch{}L.current?.setMicMuted?.(!1);let n=pe.current;pe.current=``;try{L.current?.injectAgentSpeech?.(`Thank you for submitting your email.`),L.current?.sendUserMessage?.(n||`The visitor's email is on file. Carry on helping them and never ask for it again.`)}catch{}},[oe,g,B]),V=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,f.jsxs)(`div`,{ref:Pe,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[ae&&(0,f.jsxs)(`form`,{onSubmit:Xe,style:{width:`270px`,maxWidth:`calc(100vw - 40px)`,boxSizing:`border-box`,background:`rgba(15,22,36,0.97)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,padding:`16px`,display:`flex`,flexDirection:`column`,gap:`10px`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsx)(`span`,{style:{color:`white`,fontSize:`13px`,fontWeight:600,lineHeight:1.4},children:`Please enter your email to continue`}),(0,f.jsx)(`input`,{type:`email`,inputMode:`email`,autoComplete:`email`,autoFocus:!0,value:oe,onChange:e=>{se(e.target.value),ce&&le(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:ce?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),ce&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:ce}),(0,f.jsx)(`button`,{type:`submit`,disabled:!oe.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:oe.trim()?V:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:oe.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,f.jsxs)(`div`,{style:{position:`relative`},children:[(C===`listening`||C===`thinking`)&&!T&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:C===`thinking`?b:y}),T&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`#f87171`,fontSize:`16px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Muted`}),(0,f.jsx)(cv,{size:72,voiceState:C,isMuted:T,orbColors:e})]}),C===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:Ye,title:T?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:T?`#7f1d1d`:`#1f2937`,border:T?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:T?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:T?(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsx)(jg,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>D(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,f.jsx)(zg,{size:16,color:`currentColor`})})]}),ee&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{D(!1),je.current=`chat`,Je(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(Bg,{}),x]}),i&&(0,f.jsxs)(`button`,{onClick:()=>ie(),style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`8px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`span`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,minWidth:0,overflow:`hidden`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,f.jsx)(`polygon`,{points:`3 11 22 2 13 21 11 13 3 11`})}),(0,f.jsx)(`span`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:`Auto-navigate`})]}),(0,f.jsx)(`span`,{"aria-hidden":!0,style:{width:`34px`,height:`19px`,borderRadius:`999px`,background:te?`#22c55e`:`rgba(255,255,255,0.2)`,position:`relative`,flexShrink:0,transition:`background 0.15s ease`},children:(0,f.jsx)(`span`,{style:{position:`absolute`,top:`2px`,left:te?`17px`:`2px`,width:`15px`,height:`15px`,borderRadius:`50%`,background:`white`,transition:`left 0.15s ease`}})})]}),(0,f.jsxs)(`button`,{onClick:()=>{D(!1),je.current=`minimized`,Je(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(Vg,{}),S]}),(0,f.jsx)(`button`,{onClick:()=>D(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function fv({orbColors:e}){let t=Array.isArray(e)&&e.length>0?e:[`#135bd8`,`#ef334b`,`#ffbd2e`],n=t[0],r=t[1]||t[0],i=t[2]||t[0];return(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,borderRadius:`50%`,flexShrink:0,background:`
423
423
  radial-gradient(circle at 18% 50%, ${n} 0%, ${n}99 35%, transparent 65%),
424
424
  radial-gradient(circle at 82% 50%, ${r} 0%, ${r}99 35%, transparent 65%),
425
425
  radial-gradient(circle at 50% 82%, ${i} 0%, ${i}99 30%, transparent 58%),
426
426
  white
427
- `.replace(/\s+/g,` `).trim()}})}var fv=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function pv({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:C,selectedFile:w,onFileSelect:T,onRemoveSelectedFile:E,attachmentError:ee,isUploadingAttachment:D,requiresEmail:te,emailInput:ne,setEmailInput:ie,emailError:ae,emailCaptureSuccess:k,replyContext:oe,setReplyContext:se,webRTCError:ce,micError:le,setMicError:ue,dismissCallError:de,activeCallId:fe,isCallMuted:A,toggleCallMute:pe,endWebRTCCall:j,formatCallDuration:me,callDurationSeconds:he,isCallMinimized:M,onExpand:N,onCollapse:ge,onStartVoice:_e,voiceEnabled:ve,headerBgColor:ye,onNewChat:P,showPoweredBy:F,privacyPolicyUrl:be,getVisitorChatHistory:I,resumeChat:xe,currentChatId:Se,isSessionRestoring:Ce,isClosing:L}){let we=c.length>0,Te=x||S||b,Ee=!!fe,[De,Oe]=(0,d.useState)(!1),{resolvedConfig:ke}=gn(),Ae=ke?.siteId||null,[R,je]=(0,d.useState)(()=>re(Ae)===`auto`),Me=()=>{let e=R?`ask`:`auto`;O(Ae,e),je(e===`auto`)},[Ne,Pe]=(0,d.useState)(!1),[Fe,Ie]=(0,d.useState)([]),[Le,Re]=(0,d.useState)(!1),ze=(0,d.useRef)(null),[z,Be]=(0,d.useState)(()=>typeof window<`u`?window.visualViewport?.height??window.innerHeight:600),[B,Ve]=(0,d.useState)(0);(0,d.useEffect)(()=>{if(!s)return;let e=window.visualViewport;if(!e)return;let t=()=>{Be(e.height),Ve(Math.max(0,window.innerHeight-e.offsetTop-e.height))};return e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}},[s]);let He=s&&window.innerHeight-z>150,Ue=async()=>{Oe(!1),Pe(!0),Re(!0);try{let e=await I();e?.data&&Ie(e.data)}catch(e){console.error(e)}finally{Re(!1)}},We=async e=>{Pe(!1),e.chatId!==Se&&xe?.(e.chatId)};return(0,d.useEffect)(()=>{if(!De)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ze.current&&!ze.current.contains(t)&&Oe(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[De]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`0`,right:`0`,bottom:`${B}px`,height:z>0?`${Math.round(z*(He?1:.92))}px`:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:L?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:L?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:ye||`transparent`,flexShrink:0,position:`relative`,zIndex:30},children:[(0,f.jsx)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,f.jsx)(`button`,{onClick:ge,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})})}),(()=>{let t=!!i,n=!!e.hasCustomTitle,r=t||n,a=t||!r,o=n||!r,c=a&&o;return(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:c?`minmax(72px, 40%) minmax(0, 60%)`:`1fr`,columnGap:c?`12px`:0,alignItems:`center`,justifyItems:c?`stretch`:`center`},children:[a&&(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(iv,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(av,{title:e.chatTitle})})}),o&&(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:c?`flex-start`:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]})})(),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:ze,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>Oe(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),De&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[ve&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),_e?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}})]}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),P?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,f.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new chat`]}),I&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:Ue,style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M12 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),Ae&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:Me,style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`8px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`span`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,minWidth:0,overflow:`hidden`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,f.jsx)(`polygon`,{points:`3 11 22 2 13 21 11 13 3 11`})}),(0,f.jsx)(`span`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:`Auto-navigate`})]}),(0,f.jsx)(`span`,{"aria-hidden":!0,style:{width:`34px`,height:`19px`,borderRadius:`999px`,background:R?`#22c55e`:`rgba(255,255,255,0.2)`,position:`relative`,flexShrink:0,transition:`background 0.15s ease`},children:(0,f.jsx)(`span`,{style:{position:`absolute`,top:`2px`,left:R?`17px`:`2px`,width:`15px`,height:`15px`,borderRadius:`50%`,background:`white`,transition:`left 0.15s ease`}})})]})]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),ge?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,f.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,f.jsx)(l_,{webRTCError:ce,micError:le,setMicError:ue,dismissCallError:de,isRateLimited:S,rateLimitMessage:C}),M&&(0,f.jsx)(E_,{agentName:m,agentHeadshot:h,fallbackAgentName:g,callDurationSeconds:he,isCallMuted:A,formatCallDuration:me,toggleCallMute:pe,endWebRTCCall:j,onExpand:N,primaryColor:n}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Ne?(0,f.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:(0,f.jsxs)(`button`,{onClick:()=>Pe(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,f.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,f.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Le?(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):Fe.length>0?(0,f.jsx)(`div`,{children:Fe.map(e=>(0,f.jsxs)(`div`,{onClick:()=>We(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500,display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,f.jsxs)(`span`,{children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),e.chatId===Se&&(0,f.jsx)(`span`,{style:{fontSize:`11px`,fontWeight:600,color:n,background:`${n}1a`,borderRadius:`999px`,padding:`2px 8px`},children:`Current`})]}),(0,f.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,we?(0,f.jsx)(o_,{chatHistory:c,isAiTyping:l,isLoading:x,isAgentTyping:u,setReplyContext:se,TypingDots:fv,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(dv,{orbColors:t})}):Ce?(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,f.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,f.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,f.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(sv,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})]}),k&&(0,f.jsxs)(`div`,{style:{margin:`0 16px 8px`,padding:`9px 14px`,borderRadius:`12px`,background:`#ecfdf5`,border:`1px solid #6ee7b7`,display:`flex`,alignItems:`center`,gap:`8px`,animation:`fe-orb-fade-in 0.2s ease`,flexShrink:0},children:[(0,f.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#10b981`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,f.jsx)(`polyline`,{points:`20 6 9 17 4 12`})}),(0,f.jsx)(`span`,{style:{fontSize:`13px`,fontWeight:500,color:`#065f46`},children:`Email saved — we'll be in touch!`})]}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:te?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(c_,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Ee,handleToggleVoice:_e,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Te,replyContext:oe,clearReplyContext:()=>se(null),onFileSelect:T,selectedFile:w,onRemoveSelectedFile:E,attachmentError:ee,isUploadingAttachment:D,requiresEmail:te,emailInput:ne,setEmailInput:ie,emailError:ae,inputPlaceholder:e.inputPlaceholder})}),!He&&(0,f.jsxs)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`8px 20px`,paddingBottom:`max(12px, env(safe-area-inset-bottom, 12px))`,pointerEvents:`none`},children:[be&&(0,f.jsxs)(`p`,{style:{margin:`0 0 4px`,fontSize:`10px`,color:`#9ca3af`,lineHeight:1.4,userSelect:`none`,pointerEvents:`auto`},children:[`This conversation is recorded for quality assurance purposes.`,` `,(0,f.jsx)(`a`,{href:be,target:`_blank`,rel:`noopener noreferrer`,style:{color:`#6b7280`,textDecoration:`underline`},children:`See our privacy policy`})]}),F&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})]})]})}function mv(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:C,language:w,chatId:T,historyRef:E,onMessageSync:te,beaconSyncVoiceTranscript:ne,sendMessage:re,uploadChatFile:O,openWidget:ie,captureVisitorEmail:ae,setVoiceMode:k,endConversation:oe,startNewChat:se,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,dismissCallError:fe,startTyping:A,stopTyping:pe,updateTypingDraft:j,getVisitorChatHistory:me,resumeChat:he,isSessionRestoring:M,openToChatCounter:N,voiceEndCounter:ge}=gn();(0,d.useEffect)(()=>{try{tr()}catch{}},[]),(0,d.useEffect)(()=>{N&&V!==`voice_mode`&&V!==`text_chat`&&V!==`call_screen`&&(k?.(!1),H(`text_chat`))},[N]);let _e=t?.widgetSettings||{},P=n?.widgetSettings||{},F={..._e.branding||{},...P.branding||{}},I={..._e.theme||{},...P.theme||{}},xe={..._e.features||{},...P.features||{}},Ce=xe.voice!==!1,L=Array.isArray(I.orbColors)&&I.orbColors.length>0?I.orbColors:null,we=I.buttonColor||I.primaryColor||L?.[0]||`#3B82F6`,Te={small:50,medium:64,large:80},Ee=Te[I.orbSize]||Te.small,De=I.position||`bottom-right`,Oe=F.fallbackAgentName||`Agent`,ke=tv(L??I.chatBgColors),Ae=F.logo||F.logoUrl||null,R=w||`en`,je=_e.recommendations?.[R]||[],Me=(P.recommendations?.[R]??je).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Ne=Array.isArray(F.quickChatOptions)&&F.quickChatOptions.length>0?F.quickChatOptions:Me,Pe=F.hideWatermark===!0?!1:F.showPoweredBy!==!1,Fe=F.headerBgColor||null,Ie=I.bottomPosition==null?`1.5rem`:`${I.bottomPosition}px`,Le=F.privacyPolicyUrl||null,Re=F.chatbotEnabled!==!1&&I.chatbotEnabled!==!1,[ze,z]=(0,d.useState)(()=>typeof window<`u`?window.location.pathname:`/`);(0,d.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>z(window.location.pathname),t=window.history.pushState.bind(window.history);return window.history.pushState=(...n)=>{t(...n),setTimeout(e,50)},window.addEventListener(`popstate`,e),()=>{window.history.pushState=t,window.removeEventListener(`popstate`,e)}},[]);let Be=(()=>{let e={..._e.pageVisibility||{},...P.pageVisibility||{}};return Array.isArray(e.allowedPaths)?e.allowedPaths.filter(Boolean):[]})(),B=Be.length===0||Be.some(e=>e===`*`||e===`/*`?!0:e.endsWith(`/*`)?ze.startsWith(e.slice(0,-1)):ze.replace(/\/$/,``)===e.replace(/\/$/,``)),Ve=_e.greetings?.[w]||P.greetings?.[w]||F.introGreeting||(t?.websiteName&&String(t.websiteName).trim()?`Hello, I'm here to help you know more about ${String(t.websiteName).trim()}.`:`Hello, I'm here to help — what would you like to know?`),He={entryPrompt:F.entryPrompt||`Do you want to explore in a new way?`,yesLabel:F.yesLabel||`Yes`,laterLabel:F.laterLabel||`Later`,connectionTitle:F.connectionTitle||`How would you like to connect?`,connectionSubtitle:F.connectionSubtitle||``,voiceLabel:F.voiceLabel||`Voice`,textLabel:F.textLabel||`Text`,chatTitle:F.headerName||`Chat with FlowEngage`,hasCustomTitle:!!(F.headerName&&String(F.headerName).trim()),introGreeting:Ve,inputPlaceholder:F.inputPlaceholder||`Type your message`,analysingLabel:F.analysingLabel||`analysing...`},Ue=P.elevenLabsAgentId||t?.elevenLabsAgentId||null,We=t?.siteId||n?.siteId||null,Ge=t?.apiBaseUrl||``;(0,d.useEffect)(()=>{Vn(t?.siteType||null)},[t?.siteType]);let Ke=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),qe=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Je=r.some(e=>e.sender===`user`),Ye=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),Xe=!!(P._dashboardLivePreview||_e._dashboardLivePreview),[V,H]=(0,d.useState)(()=>Xe?`text_chat`:`entry_prompt`),[U,W]=(0,d.useState)(``),[Ze,Qe]=(0,d.useState)(null),[$e,et]=(0,d.useState)(l||``),[tt,nt]=(0,d.useState)(``),[rt,it]=(0,d.useState)(!1),[at,ot]=(0,d.useState)(0),[st,ct]=(0,d.useState)(null),[G,lt]=(0,d.useState)(null),[ut,dt]=(0,d.useState)(``),[ft,pt]=(0,d.useState)(!1),[mt,ht]=(0,d.useState)(!1),[gt,_t]=(0,d.useState)(!1),vt=(0,d.useRef)(null),yt=(0,d.useRef)(!1),bt=!l&&Je&&Ye&&V!==`voice_mode`;(0,d.useLayoutEffect)(()=>{if(e!==`ready`||yt.current)return;if(yt.current=!0,!Ce){H(`minimized_orb`);return}let t=!1;try{t=Tr().shouldResumeVoice}catch{}let n=be(),r=We?ve(We):null,i=n||!!r?.transcript;if(t){ie?.({notifyChatInitiated:!0}),k?.(!0),H(`voice_mode`);return}if(Se()){ie?.({notifyChatInitiated:!1}),H(`text_chat`);return}if(i){if((typeof performance<`u`?performance.getEntriesByType?.(`navigation`)?.[0]?.type??`navigate`:`navigate`)===`reload`){H(`minimized_orb`);return}ie?.({notifyChatInitiated:!0}),k?.(!0),H(`voice_mode`);return}if(We)try{ye(We)}catch{}if(ee(We)){H(`minimized_orb`);return}},[e,r]);let[xt,St]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>St(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{et(l||``),l&&nt(``)},[l]);let Ct=(0,d.useCallback)(()=>{lt(null),dt(``)},[]),wt=(0,d.useCallback)(e=>{let t=e_(e);if(t){lt(null),dt(t);return}lt(e),dt(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){ot(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||ot(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]);let Tt=(0,d.useCallback)(()=>{H(`call_screen`),ht(!1)},[]),Et=(0,d.useCallback)(()=>{H(`text_chat`),ht(!0)},[]);(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){vt.current=null;return}if(v?.callId||b===`connecting`||b===`connected`){if(V===`minimized_orb`&&mt&&y&&!v?.callId){vt.current=e;return}!(!i||V===`minimized_orb`||V===`voice_mode`)&&vt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:V,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),vt.current=e,V===`voice_mode`&&k?.(!1),ie?.(),Tt())}},[y,b,Tt,v?.callId,i,ie,k,V]),(0,d.useEffect)(()=>{!v&&!y&&V===`call_screen`&&H(`text_chat`)},[v,y,V]),(0,d.useEffect)(()=>{!y&&mt&&ht(!1)},[y,mt]),(0,d.useEffect)(()=>{if(!o||_){j?.(``),pe?.();return}if(!U.trim()||G){j?.(``);let e=window.setTimeout(()=>pe?.(),100);return()=>window.clearTimeout(e)}A?.();let e=window.setTimeout(()=>j?.(U),120),t=window.setTimeout(()=>pe?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[U,G,o,_,A,pe,j]);let Dt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,Ot=async e=>{if(e.preventDefault(),_)return;if(bt){let e=$e.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){nt(`Please enter a valid email so we can continue helping you.`);return}await ae(e),nt(``),it(!0),setTimeout(()=>it(!1),3e3);return}let t=Dt(Ze);if(!U.trim()&&!G)return;if(G){try{pt(!0),dt(``);let e=await O(G),n=e?.data||e,r=U.trim()||`Shared file: ${n_(G)}`;W(``),Qe(null),Ct(),await re(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||G.name,fileType:n?.fileType||G.type,fileSize:n?.fileSize||G.size}})}catch(e){dt(e?.message||`Failed to upload the selected file.`)}finally{pt(!1)}return}let n=U.trim();W(``),Qe(null),await re(n,``,t)},kt=(0,d.useCallback)(()=>{r.length!==0&&se?.()},[r.length,se]),At=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},jt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await re(t.trim(),``)},[_,m,re]),Mt=xt&&V===`entry_prompt`?{inset:0}:xt&&V===`text_chat`?{left:0,right:0,bottom:0}:xt&&V===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:xt&&V===`connection_modal`?{left:`12px`,right:`12px`,bottom:`12px`}:V===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...De===`bottom-left`?{left:`1.5rem`,bottom:Ie}:{right:`1.5rem`,bottom:Ie}}:De===`bottom-left`?{left:`1.5rem`,bottom:Ie}:{right:`1.5rem`,bottom:Ie},Nt=(0,d.useCallback)(()=>{V!==`minimized_orb`&&(_t(!0),setTimeout(()=>{H(`minimized_orb`),_t(!1),y&&ht(!0)},280))},[y,V]),Pt=()=>H(`connection_modal`),Ft=()=>{try{let e=window.AudioContext||window.webkitAudioContext;if(e){let t=new e;t.resume().catch(()=>{}),setTimeout(()=>t.close().catch(()=>{}),3e3)}}catch{}ie({notifyChatInitiated:!0}),k?.(!0),H(`voice_mode`)},It=()=>{ie({notifyChatInitiated:!0}),k?.(!1),H(`text_chat`)},Lt=()=>{k?.(!1),Nt()};return e!==`ready`||!Re||xe.chat===!1||!B?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Mt},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[V===`entry_prompt`&&(0,f.jsx)(cv,{copy:He,orbColors:L,primaryColor:we,onYes:()=>{D(We),Ft()},onLater:()=>{D(We),Nt()},isMobile:xt,isClosing:gt}),V===`minimized_orb`&&(0,f.jsxs)(lh.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:De===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[y&&(0,f.jsxs)(`button`,{type:`button`,onClick:Tt,style:{maxWidth:xt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,f.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,f.jsxs)(`span`,{style:{minWidth:0},children:[(0,f.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:b===`connected`?`Call in progress`:`Call is active`}),(0,f.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:b===`connected`?`${At(at)} with ${Ke}`:`Tap to return to ${Ke}`})]})]}),(0,f.jsx)(sv,{size:Ee,orbColors:L,onClick:y?Tt:Ce?Pt:It})]}),V===`connection_modal`&&(0,f.jsx)(lv,{copy:He,orbColors:L,primaryColor:we,onVoice:Ft,onText:It,onClose:Nt,isMobile:xt,isClosing:gt}),V===`voice_mode`&&(0,f.jsx)(uv,{orbColors:L,onEnterChat:It,onEndChat:Lt,agentId:Ue,siteId:We,apiBaseUrl:Ge,chatId:T,historyRef:E,onMessageSync:te,beaconSyncVoiceTranscript:ne,widgetPosition:De,voiceEndCounter:ge,websiteName:t?.websiteName,voiceFirstMessage:_e.voiceFirstMessage||null,captureVisitorEmail:ae,emailRequired:!l,emailCaptureEnabled:xe.emailCapture!==!1&&F.disableEmailCapture!==!0,listeningLabel:F.voiceListeningLabel||`Listening...`,thinkingLabel:F.voiceThinkingLabel||`Thinking...`,enterChatModeLabel:F.voiceEnterChatLabel||`Enter Chat Mode`,endConversationLabel:F.voiceEndConversationLabel||`End Conversation`},`voice`),V===`call_screen`&&(0,f.jsx)(T_,{incomingCall:v,activeCallId:y,callConnectionState:b,callDurationSeconds:at,isCallMuted:S,agentName:Ke,agentHeadshot:qe,fallbackAgentName:Oe,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,formatCallDuration:At,onMinimize:Et,primaryColor:we,orbColors:L,chatHistory:r}),V===`text_chat`&&(0,f.jsx)(pv,{isClosing:gt,copy:He,orbColors:L,primaryColor:we,chatBgGradient:ke,logo:Ae,quickChatOptions:Ne,onQuickChatSelect:jt,isMobile:xt,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:Ke,agentHeadshot:qe,fallbackAgentName:Oe,input:U,setInput:W,onSubmit:Ot,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:G,onFileSelect:wt,onRemoveSelectedFile:Ct,attachmentError:ut,isUploadingAttachment:ft,requiresEmail:bt,emailInput:$e,setEmailInput:et,emailError:tt,emailCaptureSuccess:rt,replyContext:Ze,setReplyContext:Qe,webRTCError:C,micError:st,setMicError:ct,dismissCallError:fe,activeCallId:y,isCallMuted:S,toggleCallMute:de,endWebRTCCall:ue,formatCallDuration:At,callDurationSeconds:at,onCollapse:Nt,onStartVoice:Ft,voiceEnabled:Ce,onNewChat:kt,onMinimize:Et,onExpand:Tt,isCallMinimized:!!y,showPoweredBy:Pe,privacyPolicyUrl:Le,headerBgColor:Fe,getVisitorChatHistory:me,resumeChat:he,currentChatId:T,isSessionRestoring:M}),(0,f.jsx)(`style`,{children:`
427
+ `.replace(/\s+/g,` `).trim()}})}var pv=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function mv({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:C,selectedFile:w,onFileSelect:T,onRemoveSelectedFile:E,attachmentError:ee,isUploadingAttachment:D,requiresEmail:te,emailInput:ne,setEmailInput:ie,emailError:ae,emailCaptureSuccess:k,replyContext:oe,setReplyContext:se,webRTCError:ce,micError:le,setMicError:ue,dismissCallError:de,activeCallId:fe,isCallMuted:A,toggleCallMute:pe,endWebRTCCall:j,formatCallDuration:me,callDurationSeconds:he,isCallMinimized:M,onExpand:N,onCollapse:ge,onStartVoice:_e,voiceEnabled:ve,headerBgColor:ye,onNewChat:P,showPoweredBy:F,privacyPolicyUrl:be,getVisitorChatHistory:I,resumeChat:xe,currentChatId:Se,isSessionRestoring:Ce,isClosing:L}){let we=c.length>0,Te=x||S||b,Ee=!!fe,[De,Oe]=(0,d.useState)(!1),{resolvedConfig:ke}=gn(),Ae=ke?.siteId||null,[R,je]=(0,d.useState)(()=>re(Ae)===`auto`),Me=()=>{let e=R?`ask`:`auto`;O(Ae,e),je(e===`auto`)},[Ne,Pe]=(0,d.useState)(!1),[Fe,Ie]=(0,d.useState)([]),[Le,Re]=(0,d.useState)(!1),ze=(0,d.useRef)(null),[z,Be]=(0,d.useState)(()=>typeof window<`u`?window.visualViewport?.height??window.innerHeight:600),[B,Ve]=(0,d.useState)(0);(0,d.useEffect)(()=>{if(!s)return;let e=window.visualViewport;if(!e)return;let t=()=>{Be(e.height),Ve(Math.max(0,window.innerHeight-e.offsetTop-e.height))};return e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}},[s]);let He=s&&window.innerHeight-z>150,Ue=async()=>{Oe(!1),Pe(!0),Re(!0);try{let e=await I();e?.data&&Ie(e.data)}catch(e){console.error(e)}finally{Re(!1)}},We=async e=>{Pe(!1),e.chatId!==Se&&xe?.(e.chatId)};return(0,d.useEffect)(()=>{if(!De)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ze.current&&!ze.current.contains(t)&&Oe(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[De]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`0`,right:`0`,bottom:`${B}px`,height:z>0?`${Math.round(z*(He?1:.92))}px`:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:L?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:L?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:ye||`transparent`,flexShrink:0,position:`relative`,zIndex:30},children:[(0,f.jsx)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,f.jsx)(`button`,{onClick:ge,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})})}),(()=>{let t=!!i,n=!!e.hasCustomTitle,r=t||n,a=t||!r,o=n||!r,c=a&&o;return(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:c?`minmax(72px, 40%) minmax(0, 60%)`:`1fr`,columnGap:c?`12px`:0,alignItems:`center`,justifyItems:c?`stretch`:`center`},children:[a&&(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(av,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(ov,{title:e.chatTitle})})}),o&&(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:c?`flex-start`:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]})})(),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:ze,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>Oe(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),De&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[ve&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),_e?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}})]}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),P?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,f.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new chat`]}),I&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:Ue,style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M12 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),Ae&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:Me,style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`8px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`span`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,minWidth:0,overflow:`hidden`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,f.jsx)(`polygon`,{points:`3 11 22 2 13 21 11 13 3 11`})}),(0,f.jsx)(`span`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:`Auto-navigate`})]}),(0,f.jsx)(`span`,{"aria-hidden":!0,style:{width:`34px`,height:`19px`,borderRadius:`999px`,background:R?`#22c55e`:`rgba(255,255,255,0.2)`,position:`relative`,flexShrink:0,transition:`background 0.15s ease`},children:(0,f.jsx)(`span`,{style:{position:`absolute`,top:`2px`,left:R?`17px`:`2px`,width:`15px`,height:`15px`,borderRadius:`50%`,background:`white`,transition:`left 0.15s ease`}})})]})]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),ge?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,f.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,f.jsx)(u_,{webRTCError:ce,micError:le,setMicError:ue,dismissCallError:de,isRateLimited:S,rateLimitMessage:C}),M&&(0,f.jsx)(D_,{agentName:m,agentHeadshot:h,fallbackAgentName:g,callDurationSeconds:he,isCallMuted:A,formatCallDuration:me,toggleCallMute:pe,endWebRTCCall:j,onExpand:N,primaryColor:n}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Ne?(0,f.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:(0,f.jsxs)(`button`,{onClick:()=>Pe(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,f.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,f.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Le?(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):Fe.length>0?(0,f.jsx)(`div`,{children:Fe.map(e=>(0,f.jsxs)(`div`,{onClick:()=>We(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500,display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,f.jsxs)(`span`,{children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),e.chatId===Se&&(0,f.jsx)(`span`,{style:{fontSize:`11px`,fontWeight:600,color:n,background:`${n}1a`,borderRadius:`999px`,padding:`2px 8px`},children:`Current`})]}),(0,f.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,we?(0,f.jsx)(s_,{chatHistory:c,isAiTyping:l,isLoading:x,isAgentTyping:u,setReplyContext:se,TypingDots:pv,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(fv,{orbColors:t})}):Ce?(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,f.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,f.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,f.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(cv,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})]}),k&&(0,f.jsxs)(`div`,{style:{margin:`0 16px 8px`,padding:`9px 14px`,borderRadius:`12px`,background:`#ecfdf5`,border:`1px solid #6ee7b7`,display:`flex`,alignItems:`center`,gap:`8px`,animation:`fe-orb-fade-in 0.2s ease`,flexShrink:0},children:[(0,f.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#10b981`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,f.jsx)(`polyline`,{points:`20 6 9 17 4 12`})}),(0,f.jsx)(`span`,{style:{fontSize:`13px`,fontWeight:500,color:`#065f46`},children:`Email saved — we'll be in touch!`})]}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:te?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(l_,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Ee,handleToggleVoice:_e,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Te,replyContext:oe,clearReplyContext:()=>se(null),onFileSelect:T,selectedFile:w,onRemoveSelectedFile:E,attachmentError:ee,isUploadingAttachment:D,requiresEmail:te,emailInput:ne,setEmailInput:ie,emailError:ae,inputPlaceholder:e.inputPlaceholder})}),!He&&(0,f.jsxs)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`8px 20px`,paddingBottom:`max(12px, env(safe-area-inset-bottom, 12px))`,pointerEvents:`none`},children:[be&&(0,f.jsxs)(`p`,{style:{margin:`0 0 4px`,fontSize:`10px`,color:`#9ca3af`,lineHeight:1.4,userSelect:`none`,pointerEvents:`auto`},children:[`This conversation is recorded for quality assurance purposes.`,` `,(0,f.jsx)(`a`,{href:be,target:`_blank`,rel:`noopener noreferrer`,style:{color:`#6b7280`,textDecoration:`underline`},children:`See our privacy policy`})]}),F&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})]})]})}function hv(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:C,language:w,chatId:T,historyRef:E,onMessageSync:te,beaconSyncVoiceTranscript:ne,sendMessage:re,uploadChatFile:O,openWidget:ie,captureVisitorEmail:ae,setVoiceMode:k,endConversation:oe,startNewChat:se,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,dismissCallError:fe,startTyping:A,stopTyping:pe,updateTypingDraft:j,getVisitorChatHistory:me,resumeChat:he,isSessionRestoring:M,openToChatCounter:N,voiceEndCounter:ge}=gn();(0,d.useEffect)(()=>{try{tr()}catch{}},[]),(0,d.useEffect)(()=>{N&&V!==`voice_mode`&&V!==`text_chat`&&V!==`call_screen`&&(k?.(!1),H(`text_chat`))},[N]);let _e=t?.widgetSettings||{},P=n?.widgetSettings||{},F={..._e.branding||{},...P.branding||{}},I={..._e.theme||{},...P.theme||{}},xe={..._e.features||{},...P.features||{}},Ce=xe.voice!==!1,L=Array.isArray(I.orbColors)&&I.orbColors.length>0?I.orbColors:null,we=I.buttonColor||I.primaryColor||L?.[0]||`#3B82F6`,Te={small:50,medium:64,large:80},Ee=Te[I.orbSize]||Te.small,De=I.position||`bottom-right`,Oe=F.fallbackAgentName||`Agent`,ke=nv(L??I.chatBgColors),Ae=F.logo||F.logoUrl||null,R=w||`en`,je=_e.recommendations?.[R]||[],Me=(P.recommendations?.[R]??je).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Ne=Array.isArray(F.quickChatOptions)&&F.quickChatOptions.length>0?F.quickChatOptions:Me,Pe=F.hideWatermark===!0?!1:F.showPoweredBy!==!1,Fe=F.headerBgColor||null,Ie=I.bottomPosition==null?`1.5rem`:`${I.bottomPosition}px`,Le=F.privacyPolicyUrl||null,Re=F.chatbotEnabled!==!1&&I.chatbotEnabled!==!1,[ze,z]=(0,d.useState)(()=>typeof window<`u`?window.location.pathname:`/`);(0,d.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>z(window.location.pathname),t=window.history.pushState.bind(window.history);return window.history.pushState=(...n)=>{t(...n),setTimeout(e,50)},window.addEventListener(`popstate`,e),()=>{window.history.pushState=t,window.removeEventListener(`popstate`,e)}},[]);let Be=(()=>{let e={..._e.pageVisibility||{},...P.pageVisibility||{}};return Array.isArray(e.allowedPaths)?e.allowedPaths.filter(Boolean):[]})(),B=Be.length===0||Be.some(e=>e===`*`||e===`/*`?!0:e.endsWith(`/*`)?ze.startsWith(e.slice(0,-1)):ze.replace(/\/$/,``)===e.replace(/\/$/,``)),Ve=_e.greetings?.[w]||P.greetings?.[w]||F.introGreeting||(t?.websiteName&&String(t.websiteName).trim()?`Hello, I'm here to help you know more about ${String(t.websiteName).trim()}.`:`Hello, I'm here to help — what would you like to know?`),He={entryPrompt:F.entryPrompt||`Do you want to explore in a new way?`,yesLabel:F.yesLabel||`Yes`,laterLabel:F.laterLabel||`Later`,connectionTitle:F.connectionTitle||`How would you like to connect?`,connectionSubtitle:F.connectionSubtitle||``,voiceLabel:F.voiceLabel||`Voice`,textLabel:F.textLabel||`Text`,chatTitle:F.headerName||`Chat with FlowEngage`,hasCustomTitle:!!(F.headerName&&String(F.headerName).trim()),introGreeting:Ve,inputPlaceholder:F.inputPlaceholder||`Type your message`,analysingLabel:F.analysingLabel||`analysing...`},Ue=P.elevenLabsAgentId||t?.elevenLabsAgentId||null,We=t?.siteId||n?.siteId||null,Ge=t?.apiBaseUrl||``;(0,d.useEffect)(()=>{Vn(t?.siteType||null)},[t?.siteType]);let Ke=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),qe=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Je=r.some(e=>e.sender===`user`),Ye=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),Xe=!!(P._dashboardLivePreview||_e._dashboardLivePreview),[V,H]=(0,d.useState)(()=>Xe?`text_chat`:`entry_prompt`),[U,W]=(0,d.useState)(``),[Ze,Qe]=(0,d.useState)(null),[$e,et]=(0,d.useState)(l||``),[tt,nt]=(0,d.useState)(``),[rt,it]=(0,d.useState)(!1),[at,ot]=(0,d.useState)(0),[st,ct]=(0,d.useState)(null),[G,lt]=(0,d.useState)(null),[ut,dt]=(0,d.useState)(``),[ft,pt]=(0,d.useState)(!1),[mt,ht]=(0,d.useState)(!1),[gt,_t]=(0,d.useState)(!1),vt=(0,d.useRef)(null),yt=(0,d.useRef)(!1),bt=!l&&Je&&Ye&&V!==`voice_mode`;(0,d.useLayoutEffect)(()=>{if(e!==`ready`||yt.current)return;if(yt.current=!0,!Ce){H(`minimized_orb`);return}let t=!1;try{t=Er().shouldResumeVoice}catch{}let n=be(),r=We?ve(We):null,i=n||!!r?.transcript;if(t){ie?.({notifyChatInitiated:!0}),k?.(!0),H(`voice_mode`);return}if(Se()){ie?.({notifyChatInitiated:!1}),H(`text_chat`);return}if(i){if((typeof performance<`u`?performance.getEntriesByType?.(`navigation`)?.[0]?.type??`navigate`:`navigate`)===`reload`){H(`minimized_orb`);return}ie?.({notifyChatInitiated:!0}),k?.(!0),H(`voice_mode`);return}if(We)try{ye(We)}catch{}if(ee(We)){H(`minimized_orb`);return}},[e,r]);let[xt,St]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>St(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{et(l||``),l&&nt(``)},[l]);let Ct=(0,d.useCallback)(()=>{lt(null),dt(``)},[]),wt=(0,d.useCallback)(e=>{let t=t_(e);if(t){lt(null),dt(t);return}lt(e),dt(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){ot(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||ot(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]);let Tt=(0,d.useCallback)(()=>{H(`call_screen`),ht(!1)},[]),Et=(0,d.useCallback)(()=>{H(`text_chat`),ht(!0)},[]);(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){vt.current=null;return}if(v?.callId||b===`connecting`||b===`connected`){if(V===`minimized_orb`&&mt&&y&&!v?.callId){vt.current=e;return}!(!i||V===`minimized_orb`||V===`voice_mode`)&&vt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:V,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),vt.current=e,V===`voice_mode`&&k?.(!1),ie?.(),Tt())}},[y,b,Tt,v?.callId,i,ie,k,V]),(0,d.useEffect)(()=>{!v&&!y&&V===`call_screen`&&H(`text_chat`)},[v,y,V]),(0,d.useEffect)(()=>{!y&&mt&&ht(!1)},[y,mt]),(0,d.useEffect)(()=>{if(!o||_){j?.(``),pe?.();return}if(!U.trim()||G){j?.(``);let e=window.setTimeout(()=>pe?.(),100);return()=>window.clearTimeout(e)}A?.();let e=window.setTimeout(()=>j?.(U),120),t=window.setTimeout(()=>pe?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[U,G,o,_,A,pe,j]);let Dt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,Ot=async e=>{if(e.preventDefault(),_)return;if(bt){let e=$e.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){nt(`Please enter a valid email so we can continue helping you.`);return}await ae(e),nt(``),it(!0),setTimeout(()=>it(!1),3e3);return}let t=Dt(Ze);if(!U.trim()&&!G)return;if(G){try{pt(!0),dt(``);let e=await O(G),n=e?.data||e,r=U.trim()||`Shared file: ${r_(G)}`;W(``),Qe(null),Ct(),await re(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||G.name,fileType:n?.fileType||G.type,fileSize:n?.fileSize||G.size}})}catch(e){dt(e?.message||`Failed to upload the selected file.`)}finally{pt(!1)}return}let n=U.trim();W(``),Qe(null),await re(n,``,t)},kt=(0,d.useCallback)(()=>{r.length!==0&&se?.()},[r.length,se]),At=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},jt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await re(t.trim(),``)},[_,m,re]),Mt=xt&&V===`entry_prompt`?{inset:0}:xt&&V===`text_chat`?{left:0,right:0,bottom:0}:xt&&V===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:xt&&V===`connection_modal`?{left:`12px`,right:`12px`,bottom:`12px`}:V===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...De===`bottom-left`?{left:`1.5rem`,bottom:Ie}:{right:`1.5rem`,bottom:Ie}}:De===`bottom-left`?{left:`1.5rem`,bottom:Ie}:{right:`1.5rem`,bottom:Ie},Nt=(0,d.useCallback)(()=>{V!==`minimized_orb`&&(_t(!0),setTimeout(()=>{H(`minimized_orb`),_t(!1),y&&ht(!0)},280))},[y,V]),Pt=()=>H(`connection_modal`),Ft=()=>{try{let e=window.AudioContext||window.webkitAudioContext;if(e){let t=new e;t.resume().catch(()=>{}),setTimeout(()=>t.close().catch(()=>{}),3e3)}}catch{}ie({notifyChatInitiated:!0}),k?.(!0),H(`voice_mode`)},It=()=>{ie({notifyChatInitiated:!0}),k?.(!1),H(`text_chat`)},Lt=()=>{k?.(!1),Nt()};return e!==`ready`||!Re||xe.chat===!1||!B?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Mt},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[V===`entry_prompt`&&(0,f.jsx)(lv,{copy:He,orbColors:L,primaryColor:we,onYes:()=>{D(We),Ft()},onLater:()=>{D(We),Nt()},isMobile:xt,isClosing:gt}),V===`minimized_orb`&&(0,f.jsxs)(uh.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:De===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[y&&(0,f.jsxs)(`button`,{type:`button`,onClick:Tt,style:{maxWidth:xt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,f.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,f.jsxs)(`span`,{style:{minWidth:0},children:[(0,f.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:b===`connected`?`Call in progress`:`Call is active`}),(0,f.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:b===`connected`?`${At(at)} with ${Ke}`:`Tap to return to ${Ke}`})]})]}),(0,f.jsx)(cv,{size:Ee,orbColors:L,onClick:y?Tt:Ce?Pt:It})]}),V===`connection_modal`&&(0,f.jsx)(uv,{copy:He,orbColors:L,primaryColor:we,onVoice:Ft,onText:It,onClose:Nt,isMobile:xt,isClosing:gt}),V===`voice_mode`&&(0,f.jsx)(dv,{orbColors:L,onEnterChat:It,onEndChat:Lt,agentId:Ue,siteId:We,apiBaseUrl:Ge,chatId:T,historyRef:E,onMessageSync:te,beaconSyncVoiceTranscript:ne,widgetPosition:De,voiceEndCounter:ge,websiteName:t?.websiteName,voiceFirstMessage:_e.voiceFirstMessage||null,captureVisitorEmail:ae,emailRequired:!l,emailCaptureEnabled:xe.emailCapture!==!1&&F.disableEmailCapture!==!0,listeningLabel:F.voiceListeningLabel||`Listening...`,thinkingLabel:F.voiceThinkingLabel||`Thinking...`,enterChatModeLabel:F.voiceEnterChatLabel||`Enter Chat Mode`,endConversationLabel:F.voiceEndConversationLabel||`End Conversation`},`voice`),V===`call_screen`&&(0,f.jsx)(E_,{incomingCall:v,activeCallId:y,callConnectionState:b,callDurationSeconds:at,isCallMuted:S,agentName:Ke,agentHeadshot:qe,fallbackAgentName:Oe,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,formatCallDuration:At,onMinimize:Et,primaryColor:we,orbColors:L,chatHistory:r}),V===`text_chat`&&(0,f.jsx)(mv,{isClosing:gt,copy:He,orbColors:L,primaryColor:we,chatBgGradient:ke,logo:Ae,quickChatOptions:Ne,onQuickChatSelect:jt,isMobile:xt,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:Ke,agentHeadshot:qe,fallbackAgentName:Oe,input:U,setInput:W,onSubmit:Ot,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:G,onFileSelect:wt,onRemoveSelectedFile:Ct,attachmentError:ut,isUploadingAttachment:ft,requiresEmail:bt,emailInput:$e,setEmailInput:et,emailError:tt,emailCaptureSuccess:rt,replyContext:Ze,setReplyContext:Qe,webRTCError:C,micError:st,setMicError:ct,dismissCallError:fe,activeCallId:y,isCallMuted:S,toggleCallMute:de,endWebRTCCall:ue,formatCallDuration:At,callDurationSeconds:at,onCollapse:Nt,onStartVoice:Ft,voiceEnabled:Ce,onNewChat:kt,onMinimize:Et,onExpand:Tt,isCallMinimized:!!y,showPoweredBy:Pe,privacyPolicyUrl:Le,headerBgColor:Fe,getVisitorChatHistory:me,resumeChat:he,currentChatId:T,isSessionRestoring:M}),(0,f.jsx)(`style`,{children:`
428
428
  /* Force any SVG (or img) inside LogoSlot to fill the container height
429
429
  regardless of whether the component forwards its style prop. */
430
430
  .fe-logo-slot svg,
@@ -443,4 +443,4 @@
443
443
  @keyframes fe-orb-bar-3 { from{height:8px} to{height:20px} }
444
444
  @keyframes fe-orb-bar-4 { from{height:6px} to{height:16px} }
445
445
  @keyframes fe-dot-bounce { 0%,80%,100%{transform:translateY(0);opacity:.5} 40%{transform:translateY(-5px);opacity:1} }
446
- `})]})}var hv=class extends d.default.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`[FlowEngage] Widget crashed:`,e,t.componentStack)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}};exports.AnimatedOrb=v_,exports.ErrorBoundary=hv,exports.FlowEngageProvider=Si,exports.FlowEngageWidget=mv,exports.useFlowEngage=gn;
446
+ `})]})}var gv=class extends d.default.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`[FlowEngage] Widget crashed:`,e,t.componentStack)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}};exports.AnimatedOrb=y_,exports.ErrorBoundary=gv,exports.FlowEngageProvider=Ci,exports.FlowEngageWidget=hv,exports.useFlowEngage=gn;