@flowengage/react-chatbot 8.0.94 → 8.0.103
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,4 +1,7 @@
|
|
|
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}},te=e=>{if(!(!x||!e))try{let t=E(e);t&&window.localStorage.setItem(t,`1`)}catch{}},D=e=>e?`flowengage.persistedChatId.${e}`:null,ne=e=>{if(!x||!e)return null;try{let t=D(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},re=e=>{if(!(!x||!e))try{let t=D(e);t&&window.localStorage.removeItem(t)}catch{}},ie=(e,t)=>{if(!(!x||!e||!t))try{let n=D(e);n&&window.localStorage.setItem(n,String(t).trim())}catch{}},O=()=>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:``},k=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))}})},ae=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||``},oe=(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,se=()=>`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}},ce=e=>{if(!x||!e)return null;try{let t=j(e);if(t)return t;let n=se(),r=A(e);return r&&window.localStorage.setItem(r,n),n}catch{return se()}},M=`flowengage.tabId`,N=()=>{if(!x)return`default`;try{let e=window.sessionStorage.getItem(M);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(M,e)),e}catch{return`default`}},P=e=>e?`flowengage.voice.transcript.${e}.${N()}`:null,le=600*1e3,ue=(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:le,a={transcript:r,expiresAt:Date.now()+i};try{let t=P(e);t&&window.localStorage.setItem(t,JSON.stringify(a))}catch{}},de=e=>{if(!x||!e)return null;try{let t=P(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}},fe=e=>{if(!(!x||!e))try{let t=P(e);t&&window.localStorage.removeItem(t)}catch{}},pe=`flowengage.voice.pendingResume`,me=()=>{if(x)try{window.sessionStorage.setItem(pe,`1`)}catch{}},he=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(pe)===`1`?(window.sessionStorage.removeItem(pe),!0):!1}catch{return!1}},F=`flowengage.chat.pendingReopen`,ge=()=>{if(x)try{window.sessionStorage.setItem(F,`1`)}catch{}},_e=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(F)===`1`?(window.sessionStorage.removeItem(F),!0):!1}catch{return!1}},ve=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(pe)===`1`}catch{return!1}},ye=e=>e?`flowengage.voice.navState.${e}.${N()}`:null,I=(e,t,n,r)=>{if(!(!x||!e||!t))try{let i=ye(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{}},be=e=>{if(!x||!e)return null;try{let t=ye(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}},xe=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},Se=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}},Ce=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),xe(await Se(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)}))},we=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`;return(await xe(await Se(`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`,{method:`GET`}))).data},Te=({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={})=>xe(await Se(`${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 xe(await Se(`${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(e,t,n=`en`,r=``,i=null,o={}){return a(`/api/ai/chat`,{method:`POST`,body:JSON.stringify({session_id:e,user_query:t,lang:n,category:r,...o||{},...i||{}})})},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 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 xe(await Se(`${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)}}},L=Object.create(null);L.open=`0`,L.close=`1`,L.ping=`2`,L.pong=`3`,L.message=`4`,L.upgrade=`5`,L.noop=`6`;var Ee=Object.create(null);Object.keys(L).forEach(e=>{Ee[L[e]]=e});var De={type:`error`,data:`parser error`},Oe=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,ke=typeof ArrayBuffer==`function`,R=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Ae=({type:e,data:t},n,r)=>Oe&&t instanceof Blob?n?r(t):je(t,r):ke&&(t instanceof ArrayBuffer||R(t))?n?r(t):je(new Blob([t]),r):r(L[e]+(t||``)),je=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function Me(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Ne;function z(e,t){if(Oe&&e.data instanceof Blob)return e.data.arrayBuffer().then(Me).then(t);if(ke&&(e.data instanceof ArrayBuffer||R(e.data)))return t(Me(e.data));Ae(e,!1,e=>{Ne||=new TextEncoder,t(Ne.encode(e))})}var Pe=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Fe=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)Fe[Pe.charCodeAt(e)]=e;var Ie=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=Fe[e.charCodeAt(r)],o=Fe[e.charCodeAt(r+1)],s=Fe[e.charCodeAt(r+2)],c=Fe[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},Le=typeof ArrayBuffer==`function`,Re=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Be(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:ze(e.substring(1),t)}:Ee[n]?e.length>1?{type:Ee[n],data:e.substring(1)}:{type:Ee[n]}:De},ze=(e,t)=>Le?Be(Ie(e),t):{base64:!0,data:e},Be=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Ve=``,He=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{Ae(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Ve))})})},Ue=(e,t)=>{let n=e.split(Ve),r=[];for(let e=0;e<n.length;e++){let i=Re(n[e],t);if(r.push(i),i.type===`error`)break}return r};function We(){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 Ge;function Ke(e){return e.reduce((e,t)=>e+t.length,0)}function B(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 V(e,t){Ge||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(Ke(n)<1)break;let e=B(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(Ke(n)<2)break;let e=B(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(Ke(n)<8)break;let e=B(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(De);break}i=a*2**32+t.getUint32(4),r=3}else{if(Ke(n)<i)break;let e=B(n,i);s.enqueue(Re(a?e:Ge.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(De);break}}}})}function H(e){if(e)return qe(e)}function qe(e){for(var t in H.prototype)e[t]=H.prototype[t];return e}H.prototype.on=H.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},H.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},H.prototype.off=H.prototype.removeListener=H.prototype.removeAllListeners=H.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},H.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},H.prototype.emitReserved=H.prototype.emit,H.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},H.prototype.hasListeners=function(e){return!!this.listeners(e).length};var U=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),W=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Je=`arraybuffer`;function Ye(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Xe=W.setTimeout,Ze=W.clearTimeout;function Qe(e,t){t.useNativeTimers?(e.setTimeoutFn=Xe.bind(W),e.clearTimeoutFn=Ze.bind(W)):(e.setTimeoutFn=W.setTimeout.bind(W),e.clearTimeoutFn=W.clearTimeout.bind(W))}var $e=1.33;function et(e){return typeof e==`string`?tt(e):Math.ceil((e.byteLength||e.size)*$e)}function tt(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 nt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function rt(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function it(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 at=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},ot=class extends H{constructor(e){super(),this.writable=!1,Qe(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 at(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=Re(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=rt(e);return t.length?`?`+t:``}},st=class extends ot{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){Ue(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,He(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]=nt()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},ct=!1;try{ct=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var lt=ct;function ut(){}var dt=class extends st{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}},ft=class e extends H{constructor(e,t,n){super(),this.createRequest=e,Qe(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=Ye(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=ut,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(ft.requestsCount=0,ft.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,pt);else if(typeof addEventListener==`function`){let e=`onpagehide`in W?`pagehide`:`unload`;addEventListener(e,pt,!1)}}function pt(){for(let e in ft.requests)ft.requests.hasOwnProperty(e)&&ft.requests[e].abort()}var mt=(function(){let e=gt({xdomain:!1});return e&&e.responseType!==null})(),ht=class extends dt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=mt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new ft(gt,this.uri(),e)}};function gt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||lt))return new XMLHttpRequest}catch{}if(!t)try{return new W[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var _t=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,vt=class extends ot{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=_t?{}:Ye(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;Ae(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&U(()=>{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]=nt()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},yt=W.WebSocket||W.MozWebSocket,bt={websocket:class extends vt{createSocket(e,t,n){return _t?new yt(e,t,n):t?new yt(e,t):new yt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends ot{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=V(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=We();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&&U(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:ht},xt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,St=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function Ct(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=xt.exec(e||``),a={},o=14;for(;o--;)a[St[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=wt(a,a.path),a.queryKey=Tt(a,a.query),a}function wt(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 Tt(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var Et=typeof addEventListener==`function`&&typeof removeEventListener==`function`,Dt=[];Et&&addEventListener(`offline`,()=>{Dt.forEach(e=>e())},!1);var Ot=class e extends H{constructor(e,t){if(super(),this.binaryType=Je,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=Ct(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=Ct(t.host).host);Qe(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=it(this.opts.query)),Et&&(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`})},Dt.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+=et(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,U(()=>{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(),Et&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=Dt.indexOf(this._offlineEventListener);e!==-1&&Dt.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Ot.protocol=4;var kt=class extends Ot{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;Ot.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;Ot.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}},At=class extends kt{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=>bt[e]).filter(e=>!!e)),super(e,n)}};At.protocol;function jt(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=Ct(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 Mt=typeof ArrayBuffer==`function`,Nt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Pt=Object.prototype.toString,Ft=typeof Blob==`function`||typeof Blob<`u`&&Pt.call(Blob)===`[object BlobConstructor]`,It=typeof File==`function`||typeof File<`u`&&Pt.call(File)===`[object FileConstructor]`;function Lt(e){return Mt&&(e instanceof ArrayBuffer||Nt(e))||Ft&&e instanceof Blob||It&&e instanceof File}function Rt(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Rt(e[t]))return!0;return!1}if(Lt(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Rt(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Rt(e[t]))return!0;return!1}function zt(e){let t=[],n=e.data,r=e;return r.data=Bt(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Bt(e,t){if(!e)return e;if(Lt(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]=Bt(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]=Bt(e[r],t));return n}return e}function Vt(e,t){return e.data=Ht(e.data,t),delete e.attachments,e}function Ht(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]=Ht(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Ht(e[n],t));return e}var Ut=s({Decoder:()=>Kt,Encoder:()=>Gt,PacketType:()=>G,isPacketValid:()=>$t,protocol:()=>5}),Wt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],G;(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`})(G||={});var Gt=class{constructor(e){this.replacer=e}encode(e){return(e.type===G.EVENT||e.type===G.ACK)&&Rt(e)?this.encodeAsBinary({type:e.type===G.EVENT?G.BINARY_EVENT:G.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===G.BINARY_EVENT||e.type===G.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=zt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Kt=class e extends H{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===G.BINARY_EVENT;n||t.type===G.BINARY_ACK?(t.type=n?G.EVENT:G.ACK,this.reconstructor=new qt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(Lt(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(G[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===G.BINARY_EVENT||r.type===G.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(!Yt(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 G.CONNECT:return Zt(t);case G.DISCONNECT:return t===void 0;case G.CONNECT_ERROR:return typeof t==`string`||Zt(t);case G.EVENT:case G.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Wt.indexOf(t[0])===-1);case G.ACK:case G.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=Vt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Jt(e){return typeof e==`string`}var Yt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Xt(e){return e===void 0||Yt(e)}function Zt(e){return Object.prototype.toString.call(e)===`[object Object]`}function Qt(e,t){switch(e){case G.CONNECT:return t===void 0||Zt(t);case G.DISCONNECT:return t===void 0;case G.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Wt.indexOf(t[0])===-1);case G.ACK:return Array.isArray(t);case G.CONNECT_ERROR:return typeof t==`string`||Zt(t);default:return!1}}function $t(e){return Jt(e.nsp)&&Xt(e.id)&&Qt(e.type,e.data)}function en(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var tn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),nn=class extends H{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=[en(e,`open`,this.onopen.bind(this)),en(e,`packet`,this.onpacket.bind(this)),en(e,`error`,this.onerror.bind(this)),en(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(tn.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:G.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:G.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 G.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 G.EVENT:case G.BINARY_EVENT:this.onevent(e);break;case G.ACK:case G.BINARY_ACK:this.onack(e);break;case G.DISCONNECT:this.ondisconnect();break;case G.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:G.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:G.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 rn(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}rn.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},rn.prototype.reset=function(){this.attempts=0},rn.prototype.setMin=function(e){this.ms=e},rn.prototype.setMax=function(e){this.max=e},rn.prototype.setJitter=function(e){this.jitter=e};var an=class extends H{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,Qe(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 rn({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||Ut;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 At(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=en(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=en(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(en(e,`ping`,this.onping.bind(this)),en(e,`data`,this.ondata.bind(this)),en(e,`error`,this.onerror.bind(this)),en(e,`close`,this.onclose.bind(this)),en(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){U(()=>{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 nn(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)}},on={};function sn(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=jt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=on[i]&&a in on[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new an(r,t):(on[i]||(on[i]=new an(r,t)),c=on[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(sn,{Manager:an,Socket:nn,io:sn,connect:sn});var cn=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>sn(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),ln=({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)}}},un=(0,d.createContext)(null),dn=()=>{let e=(0,d.useContext)(un);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function fn(){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 pn=80;function mn(e){requestAnimationFrame(()=>{let t=e.getBoundingClientRect(),n=t.top+t.height/2,r=pn+(window.innerHeight-pn)/2,i=window.pageYOffset+n-r;window.scrollTo({top:Math.max(0,i),behavior:`smooth`})})}function hn(e){e&&(e.hasAttribute(`data-fe-highlighted`)||(gn(),e.classList?.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`),mn(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=`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.padding=`12px 16px`,e.style.transition=`all 0.4s ease`))}function gn(){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 _n=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function vn(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(_n)}catch{return!1}}function yn(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 K(...e){fn()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var bn=`fe_pending_nav_section`,xn=15e3,Sn=`fe_voice_nav_state`,Cn=2e4,wn=!1,Tn=null;function En(e=3e3){wn=!0,Tn&&clearTimeout(Tn),Tn=setTimeout(()=>{wn=!1,Tn=null},e)}function Dn(){return wn}var On=!1,kn=null;function An(){On||typeof window>`u`||(On=!0,window.addEventListener(`popstate`,async()=>{let e=window.location.href;if(K(`popstate: body-swap to`,e),kn){try{zn(kn)}catch{}try{Hn(kn)}catch{}}try{if(await rr(e,{skipPushState:!0,isBack:!0})){K(`popstate: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] popstate body-swap error:`,e)}K(`popstate: body-swap failed, falling back to reload`),window.location.reload()}))}var jn=!1;function Mn(){jn||typeof window>`u`||typeof document>`u`||(jn=!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(),K(`link-intercept: body-swap to`,r.href),Kn();try{try{zn()}catch{}try{Hn()}catch{}if(await rr(r.href)){K(`link-intercept: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] link-intercept body-swap error:`,e)}K(`link-intercept: body-swap failed, falling back to normal navigation`),qn(),window.location.href=r.href}},!0))}var Nn=null;function Pn(e){Nn=e===`spa`||e===`traditional`?e:null}function Fn(){if(typeof window>`u`||Nn===`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 Nn===`spa`?`backend-spa`:null}var In=`data-fe-swap-css`;function Ln(){typeof document>`u`||document.querySelectorAll(`[${In}]`).forEach(e=>e.remove())}var Rn=`fe_form_state:`;function zn(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=Rn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({state:n,ts:Date.now()}))}catch{}}function Bn(){if(typeof document>`u`||typeof sessionStorage>`u`)return;let e=Rn+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 Vn=`fe_scroll:`;function Hn(e){if(!(typeof window>`u`||typeof sessionStorage>`u`))try{let t=Vn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({y:window.scrollY,ts:Date.now()}))}catch{}}function Un(){if(typeof window>`u`||typeof sessionStorage>`u`)return;let e=Vn+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 Wn(e){if(!(typeof window>`u`))try{window.dispatchEvent(new CustomEvent(`flowengage:pageswap`,{detail:{url:e,timestamp:Date.now()}}))}catch{}}var Gn=`fe-nav-loader`;function Kn(){if(typeof document>`u`||document.getElementById(Gn))return;let e=document.createElement(`div`);e.id=Gn,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 qn(){if(typeof document>`u`)return;let e=document.getElementById(Gn);e&&(e.style.width=`100%`,setTimeout(()=>{e.style.opacity=`0`,e.style.transition=`opacity 0.3s ease`,setTimeout(()=>e.remove(),350)},200))}function Jn(){if(typeof window>`u`||typeof document>`u`)return;try{window.history.state?.flowengageSpa&&An()}catch{}let e;try{e=JSON.parse(sessionStorage.getItem(bn)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(bn)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>xn){K(`initNavigationHighlight: pending section expired, skipping:`,t);return}K(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=Xn(null,t);if(e){Zn(e),K(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):K(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var Yn=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
|
|
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||`http://localhost:5008`).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}},te=e=>{if(!(!x||!e))try{let t=E(e);t&&window.localStorage.setItem(t,`1`)}catch{}},D=e=>e?`flowengage.persistedChatId.${e}`:null,ne=e=>{if(!x||!e)return null;try{let t=D(e),n=t?window.localStorage.getItem(t):null;return n&&String(n).trim()?String(n).trim():null}catch{return null}},re=e=>{if(!(!x||!e))try{let t=D(e);t&&window.localStorage.removeItem(t)}catch{}},ie=(e,t)=>{if(!(!x||!e||!t))try{let n=D(e);n&&window.localStorage.setItem(n,String(t).trim())}catch{}},O=()=>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:``},k=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))}})},ae=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||``},oe=(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,se=()=>`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}},ce=e=>{if(!x||!e)return null;try{let t=j(e);if(t)return t;let n=se(),r=A(e);return r&&window.localStorage.setItem(r,n),n}catch{return se()}},M=`flowengage.tabId`,N=()=>{if(!x)return`default`;try{let e=window.sessionStorage.getItem(M);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(M,e)),e}catch{return`default`}},P=e=>e?`flowengage.voice.transcript.${e}.${N()}`:null,le=600*1e3,ue=(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:le,a={transcript:r,expiresAt:Date.now()+i};try{let t=P(e);t&&window.localStorage.setItem(t,JSON.stringify(a))}catch{}},de=e=>{if(!x||!e)return null;try{let t=P(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}},fe=e=>{if(!(!x||!e))try{let t=P(e);t&&window.localStorage.removeItem(t)}catch{}},pe=`flowengage.voice.pendingResume`,me=()=>{if(x)try{window.sessionStorage.setItem(pe,`1`)}catch{}},he=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(pe)===`1`?(window.sessionStorage.removeItem(pe),!0):!1}catch{return!1}},F=`flowengage.chat.pendingReopen`,ge=()=>{if(x)try{window.sessionStorage.setItem(F,`1`)}catch{}},_e=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(F)===`1`?(window.sessionStorage.removeItem(F),!0):!1}catch{return!1}},ve=()=>{if(!x)return!1;try{return window.sessionStorage.getItem(pe)===`1`}catch{return!1}},ye=e=>e?`flowengage.voice.navState.${e}.${N()}`:null,I=(e,t,n,r)=>{if(!(!x||!e||!t))try{let i=ye(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{}},be=e=>{if(!x||!e)return null;try{let t=ye(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}},xe=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},Se=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}},Ce=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),xe(await Se(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)}))},we=async({apiBaseUrl:e,siteId:t})=>{let n=typeof window<`u`?window.location.origin:`http://localhost`;return(await xe(await Se(`${e}/api/widget/chatbot-loader?${new URLSearchParams({siteId:t,origin:n}).toString()}`,{method:`GET`}))).data},Te=({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={})=>xe(await Se(`${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 xe(await Se(`${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 Se(`${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 xe(p);let m=p.body.getReader(),h=new TextDecoder,g=``,_=null,v=e=>{let t=e.split(`
|
|
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
|
+
|
|
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 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 xe(await Se(`${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)}}},L=Object.create(null);L.open=`0`,L.close=`1`,L.ping=`2`,L.pong=`3`,L.message=`4`,L.upgrade=`5`,L.noop=`6`;var Ee=Object.create(null);Object.keys(L).forEach(e=>{Ee[L[e]]=e});var De={type:`error`,data:`parser error`},Oe=typeof Blob==`function`||typeof Blob<`u`&&Object.prototype.toString.call(Blob)===`[object BlobConstructor]`,ke=typeof ArrayBuffer==`function`,R=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Ae=({type:e,data:t},n,r)=>Oe&&t instanceof Blob?n?r(t):je(t,r):ke&&(t instanceof ArrayBuffer||R(t))?n?r(t):je(new Blob([t]),r):r(L[e]+(t||``)),je=(e,t)=>{let n=new FileReader;return n.onload=function(){let e=n.result.split(`,`)[1];t(`b`+(e||``))},n.readAsDataURL(e)};function Me(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Ne;function z(e,t){if(Oe&&e.data instanceof Blob)return e.data.arrayBuffer().then(Me).then(t);if(ke&&(e.data instanceof ArrayBuffer||R(e.data)))return t(Me(e.data));Ae(e,!1,e=>{Ne||=new TextEncoder,t(Ne.encode(e))})}var Pe=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Fe=typeof Uint8Array>`u`?[]:new Uint8Array(256);for(let e=0;e<64;e++)Fe[Pe.charCodeAt(e)]=e;var Ie=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=Fe[e.charCodeAt(r)],o=Fe[e.charCodeAt(r+1)],s=Fe[e.charCodeAt(r+2)],c=Fe[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},Le=typeof ArrayBuffer==`function`,Re=(e,t)=>{if(typeof e!=`string`)return{type:`message`,data:Be(e,t)};let n=e.charAt(0);return n===`b`?{type:`message`,data:ze(e.substring(1),t)}:Ee[n]?e.length>1?{type:Ee[n],data:e.substring(1)}:{type:Ee[n]}:De},ze=(e,t)=>Le?Be(Ie(e),t):{base64:!0,data:e},Be=(e,t)=>{switch(t){case`blob`:return e instanceof Blob?e:new Blob([e]);default:return e instanceof ArrayBuffer?e:e.buffer}},Ve=``,He=(e,t)=>{let n=e.length,r=Array(n),i=0;e.forEach((e,a)=>{Ae(e,!1,e=>{r[a]=e,++i===n&&t(r.join(Ve))})})},Ue=(e,t)=>{let n=e.split(Ve),r=[];for(let e=0;e<n.length;e++){let i=Re(n[e],t);if(r.push(i),i.type===`error`)break}return r};function We(){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 Ge;function Ke(e){return e.reduce((e,t)=>e+t.length,0)}function B(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 V(e,t){Ge||=new TextDecoder;let n=[],r=0,i=-1,a=!1;return new TransformStream({transform(o,s){for(n.push(o);;){if(r===0){if(Ke(n)<1)break;let e=B(n,1);a=(e[0]&128)==128,i=e[0]&127,r=i<126?3:i===126?1:2}else if(r===1){if(Ke(n)<2)break;let e=B(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(r===2){if(Ke(n)<8)break;let e=B(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),a=t.getUint32(0);if(a>2**21-1){s.enqueue(De);break}i=a*2**32+t.getUint32(4),r=3}else{if(Ke(n)<i)break;let e=B(n,i);s.enqueue(Re(a?e:Ge.decode(e),t)),r=0}if(i===0||i>e){s.enqueue(De);break}}}})}function H(e){if(e)return qe(e)}function qe(e){for(var t in H.prototype)e[t]=H.prototype[t];return e}H.prototype.on=H.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[`$`+e]=this._callbacks[`$`+e]||[]).push(t),this},H.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},H.prototype.off=H.prototype.removeListener=H.prototype.removeAllListeners=H.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},H.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},H.prototype.emitReserved=H.prototype.emit,H.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[`$`+e]||[]},H.prototype.hasListeners=function(e){return!!this.listeners(e).length};var U=typeof Promise==`function`&&typeof Promise.resolve==`function`?e=>Promise.resolve().then(e):(e,t)=>t(e,0),W=typeof self<`u`?self:typeof window<`u`?window:Function(`return this`)(),Je=`arraybuffer`;function Ye(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}var Xe=W.setTimeout,Ze=W.clearTimeout;function Qe(e,t){t.useNativeTimers?(e.setTimeoutFn=Xe.bind(W),e.clearTimeoutFn=Ze.bind(W)):(e.setTimeoutFn=W.setTimeout.bind(W),e.clearTimeoutFn=W.clearTimeout.bind(W))}var $e=1.33;function et(e){return typeof e==`string`?tt(e):Math.ceil((e.byteLength||e.size)*$e)}function tt(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 nt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function rt(e){let t=``;for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+=`&`),t+=encodeURIComponent(n)+`=`+encodeURIComponent(e[n]));return t}function it(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 at=class extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type=`TransportError`}},ot=class extends H{constructor(e){super(),this.writable=!1,Qe(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 at(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=Re(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=rt(e);return t.length?`?`+t:``}},st=class extends ot{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){Ue(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,He(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]=nt()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},ct=!1;try{ct=typeof XMLHttpRequest<`u`&&`withCredentials`in new XMLHttpRequest}catch{}var lt=ct;function ut(){}var dt=class extends st{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}},ft=class e extends H{constructor(e,t,n){super(),this.createRequest=e,Qe(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=Ye(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=ut,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(ft.requestsCount=0,ft.requests={},typeof document<`u`){if(typeof attachEvent==`function`)attachEvent(`onunload`,pt);else if(typeof addEventListener==`function`){let e=`onpagehide`in W?`pagehide`:`unload`;addEventListener(e,pt,!1)}}function pt(){for(let e in ft.requests)ft.requests.hasOwnProperty(e)&&ft.requests[e].abort()}var mt=(function(){let e=gt({xdomain:!1});return e&&e.responseType!==null})(),ht=class extends dt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=mt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new ft(gt,this.uri(),e)}};function gt(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<`u`&&(!t||lt))return new XMLHttpRequest}catch{}if(!t)try{return new W[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}}var _t=typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`,vt=class extends ot{get name(){return`websocket`}doOpen(){let e=this.uri(),t=this.opts.protocols,n=_t?{}:Ye(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;Ae(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch{}r&&U(()=>{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]=nt()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},yt=W.WebSocket||W.MozWebSocket,bt={websocket:class extends vt{createSocket(e,t,n){return _t?new yt(e,t,n):t?new yt(e,t):new yt(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends ot{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=V(2**53-1,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=We();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&&U(()=>{this.writable=!0,this.emitReserved(`drain`)},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)==null||e.close()}},polling:ht},xt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,St=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];function Ct(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=xt.exec(e||``),a={},o=14;for(;o--;)a[St[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=wt(a,a.path),a.queryKey=Tt(a,a.query),a}function wt(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 Tt(e,t){let n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}var Et=typeof addEventListener==`function`&&typeof removeEventListener==`function`,Dt=[];Et&&addEventListener(`offline`,()=>{Dt.forEach(e=>e())},!1);var Ot=class e extends H{constructor(e,t){if(super(),this.binaryType=Je,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=Ct(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=Ct(t.host).host);Qe(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=it(this.opts.query)),Et&&(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`})},Dt.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+=et(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,U(()=>{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(),Et&&(this._beforeunloadEventListener&&removeEventListener(`beforeunload`,this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=Dt.indexOf(this._offlineEventListener);e!==-1&&Dt.splice(e,1)}this.readyState=`closed`,this.id=null,this.emitReserved(`close`,e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Ot.protocol=4;var kt=class extends Ot{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;Ot.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;Ot.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}},At=class extends kt{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=>bt[e]).filter(e=>!!e)),super(e,n)}};At.protocol;function jt(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=Ct(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 Mt=typeof ArrayBuffer==`function`,Nt=e=>typeof ArrayBuffer.isView==`function`?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Pt=Object.prototype.toString,Ft=typeof Blob==`function`||typeof Blob<`u`&&Pt.call(Blob)===`[object BlobConstructor]`,It=typeof File==`function`||typeof File<`u`&&Pt.call(File)===`[object FileConstructor]`;function Lt(e){return Mt&&(e instanceof ArrayBuffer||Nt(e))||Ft&&e instanceof Blob||It&&e instanceof File}function Rt(e,t){if(!e||typeof e!=`object`)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(Rt(e[t]))return!0;return!1}if(Lt(e))return!0;if(e.toJSON&&typeof e.toJSON==`function`&&arguments.length===1)return Rt(e.toJSON(),!0);for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Rt(e[t]))return!0;return!1}function zt(e){let t=[],n=e.data,r=e;return r.data=Bt(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Bt(e,t){if(!e)return e;if(Lt(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]=Bt(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]=Bt(e[r],t));return n}return e}function Vt(e,t){return e.data=Ht(e.data,t),delete e.attachments,e}function Ht(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]=Ht(e[n],t);else if(typeof e==`object`)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Ht(e[n],t));return e}var Ut=s({Decoder:()=>Kt,Encoder:()=>Gt,PacketType:()=>G,isPacketValid:()=>$t,protocol:()=>5}),Wt=[`connect`,`connect_error`,`disconnect`,`disconnecting`,`newListener`,`removeListener`],G;(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`})(G||={});var Gt=class{constructor(e){this.replacer=e}encode(e){return(e.type===G.EVENT||e.type===G.ACK)&&Rt(e)?this.encodeAsBinary({type:e.type===G.EVENT?G.BINARY_EVENT:G.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=``+e.type;return(e.type===G.BINARY_EVENT||e.type===G.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=zt(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}},Kt=class e extends H{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===G.BINARY_EVENT;n||t.type===G.BINARY_ACK?(t.type=n?G.EVENT:G.ACK,this.reconstructor=new qt(t),t.attachments===0&&super.emitReserved(`decoded`,t)):super.emitReserved(`decoded`,t)}else if(Lt(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(G[r.type]===void 0)throw Error(`unknown packet type `+r.type);if(r.type===G.BINARY_EVENT||r.type===G.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(!Yt(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 G.CONNECT:return Zt(t);case G.DISCONNECT:return t===void 0;case G.CONNECT_ERROR:return typeof t==`string`||Zt(t);case G.EVENT:case G.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Wt.indexOf(t[0])===-1);case G.ACK:case G.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=Vt(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function Jt(e){return typeof e==`string`}var Yt=Number.isInteger||function(e){return typeof e==`number`&&isFinite(e)&&Math.floor(e)===e};function Xt(e){return e===void 0||Yt(e)}function Zt(e){return Object.prototype.toString.call(e)===`[object Object]`}function Qt(e,t){switch(e){case G.CONNECT:return t===void 0||Zt(t);case G.DISCONNECT:return t===void 0;case G.EVENT:return Array.isArray(t)&&(typeof t[0]==`number`||typeof t[0]==`string`&&Wt.indexOf(t[0])===-1);case G.ACK:return Array.isArray(t);case G.CONNECT_ERROR:return typeof t==`string`||Zt(t);default:return!1}}function $t(e){return Jt(e.nsp)&&Xt(e.id)&&Qt(e.type,e.data)}function en(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var tn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),nn=class extends H{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=[en(e,`open`,this.onopen.bind(this)),en(e,`packet`,this.onpacket.bind(this)),en(e,`error`,this.onerror.bind(this)),en(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(tn.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:G.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:G.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 G.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 G.EVENT:case G.BINARY_EVENT:this.onevent(e);break;case G.ACK:case G.BINARY_ACK:this.onack(e);break;case G.DISCONNECT:this.ondisconnect();break;case G.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:G.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:G.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 rn(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}rn.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},rn.prototype.reset=function(){this.attempts=0},rn.prototype.setMin=function(e){this.ms=e},rn.prototype.setMax=function(e){this.max=e},rn.prototype.setJitter=function(e){this.jitter=e};var an=class extends H{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,Qe(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 rn({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||Ut;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 At(this.uri,this.opts);let t=this.engine,n=this;this._readyState=`opening`,this.skipReconnect=!1;let r=en(t,`open`,function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState=`closed`,this.emitReserved(`error`,t),e?e(t):this.maybeReconnectOnOpen()},a=en(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(en(e,`ping`,this.onping.bind(this)),en(e,`data`,this.ondata.bind(this)),en(e,`error`,this.onerror.bind(this)),en(e,`close`,this.onclose.bind(this)),en(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){U(()=>{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 nn(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)}},on={};function sn(e,t){typeof e==`object`&&(t=e,e=void 0),t||={};let n=jt(e,t.path||`/socket.io`),r=n.source,i=n.id,a=n.path,o=on[i]&&a in on[i].nsps,s=t.forceNew||t[`force new connection`]||!1===t.multiplex||o,c;return s?c=new an(r,t):(on[i]||(on[i]=new an(r,t)),c=on[i]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(sn,{Manager:an,Socket:nn,io:sn,connect:sn});var cn=({apiBaseUrl:e,userId:t,chatId:n,siteId:r})=>sn(e,{transports:[`polling`,`websocket`],upgrade:!0,rememberUpgrade:!1,auth:{userId:t,chatId:n,siteId:r},query:{chatId:n,siteId:r}}),ln=({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)}}},un=(0,d.createContext)(null),dn=()=>{let e=(0,d.useContext)(un);if(!e)throw Error(`useFlowEngage must be used inside FlowEngageProvider`);return e};function fn(){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 pn=80;function mn(e){requestAnimationFrame(()=>{let t=e.getBoundingClientRect(),n=t.top+t.height/2,r=pn+(window.innerHeight-pn)/2,i=window.pageYOffset+n-r;window.scrollTo({top:Math.max(0,i),behavior:`smooth`})})}function hn(e){e&&(e.hasAttribute(`data-fe-highlighted`)||(gn(),e.classList?.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`),mn(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=`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.padding=`12px 16px`,e.style.transition=`all 0.4s ease`))}function gn(){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 _n=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function vn(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(_n)}catch{return!1}}function yn(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 K(...e){fn()&&console.log(`[FlowEngage:shadowNavigate]`,...e)}var bn=`fe_pending_nav_section`,xn=15e3,Sn=`fe_voice_nav_state`,Cn=2e4,wn=!1,Tn=null;function En(e=3e3){wn=!0,Tn&&clearTimeout(Tn),Tn=setTimeout(()=>{wn=!1,Tn=null},e)}function Dn(){return wn}var On=!1,kn=null;function An(){On||typeof window>`u`||(On=!0,window.addEventListener(`popstate`,async()=>{let e=window.location.href;if(K(`popstate: body-swap to`,e),kn){try{zn(kn)}catch{}try{Hn(kn)}catch{}}try{if(await rr(e,{skipPushState:!0,isBack:!0})){K(`popstate: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] popstate body-swap error:`,e)}K(`popstate: body-swap failed, falling back to reload`),window.location.reload()}))}var jn=!1;function Mn(){jn||typeof window>`u`||typeof document>`u`||(jn=!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(),K(`link-intercept: body-swap to`,r.href),Kn();try{try{zn()}catch{}try{Hn()}catch{}if(await rr(r.href)){K(`link-intercept: body-swap succeeded`);return}}catch(e){console.warn(`[FlowEngage] link-intercept body-swap error:`,e)}K(`link-intercept: body-swap failed, falling back to normal navigation`),qn(),window.location.href=r.href}},!0))}var Nn=null;function Pn(e){Nn=e===`spa`||e===`traditional`?e:null}function Fn(){if(typeof window>`u`||Nn===`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 Nn===`spa`?`backend-spa`:null}var In=`data-fe-swap-css`;function Ln(){typeof document>`u`||document.querySelectorAll(`[${In}]`).forEach(e=>e.remove())}var Rn=`fe_form_state:`;function zn(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=Rn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({state:n,ts:Date.now()}))}catch{}}function Bn(){if(typeof document>`u`||typeof sessionStorage>`u`)return;let e=Rn+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 Vn=`fe_scroll:`;function Hn(e){if(!(typeof window>`u`||typeof sessionStorage>`u`))try{let t=Vn+(e||window.location.pathname);sessionStorage.setItem(t,JSON.stringify({y:window.scrollY,ts:Date.now()}))}catch{}}function Un(){if(typeof window>`u`||typeof sessionStorage>`u`)return;let e=Vn+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 Wn(e){if(!(typeof window>`u`))try{window.dispatchEvent(new CustomEvent(`flowengage:pageswap`,{detail:{url:e,timestamp:Date.now()}}))}catch{}}var Gn=`fe-nav-loader`;function Kn(){if(typeof document>`u`||document.getElementById(Gn))return;let e=document.createElement(`div`);e.id=Gn,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 qn(){if(typeof document>`u`)return;let e=document.getElementById(Gn);e&&(e.style.width=`100%`,setTimeout(()=>{e.style.opacity=`0`,e.style.transition=`opacity 0.3s ease`,setTimeout(()=>e.remove(),350)},200))}function Jn(){if(typeof window>`u`||typeof document>`u`)return;try{window.history.state?.flowengageSpa&&An()}catch{}let e;try{e=JSON.parse(sessionStorage.getItem(bn)||`null`)}catch{return}if(!e)return;try{sessionStorage.removeItem(bn)}catch{}let{sectionText:t,ts:n}=e;if(!t)return;if(Date.now()-n>xn){K(`initNavigationHighlight: pending section expired, skipping:`,t);return}K(`initNavigationHighlight: replaying section highlight:`,t);let r=0,i=()=>{r+=1;let e=Xn(null,t);if(e){Zn(e),K(`initNavigationHighlight: highlighted on attempt`,r);return}r<8?setTimeout(i,300):K(`initNavigationHighlight: could not find element after 8 attempts:`,t)};setTimeout(i,250)}var Yn=()=>{if(typeof document>`u`||document.getElementById(`fe-highlight-styles`))return;let e=document.createElement(`style`);e.id=`fe-highlight-styles`,e.textContent=`
|
|
2
5
|
.fe-highlight-section {
|
|
3
6
|
outline: 3px solid #7c3aed !important;
|
|
4
7
|
box-shadow: 0 0 15px rgba(124, 58, 237, 0.6) !important;
|
|
@@ -22,7 +25,7 @@
|
|
|
22
25
|
box-shadow: none !important;
|
|
23
26
|
transition: outline-color 0.25s ease, box-shadow 0.25s ease !important;
|
|
24
27
|
}
|
|
25
|
-
`,document.head.appendChild(e)};function Xn(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(vn(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(yn(e).toLowerCase()===n)return e;for(let e of i){let t=yn(e).toLowerCase();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=yn(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=yn(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=yn(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=>!vn(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(vn(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(vn(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(vn(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=>!vn(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(vn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function Zn(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;Yn();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 Qn(){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`)),gn())}function $n(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 er(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 tr(e,{siteId:t,apiBaseUrl:n}){if(!e)return{allowed:!1,correctedUrl:null};let r=!1;try{r=!!Fn()}catch{r=!1}let i=async()=>({allowed:r?!1:await er(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 nr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(bn,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function rr(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}Kn();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 qn(),!1;let o=await a.text(),s=new DOMParser().parseFromString(o,`text/html`),c=document.getElementById(`flowengage-root`);if(!c)return qn(),!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()}),Ln();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(In,`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(In,`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,K(`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){K(`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,K(`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){K(`trySpaNavigate: blocked location.assign from replayed script:`,e);return}return d(e)},window.location.replace=e=>{if(p){K(`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;K(`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)){K(`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:`)&&(K(`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`)||``}),K(`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),K(`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(An(),Mn(),n){try{Bn()}catch{}try{Un()}catch{}}else window.scrollTo(0,0);qn(),Wn(e);try{sessionStorage.removeItem(bn)}catch{}try{sessionStorage.removeItem(Sn)}catch{}try{kn=new URL(e,window.location.origin).pathname}catch{}return K(`trySpaNavigate: succeeded →`,e),!0}catch{return clearTimeout(i),qn(),!1}}function ir(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Sn,JSON.stringify({voiceWasActive:!0,targetUrl:String(e),ts:Date.now()}))}catch{}}function ar(){if(!(typeof sessionStorage>`u`))try{sessionStorage.removeItem(Sn)}catch{}}function or(){if(typeof window>`u`||typeof sessionStorage>`u`)return{shouldResumeVoice:!1,targetUrl:null};let e;try{e=JSON.parse(sessionStorage.getItem(Sn)||`null`)}catch{return{shouldResumeVoice:!1,targetUrl:null}}if(!e)return{shouldResumeVoice:!1,targetUrl:null};try{sessionStorage.removeItem(Sn)}catch{}return e.voiceWasActive?Date.now()-e.ts>Cn?(K(`initVoiceNavResume: state expired, skipping`),{shouldResumeVoice:!1,targetUrl:null}):(K(`initVoiceNavResume: voice was active during navigation to`,e.targetUrl),{shouldResumeVoice:!0,targetUrl:e.targetUrl||null}):{shouldResumeVoice:!1,targetUrl:null}}function sr(){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 cr=6e3,lr=250,ur=700;async function dr(){if(typeof window>`u`)return;let e=window.__fe_agentAudioPlaying;if(typeof e!=`function`){await new Promise(e=>setTimeout(e,ur));return}let t=Date.now()+cr;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,lr))}async function fr(e,t={}){if(typeof window>`u`)return{navigated:!1};let{sectionText:n,voiceActive:r=!1}=t;try{let t=$n(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&&nr(n),r||ge(),r?dr().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(Fn()){n&&nr(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)),sr()){try{window.history.pushState({},``,e),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}}))}catch{}return n&&nr(n),r||ge(),window.location.assign(i.href),{navigated:!0}}return{navigated:!0}}return n&&nr(n),r||ge(),window.location.assign(i.href),{navigated:!0}}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&nr(n);try{window.location.href=$n(e)}catch{window.location.href=e}return{navigated:!0}}}var pr=!1,mr=null;function hr(e){mr=e,typeof window<`u`&&(window.__fe_triggerVoiceNavHooks=()=>{try{e.onBeforeNavigate()}catch{}}),!pr&&(pr=!0,!(typeof document>`u`)&&(document.addEventListener(`click`,e=>{if(!mr)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)){K(`voice-link-hook: saving state before navigation →`,r.href);try{mr.onBeforeNavigate()}catch{}}},!0),document.addEventListener(`submit`,e=>{if(mr&&!e.target?.closest?.(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)){K(`voice-form-hook: saving state before form submit`);try{mr.onBeforeNavigate()}catch{}}},!0)))}function gr(){mr=null,K(`voice-nav-hooks: deactivated`)}var _r=4e3,vr=null;function yr(){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(),_r);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 xr(){if(vr!==null)return vr;if(typeof window>`u`)return vr=!1;if(window.Shopify)return vr=!0;try{let e=await br(`${yr()}cart.js`);vr=e&&typeof e.item_count==`number`}catch{vr=!1}return vr}async function Sr(){return br(`${yr()}cart.js`)}function Cr(){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 Tr(){try{if(!await xr())return null;let e=await Sr();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 Er(e,t=null){let n=await br(`${yr()}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 Dr(e,t=1){return br(`${yr()}cart/add.js`,{method:`POST`,body:JSON.stringify({items:[{id:e,quantity:t}]})})}async function Or(e,t){return br(`${yr()}cart/change.js`,{method:`POST`,body:JSON.stringify({line:e,quantity:t})})}function kr(){return`${yr()}cart`}function Ar(){return`${yr()}checkout`}function jr(e){return`${yr()}products/${encodeURIComponent(e)}`}async function Mr(e,t=6){let n=new URLSearchParams({q:e,"resources[type]":`product`,"resources[limit]":String(t)});try{return((await br(`${yr()}search/suggest.json?${n.toString()}`))?.resources?.results?.products||[]).map(e=>({title:e.title,handle:e.handle,price:e.price||null,url:e.url||null}))}catch{return[]}}function Nr(){return typeof window>`u`?!1:/\/cart\/?$/.test(window.location.pathname)}var Pr=[`form[action*="/cart"]`,`cart-items`,`cart-drawer-items`,`.cart-items`,`.cart__items`,`#main-cart-items`,`[data-cart-items]`].join(`, `);function Fr(e){if(/cart/i.test(e.id))return!0;try{return!!e.querySelector(Pr)}catch{return!1}}async function Ir(){if(typeof document>`u`)return!1;let e=Array.from(document.querySelectorAll(`[id^="shopify-section-"]`)).filter(Fr);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 Lr=[`[data-cart-count]`,`.cart-count-bubble`,`.cart-count`,`#CartCount`,`.cart-link__bubble`,`.site-header__cart-count`,`#cart-icon-bubble`];function Rr(e){if(typeof document>`u`)return;let t=String(e);for(let e of Lr)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 zr(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 Br(e){let t=await Ir();return!t&&Nr()&&(await new Promise(e=>setTimeout(e,600)),t=await Ir()),e&&typeof e.item_count==`number`&&Rr(e.item_count),zr(e||null),{sectionsSwapped:t}}async function Vr(e){try{let{sectionsSwapped:t}=await Br(e);if(!t&&Nr())return` (The list on this page may need a quick refresh to show it.)`}catch{}return``}function Hr(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 Ur(e,t){let n=t.title&&t.title!==`Default Title`;return`${e.title}${n?` (${t.title})`:``}`}function Wr(e,t){return e?.userMessage||t}var Gr={async add(e){let{variant:t,product:n}=await Er(e.productHandle,e.variantTitle||null);await Dr(t.id,e.quantity||1);let r=await Sr(),i=await Vr(r);return{message:`✅ Added ${e.quantity||1} × ${Ur(n,t)} to your cart.${Hr(r)}${i}`}},async update(e){let t=(await Sr()).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 Or(e.line,e.quantity),r=await Vr(n);return{message:`✅ Updated ${t.product_title||t.title} to quantity ${e.quantity}.${Hr(n)}${r}`}},async remove(e){let t=(await Sr()).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 Or(e.line,0),r=await Vr(n);return{message:`🗑️ Removed ${t.product_title||t.title} from your cart.${Hr(n)}${r}`}},async view_cart(){return{message:`Opening your cart…`,navigateTo:kr()}},async checkout(){return(await Sr()).item_count?{message:`Taking you to checkout…`,navigateTo:Ar()}:{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:jr(e.productHandle)}}},Kr={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 qr(e){let t={messages:[],navigateTo:null};if(!Array.isArray(e)||e.length===0)return t;if(!await xr())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=Gr[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(Wr(e,Kr[n.type]))}}return t}var Jr=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(),Yr=(e=[])=>e.filter(e=>e.type!==`call_recording`&&!(typeof e.message==`string`&&e.message.includes(`AI chat recording`))).map(e=>({...e,message:Jr(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`}));function Xr(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 Zr=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,Qr=(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}:{}}},$r=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},ei=(e=[],t,n=6)=>!t?.message||e.slice(-n).some(e=>e.sender===`system`&&e.message===t.message)?e:[...e,t];function ti({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=(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()}])},[]),ee=(0,d.useCallback)(e=>{qr(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)})},[]),te=(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()}])},[]),[D,A]=(0,d.useState)(O().isOpen),[se,j]=(0,d.useState)(O().activeScreen),[M,N]=(0,d.useState)(O().isHumanHandled),[P,le]=(0,d.useState)(O().agentName),[ue,de]=(0,d.useState)(O().agentHeadshot),[fe,pe]=(0,d.useState)(()=>ae(i?.siteId)),[he,F]=(0,d.useState)(!1),[ge,_e]=(0,d.useState)(!1),[ve,ye]=(0,d.useState)(`idle`),[I,be]=(0,d.useState)(!1),[xe,Se]=(0,d.useState)(!1),[L,Ee]=(0,d.useState)(``),[De,Oe]=(0,d.useState)(!1),[ke,R]=(0,d.useState)(0),[Ae,je]=(0,d.useState)(0),[Me,Ne]=(0,d.useState)(!1),[z,Pe]=(0,d.useState)(null),[Fe,Ie]=(0,d.useState)(null),[Le,Re]=(0,d.useState)(`idle`),[ze,Be]=(0,d.useState)(null),[Ve,He]=(0,d.useState)(!1),[Ue,We]=(0,d.useState)(``),[Ge,Ke]=(0,d.useState)(!1),B=(0,d.useRef)(null),V=(0,d.useRef)(null),H=(0,d.useRef)(``),qe=(0,d.useRef)(!1),U=(0,d.useRef)(null),W=(0,d.useRef)(null),Je=(0,d.useRef)(null),Ye=(0,d.useRef)(null),Xe=(0,d.useRef)(null),Ze=(0,d.useRef)(null),Qe=(0,d.useRef)(null),$e=(0,d.useRef)(!1),et=(0,d.useRef)({url:null,at:0}),tt=(0,d.useCallback)((e,t)=>{En(6e3);let n=e;try{n=new URL(e,window.location.origin).href}catch{}let r=et.current;return r.url===n&&Date.now()-r.at<4e3?Promise.resolve({navigated:!0,deduped:!0}):(et.current={url:n,at:Date.now()},fr(e,t))},[]),nt=(0,d.useRef)([]),rt=(0,d.useRef)(null),it=(0,d.useRef)(null),at=(0,d.useRef)(null),ot=(0,d.useRef)(!1),st=(0,d.useRef)(!1),ct=(0,d.useRef)(``),lt=(0,d.useRef)(null),ut=(0,d.useRef)(null),dt=(0,d.useRef)([]),ft=(0,d.useRef)(0),pt=(0,d.useRef)(P),mt=(0,d.useRef)([]),ht=(0,d.useRef)(!1),gt=(0,d.useRef)(!1),_t=(0,d.useRef)(i),vt=(0,d.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),yt=(0,d.useCallback)((e={})=>{let t=!!e.is_human_handled;return N(t),t?(j(`agent`),e.agent_info?.name&&le(e.agent_info.name),e.agent_info?.headshot&&de(e.agent_info.headshot),t):(j(`ai`),t)},[]),bt=(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)(()=>{W.current=z},[z]),(0,d.useEffect)(()=>{pt.current=P},[P]),(0,d.useEffect)(()=>{gt.current=De},[De]),(0,d.useEffect)(()=>{_t.current=i},[i]);let xt=()=>{We(``)},St=(0,d.useCallback)(()=>{at.current&&=(window.clearTimeout(at.current),null)},[]),Ct=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return pe(t),oe(t,i?.siteId),t};(0,d.useEffect)(()=>{let e=i?.siteId;if(!e)return;let t=ae(e);if(t){pe(t);return}pe(t=>(t&&oe(t,e),t))},[i?.siteId]);let wt=(e=`unspecified`)=>{let t=rt.current||Ze.current?.callId,n=ft.current,r=lt.current;if(lt.current=null,ft.current=0,r&&r.state!==`inactive`){r.onstop=()=>{let e=dt.current;if(dt.current=[],e.length>0&&t&&V.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;V.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,dt.current=[]}}else if(r&&r.state===`inactive`){let e=dt.current;if(dt.current=[],e.length>0&&t&&V.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;V.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}}else dt.current=[];if(ut.current){try{ut.current.close()}catch{}ut.current=null}Je.current&&=(Je.current.close(),null),Ye.current&&=(Ye.current.getTracks().forEach(e=>e.stop()),null),Xe.current&&=(Xe.current.srcObject=null,Xe.current.remove(),null),St(),Ze.current=null,nt.current=[],rt.current=null,it.current=null,ot.current=!1,He(!1),Pe(null),Ie(null),Re(`idle`),Be(null)},Tt=(e=new Date().toISOString())=>{let t=B.current,n=rt.current||Ze.current?.callId;if(!(!t?.connected||!n||ot.current)){ot.current=!0,t.emit(`call:connected`,{callId:n,chatId:H.current,connectedAt:e});try{let e=Ye.current,t=Xe.current?.srcObject;if(e&&t&&!lt.current){dt.current=[];let n=new(window.AudioContext||window.webkitAudioContext);ut.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&&dt.current.push(e.data)},lt.current=a,ft.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{}}},Et=(e={})=>{if(!e.callId)return;let t=it.current===e.callId,n=rt.current===e.callId,r=W.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(St(),Pe(null),t||n){rt.current=e.callId,Ie(e.callId),Re(e=>e===`connected`?e:`connecting`),A(!0);return}Re(`idle`)}},Dt=(e={})=>{if(!e.callId)return;let t=it.current===e.callId,n=rt.current===e.callId,r=W.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(St(),n){wt();return}it.current=null,Ze.current=null,nt.current=[],Pe(null),Re(`idle`)}},Ot=async(e={})=>{let t=Je.current,n=B.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:H.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ze.current=e;return}if(await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),nt.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:H.current,queuedCount:nt.current.length});for(let e of nt.current)await t.addIceCandidate(new RTCIceCandidate(e));nt.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:H.current})};(0,d.useEffect)(()=>{k({isOpen:D,activeScreen:se,isHumanHandled:M,agentName:P,agentHeadshot:ue})},[D,se,M,P,ue]),(0,d.useEffect)(()=>{let e=!0;return(async()=>{Ke(!0);try{let t=p(i),n=await we(t);if(!e)return;let a=t.siteId,o=ne(a),s=ce(a),l=``;try{let e=qe.current,r=U.current;if(qe.current=!1,U.current=null,l=(await Ce({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(),ie(a,l)}catch(e){console.warn(`[FlowEngageProvider] resolve-session failed, reusing persisted or ephemeral chat id`,e?.message||e),l=o||T(),ie(a,l)}H.current=l;let u=Te({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId,visitorId:s});V.current=u,h({...n,apiBaseUrl:t.apiBaseUrl}),_(l);let d=n?.widgetSettings?.branding?.fallbackAgentName||`Agent`,f=cn({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:l,siteId:t.siteId});B.current=f,f.on(`connect`,async()=>{ye(`connected`);let e=H.current;if(e&&V.current)try{yt(await V.current.checkHumanHandled(e))}catch{}}),f.on(`disconnect`,()=>{ye(`disconnected`)}),f.on(`aiTyping`,()=>{_e(!0)}),f.on(`ai:typing`,()=>{_e(!0)}),f.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:Jr(t.message)};_e(!1),F(!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:Jr(t.message)};_e(!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`)&&F(!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)&&(N(!0),j(`agent`),le($r([n.agent_name,n.agentName,n.metadata?.agentName],d)),n.sender_headshot&&de(n.sender_headshot),A(!0),R(e=>e+1)))});let m=(e={})=>{let t=$r([e.agent?.name,e.agentName,e.agent_name,pt.current],d);N(!0),j(`agent`),le(t),de(e.agent?.headshot||null),A(!0),R(e=>e+1),S(e=>ei(e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}))},g=(e={})=>{let t=$r([e.agent?.name,e.agentName,e.agent_name,pt.current],d);N(!1),j(`ai`),S(e=>ei(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=>{Ne(!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=Yr(e.chat_history||[]);S(t),t.length===0&&(Ne(!1),N(!1),j(`ai`),_e(!1),F(!1))}),f.on(`conversation:reset`,()=>{S([]),Ne(!1),N(!1),j(`ai`),_e(!1),F(!1)}),f.on(`voice:end_session`,(e={})=>{console.log(`[FlowEngageProvider] voice:end_session received — ending voice session`),je(e=>e+1),A(!0),R(e=>e+1)}),f.on(`typing:start`,e=>{e.sender===`agent`&&F(!0)}),f.on(`typing:stop`,e=>{e.sender===`agent`&&F(!1)}),f.on(`call:incoming`,(e={})=>{let t=$r([e.agentName,e.ownerName,e.agent?.name,pt.current],`Agent`);xt(),St(),ot.current=!1,Pe({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),le(e=>$r([t,e],`Agent`)),Re(`incoming`),Be(null),A(!0)}),f.on(`call:offer`,async(e={})=>{Ze.current=e;try{await Ot(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=Qr(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(!Je.current||!Je.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||H.current,queueSize:nt.current.length+1}),nt.current.push(t);return}await Je.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),f.on(`call:ended`,()=>{xt(),wt(`socket:call_ended`)}),f.on(`call:accepted`,(e={})=>{Et(e)}),f.on(`call:accepted_by_other`,(e={})=>{Et(e)}),f.on(`call:rejected`,(e={})=>{Dt(e)}),f.on(`call:missed`,(e={})=>{Dt(e)}),f.on(`call:failed`,(e={})=>{Dt(e)}),f.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=it.current===e.callId,n=rt.current===e.callId,r=Ze.current?.callId===e.callId,i=W.current?.callId===e.callId;if(!t&&!n&&!r){i&&(Pe(null),Re(`idle`));return}ot.current=!0,it.current=null,rt.current=e.callId,Ie(e.callId),Pe(null),Re(`connected`),Be(e.connectedAt||new Date().toISOString()),A(!0)}),f.on(`call:unavailable`,(e={})=>{wt(`socket:call_unavailable`),We(Zr(e,`This visitor is not available for a call right now.`)),A(!0)}),f.on(`call:error`,(e={})=>{wt(`socket:call_error`),We(Zr(e,`We couldn't connect the call right now.`)),A(!0)}),f.on(`visitor:navigate`,async({url:e,section:t,highlight:n}={})=>{e&&tt(e,{voiceActive:gt.current}).then(({navigated:e,reason:r})=>{if(!e){r===`not-found`?E():r===`already-on-page`&&te();return}let i=t||n;i&&setTimeout(()=>{let e=Xn(null,i);e&&Zn(e)},300)})}),f.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;let n=Xn(e||null,t||null);n&&Zn(n)}),f.on(`visitor:clear_highlight`,()=>{Qn()}),vt.current=ln({socket:f,chatId:l});let v=await u.loadHistory(l,r);if(!e)return;S(Yr(v.chat_history||[])),N(!!v.is_human_handled),j(v.is_human_handled?`agent`:se);let y=v?.visitor_email||v?.visitorEmail;if(y&&String(y).trim()&&Ct(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&&Ke(!1)}})(),()=>{e=!1,vt.current?.cleanup?.(),wt(),B.current?.disconnect()}},[i,r,a]),(0,d.useEffect)(()=>()=>{if(De&&!ht.current&&mt.current.length>0){let e=H.current,t=mt.current,n=V.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(()=>{}),ht.current=!0)}},[De,m]);let kt=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e=V.current;!e||!g||kt.current!==D&&(D&&kt.current!==null?e.updateChatStatus(g,`open`).catch(()=>{}):kt.current===!0&&e.updateChatStatus(g,`widget_closed`).catch(()=>{}),kt.current=D)},[D,g]),(0,d.useEffect)(()=>{let e=()=>{let e=H.current,t=V.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 At=async()=>{if(!(!z?.callId||!V.current||!B.current||!g)){xt(),it.current=z.callId,St();try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});Ye.current=e;let t=[{urls:`stun:stun.l.google.com:19302`}];try{let e=await V.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});Je.current=n,n.onconnectionstatechange=()=>{let e=n.connectionState;if(e===`connected`){let e=new Date().toISOString();Re(`connected`),Be(t=>t||e),Tt(e);return}if(e===`connecting`){Re(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&wt(`peer:connection_${e}`)},n.oniceconnectionstatechange=()=>{let e=n.iceConnectionState;if(e===`connected`||e===`completed`){let e=new Date().toISOString();Re(`connected`),Be(t=>t||e),Tt(e);return}if(e===`checking`||e===`new`){Re(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&wt(`peer:ice_${e}`)},n.onsignalingstatechange=()=>{},n.onicegatheringstatechange=()=>{},e.getTracks().forEach(t=>{n.addTrack(t,e)}),n.onicecandidate=e=>{if(!e.candidate||!B.current?.connected)return;let t=e.candidate;B.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(!Xe.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=>{},Xe.current=e,document.body.appendChild(e)}Xe.current.srcObject=e.streams[0];let r=z?.callId,i=r&&(it.current===r||rt.current===r);if(!ot.current&&i){let e=new Date().toISOString();Re(`connected`),Be(t=>t||e),rt.current=r,Ie(r),Tt(e)}Xe.current.srcObject=t||null;let a=Xe.current.play?.();a?.catch&&a.catch(e=>{})};let r=Ze.current;r&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:r.callId||z.callId,chatId:g}),await Ot({...r,callId:r.callId||z.callId})),await V.current.acceptCall(z.callId,g),B.current?.emit(`call:accepted`,{callId:z.callId,chatId:g}),rt.current=z.callId,Ie(z.callId),Re(e=>e===`connected`||ot.current?`connected`:`connecting`),Pe(null),A(!0)}catch(e){if(it.current=null,wt(`accept_call_failed`),e?.status===404||e?.status===409||e?.status===422){We(Zr(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await V.current.rejectCall(z.callId,g)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}We(`Microphone access was denied. Please allow microphone access to accept the call.`);return}We(`We couldn't connect the call right now. Please try again.`)}}},jt=async()=>{if(!z?.callId||!V.current||!g){wt(`reject_call_without_server_context`);return}let e=z.callId;St(),xt(),B.current?.emit(`call:rejected`,{callId:e,chatId:g,reason:`visitor_declined`});try{await V.current.rejectCall(e,g)}catch(e){We(Zr(e,`We couldn't decline the call cleanly.`))}finally{wt(`reject_call_finally`)}},Mt=(0,d.useRef)(jt);Mt.current=jt,(0,d.useEffect)(()=>{if(!z?.callId||Fe){St();return}let e=z.callId;return St(),at.current=window.setTimeout(()=>{W.current?.callId===e&&it.current!==e&&rt.current!==e&&Mt.current()},b),()=>{at.current&&=(window.clearTimeout(at.current),null)}},[Fe,St,z?.callId]);let Nt=async()=>{if(!Fe||!V.current||!g){wt(`end_call_without_server_context`);return}xt();try{await V.current.endWebRTCCall(Fe,g)}catch(e){We(Zr(e,`The call ended locally, but the server could not be updated.`))}finally{wt(`end_call_finally`)}},Pt=()=>{let e=Ye.current?.getAudioTracks?.()||[],t=Je.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0)return;let r=!Ve;n.forEach(e=>{e.enabled=!r}),He(r)},Ft=async(e={})=>{let t=e.notifyChatInitiated===!0;if(A(!0),!(!t||!V.current||!g||typeof window>`u`)){try{await V.current.trackVisitor({chatId:g,currentPagePath:window.location.pathname||`/`})}catch{}try{await V.current.updateChatStatus(g,`open`)}catch{}}},It=async e=>{let t=Ct(e);if(!t||!V.current||!H.current)return t;try{await V.current.trackVisitor({chatId:H.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Lt=()=>{!g||!B.current?.connected||st.current||(st.current=!0,B.current.emit(`typing:start`,{chatId:g,sender:`user`}))},Rt=()=>{!g||!B.current?.connected||!st.current||(st.current=!1,B.current.emit(`typing:stop`,{chatId:g,sender:`user`}))},zt=(e=``)=>{let t=typeof e==`string`?e:``;!g||!B.current?.connected||t!==``&&ct.current===t||(ct.current=t,B.current.emit(`typing:update`,{chatId:g,sender:`user`,text:t}))};function Bt(){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 Vt=async(e,t=``,n=null,i={})=>{let a=typeof e==`string`?e.trim():``;if(!a||!V.current||!g||s!==`ready`||Me)return;Rt(),$e.current=!1;let o=/^\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,c=/^\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,l=/\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(Qe.current&&o.test(a)&&!c.test(a)){let{url:e,section:t}=Qe.current;Qe.current=null,$e.current=!0,console.log(`[FWH Nav] Client-side nav firing →`,e),tt(e,{voiceActive:gt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?E():n===`already-on-page`&&te();return}!t||!gt.current||setTimeout(()=>{let e=Xn(null,t);e&&Zn(e)},300)})}else o.test(a)||(Qe.current=null);let d=`pending-user-${Date.now()}`,f={id:d,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,type:i?.type||`text`,metadata:i?.metadata||void 0,...n||{}};S(e=>[...e,f]);let p=M;if(p)try{p=yt(await V.current.checkHumanHandled(g))}catch{}if(p&&B.current?.connected){B.current.emit(`customer:message`,{chatId:g,content:e,sender:`user`,email:fe||void 0,type:i?.type||`text`,metadata:i?.metadata||{},...n||{}});return}be(!0);try{let o=await Tr(),s=Cr(),c=await V.current.sendAiMessage(g,e,r,t,{...n||{},...fe?{email:fe}:{}},{...i,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:Bt()||void 0,...o?{shopifyCart:o}:{},...s?{shopifyCustomerId:s}:{}}),u=c.chat_history||[];if(console.log(`[FWH Nav Debug] API response fields:`,{has_navigate:!!c.navigate,navigate:c.navigate,has_pending_navigate:!!c.pending_navigate,pending_navigate:c.pending_navigate,last_bot_msg:[...u].reverse().find(e=>e.sender===`bot`)?.message?.substring(0,80)}),c.pending_navigate?.url){let e={url:c.pending_navigate.url,section:c.pending_navigate.section||null};l.test(a)?(console.log(`[FWH Nav] Auto-navigating (intent detected) →`,e.url),tt(e.url,{voiceActive:gt.current}).then(({navigated:t,reason:n})=>{if(!t){n===`not-found`?E():n===`already-on-page`&&te();return}e.section&&setTimeout(()=>{let t=Xn(null,e.section);t&&Zn(t)},300)})):(Qe.current=e,console.log(`[FWH Nav] Stored pending nav →`,Qe.current))}if(c.navigate?.url)if($e.current)$e.current=!1;else{let{url:e,section:t}=c.navigate;tt(e,{voiceActive:gt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?E():n===`already-on-page`&&te();return}t&&setTimeout(()=>{let e=Xn(null,t);e&&Zn(e)},300)})}else if(c.highlight?.section){let e=c.highlight.section;setTimeout(()=>{let t=Xn(null,e);t&&Zn(t)},150)}else{let e=[...u].reverse().find(e=>e.sender===`bot`||e.sender===`assistant`);if(e?.message){let t=Xr(e.message);t&&tr(t.url,{siteId:_t.current?.siteId,apiBaseUrl:_t.current?.apiBaseUrl}).then(({allowed:e,correctedUrl:n})=>{if(!e){E();return}tt(n||t.url,{voiceActive:gt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?E():n===`already-on-page`&&te();return}!t.section||!gt.current||setTimeout(()=>{let e=Xn(null,t.section);e&&Zn(e)},300)})})}}S(Yr(u)),Array.isArray(c.cart_actions)&&c.cart_actions.length&&ee(c.cart_actions),N(!!c.is_human_handled),j(c.is_human_handled?`agent`:`ai`),_e(!1),be(!1),await V.current.updateChatStatus(g,`messageSent`)}catch(e){S(e=>e.filter(e=>e.id!==d)),_e(!1),be(!1),e.status===429?(Se(!0),Ee(e.message),window.setTimeout(()=>{Se(!1),Ee(``)},v)):u(e)}},Ht=async e=>{if(!V.current||!e)throw Error(`Upload is unavailable right now.`);return V.current.uploadChatFile(e)},Ut=async e=>{if(!(!V.current||!g)){try{let t=e?`voice`:`text`;await V.current.setChatMode(g,t)}catch{}Oe(e),e&&(ht.current=!1)}},Wt=async e=>{if(ht.current)return;if(ht.current=!0,!V.current||!g||!e?.length){Oe(!1);return}let t=()=>{let t=Yr(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 V.current.syncVoice(g,e);if(n?.chat_history?.length)S(Yr(n.chat_history));else if(n?.success)try{let e=await V.current.loadHistory(g,r);e?.chat_history?.length?S(Yr(e.chat_history)):t()}catch{t()}else t()}catch{t()}finally{Oe(!1)}},G=async()=>{if(!(!V.current||!g)){De&&!ht.current&&mt.current.length>0&&await Wt(mt.current);try{await V.current.endConversation(g)}catch{try{await V.current.updateChatStatus(g,`ended`)}catch{}}Ne(!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(Le!==`connected`||!Fe||!g||!ze||!bt)return;let e=new Date(ze).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,bt*1e3-t),r=window.setTimeout(()=>{We(`The call ended because it reached the time limit.`),Nt()},n);return()=>window.clearTimeout(r)},[Fe,ze,Le,g,Nt,bt]),(0,d.useEffect)(()=>{let e=()=>{let e=H.current,t=V.current;if(!t||!e)return;if(gt.current&&mt.current.length>0&&me(),!ht.current&&mt.current.length>0&&(t.beaconSyncVoice(e,mt.current)||t.syncVoice(e,mt.current).catch(()=>{}),ht.current=!0),rt.current){t.beaconEndWebRTCCall(rt.current,e);return}let n=it.current||W.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 Gt=(0,d.useCallback)(()=>{let e=i?.siteId;re(e),qe.current=!0,U.current=null,B.current?.disconnect(),S([]),_(``),H.current=``,Ne(!1),N(!1),le(null),de(null),Ke(!0),o(e=>e+1)},[i?.siteId]),Kt=(0,d.useCallback)(e=>{i?.siteId,qe.current=!1,U.current=e,B.current?.disconnect(),S([]),_(``),H.current=``,Ne(!1),N(!1),le(null),de(null),Ke(!0),o(e=>e+1)},[i?.siteId]),qt=(0,d.useMemo)(()=>({status:s,error:l,runtimeConfig:m,resolvedConfig:i,chatId:g,chatHistory:x,isOpen:D,activeScreen:se,isHumanHandled:M,agentName:P,agentHeadshot:ue,visitorEmail:fe,isAgentTyping:he,isAiTyping:ge,connectionStatus:ve,isLoading:I,isVoiceMode:De,isRateLimited:xe,rateLimitMessage:L,isConversationEnded:Me,isSessionRestoring:Ge,openToChatCounter:ke,voiceEndCounter:Ae,incomingCall:z,activeCallId:Fe,callConnectionState:Le,callConnectedAt:ze,isCallMuted:Ve,webRTCError:Ue,language:r,historyRef:mt,hasSyncedRef:ht,dismissCallError:xt,captureVisitorEmail:It,startTyping:Lt,stopTyping:Rt,updateTypingDraft:zt,notifyRouteChange:()=>vt.current?.notifyRouteChange?.(),openWidget:Ft,closeWidget:()=>A(!1),toggleWidget:()=>{if(D){A(!1);return}Ft({notifyChatInitiated:!0})},sendMessage:Vt,uploadChatFile:Ht,setVoiceMode:Ut,onMessageSync:Wt,endConversation:G,startNewChat:Gt,resumeChat:Kt,getVisitorChatHistory:()=>V.current?.getVisitorChatHistory?.(),getVisitorChatThread:e=>V.current?.getVisitorChatThread?.(e),acceptCall:At,rejectCall:jt,endWebRTCCall:Nt,toggleCallMute:Pt}),[s,l,m,i,g,x,D,se,M,P,ue,fe,he,ge,ve,I,De,xe,L,Me,Ge,ke,Ae,z,Fe,Le,ze,Ve,Ue,r,It,Lt,Rt,zt,At,jt,Nt,Pt,Ft,Vt,Ht,Ut,Wt,G,Gt,xt]);return(0,f.jsx)(un.Provider,{value:qt,children:n})}var ni=(0,d.createContext)({});function ri(e){let t=(0,d.useRef)(null);return t.current===null&&(t.current=e()),t.current}var ii=typeof window<`u`?d.useLayoutEffect:d.useEffect,ai=(0,d.createContext)(null);function oi(e,t){e.indexOf(t)===-1&&e.push(t)}function si(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var ci=(e,t,n)=>n>t?t:n<e?e:n;function li(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}var ui=()=>{},di=()=>{};typeof process<`u`&&process.env.NODE_ENV!==`production`&&(ui=(e,t,n)=>{!e&&typeof console<`u`&&console.warn(li(t,n))},di=(e,t,n)=>{if(!e)throw Error(li(t,n))});var fi={},pi=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function mi(e){return typeof e==`object`&&!!e}var hi=e=>/^0[^.\s]+$/u.test(e);function gi(e){let t;return()=>(t===void 0&&(t=e()),t)}var _i=e=>e,vi=(e,t)=>n=>t(e(n)),yi=(...e)=>e.reduce(vi),bi=(e,t,n)=>{let r=t-e;return r===0?1:(n-e)/r},xi=class{constructor(){this.subscriptions=[]}add(e){return oi(this.subscriptions,e),()=>si(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}},Si=e=>e*1e3,Ci=e=>e/1e3;function wi(e,t){return t?1e3/t*e:0}var Ti=new Set;function Ei(e,t,n){e||Ti.has(t)||(console.warn(li(t,n)),Ti.add(t))}var Di=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Oi=1e-7,ki=12;function Ai(e,t,n,r,i){let a,o,s=0;do o=t+(n-t)/2,a=Di(o,r,i)-e,a>0?n=o:t=o;while(Math.abs(a)>Oi&&++s<ki);return o}function ji(e,t,n,r){if(e===t&&n===r)return _i;let i=t=>Ai(t,0,1,e,n);return e=>e===0||e===1?e:Di(i(e),t,r)}var Mi=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Ni=e=>t=>1-e(1-t),Pi=ji(.33,1.53,.69,.99),Fi=Ni(Pi),Ii=Mi(Fi),Li=e=>e>=1?1:(e*=2)<1?.5*Fi(e):.5*(2-2**(-10*(e-1))),Ri=e=>1-Math.sin(Math.acos(e)),zi=Ni(Ri),Bi=Mi(Ri),Vi=ji(.42,0,1,1),Hi=ji(0,0,.58,1),Ui=ji(.42,0,.58,1),Wi=e=>Array.isArray(e)&&typeof e[0]!=`number`,Gi=e=>Array.isArray(e)&&typeof e[0]==`number`,Ki={linear:_i,easeIn:Vi,easeInOut:Ui,easeOut:Hi,circIn:Ri,circInOut:Bi,circOut:zi,backIn:Fi,backInOut:Ii,backOut:Pi,anticipate:Li},qi=e=>typeof e==`string`,Ji=e=>{if(Gi(e)){di(e.length===4,`Cubic bezier arrays must contain four numerical values.`,`cubic-bezier-length`);let[t,n,r,i]=e;return ji(t,n,r,i)}else if(qi(e))return di(Ki[e]!==void 0,`Invalid easing type '${e}'`,`invalid-easing-type`),Ki[e];return e},Yi=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`],Xi={value:null,addProjectionMetrics:null};function Zi(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&&Xi.value&&Xi.value.frameloop[t].push(c),c=0,n.clear(),i=!1,a&&(a=!1,u.process(e))}};return u}var Qi=40;function $i(e,t){let n=!1,r=!0,i={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,o=Yi.reduce((e,n)=>(e[n]=Zi(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=fi.useManualTiming,o=a?i.timestamp:performance.now();n=!1,a||(i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,Qi),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:Yi.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<Yi.length;t++)o[Yi[t]].cancel(e)},state:i,steps:o}}var{schedule:q,cancel:ea,state:ta,steps:na}=$i(typeof requestAnimationFrame<`u`?requestAnimationFrame:_i,!0),ra;function ia(){ra=void 0}var aa={now:()=>(ra===void 0&&aa.set(ta.isProcessing||fi.useManualTiming?ta.timestamp:performance.now()),ra),set:e=>{ra=e,queueMicrotask(ia)}},oa={layout:0,mainThread:0,waapi:0},sa=e=>t=>typeof t==`string`&&t.startsWith(e),ca=sa(`--`),la=sa(`var(--`),ua=e=>la(e)?da.test(e.split(`/*`)[0].trim()):!1,da=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function fa(e){return typeof e==`string`?e.split(`/*`)[0].includes(`var(--`):!1}var pa={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},ma={...pa,transform:e=>ci(0,1,e)},ha={...pa,default:1},ga=e=>Math.round(e*1e5)/1e5,_a=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function va(e){return e==null}var ya=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ba=(e,t)=>n=>!!(typeof n==`string`&&ya.test(n)&&n.startsWith(e)||t&&!va(n)&&Object.prototype.hasOwnProperty.call(n,t)),xa=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(_a);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},Sa=e=>ci(0,255,e),Ca={...pa,transform:e=>Math.round(Sa(e))},wa={test:ba(`rgb`,`red`),parse:xa(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Ca.transform(e)+`, `+Ca.transform(t)+`, `+Ca.transform(n)+`, `+ga(ma.transform(r))+`)`};function Ta(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 Ea={test:ba(`#`),parse:Ta,transform:wa.transform},Da=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Oa=Da(`deg`),ka=Da(`%`),J=Da(`px`),Aa=Da(`vh`),ja=Da(`vw`),Ma={...ka,parse:e=>ka.parse(e)/100,transform:e=>ka.transform(e*100)},Na={test:ba(`hsl`,`hue`),parse:xa(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+ka.transform(ga(t))+`, `+ka.transform(ga(n))+`, `+ga(ma.transform(r))+`)`},Y={test:e=>wa.test(e)||Ea.test(e)||Na.test(e),parse:e=>wa.test(e)?wa.parse(e):Na.test(e)?Na.parse(e):Ea.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?wa.transform(e):Na.transform(e),getAnimatableNone:e=>{let t=Y.parse(e);return t.alpha=0,Y.transform(t)}},Pa=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Fa(e){return isNaN(e)&&typeof e==`string`&&(e.match(_a)?.length||0)+(e.match(Pa)?.length||0)>0}var Ia=`number`,La=`color`,Ra=`var`,za=`var(`,Ba="${}",Va=/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 Ha(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(Va,e=>(Y.test(e)?(r.color.push(a),i.push(La),n.push(Y.parse(e))):e.startsWith(za)?(r.var.push(a),i.push(Ra),n.push(e)):(r.number.push(a),i.push(Ia),n.push(parseFloat(e))),++a,Ba)).split(Ba),indexes:r,types:i}}function Ua(e){return Ha(e).values}function Wa({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===Ia?i+=ga(r[a]):e===La?i+=Y.transform(r[a]):i+=r[a]}return i}}function Ga(e){return Wa(Ha(e))}var Ka=e=>typeof e==`number`?0:Y.test(e)?Y.getAnimatableNone(e):e,qa=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:Ka(e);function Ja(e){let t=Ha(e);return Wa(t)(t.values.map((e,n)=>qa(e,t.split[n])))}var Ya={test:Fa,parse:Ua,createTransformer:Ga,getAnimatableNone:Ja};function Xa(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 Za({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=Xa(s,r,e+1/3),a=Xa(s,r,e),o=Xa(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function Qa(e,t){return n=>n>0?t:e}var X=(e,t,n)=>e+(t-e)*n,$a=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},eo=[Ea,wa,Na],to=e=>eo.find(t=>t.test(e));function no(e){let t=to(e);if(ui(!!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===Na&&(n=Za(n)),n}var ro=(e,t)=>{let n=no(e),r=no(t);if(!n||!r)return Qa(e,t);let i={...n};return e=>(i.red=$a(n.red,r.red,e),i.green=$a(n.green,r.green,e),i.blue=$a(n.blue,r.blue,e),i.alpha=X(n.alpha,r.alpha,e),wa.transform(i))},io=new Set([`none`,`hidden`]);function ao(e,t){return io.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function oo(e,t){return n=>X(e,t,n)}function so(e){return typeof e==`number`?oo:typeof e==`string`?ua(e)?Qa:Y.test(e)?ro:fo:Array.isArray(e)?co:typeof e==`object`?Y.test(e)?ro:lo:Qa}function co(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>so(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function lo(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=so(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function uo(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=Ya.createTransformer(t),r=Ha(e),i=Ha(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?io.has(e)&&!i.values.length||io.has(t)&&!r.values.length?ao(e,t):yi(co(uo(r,i),i.values),n):(ui(!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`),Qa(e,t))};function po(e,t,n){return typeof e==`number`&&typeof t==`number`&&typeof n==`number`?X(e,t,n):so(e)(e,t)}var mo=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>q.update(t,e),stop:()=>ea(t),now:()=>ta.isProcessing?ta.timestamp:aa.now()}},ho=(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)})`},go=2e4;function _o(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(_o(r),go);return{type:`keyframes`,ease:e=>r.next(i*e).value/t,duration:Ci(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 yo(e,t){return e*Math.sqrt(1-t*t)}var bo=12;function xo(e,t,n){let r=n;for(let n=1;n<bo;n++)r-=e(r)/t(r);return r}var So=.001;function Co({duration:e=Z.duration,bounce:t=Z.bounce,velocity:n=Z.velocity,mass:r=Z.mass}){let i,a;ui(e<=Si(Z.maxDuration),`Spring duration must be 10 seconds or less`,`spring-duration-limit`);let o=1-t;o=ci(Z.minDamping,Z.maxDamping,o),e=ci(Z.minDuration,Z.maxDuration,Ci(e)),o<1?(i=t=>{let r=t*o,i=r*e,a=r-n,s=yo(t,o),c=Math.exp(-i);return So-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=yo(t**2,o);return(-i(t)+So>0?-1:1)*((a-s)*c)/l}):(i=t=>{let r=Math.exp(-t*e),i=(t-n)*e+1;return-So+r*i},a=t=>Math.exp(-t*e)*((n-t)*(e*e)));let s=5/e,c=xo(i,a,s);if(e=Si(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 wo=[`duration`,`bounce`],To=[`stiffness`,`damping`,`mass`];function Eo(e,t){return t.some(t=>e[t]!==void 0)}function Do(e){let t={velocity:Z.velocity,stiffness:Z.stiffness,damping:Z.damping,mass:Z.mass,isResolvedFromDuration:!1,...e};if(!Eo(e,To)&&Eo(e,wo))if(t.velocity=0,e.visualDuration){let n=e.visualDuration,r=2*Math.PI/(n*1.2),i=r*r,a=2*ci(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:Z.mass,stiffness:i,damping:a}}else{let n=Co({...e,velocity:0});t={...t,...n,mass:Z.mass},t.isResolvedFromDuration=!0}return t}function Oo(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}=Do({...n,velocity:-Ci(n.velocity||0)}),m=f||0,h=l/(2*Math.sqrt(c*u)),g=o-a,_=Ci(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=yo(_,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=>Si(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=Si(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=Si(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(_o(T),go),t=ho(t=>T.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return T}Oo.applyToOptions=e=>{let t=vo(e,100,Oo);return e.ease=t.ease,e.duration=Si(t.duration),e.type=`keyframes`,e};var ko=5;function Ao(e,t,n){let r=Math.max(t-ko,0);return wi(n-e(r),t-r)}function jo({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=Oo({keyframes:[f.value,m(f.value)],velocity:Ao(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 Mo(e,t,n){let r=[],i=n||fi.mix||po,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=yi(Array.isArray(t)?t[n]||_i:t,a)),r.push(a)}return r}function No(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(di(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=Mo(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=bi(e[r],e[r+1],n);return s[r](i)};return n?t=>l(ci(e[0],e[a-1],t)):l}function Po(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=bi(0,t,r);e.push(X(n,1,i))}}function Fo(e){let t=[0];return Po(t,e.length-1),t}function Io(e,t){return e.map(e=>e*t)}function Lo(e,t){return e.map(()=>t||Ui).splice(0,e.length-1)}function Ro({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=Wi(r)?r.map(Ji):Ji(r),a={done:!1,value:t[0]},o=No(Io(n&&n.length===t.length?n:Fo(t),e),t,{ease:Array.isArray(i)?i:Lo(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var zo=e=>e!==null;function Bo(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(zo),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var Vo={decay:jo,inertia:jo,tween:Ro,keyframes:Ro,spring:Oo};function Ho(e){typeof e.type==`string`&&(e.type=Vo[e.type])}var Uo=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)}},Wo=e=>e/100,Go=class extends Uo{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!==aa.now()&&this.tick(aa.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;Ho(e);let{type:t=Ro,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||Ro;process.env.NODE_ENV!==`production`&&s!==Ro&&di(o.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${o}`,`spring-two-frames`),s!==Ro&&typeof o[0]!=`number`&&(this.mixKeyframes=yi(Wo,po(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=_o(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=ci(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!==jo&&(b.value=Bo(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 Ci(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Ci(e)}get time(){return Ci(this.currentTime)}set time(e){e=Si(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 Ao(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(aa.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=Ci(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=mo,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(aa.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 Ko(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var qo=e=>e*180/Math.PI,Jo=e=>Xo(qo(Math.atan2(e[1],e[0]))),Yo={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Jo,rotateZ:Jo,skewX:e=>qo(Math.atan(e[1])),skewY:e=>qo(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Xo=e=>(e%=360,e<0&&(e+=360),e),Zo=Jo,Qo=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),$o=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),es={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Qo,scaleY:$o,scale:e=>(Qo(e)+$o(e))/2,rotateX:e=>Xo(qo(Math.atan2(e[6],e[5]))),rotateY:e=>Xo(qo(Math.atan2(-e[2],e[0]))),rotateZ:Zo,rotate:Zo,skewX:e=>qo(Math.atan(e[4])),skewY:e=>qo(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function ts(e){return e.includes(`scale`)?1:0}function ns(e,t){if(!e||e===`none`)return ts(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=es,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=Yo,i=t}if(!i)return ts(t);let a=r[t],o=i[1].split(`,`).map(is);return typeof a==`function`?a(o):o[a]}var rs=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return ns(n,t)};function is(e){return parseFloat(e.trim())}var as=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],os=new Set(as),ss=e=>e===pa||e===J,cs=new Set([`x`,`y`,`z`]),ls=as.filter(e=>!cs.has(e));function us(e){let t=[];return ls.forEach(n=>{let r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith(`scale`)?1:0))}),t}var ds={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})=>ns(t,`x`),y:(e,{transform:t})=>ns(t,`y`)};ds.translateX=ds.x,ds.translateY=ds.y;var fs=new Set,ps=!1,ms=!1,hs=!1;function gs(){if(ms){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=us(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)})}ms=!1,ps=!1,fs.forEach(e=>e.complete(hs)),fs.clear()}function _s(){fs.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(ms=!0)})}function vs(){hs=!0,_s(),gs(),hs=!1}var ys=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),ps||(ps=!0,q.read(_s),q.resolveKeyframes(gs))):(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])}Ko(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()}},bs=e=>e.startsWith(`--`);function xs(e,t,n){bs(t)?e.style.setProperty(t,n):e.style[t]=n}var Ss={};function Cs(e,t){let n=gi(e);return()=>Ss[t]??n()}var ws=Cs(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),Ts=Cs(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),Es=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,Ds={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:Es([0,.65,.55,1]),circOut:Es([.55,0,1,.45]),backIn:Es([.31,.01,.66,-.59]),backOut:Es([.33,1.53,.69,.99])};function Os(e,t){if(e)return typeof e==`function`?Ts()?ho(e,t):`ease-out`:Gi(e)?Es(e):Array.isArray(e)?e.map(e=>Os(e,t)||Ds.easeOut):Ds[e]}function ks(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=Os(s,i);Array.isArray(d)&&(u.easing=d),Xi.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 Xi.value&&p.finished.finally(()=>{oa.waapi--}),p}function As(e){return typeof e==`function`&&`applyToOptions`in e}function js({type:e,...t}){return As(e)&&Ts()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var Ms=class extends Uo{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,di(typeof e.type!=`string`,`Mini animate() doesn't support "type" as a string.`,`mini-spring`);let c=js(e);this.animation=ks(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=Bo(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),xs(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 Ci(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Ci(e)}get time(){return Ci(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Si(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&&ws()?(this.animation.timeline=e,t&&(this.animation.rangeStart=t),n&&(this.animation.rangeEnd=n),_i):r(this)}},Ns={anticipate:Li,backInOut:Ii,circInOut:Bi};function Ps(e){return e in Ns}function Fs(e){typeof e.ease==`string`&&Ps(e.ease)&&(e.ease=Ns[e.ease])}var Is=10,Ls=class extends Ms{constructor(e){Fs(e),Ho(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 Go({...a,autoplay:!1}),s=Math.max(Is,aa.now()-this.startTime),c=ci(0,Is,s-Is),l=o.sample(s).value,{name:u}=this.options;i&&u&&xs(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},Rs=(e,t)=>t===`zIndex`?!1:!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(Ya.test(e)||e===`0`)&&!e.startsWith(`url(`));function zs(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 Bs(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=Rs(i,t),s=Rs(a,t);return ui(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:zs(e)||(n===`spring`||As(n))&&r}function Vs(e){e.duration=0,e.type=`keyframes`}var Hs=new Set([`opacity`,`clipPath`,`filter`,`transform`]),Us=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function Ws(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&Us.test(e[t]))return!0;return!1}var Gs=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),Ks=gi(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function qs(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 Ks()&&n&&(Hs.has(n)||Gs.has(n)&&Ws(s))&&(n!==`transform`||!l)&&!c&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var Js=40,Ys=class extends Uo{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=aa.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||ys)(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=aa.now();let u=!0;Bs(e,i,a,o)||(u=!1,(fi.instantAnimations||!s)&&l?.(Bo(e,n,t)),e[0]=e[e.length-1],Vs(n),n.repeat=0);let d={startTime:r?this.resolvedAt&&this.resolvedAt-this.createdAt>Js?this.resolvedAt:this.createdAt:void 0,finalKeyframe:t,...n,keyframes:e},f=u&&!c&&qs(d),p=d.motionValue?.owner?.current,m;if(f)try{m=new Ls({...d,element:p})}catch{m=new Go(d)}else m=new Go(d);m.finished.then(()=>{this.notifyFinished()}).catch(_i),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 Xs(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 Zs=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Qs(e){let t=Zs.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}var $s=4;function ec(e,t,n=1){di(n<=$s,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,`max-css-var-depth`);let[r,i]=Qs(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return pi(e)?parseFloat(e):e}return ua(i)?ec(i,t,n+1):i}var tc={type:`spring`,stiffness:500,damping:25,restSpeed:10},nc=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),rc={type:`keyframes`,duration:.8},ic={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},ac=(e,{keyframes:t})=>t.length>2?rc:os.has(e)?e.startsWith(`scale`)?nc(t[1]):tc:ic;function oc(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function sc(e,t){let n=e?.[t]??e?.default??e;return n===e?n:oc(n,e)}var cc=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function lc(e){for(let t in e)if(!cc.has(t))return!0;return!1}var uc=(e,t,n,r={},i,a)=>o=>{let s=sc(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=Si(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};lc(s)||Object.assign(u,ac(e,u)),u.duration&&=Si(u.duration),u.repeatDelay&&=Si(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(Vs(u),u.delay===0&&(d=!0)),(fi.instantAnimations||fi.skipAnimations||i?.shouldSkipAnimations)&&(d=!0,Vs(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=Bo(u.keyframes,s);if(e!==void 0){q.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new Go(u):new Ys(u)};function dc(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]=dc(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]=dc(r);t=t(n===void 0?e.custom:n,i,a)}return t}function pc(e,t,n){let r=e.getProps();return fc(r,t,n===void 0?r.custom:n,e)}var mc=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...as]),hc=30,gc=e=>!isNaN(parseFloat(e)),_c={current:void 0},vc=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=aa.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=aa.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=gc(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!==`production`&&Ei(!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 xi);let n=this.events[e].add(t);return e===`change`?()=>{n(),q.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 _c.current&&_c.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=aa.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>hc)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,hc);return wi(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 yc(e,t){return new vc(e,t)}var bc=e=>Array.isArray(e);function xc(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,yc(n))}function Sc(e){return bc(e)?e[e.length-1]||0:e}function Cc(e,t){let{transitionEnd:n={},transition:r={},...i}=pc(e,t)||{};i={...i,...n};for(let t in i)xc(e,t,Sc(i[t]))}var wc=e=>!!(e&&e.getVelocity);function Tc(e){return!!(wc(e)&&e.add)}function Ec(e,t){let n=e.getValue(`willChange`);if(Tc(n))return n.add(t);if(!n&&fi.WillChange){let n=new fi.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function Dc(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var Oc=`data-`+Dc(`framerAppearId`);function kc(e){return e.props[Oc]}function Ac({protectedKeys:e,needsAnimating:t},n){let r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function jc(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&&Ac(d,t))continue;let o={delay:n,...sc(a||{},t)},c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){q.update(()=>r.set(i));continue}let f=!1;if(window.MotionHandoffAnimation){let n=kc(e);if(n){let e=window.MotionHandoffAnimation(n,t,q);e!==null&&(o.startTime=e,f=!0)}}Ec(e,t);let p=l??e.shouldReduceMotion;r.start(uc(t,r,i,p&&mc.has(t)?{type:!1}:o,e,f));let m=r.animation;m&&u.push(m)}if(o){let t=()=>q.update(()=>{o&&Cc(e,o)});u.length?Promise.all(u).then(t):t()}return u}function Mc(e,t,n={}){let r=pc(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(jc(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{let{delayChildren:a=0,staggerChildren:o,staggerDirection:s}=i;return Nc(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 Nc(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(Mc(c,t,{...o,delay:n+(typeof r==`function`?0:r)+Xs(e.variantChildren,c,r,i,a)}).then(()=>c.notify(`AnimationComplete`,t)));return Promise.all(s)}function Pc(e,t,n={}){e.notify(`AnimationStart`,t);let r;if(Array.isArray(t)){let i=t.map(t=>Mc(e,t,n));r=Promise.all(i)}else if(typeof t==`string`)r=Mc(e,t,n);else{let i=typeof t==`function`?pc(e,t,n.custom):t;r=Promise.all(jc(e,i,n))}return r.then(()=>{e.notify(`AnimationComplete`,t)})}var Fc={test:e=>e===`auto`,parse:e=>e},Ic=e=>t=>t.test(e),Lc=[pa,J,ka,Oa,ja,Aa,Fc],Rc=e=>Lc.find(Ic(e));function zc(e){return typeof e==`number`?e===0:e===null?!0:e===`none`||e===`0`||hi(e)}var Bc=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function Vc(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(_a)||[];if(!r)return e;let i=n.replace(r,``),a=Bc.has(t)?1:0;return r!==n&&(a*=100),t+`(`+a+i+`)`}var Hc=/\b([a-z-]*)\(.*?\)/gu,Uc={...Ya,getAnimatableNone:e=>{let t=e.match(Hc);return t?t.map(Vc).join(` `):e}},Wc={...Ya,getAnimatableNone:e=>{let t=Ya.parse(e);return Ya.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},Gc={...pa,transform:Math.round},Kc={borderWidth:J,borderTopWidth:J,borderRightWidth:J,borderBottomWidth:J,borderLeftWidth:J,borderRadius:J,borderTopLeftRadius:J,borderTopRightRadius:J,borderBottomRightRadius:J,borderBottomLeftRadius:J,width:J,maxWidth:J,height:J,maxHeight:J,top:J,right:J,bottom:J,left:J,inset:J,insetBlock:J,insetBlockStart:J,insetBlockEnd:J,insetInline:J,insetInlineStart:J,insetInlineEnd:J,padding:J,paddingTop:J,paddingRight:J,paddingBottom:J,paddingLeft:J,paddingBlock:J,paddingBlockStart:J,paddingBlockEnd:J,paddingInline:J,paddingInlineStart:J,paddingInlineEnd:J,margin:J,marginTop:J,marginRight:J,marginBottom:J,marginLeft:J,marginBlock:J,marginBlockStart:J,marginBlockEnd:J,marginInline:J,marginInlineStart:J,marginInlineEnd:J,fontSize:J,backgroundPositionX:J,backgroundPositionY:J,rotate:Oa,rotateX:Oa,rotateY:Oa,rotateZ:Oa,scale:ha,scaleX:ha,scaleY:ha,scaleZ:ha,skew:Oa,skewX:Oa,skewY:Oa,distance:J,translateX:J,translateY:J,translateZ:J,x:J,y:J,z:J,perspective:J,transformPerspective:J,opacity:ma,originX:Ma,originY:Ma,originZ:J,zIndex:Gc,fillOpacity:ma,strokeOpacity:ma,numOctaves:Gc},qc={...Kc,color:Y,backgroundColor:Y,outlineColor:Y,fill:Y,stroke:Y,borderColor:Y,borderTopColor:Y,borderRightColor:Y,borderBottomColor:Y,borderLeftColor:Y,filter:Uc,WebkitFilter:Uc,mask:Wc,WebkitMask:Wc},Jc=e=>qc[e],Yc=new Set([Uc,Wc]);function Xc(e,t){let n=Jc(e);return Yc.has(n)||(n=Ya),n.getAnimatableNone?n.getAnimatableNone(t):void 0}var Zc=new Set([`auto`,`none`,`0`]);function Qc(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!Zc.has(t)&&Ha(t).values.length&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]=Xc(n,i)}var $c=class extends ys{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(),ua(r))){let i=ec(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!mc.has(n)||e.length!==2)return;let[r,i]=e,a=Rc(r),o=Rc(i);if(fa(r)!==fa(i)&&ds[n]){this.needsMeasurement=!0;return}if(a!==o)if(ss(a)&&ss(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else ds[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||zc(e[t]))&&n.push(t);n.length&&Qc(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=ds[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]=ds[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 el(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 tl=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function nl(e){return mi(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}var{schedule:rl,cancel:il}=$i(queueMicrotask,!1),al={x:!1,y:!1};function ol(){return al.x||al.y}function sl(e){return e===`x`||e===`y`?al[e]?null:(al[e]=!0,()=>{al[e]=!1}):al.x||al.y?null:(al.x=al.y=!0,()=>{al.x=al.y=!1})}function cl(e,t){let n=el(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function ll(e){return!(e.pointerType===`touch`||ol())}function ul(e,t,n={}){let[r,i,a]=cl(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(!ll(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 dl=(e,t)=>t?e===t?!0:dl(e,t.parentElement):!1,fl=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,pl=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function ml(e){return pl.has(e.tagName)||e.isContentEditable===!0}var hl=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function gl(e){return hl.has(e.tagName)||e.isContentEditable===!0}var _l=new WeakSet;function vl(e){return t=>{t.key===`Enter`&&e(t)}}function yl(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var bl=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=vl(()=>{if(_l.has(n))return;yl(n,`down`);let e=vl(()=>{yl(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>yl(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function xl(e){return fl(e)&&!ol()}var Sl=new WeakSet;function Cl(e,t,n={}){let[r,i,a]=cl(e,n),o=e=>{let r=e.currentTarget;if(!xl(e)||Sl.has(e))return;_l.add(r),n.stopPropagation&&Sl.add(e);let a=t(r,e),o=(e,t)=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c),_l.has(r)&&_l.delete(r),xl(e)&&typeof a==`function`&&a(e,{success:t})},s=e=>{o(e,r===window||r===document||n.useGlobalTarget||dl(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),nl(e)&&(e.addEventListener(`focus`,e=>bl(e,i)),!ml(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}function wl(e){return mi(e)&&`ownerSVGElement`in e}var Tl=new WeakMap,El,Dl=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:wl(r)&&`getBBox`in r?r.getBBox()[t]:r[n],Ol=Dl(`inline`,`width`,`offsetWidth`),kl=Dl(`block`,`height`,`offsetHeight`);function Al({target:e,borderBoxSize:t}){Tl.get(e)?.forEach(n=>{n(e,{get width(){return Ol(e,t)},get height(){return kl(e,t)}})})}function jl(e){e.forEach(Al)}function Ml(){typeof ResizeObserver>`u`||(El=new ResizeObserver(jl))}function Nl(e,t){El||Ml();let n=el(e);return n.forEach(e=>{let n=Tl.get(e);n||(n=new Set,Tl.set(e,n)),n.add(t),El?.observe(e)}),()=>{n.forEach(e=>{let n=Tl.get(e);n?.delete(t),n?.size||El?.unobserve(e)})}}var Pl=new Set,Fl;function Il(){Fl=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};Pl.forEach(t=>t(e))},window.addEventListener(`resize`,Fl)}function Ll(e){return Pl.add(e),Fl||Il(),()=>{Pl.delete(e),!Pl.size&&typeof Fl==`function`&&(window.removeEventListener(`resize`,Fl),Fl=void 0)}}function Rl(e,t){return typeof e==`function`?Ll(e):Nl(e,t)}function zl(e){return wl(e)&&e.tagName===`svg`}var Bl=[...Lc,Y,Ya],Vl=e=>Bl.find(Ic(e)),Hl=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ul=()=>({x:Hl(),y:Hl()}),Wl=()=>({min:0,max:0}),Gl=()=>({x:Wl(),y:Wl()}),Kl=new WeakMap;function ql(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function Jl(e){return typeof e==`string`||Array.isArray(e)}var Yl=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],Xl=[`initial`,...Yl];function Zl(e){return ql(e.animate)||Xl.some(t=>Jl(e[t]))}function Ql(e){return!!(Zl(e)||e.variants)}function $l(e,t,n){for(let r in t){let i=t[r],a=n[r];if(wc(i))e.addValue(r,i);else if(wc(a))e.addValue(r,yc(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,yc(t===void 0?i:t,{owner:e}))}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var eu={current:null},tu={current:!1},nu=typeof window<`u`;function ru(){if(tu.current=!0,nu)if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>eu.current=e.matches;e.addEventListener(`change`,t),t()}else eu.current=!1}var iu=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],au={};function ou(e){au=e}function su(){return au}var cu=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=ys,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=aa.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,q.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=Zl(t),this.isVariantNode=Ql(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&&wc(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,Kl.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:(tu.current||ru(),this.shouldReduceMotion=eu.current),process.env.NODE_ENV!==`production`&&Ei(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(),ea(this.notifyUpdate),ea(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&&Hs.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new Ms({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:Si(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&&q.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 au){let t=au[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):Gl()}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<iu.length;t++){let n=iu[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=$l(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=yc(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)||hi(n))?n=parseFloat(n):!Vl(n)&&Ya.test(t)&&(n=Xc(e,t)),this.setBaseTarget(e,wc(n)?n.get():n)),wc(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&&!wc(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 xi),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){rl.render(this.render)}},lu=class extends cu{constructor(){super(...arguments),this.KeyframeResolver=$c}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;wc(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},uu=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function du({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 pu(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 mu(e){return e===void 0||e===1}function hu({scale:e,scaleX:t,scaleY:n}){return!mu(e)||!mu(t)||!mu(n)}function gu(e){return hu(e)||_u(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function _u(e){return vu(e.x)||vu(e.y)}function vu(e){return e&&e!==`0%`}function yu(e,t,n){return n+t*(e-n)}function bu(e,t,n,r,i){return i!==void 0&&(e=yu(e,i,r)),yu(e,n,r)+t}function xu(e,t=0,n=1,r,i){e.min=bu(e.min,t,n,r,i),e.max=bu(e.max,t,n,r,i)}function Su(e,{x:t,y:n}){xu(e.x,t.translate,t.scale,t.originPoint),xu(e.y,n.translate,n.scale,n.originPoint)}var Cu=.999999999999,wu=1.0000000000001;function Tu(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&&(Eu(e.x,-a.scroll.offset.x),Eu(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Su(e,o)),r&&gu(a.latestValues)&&ku(e,a.latestValues,a.layout?.layoutBox))}t.x<wu&&t.x>Cu&&(t.x=1),t.y<wu&&t.y>Cu&&(t.y=1)}function Eu(e,t){e.min+=t,e.max+=t}function Du(e,t,n,r,i=.5){xu(e,t,n,X(e.min,e.max,i),r)}function Ou(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function ku(e,t,n){let r=n??e;Du(e.x,Ou(t.x,r.x),t.scaleX,t.scale,t.originX),Du(e.y,Ou(t.y,r.y),t.scaleY,t.scale,t.originY)}function Au(e,t){return du(pu(e.getBoundingClientRect(),t))}function ju(e,t,n){let r=Au(e,n),{scroll:i}=t;return i&&(Eu(r.x,i.offset.x),Eu(r.y,i.offset.y)),r}var Mu={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},Nu=as.length;function Pu(e,t,n){let r=``,i=!0;for(let a=0;a<Nu;a++){let o=as[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=tl(s,Kc[o]);if(!c){i=!1;let t=Mu[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}return r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function Fu(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(ca(e)){i[e]=n;continue}else{let t=tl(n,Kc[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=Pu(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 Iu(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 Lu(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var Ru={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`)if(J.test(e))e=parseFloat(e);else return e;return`${Lu(e,t.target.x)}% ${Lu(e,t.target.y)}%`}},zu={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=Ya.parse(e);if(i.length>5)return r;let a=Ya.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)}},Bu={borderRadius:{...Ru,applyTo:[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`]},borderTopLeftRadius:Ru,borderTopRightRadius:Ru,borderBottomLeftRadius:Ru,borderBottomRightRadius:Ru,boxShadow:zu};function Vu(e,{layout:t,layoutId:n}){return os.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!Bu[e]||e===`opacity`)}function Hu(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(wc(r[t])||i&&wc(i[t])||Vu(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function Uu(e){return window.getComputedStyle(e)}var Wu=class extends lu{constructor(){super(...arguments),this.type=`html`,this.renderInstance=Iu}readValueFromInstance(e,t){if(os.has(t))return this.projection?.isProjecting?ts(t):rs(e,t);{let n=Uu(e),r=(ca(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return Au(e,t)}build(e,t,n){Fu(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return Hu(e,t,n)}},Gu={offset:`stroke-dashoffset`,array:`stroke-dasharray`},Ku={offset:`strokeDashoffset`,array:`strokeDasharray`};function qu(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?Gu:Ku;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var Ju=[`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function Yu(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(Fu(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 Ju)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&&qu(d,i,a,o,!1)}var Xu=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`]),Zu=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function Qu(e,t,n,r){Iu(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(Xu.has(n)?n:Dc(n),t.attrs[n])}function $u(e,t,n){let r=Hu(e,t,n);for(let n in e)if(wc(e[n])||wc(t[n])){let t=as.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var ed=class extends lu{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=Gl}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(os.has(t)){let e=Jc(t);return e&&e.default||0}return t=Xu.has(t)?t:Dc(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return $u(e,t,n)}build(e,t,n){Yu(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){Qu(e,t,n,r)}mount(e){this.isSVGTag=Zu(e.tagName),super.mount(e)}},td=Xl.length;function nd(e){if(!e)return;if(!e.isControllingVariants){let t=e.parent&&nd(e.parent)||{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}let t={};for(let n=0;n<td;n++){let r=Xl[n],i=e.props[r];(Jl(i)||i===!1)&&(t[r]=i)}return t}function rd(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 id=[...Yl].reverse(),ad=Yl.length;function od(e){return t=>Promise.all(t.map(({animation:t,options:n})=>Pc(e,t,n)))}function sd(e){let t=od(e),n=ud(),r=!0,i=!1,a=t=>(n,r)=>{let i=pc(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=nd(e.parent)||{},l=[],u=new Set,d={},f=1/0;for(let t=0;t<ad;t++){let p=id[t],m=n[p],h=s[p]===void 0?c[p]:s[p],g=Jl(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||ql(h)||typeof h==`boolean`)continue;if(p===`exit`&&m.isActive&&_!==!0){m.prevResolvedValues&&(d={...d,...m.prevResolvedValues});continue}let y=cd(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=bc(t)&&bc(n)?!rd(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=pc(r,t);if(r.enteringChildren&&i){let{delayChildren:t}=i.transition||{};n.delay=Xs(r.enteringChildren,e,t)}}return{animation:t,options:n}}))}if(u.size){let t={};if(typeof s.initial!=`boolean`){let n=pc(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=ud(),i=!0}}}function cd(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!rd(t,e):!1}function ld(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ud(){return{animate:ld(!0),whileInView:ld(),whileHover:ld(),whileTap:ld(),whileDrag:ld(),whileFocus:ld(),exit:ld()}}function dd(e,t){e.min=t.min,e.max=t.max}function fd(e,t){dd(e.x,t.x),dd(e.y,t.y)}function pd(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var md=1e-4,hd=1-md,gd=1+md,_d=.01,vd=0-_d,yd=0+_d;function bd(e){return e.max-e.min}function xd(e,t,n){return Math.abs(e-t)<=n}function Sd(e,t,n,r=.5){e.origin=r,e.originPoint=X(t.min,t.max,e.origin),e.scale=bd(n)/bd(t),e.translate=X(n.min,n.max,e.origin)-e.originPoint,(e.scale>=hd&&e.scale<=gd||isNaN(e.scale))&&(e.scale=1),(e.translate>=vd&&e.translate<=yd||isNaN(e.translate))&&(e.translate=0)}function Cd(e,t,n,r){Sd(e.x,t.x,n.x,r?r.originX:void 0),Sd(e.y,t.y,n.y,r?r.originY:void 0)}function wd(e,t,n,r=0){e.min=(r?X(n.min,n.max,r):n.min)+t.min,e.max=e.min+bd(t)}function Td(e,t,n,r){wd(e.x,t.x,n.x,r?.x),wd(e.y,t.y,n.y,r?.y)}function Ed(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+bd(t)}function Dd(e,t,n,r){Ed(e.x,t.x,n.x,r?.x),Ed(e.y,t.y,n.y,r?.y)}function Od(e,t,n,r,i){return e-=t,e=yu(e,1/n,r),i!==void 0&&(e=yu(e,1/i,r)),e}function kd(e,t=0,n=1,r=.5,i,a=e,o=e){if(ka.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=Od(e.min,t,n,s,i),e.max=Od(e.max,t,n,s,i)}function Ad(e,t,[n,r,i],a,o){kd(e,t[n],t[r],t[i],t.scale,a,o)}var jd=[`x`,`scaleX`,`originX`],Md=[`y`,`scaleY`,`originY`];function Nd(e,t,n,r){Ad(e.x,t,jd,n?n.x:void 0,r?r.x:void 0),Ad(e.y,t,Md,n?n.y:void 0,r?r.y:void 0)}function Pd(e){return e.translate===0&&e.scale===1}function Fd(e){return Pd(e.x)&&Pd(e.y)}function Id(e,t){return e.min===t.min&&e.max===t.max}function Ld(e,t){return Id(e.x,t.x)&&Id(e.y,t.y)}function Rd(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function zd(e,t){return Rd(e.x,t.x)&&Rd(e.y,t.y)}function Bd(e){return bd(e.x)/bd(e.y)}function Vd(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function Hd(e){return[e(`x`),e(`y`)]}function Ud(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 Wd=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`],Gd=Wd.length,Kd=e=>typeof e==`string`?parseFloat(e):e,qd=e=>typeof e==`number`||J.test(e);function Jd(e,t,n,r,i,a){i?(e.opacity=X(0,n.opacity??1,Xd(r)),e.opacityExit=X(t.opacity??1,0,Zd(r))):a&&(e.opacity=X(t.opacity??1,n.opacity??1,r));for(let i=0;i<Gd;i++){let a=Wd[i],o=Yd(t,a),s=Yd(n,a);o===void 0&&s===void 0||(o||=0,s||=0,o===0||s===0||qd(o)===qd(s)?(e[a]=Math.max(X(Kd(o),Kd(s),r),0),(ka.test(s)||ka.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=X(t.rotate||0,n.rotate||0,r))}function Yd(e,t){return e[t]===void 0?e.borderRadius:e[t]}var Xd=Qd(0,.5,zi),Zd=Qd(.5,.95,_i);function Qd(e,t,n){return r=>r<e?0:r>t?1:n(bi(e,t,r))}function $d(e,t,n){let r=wc(e)?e:yc(e);return r.start(uc(``,r,t,n)),r.animation}function ef(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}var tf=(e,t)=>e.depth-t.depth,nf=class{constructor(){this.children=[],this.isDirty=!1}add(e){oi(this.children,e),this.isDirty=!0}remove(e){si(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(tf),this.isDirty=!1,this.children.forEach(e)}};function rf(e,t){let n=aa.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(ea(r),e(a-t))};return q.setup(r,!0),()=>ea(r)}function af(e){return wc(e)?e.get():e}var of=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&&(si(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(si(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)}},sf={hasAnimatedSinceResize:!0,hasEverUpdated:!1},cf={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},lf=[``,`X`,`Y`,`Z`],uf=1e3,df=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 pf(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=kc(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,q,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&pf(r)}function mf({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=df++,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,Xi.value&&(cf.nodes=cf.calculatedTargetDeltas=cf.calculatedProjections=0),this.nodes.forEach(_f),this.nodes.forEach(Ef),this.nodes.forEach(Df),this.nodes.forEach(vf),Xi.addProjectionMetrics&&Xi.addProjectionMetrics(cf)},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 nf)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new xi),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=wl(t)&&!zl(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;q.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=rf(i,250),sf.hasAnimatedSinceResize&&(sf.hasAnimatedSinceResize=!1,this.nodes.forEach(Tf)))})}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()||Pf,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!zd(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={...sc(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||Tf(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(),ea(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(Of),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&&pf(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(xf),this.nodes.forEach(bf);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Sf);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Cf),this.nodes.forEach(wf),this.nodes.forEach(hf),this.nodes.forEach(gf)):this.nodes.forEach(Sf),this.clearAllSnapshots();let e=aa.now();ta.delta=ci(0,1e3/60,e-ta.timestamp),ta.timestamp=e,ta.isProcessing=!0,na.update.process(ta),na.preRender.process(ta),na.render.process(ta),ta.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,rl.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(yf),this.sharedNodes.forEach(kf)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,q.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){q.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!bd(this.snapshot.measuredBox.x)&&!bd(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||=Gl(),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&&!Fd(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||gu(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)),Rf(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return Gl();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Bf))){let{scroll:e}=this.root;e&&(Eu(t.x,e.offset.x),Eu(t.y,e.offset.y))}return t}removeElementScroll(e){let t=Gl();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),Eu(t.x,i.offset.x),Eu(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||Gl();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&&(Eu(r.x,-n.scroll.offset.x),Eu(r.y,-n.scroll.offset.y)),gu(n.latestValues)&&ku(r,n.latestValues,n.layout?.layoutBox)}return gu(this.latestValues)&&ku(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=Gl();fd(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!gu(n.latestValues))continue;let r;n.instance&&(hu(n.latestValues)&&n.updateSnapshot(),r=Gl(),fd(r,n.measurePageBox())),Nd(t,n.latestValues,n.snapshot?.layoutBox,r)}return gu(this.latestValues)&&Nd(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!==ta.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=ta.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=Gl(),this.targetWithTransforms=Gl()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Td(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),Su(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),Xi.value&&cf.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||hu(this.parent.latestValues)||_u(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=Gl(),this.relativeTargetOrigin=Gl(),Dd(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===ta.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;Tu(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=Gl());let{target:s}=e;if(!s){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(pd(this.prevProjectionDelta.x,this.projectionDelta.x),pd(this.prevProjectionDelta.y,this.projectionDelta.y)),Cd(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!Vd(this.projectionDelta.x,this.prevProjectionDelta.x)||!Vd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),Xi.value&&cf.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=Ul(),this.projectionDelta=Ul(),this.projectionDeltaWithTransform=Ul()}setAnimationOrigin(e,t=!1){let n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},a=Ul();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let o=Gl(),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(Nf));this.animationProgress=0;let d;this.mixTargetDelta=t=>{let n=t/1e3;Af(a.x,e.x,n),Af(a.y,e.y,n),this.setTargetDelta(a),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Dd(o,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),Mf(this.relativeTarget,this.relativeTargetOrigin,o,n),d&&Ld(this.relativeTarget,d)&&(this.isProjectionDirty=!1),d||=Gl(),fd(d,this.relativeTarget)),s&&(this.animationValues=i,Jd(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&&=(ea(this.pendingAnimation),void 0),this.pendingAnimation=q.update(()=>{sf.hasAnimatedSinceResize=!0,oa.layout++,this.motionValue||=yc(0),this.motionValue.jump(0,!1),this.currentAnimation=$d(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(uf),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&&zf(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||Gl();let t=bd(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;let r=bd(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}fd(t,n),ku(t,i),Cd(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&&ff(`z`,e,r,this.animationValues);for(let t=0;t<lf.length;t++)ff(`rotate${lf[t]}`,e,r,this.animationValues),ff(`skew${lf[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=af(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=af(t?.pointerEvents)||``),this.hasProjected&&!gu(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=Ud(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 Bu){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=Bu[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?af(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(bf),this.root.sharedNodes.clear()}}}function hf(e){e.updateLayout()}function gf(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`)Hd(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=bd(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;dd(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else zf(i,t.layoutBox,n)&&Hd(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=bd(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=Ul();Cd(o,n,t.layoutBox);let s=Ul();a?Cd(s,e.applyTransform(r,!0),t.measuredBox):Cd(s,n,t.layoutBox);let c=!Fd(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=Gl();Dd(s,t.layoutBox,i.layoutBox,o);let c=Gl();Dd(c,n,a.layoutBox,o),zd(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 _f(e){Xi.value&&cf.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 yf(e){e.clearSnapshot()}function bf(e){e.clearMeasurements()}function xf(e){e.isLayoutDirty=!0,e.updateLayout()}function Sf(e){e.isLayoutDirty=!1}function Cf(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function wf(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function Tf(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Ef(e){e.resolveTargetDelta()}function Df(e){e.calcProjection()}function Of(e){e.resetSkewAndRotation()}function kf(e){e.removeLeadSnapshot()}function Af(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 jf(e,t,n,r){e.min=X(t.min,n.min,r),e.max=X(t.max,n.max,r)}function Mf(e,t,n,r){jf(e.x,t.x,n.x,r),jf(e.y,t.y,n.y,r)}function Nf(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var Pf={duration:.45,ease:[.4,0,.1,1]},Ff=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),If=Ff(`applewebkit/`)&&!Ff(`chrome/`)?Math.round:_i;function Lf(e){e.min=If(e.min),e.max=If(e.max)}function Rf(e){Lf(e.x),Lf(e.y)}function zf(e,t,n){return e===`position`||e===`preserve-aspect`&&!xd(Bd(t),Bd(n),.2)}function Bf(e){return e!==e.root&&e.scroll?.wasRoot}var Vf=mf({attachResizeListener:(e,t)=>ef(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),Hf={current:void 0},Uf=mf({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Hf.current){let e=new Vf({});e.mount(window),e.setOptions({layoutScroll:!0}),Hf.current=e}return Hf.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),Wf=(0,d.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function Gf(e=!0){let t=(0,d.useContext)(ai);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 Kf=(0,d.createContext)({strict:!1}),qf={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`]},Jf=!1;function Yf(){if(Jf)return;let e={};for(let t in qf)e[t]={isEnabled:e=>qf[t].some(t=>!!e[t])};ou(e),Jf=!0}function Xf(){return Yf(),su()}function Zf(e){let t=Xf();for(let n in e)t[n]={...t[n],...e[n]};ou(t)}var Qf=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 $f(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||Qf.has(e)}var ep=s({default:()=>tp}),tp,np=o((()=>{throw tp={},Error(`Could not resolve "@emotion/is-prop-valid" imported by "framer-motion". Is it installed?`)})),rp=e=>!$f(e);function ip(e){typeof e==`function`&&(rp=t=>t.startsWith(`on`)?!$f(t):e(t))}try{ip((np(),u(ep)).default)}catch{}function ap(e,t,n){let r={};for(let i in e)i===`values`&&typeof e.values==`object`||wc(e[i])||(rp(i)||n===!0&&$f(i)||!t&&!$f(i)||e.draggable&&i.startsWith(`onDrag`))&&(r[i]=e[i]);return r}var op=(0,d.createContext)({});function sp(e,t){if(Zl(e)){let{initial:t,animate:n}=e;return{initial:t===!1||Jl(t)?t:void 0,animate:Jl(n)?n:void 0}}return e.inherit===!1?{}:t}function cp(e){let{initial:t,animate:n}=sp(e,(0,d.useContext)(op));return(0,d.useMemo)(()=>({initial:t,animate:n}),[lp(t),lp(n)])}function lp(e){return Array.isArray(e)?e.join(` `):e}var up=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function dp(e,t,n){for(let r in t)!wc(t[r])&&!Vu(r,n)&&(e[r]=t[r])}function fp({transformTemplate:e},t){return(0,d.useMemo)(()=>{let n=up();return Fu(n,t,e),Object.assign({},n.vars,n.style)},[t])}function pp(e,t){let n=e.style||{},r={};return dp(r,n,e),Object.assign(r,fp(e,t)),r}function mp(e,t){let n={},r=pp(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 hp=()=>({...up(),attrs:{}});function gp(e,t,n,r){let i=(0,d.useMemo)(()=>{let n=hp();return Yu(n,t,Zu(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};dp(t,e.style,e),i.style={...t,...i.style}}return i}var _p=[`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:!!(_p.indexOf(e)>-1||/[A-Z]/u.test(e))}function yp(e,t,n,{latestValues:r},i,a=!1,o){let s=(o??vp(e)?gp:mp)(t,r,i,e),c=ap(t,typeof e==`string`,a),l=e===d.Fragment?{}:{...c,...s,ref:n},{children:u}=t,f=(0,d.useMemo)(()=>wc(u)?u.get():u,[u]);return(0,d.createElement)(e,{...l,children:f})}function bp({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:xp(n,r,i,e),renderState:t()}}function xp(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=af(a[e]);let{initial:o,animate:s}=e,c=Zl(e),l=Ql(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`&&!ql(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 Sp=e=>(t,n)=>{let r=(0,d.useContext)(op),i=(0,d.useContext)(ai),a=()=>bp(e,t,r,i);return n?a():ri(a)},Cp=Sp({scrapeMotionValuesFromProps:Hu,createRenderState:up}),wp=Sp({scrapeMotionValuesFromProps:$u,createRenderState:hp}),Tp=Symbol.for(`motionComponentSymbol`);function Ep(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 Dp=(0,d.createContext)({});function Op(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function kp(e,t,n,r,i,a){let{visualElement:o}=(0,d.useContext)(op),s=(0,d.useContext)(Kf),c=(0,d.useContext)(ai),l=(0,d.useContext)(Wf),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)(Dp);h&&!h.projection&&i&&(h.type===`html`||h.type===`svg`)&&Ap(p.current,n,i,g);let _=(0,d.useRef)(!1);(0,d.useInsertionEffect)(()=>{h&&_.current&&h.update(n,c)});let v=n[Oc],y=(0,d.useRef)(!!v&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(v)&&window.MotionHasOptimisedAnimation?.(v));return ii(()=>{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 Ap(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:jp(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&Op(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function jp(e){if(e)return e.options.allowProjection===!1?jp(e.parent):e.projection}function Mp(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&Zf(r);let a=n?n===`svg`:vp(e),o=a?wp:Cp;function s(n,s){let c,l={...(0,d.useContext)(Wf),...n,layoutId:Np(n)},{isStatic:u}=l,p=cp(n),m=o(n,u);if(!u&&typeof window<`u`){Pp(l,r);let t=Fp(l);c=t.MeasureLayout,p.visualElement=kp(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,yp(e,n,Ep(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[Tp]=e,c}function Np({layoutId:e}){let t=(0,d.useContext)(ni).id;return t&&e!==void 0?t+`-`+e:e}function Pp(e,t){let n=(0,d.useContext)(Kf).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?ui(!1,t,`lazy-strict-mode`):di(!1,t,`lazy-strict-mode`)}}function Fp(e){let{drag:t,layout:n}=Xf();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function Ip(e,t){if(typeof Proxy>`u`)return Mp;let n=new Map,r=(n,r)=>Mp(n,r,e,t);return new Proxy((e,t)=>(process.env.NODE_ENV!==`production`&&Ei(!1,`motion() is deprecated. Use motion.create() instead.`),r(e,t)),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,Mp(a,void 0,e,t)),n.get(a))})}var Lp=(e,t)=>t.isSVG??vp(e)?new ed(t):new Wu(t,{allowProjection:e!==d.Fragment}),Rp=class extends uu{constructor(e){super(e),e.animationState||=sd(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();ql(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?.()}},zp=0,Bp={animation:{Feature:Rp},exit:{Feature:class extends uu{constructor(){super(...arguments),this.id=zp++,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=pc(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 Vp(e){return{point:{x:e.pageX,y:e.pageY}}}var Hp=e=>t=>fl(t)&&e(t,Vp(t));function Up(e,t,n,r){return ef(e,t,Hp(n),r)}var Wp=({current:e})=>e?e.ownerDocument.defaultView:null,Gp=(e,t)=>Math.abs(e-t);function Kp(e,t){let n=Gp(e.x,t.x),r=Gp(e.y,t.y);return Math.sqrt(n**2+r**2)}var qp=new Set([`auto`,`scroll`]),Jp=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=Yp(this.lastRawMoveEventInfo,this.transformPagePoint));let e=Zp(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=Kp(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e,{timestamp:i}=ta;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=Yp(t,this.transformPagePoint),q.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=Zp(e.type===`pointercancel`?this.lastMoveEventInfo:Yp(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=Yp(Vp(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=ta;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,Zp(s,this.history)),this.removeListeners=yi(Up(this.contextWindow,`pointermove`,this.handlePointerMove),Up(this.contextWindow,`pointerup`,this.handlePointerUp),Up(this.contextWindow,`pointercancel`,this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let t=e.parentElement;for(;t;){let e=getComputedStyle(t);(qp.has(e.overflowX)||qp.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),q.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),ea(this.updatePoint)}};function Yp(e,t){return t?{point:t(e.point)}:e}function Xp(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Zp({point:e},t){return{point:e,delta:Xp(e,$p(t)),offset:Xp(e,Qp(t)),velocity:em(t,.1)}}function Qp(e){return e[0]}function $p(e){return e[e.length-1]}function em(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=$p(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>Si(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>Si(t)*2&&(r=e[1]);let a=Ci(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 tm(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 nm(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 rm(e,{top:t,left:n,bottom:r,right:i}){return{x:nm(e.x,n,i),y:nm(e.y,t,r)}}function im(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 am(e,t){return{x:im(e.x,t.x),y:im(e.y,t.y)}}function om(e,t){let n=.5,r=bd(e),i=bd(t);return i>r?n=bi(t.min,t.max-r,e.min):r>i&&(n=bi(e.min,e.max-i,t.min)),ci(0,1,n)}function sm(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 cm=.35;function lm(e=cm){return e===!1?e=0:e===!0&&(e=cm),{x:um(e,`left`,`right`),y:um(e,`top`,`bottom`)}}function um(e,t,n){return{min:dm(e,t),max:dm(e,n)}}function dm(e,t){return typeof e==`number`?e:e[t]||0}var fm=new WeakMap,pm=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=Gl(),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(Vp(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=sl(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),Hd(e=>{let t=this.getAxisMotionValue(e).get()||0;if(ka.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=bd(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&q.update(()=>i(e,t),!1,!0),Ec(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=_m(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&&q.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 Jp(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:Wp(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&&q.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||!gm(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=tm(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&&Op(e)?this.constraints||=this.resolveRefConstraints():e&&n?this.constraints=rm(n.layoutBox,e):this.constraints=!1,this.elastic=lm(t),r!==this.constraints&&!Op(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&Hd(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=sm(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Op(e))return!1;let n=e.current;di(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=ju(n,r.root,this.visualElement.getTransformPagePoint()),a=am(r.layout.layoutBox,i);if(t){let e=t(fu(a));this.hasMutatedConstraints=!!e,e&&(a=du(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=Hd(o=>{if(!gm(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 Ec(this.visualElement,e),n.start(uc(e,n,0,t,this.visualElement,!1))}stopAnimation(){Hd(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){Hd(t=>{let{drag:n}=this.getProps();if(!gm(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(!Op(t)||!n||!this.constraints)return;this.stopAnimation();let r={x:0,y:0};Hd(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(),Hd(t=>{if(!gm(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=Up(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&gl(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();Op(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=hm(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),q.read(r);let o=ef(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(Hd(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=cm,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function mm(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function hm(e,t,n){let r=Rl(e,mm(n)),i=Rl(t,mm(n));return()=>{r(),i()}}function gm(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function _m(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 uu{constructor(e){super(e),this.removeGroupControls=_i,this.removeListeners=_i,this.controls=new pm(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||_i}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()}},ym=e=>(t,n)=>{e&&q.update(()=>e(t,n),!1,!0)},bm=class extends uu{constructor(){super(...arguments),this.removePointerDownListener=_i}onPointerDown(e){this.session=new Jp(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Wp(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:ym(e),onStart:ym(t),onMove:ym(n),onEnd:(e,t)=>{delete this.session,r&&q.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=Up(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},xm=!1,Sm=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),xm&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),sf.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}),xm=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||q.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(),rl.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;xm=!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 Cm(e){let[t,n]=Gf(),r=(0,d.useContext)(ni);return(0,f.jsx)(Sm,{...e,layoutGroup:r,switchLayoutGroup:(0,d.useContext)(Dp),isPresent:t,safeToRemove:n})}var wm={pan:{Feature:bm},drag:{Feature:vm,ProjectionNode:Uf,MeasureLayout:Cm}};function Tm(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&q.postRender(()=>i(t,Vp(t)))}var Em=class extends uu{mount(){let{current:e}=this.node;e&&(this.unmount=ul(e,(e,t)=>(Tm(this.node,t,`Start`),e=>Tm(this.node,e,`End`))))}unmount(){}},Dm=class extends uu{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=yi(ef(this.node.current,`focus`,()=>this.onFocus()),ef(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function Om(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&&q.postRender(()=>i(t,Vp(t)))}var km=class extends uu{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=Cl(e,(e,t)=>(Om(this.node,t,`Start`),(e,{success:t})=>Om(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},Am=new WeakMap,jm=new WeakMap,Mm=e=>{let t=Am.get(e.target);t&&t(e)},Nm=e=>{e.forEach(Mm)};function Pm({root:e,...t}){let n=e||document;jm.has(n)||jm.set(n,{});let r=jm.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(Nm,{root:e,...t})),r[i]}function Fm(e,t,n){let r=Pm(t);return Am.set(e,n),r.observe(e),()=>{Am.delete(e),r.unobserve(e)}}var Im={some:0,all:1},Lm=class extends uu{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:Im[r]};this.stopObserver=Fm(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(Rm(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function Rm({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var zm={inView:{Feature:Lm},tap:{Feature:km},focus:{Feature:Dm},hover:{Feature:Em}},Bm={layout:{ProjectionNode:Uf,MeasureLayout:Cm}},Vm=Ip({...Bp,...zm,...wm,...Bm},Lp),Hm=24e3,Um=2048,Wm=1200,Gm=.05,Km=4,qm=.03,Jm=2,Ym=11;function Xm(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}function Zm(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 Qm(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]/32768;return t}var $m=.09,eh=[`audio/webm`,`audio/mp4`];function th(){return typeof window>`u`||window.MediaRecorder===void 0?null:eh.find(e=>window.MediaRecorder.isTypeSupported(e))||null}function nh(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))}function rh(e,t,n){let r=0,i=0,a=[],o=()=>{a.forEach(e=>{try{e.stop()}catch{}}),a=[],r=0},s=()=>r>e.currentTime;return{enqueue:o=>{let c=Qm(o),l=e.createBuffer(1,c.length,Hm);l.copyToChannel(c,0);let u=e.createBufferSource();u.buffer=l,u.connect(e.destination),n&&u.connect(n);let d=!s(),f=d?e.currentTime+$m:r;d&&(i=f),u.start(f),r=f+l.duration,a.push(u),u.onended=()=>{a=a.filter(e=>e!==u),!a.length&&!s()&&t?.()}},stop:o,isPlaying:s,playedMs:()=>Math.max(0,(e.currentTime-i)*1e3)}}async function ih(e,t,n){let r=new URLSearchParams({siteId:t||``});n&&r.set(`chatId`,n);let i=Cr();i&&r.set(`shopifyCustomerId`,String(i));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 ah(e){let{apiBaseUrl:t,siteId:n,chatId:r,clientTools:i={},onConnect:a,onDisconnect:o,onMessage:s,onModeChange:c,onError:l,onUnhandledClientToolCall:u,onAgentTurnEnd:d,onSessionInfo:f,onSessionEnding:p}=e,m=await ih(t,n,r);f?.({emailOnFile:!!m.emailOnFile});let h={type:`Start`};e.greeting!==void 0&&(h.greeting=e.greeting||null);let g=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),_=new(window.AudioContext||window.webkitAudioContext)({sampleRate:Hm});_.state===`suspended`&&await _.resume();let v=_.createMediaStreamDestination(),y=th(),b=[],x=null,S=r||n||null;y&&(x=new window.MediaRecorder(v.stream,{mimeType:y}),x.ondataavailable=e=>{e.data&&e.data.size>0&&b.push(e.data)},x.start());let C=new WebSocket(m.wsUrl);C.binaryType=`arraybuffer`;let w=new Set,T={role:null,text:``,timer:null,debug:null},E=``,ee=()=>{T.timer&&=(clearTimeout(T.timer),null);let e=T.text.trim(),t=T.role,n=T.debug;if(T.text=``,T.role=null,T.debug=null,!(!e||!t)){if(t===`agent`){if(e===E){console.debug(`[FlowEngage] duplicate agent turn suppressed`);return}E=e}s?.({role:t,message:e,debug:n})}},te=(e,t,n)=>{t&&(T.role&&T.role!==e&&ee(),T.role=e,T.text=T.text?`${T.text} ${t}`.replace(/\s+/g,` `):t,n&&(T.debug=n),T.timer&&clearTimeout(T.timer),T.timer=setTimeout(ee,Wm))},D=!1,ne=!1,re=!1,ie=!1,O=!0,k=0,ae=!1,oe=!1,A=Gm,se=Km,j=null,ce=!1,M=!1,N=()=>{j&&clearTimeout(j);let e=()=>{if(!D){if(P.isPlaying()){j=setTimeout(e,150);return}if(j=null,ce){p?.();return}!D&&C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:`PlaybackDrained`})),M&&(M=!1,d?.())}};j=setTimeout(e,150)},P=rh(_,()=>{ie&&(ie=!1,c?.({mode:`listening`}))},v);typeof window<`u`&&(window.__fe_agentAudioPlaying=()=>P.isPlaying());let le=_.createMediaStreamSource(g);le.connect(v);let ue=_.createScriptProcessor(Um,1,1),de=!1,fe=0,pe=0;ue.onaudioprocess=e=>{if(D||C.readyState!==WebSocket.OPEN)return;let t=e.inputBuffer.getChannelData(0),n=()=>C.send(new Int16Array(t.length).buffer);if(ne){re||(re=!0,console.debug(`[FlowEngage] mic held — streaming silence to keep socket alive`)),de=!1,fe=0,pe=0,n();return}let r=Xm(t);if(P.isPlaying()||oe?(de=!1,fe=0,pe=0):r>=qm?(pe=0,fe+=1,!de&&fe>=Jm&&(de=!0,c?.({mode:`user-speaking`}))):(fe=0,de&&++pe>=Ym&&(de=!1,pe=0,c?.({mode:`thinking`,tentative:!0}))),(P.isPlaying()||oe)&&!ae){if(r<A){k=0,n();return}if(k+=1,k<se){n();return}ae=!0,k=0;let e=P.playedMs();P.stop(),O=!1,oe=!1,j&&!ce&&(clearTimeout(j),j=null),M=!1,C.send(JSON.stringify({type:`VisitorInterrupted`,played_ms:Math.round(e)})),console.debug(`[FlowEngage] barge-in — visitor spoke over the agent`)}C.send(Zm(t).buffer)},le.connect(ue),ue.connect(_.destination);let me=()=>{if(!D){D=!0,j&&=(clearTimeout(j),null),ee(),P.stop(),typeof window<`u`&&delete window.__fe_agentAudioPlaying;try{ue.disconnect(),le.disconnect()}catch{}if(g.getTracks().forEach(e=>e.stop()),x&&x.state!==`inactive`){x.onstop=()=>nh(t,n,S,b,y);try{x.stop()}catch{x.onstop=null}}else b.length&&nh(t,n,S,b,y);_.close().catch(()=>{}),(C.readyState===WebSocket.OPEN||C.readyState===WebSocket.CONNECTING)&&C.close()}},he=async e=>{let t=i[e.name];if(!t)return u?.({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`}}},F=async e=>{for(let t of e.functions||[]){if(!t.client_side)continue;let e=await he(t);if(D||C.readyState!==WebSocket.OPEN)return;C.send(JSON.stringify({type:`FunctionCallResponse`,id:t.id,name:t.name,content:typeof e==`string`?e:JSON.stringify(e??{})}))}},ge=e=>{switch(e.type){case`Welcome`:Number.isFinite(e.barge_in_rms)&&e.barge_in_rms>0&&(A=e.barge_in_rms),Number.isFinite(e.barge_in_frames)&&e.barge_in_frames>0&&(se=e.barge_in_frames),S=e.session_id||r||n||null,a?.({conversationId:S});break;case`ConversationText`:{let t=String(e.content||``);if(e.role===`user`){let e=t.trim();if(w.has(e)){w.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}}te(e.role===`user`?`user`:`agent`,t,e.debug);break}case`UserStartedSpeaking`:ee(),P.stop(),oe=!1,O=!1,ie=!1,j&&!ce&&(clearTimeout(j),j=null),M=!1,c?.({mode:`listening`});break;case`AgentStartedSpeaking`:O=!0,ie=!0,ae=!1,k=0,c?.({mode:`speaking`});break;case`AgentAudioDone`:oe=!1,ee(),N(),P.isPlaying()||(ie=!1,c?.({mode:`listening`}));break;case`FunctionCallRequest`:F(e);break;case`AgentPreparing`:oe=!0;break;case`AgentTurnComplete`:M=!0,N();break;case`SessionEnding`:console.debug(`[FlowEngage] server is ending the session:`,e.reason||`unspecified`),ce=!0;break;case`AgentThinking`:c?.({mode:`thinking`});break;case`PromptUpdated`:break;case`Error`:console.error(`[FlowEngage:Voice]`,e.code||``,e.description||e),l?.(Error(e.description||`Voice service error`));break;case`Warning`:console.warn(`[FlowEngage:Voice]`,e.code||``,e.description||``);break;default:break}};return C.onopen=()=>C.send(JSON.stringify(h)),C.onmessage=e=>{if(e.data instanceof ArrayBuffer){O&&P.enqueue(new Int16Array(e.data));return}try{ge(JSON.parse(e.data))}catch{}},C.onerror=()=>l?.(Error(`Voice connection failed`)),C.onclose=()=>{me(),o?.()},{endSession:async()=>me(),sendContextualUpdate:e=>{D||C.readyState!==WebSocket.OPEN||!e||C.send(JSON.stringify({type:`UpdatePrompt`,prompt:e}))},sendUserMessage:(e,{silent:t=!0,suppressQuestion:n=!1}={})=>{D||C.readyState!==WebSocket.OPEN||!e||(t&&w.add(e.trim()),C.send(JSON.stringify({type:`InjectUserMessage`,content:e,suppress_question:n})))},injectAgentSpeech:(e,t=`interrupt`)=>{D||C.readyState!==WebSocket.OPEN||!e||C.send(JSON.stringify({type:`InjectAgentMessage`,message:e,behavior:t}))},setWalkthroughActive:e=>{D||C.readyState!==WebSocket.OPEN||C.send(JSON.stringify({type:`WalkthroughActive`,active:!!e}))},setMicMuted:e=>{ne=!!e,!D&&C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:`MicHeld`,held:ne}))},get status(){return D?`disconnected`:`connected`}}}var oh={startSession:ah},sh=({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`})]}),ch=({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`})]}),lh=({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`})]}),uh=()=>(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`})]}),dh=()=>(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`})}),fh=({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`})]}),ph=({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`})]}),mh=({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`})]}),hh=({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})]}),gh=({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`})]}),_h=()=>(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`})}),vh=({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`})]}),yh=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),bh=(e=``)=>String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),xh=new Set([`p`,`br`,`ul`,`ol`,`li`,`strong`,`em`,`b`,`i`,`a`]),Sh=/^https?:\/\//i;function Ch(e){let t=Array.from(e.childNodes);for(let n of t)if(n.nodeType===Node.ELEMENT_NODE){let t=n.tagName.toLowerCase();if(!xh.has(t)){e.replaceChild(document.createTextNode(n.textContent),n);continue}let r={};if(t===`a`){let e=n.getAttribute(`href`)||``;Sh.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);Ch(n)}else n.nodeType!==Node.TEXT_NODE&&e.removeChild(n)}function wh(e){let t=document.createElement(`div`);return t.innerHTML=e,Ch(t),t.innerHTML}function Th(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 Eh=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return Th(wh(t));let n=t.replace(/\r\n/g,`
|
|
28
|
+
`,document.head.appendChild(e)};function Xn(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(vn(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(yn(e).toLowerCase()===n)return e;for(let e of i){let t=yn(e).toLowerCase();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=yn(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=yn(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=yn(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=>!vn(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(vn(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(vn(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(vn(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=>!vn(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(vn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function Zn(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;Yn();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 Qn(){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`)),gn())}function $n(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 er(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 tr(e,{siteId:t,apiBaseUrl:n}){if(!e)return{allowed:!1,correctedUrl:null};let r=!1;try{r=!!Fn()}catch{r=!1}let i=async()=>({allowed:r?!1:await er(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 nr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(bn,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function rr(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}Kn();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 qn(),!1;let o=await a.text(),s=new DOMParser().parseFromString(o,`text/html`),c=document.getElementById(`flowengage-root`);if(!c)return qn(),!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()}),Ln();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(In,`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(In,`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,K(`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){K(`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,K(`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){K(`trySpaNavigate: blocked location.assign from replayed script:`,e);return}return d(e)},window.location.replace=e=>{if(p){K(`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;K(`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)){K(`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:`)&&(K(`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`)||``}),K(`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),K(`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(An(),Mn(),n){try{Bn()}catch{}try{Un()}catch{}}else window.scrollTo(0,0);qn(),Wn(e);try{sessionStorage.removeItem(bn)}catch{}try{sessionStorage.removeItem(Sn)}catch{}try{kn=new URL(e,window.location.origin).pathname}catch{}return K(`trySpaNavigate: succeeded →`,e),!0}catch{return clearTimeout(i),qn(),!1}}function ir(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Sn,JSON.stringify({voiceWasActive:!0,targetUrl:String(e),ts:Date.now()}))}catch{}}function ar(){if(!(typeof sessionStorage>`u`))try{sessionStorage.removeItem(Sn)}catch{}}function or(){if(typeof window>`u`||typeof sessionStorage>`u`)return{shouldResumeVoice:!1,targetUrl:null};let e;try{e=JSON.parse(sessionStorage.getItem(Sn)||`null`)}catch{return{shouldResumeVoice:!1,targetUrl:null}}if(!e)return{shouldResumeVoice:!1,targetUrl:null};try{sessionStorage.removeItem(Sn)}catch{}return e.voiceWasActive?Date.now()-e.ts>Cn?(K(`initVoiceNavResume: state expired, skipping`),{shouldResumeVoice:!1,targetUrl:null}):(K(`initVoiceNavResume: voice was active during navigation to`,e.targetUrl),{shouldResumeVoice:!0,targetUrl:e.targetUrl||null}):{shouldResumeVoice:!1,targetUrl:null}}function sr(){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 cr=6e3,lr=250,ur=700;async function dr(){if(typeof window>`u`)return;let e=window.__fe_agentAudioPlaying;if(typeof e!=`function`){await new Promise(e=>setTimeout(e,ur));return}let t=Date.now()+cr;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,lr))}async function fr(e,t={}){if(typeof window>`u`)return{navigated:!1};let{sectionText:n,voiceActive:r=!1}=t;try{let t=$n(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&&nr(n),r||ge(),r?dr().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(Fn()){n&&nr(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)),sr()){try{window.history.pushState({},``,e),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}}))}catch{}return n&&nr(n),r||ge(),window.location.assign(i.href),{navigated:!0}}return{navigated:!0}}return n&&nr(n),r||ge(),window.location.assign(i.href),{navigated:!0}}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&nr(n);try{window.location.href=$n(e)}catch{window.location.href=e}return{navigated:!0}}}var pr=!1,mr=null;function hr(e){mr=e,typeof window<`u`&&(window.__fe_triggerVoiceNavHooks=()=>{try{e.onBeforeNavigate()}catch{}}),!pr&&(pr=!0,!(typeof document>`u`)&&(document.addEventListener(`click`,e=>{if(!mr)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)){K(`voice-link-hook: saving state before navigation →`,r.href);try{mr.onBeforeNavigate()}catch{}}},!0),document.addEventListener(`submit`,e=>{if(mr&&!e.target?.closest?.(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)){K(`voice-form-hook: saving state before form submit`);try{mr.onBeforeNavigate()}catch{}}},!0)))}function gr(){mr=null,K(`voice-nav-hooks: deactivated`)}var _r=4e3,vr=null;function yr(){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(),_r);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 xr(){if(vr!==null)return vr;if(typeof window>`u`)return vr=!1;if(window.Shopify)return vr=!0;try{let e=await br(`${yr()}cart.js`);vr=e&&typeof e.item_count==`number`}catch{vr=!1}return vr}async function Sr(){return br(`${yr()}cart.js`)}function Cr(){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 Tr(){try{if(!await xr())return null;let e=await Sr();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 Er(e,t=null){let n=await br(`${yr()}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 Dr(e,t=1){return br(`${yr()}cart/add.js`,{method:`POST`,body:JSON.stringify({items:[{id:e,quantity:t}]})})}async function Or(e,t){return br(`${yr()}cart/change.js`,{method:`POST`,body:JSON.stringify({line:e,quantity:t})})}function kr(){return`${yr()}cart`}function Ar(){return`${yr()}checkout`}function jr(e){return`${yr()}products/${encodeURIComponent(e)}`}async function Mr(e,t=6){let n=new URLSearchParams({q:e,"resources[type]":`product`,"resources[limit]":String(t)});try{return((await br(`${yr()}search/suggest.json?${n.toString()}`))?.resources?.results?.products||[]).map(e=>({title:e.title,handle:e.handle,price:e.price||null,url:e.url||null}))}catch{return[]}}function Nr(){return typeof window>`u`?!1:/\/cart\/?$/.test(window.location.pathname)}var Pr=[`form[action*="/cart"]`,`cart-items`,`cart-drawer-items`,`.cart-items`,`.cart__items`,`#main-cart-items`,`[data-cart-items]`].join(`, `);function Fr(e){if(/cart/i.test(e.id))return!0;try{return!!e.querySelector(Pr)}catch{return!1}}async function Ir(){if(typeof document>`u`)return!1;let e=Array.from(document.querySelectorAll(`[id^="shopify-section-"]`)).filter(Fr);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 Lr=[`[data-cart-count]`,`.cart-count-bubble`,`.cart-count`,`#CartCount`,`.cart-link__bubble`,`.site-header__cart-count`,`#cart-icon-bubble`];function Rr(e){if(typeof document>`u`)return;let t=String(e);for(let e of Lr)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 zr(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 Br(e){let t=await Ir();return!t&&Nr()&&(await new Promise(e=>setTimeout(e,600)),t=await Ir()),e&&typeof e.item_count==`number`&&Rr(e.item_count),zr(e||null),{sectionsSwapped:t}}async function Vr(e){try{let{sectionsSwapped:t}=await Br(e);if(!t&&Nr())return` (The list on this page may need a quick refresh to show it.)`}catch{}return``}function Hr(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 Ur(e,t){let n=t.title&&t.title!==`Default Title`;return`${e.title}${n?` (${t.title})`:``}`}function Wr(e,t){return e?.userMessage||t}var Gr={async add(e){let{variant:t,product:n}=await Er(e.productHandle,e.variantTitle||null);await Dr(t.id,e.quantity||1);let r=await Sr(),i=await Vr(r);return{message:`✅ Added ${e.quantity||1} × ${Ur(n,t)} to your cart.${Hr(r)}${i}`}},async update(e){let t=(await Sr()).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 Or(e.line,e.quantity),r=await Vr(n);return{message:`✅ Updated ${t.product_title||t.title} to quantity ${e.quantity}.${Hr(n)}${r}`}},async remove(e){let t=(await Sr()).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 Or(e.line,0),r=await Vr(n);return{message:`🗑️ Removed ${t.product_title||t.title} from your cart.${Hr(n)}${r}`}},async view_cart(){return{message:`Opening your cart…`,navigateTo:kr()}},async checkout(){return(await Sr()).item_count?{message:`Taking you to checkout…`,navigateTo:Ar()}:{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:jr(e.productHandle)}}},Kr={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 qr(e){let t={messages:[],navigateTo:null};if(!Array.isArray(e)||e.length===0)return t;if(!await xr())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=Gr[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(Wr(e,Kr[n.type]))}}return t}var Jr=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(),Yr=(e=[])=>e.filter(e=>e.type!==`call_recording`&&!(typeof e.message==`string`&&e.message.includes(`AI chat recording`))).map(e=>({...e,message:Jr(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`}));function Xr(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 Zr=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,Qr=(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}:{}}},$r=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},ei=(e=[],t,n=6)=>!t?.message||e.slice(-n).some(e=>e.sender===`system`&&e.message===t.message)?e:[...e,t];function ti({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=(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()}])},[]),ee=(0,d.useCallback)(e=>{qr(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)})},[]),te=(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()}])},[]),[D,A]=(0,d.useState)(O().isOpen),[se,j]=(0,d.useState)(O().activeScreen),[M,N]=(0,d.useState)(O().isHumanHandled),[P,le]=(0,d.useState)(O().agentName),[ue,de]=(0,d.useState)(O().agentHeadshot),[fe,pe]=(0,d.useState)(()=>ae(i?.siteId)),[he,F]=(0,d.useState)(!1),[ge,_e]=(0,d.useState)(!1),[ve,ye]=(0,d.useState)(`idle`),[I,be]=(0,d.useState)(!1),[xe,Se]=(0,d.useState)(!1),[L,Ee]=(0,d.useState)(``),[De,Oe]=(0,d.useState)(!1),[ke,R]=(0,d.useState)(0),[Ae,je]=(0,d.useState)(0),[Me,Ne]=(0,d.useState)(!1),[z,Pe]=(0,d.useState)(null),[Fe,Ie]=(0,d.useState)(null),[Le,Re]=(0,d.useState)(`idle`),[ze,Be]=(0,d.useState)(null),[Ve,He]=(0,d.useState)(!1),[Ue,We]=(0,d.useState)(``),[Ge,Ke]=(0,d.useState)(!1),B=(0,d.useRef)(null),V=(0,d.useRef)(null),H=(0,d.useRef)(``),qe=(0,d.useRef)(!1),U=(0,d.useRef)(null),W=(0,d.useRef)(null),Je=(0,d.useRef)(null),Ye=(0,d.useRef)(null),Xe=(0,d.useRef)(null),Ze=(0,d.useRef)(null),Qe=(0,d.useRef)(null),$e=(0,d.useRef)(!1),et=(0,d.useRef)({url:null,at:0}),tt=(0,d.useCallback)((e,t)=>{En(6e3);let n=e;try{n=new URL(e,window.location.origin).href}catch{}let r=et.current;return r.url===n&&Date.now()-r.at<4e3?Promise.resolve({navigated:!0,deduped:!0}):(et.current={url:n,at:Date.now()},fr(e,t))},[]),nt=(0,d.useRef)([]),rt=(0,d.useRef)(null),it=(0,d.useRef)(null),at=(0,d.useRef)(null),ot=(0,d.useRef)(!1),st=(0,d.useRef)(!1),ct=(0,d.useRef)(``),lt=(0,d.useRef)(null),ut=(0,d.useRef)(null),dt=(0,d.useRef)([]),ft=(0,d.useRef)(0),pt=(0,d.useRef)(P),mt=(0,d.useRef)([]),ht=(0,d.useRef)(!1),gt=(0,d.useRef)(!1),_t=(0,d.useRef)(i),vt=(0,d.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),yt=(0,d.useCallback)((e={})=>{let t=!!e.is_human_handled;return N(t),t?(j(`agent`),e.agent_info?.name&&le(e.agent_info.name),e.agent_info?.headshot&&de(e.agent_info.headshot),t):(j(`ai`),t)},[]),bt=(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)(()=>{W.current=z},[z]),(0,d.useEffect)(()=>{pt.current=P},[P]),(0,d.useEffect)(()=>{gt.current=De},[De]),(0,d.useEffect)(()=>{_t.current=i},[i]);let xt=()=>{We(``)},St=(0,d.useCallback)(()=>{at.current&&=(window.clearTimeout(at.current),null)},[]),Ct=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return pe(t),oe(t,i?.siteId),t};(0,d.useEffect)(()=>{let e=i?.siteId;if(!e)return;let t=ae(e);if(t){pe(t);return}pe(t=>(t&&oe(t,e),t))},[i?.siteId]);let wt=(e=`unspecified`)=>{let t=rt.current||Ze.current?.callId,n=ft.current,r=lt.current;if(lt.current=null,ft.current=0,r&&r.state!==`inactive`){r.onstop=()=>{let e=dt.current;if(dt.current=[],e.length>0&&t&&V.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;V.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,dt.current=[]}}else if(r&&r.state===`inactive`){let e=dt.current;if(dt.current=[],e.length>0&&t&&V.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;V.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}}else dt.current=[];if(ut.current){try{ut.current.close()}catch{}ut.current=null}Je.current&&=(Je.current.close(),null),Ye.current&&=(Ye.current.getTracks().forEach(e=>e.stop()),null),Xe.current&&=(Xe.current.srcObject=null,Xe.current.remove(),null),St(),Ze.current=null,nt.current=[],rt.current=null,it.current=null,ot.current=!1,He(!1),Pe(null),Ie(null),Re(`idle`),Be(null)},Tt=(e=new Date().toISOString())=>{let t=B.current,n=rt.current||Ze.current?.callId;if(!(!t?.connected||!n||ot.current)){ot.current=!0,t.emit(`call:connected`,{callId:n,chatId:H.current,connectedAt:e});try{let e=Ye.current,t=Xe.current?.srcObject;if(e&&t&&!lt.current){dt.current=[];let n=new(window.AudioContext||window.webkitAudioContext);ut.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&&dt.current.push(e.data)},lt.current=a,ft.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{}}},Et=(e={})=>{if(!e.callId)return;let t=it.current===e.callId,n=rt.current===e.callId,r=W.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(St(),Pe(null),t||n){rt.current=e.callId,Ie(e.callId),Re(e=>e===`connected`?e:`connecting`),A(!0);return}Re(`idle`)}},Dt=(e={})=>{if(!e.callId)return;let t=it.current===e.callId,n=rt.current===e.callId,r=W.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(St(),n){wt();return}it.current=null,Ze.current=null,nt.current=[],Pe(null),Re(`idle`)}},Ot=async(e={})=>{let t=Je.current,n=B.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:H.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ze.current=e;return}if(await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),nt.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:H.current,queuedCount:nt.current.length});for(let e of nt.current)await t.addIceCandidate(new RTCIceCandidate(e));nt.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:H.current})};(0,d.useEffect)(()=>{k({isOpen:D,activeScreen:se,isHumanHandled:M,agentName:P,agentHeadshot:ue})},[D,se,M,P,ue]),(0,d.useEffect)(()=>{let e=!0;return(async()=>{Ke(!0);try{let t=p(i),n=await we(t);if(!e)return;let a=t.siteId,o=ne(a),s=ce(a),l=``;try{let e=qe.current,r=U.current;if(qe.current=!1,U.current=null,l=(await Ce({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(),ie(a,l)}catch(e){console.warn(`[FlowEngageProvider] resolve-session failed, reusing persisted or ephemeral chat id`,e?.message||e),l=o||T(),ie(a,l)}H.current=l;let u=Te({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId,visitorId:s});V.current=u,h({...n,apiBaseUrl:t.apiBaseUrl}),_(l);let d=n?.widgetSettings?.branding?.fallbackAgentName||`Agent`,f=cn({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:l,siteId:t.siteId});B.current=f,f.on(`connect`,async()=>{ye(`connected`);let e=H.current;if(e&&V.current)try{yt(await V.current.checkHumanHandled(e))}catch{}}),f.on(`disconnect`,()=>{ye(`disconnected`)}),f.on(`aiTyping`,()=>{_e(!0)}),f.on(`ai:typing`,()=>{_e(!0)}),f.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:Jr(t.message)};_e(!1),F(!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:Jr(t.message)};_e(!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`)&&F(!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)&&(N(!0),j(`agent`),le($r([n.agent_name,n.agentName,n.metadata?.agentName],d)),n.sender_headshot&&de(n.sender_headshot),A(!0),R(e=>e+1)))});let m=(e={})=>{let t=$r([e.agent?.name,e.agentName,e.agent_name,pt.current],d);N(!0),j(`agent`),le(t),de(e.agent?.headshot||null),A(!0),R(e=>e+1),S(e=>ei(e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}))},g=(e={})=>{let t=$r([e.agent?.name,e.agentName,e.agent_name,pt.current],d);N(!1),j(`ai`),S(e=>ei(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=>{Ne(!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=Yr(e.chat_history||[]);S(t),t.length===0&&(Ne(!1),N(!1),j(`ai`),_e(!1),F(!1))}),f.on(`conversation:reset`,()=>{S([]),Ne(!1),N(!1),j(`ai`),_e(!1),F(!1)}),f.on(`voice:end_session`,(e={})=>{console.log(`[FlowEngageProvider] voice:end_session received — ending voice session`),je(e=>e+1),A(!0),R(e=>e+1)}),f.on(`typing:start`,e=>{e.sender===`agent`&&F(!0)}),f.on(`typing:stop`,e=>{e.sender===`agent`&&F(!1)}),f.on(`call:incoming`,(e={})=>{let t=$r([e.agentName,e.ownerName,e.agent?.name,pt.current],`Agent`);xt(),St(),ot.current=!1,Pe({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),le(e=>$r([t,e],`Agent`)),Re(`incoming`),Be(null),A(!0)}),f.on(`call:offer`,async(e={})=>{Ze.current=e;try{await Ot(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=Qr(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(!Je.current||!Je.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||H.current,queueSize:nt.current.length+1}),nt.current.push(t);return}await Je.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),f.on(`call:ended`,()=>{xt(),wt(`socket:call_ended`)}),f.on(`call:accepted`,(e={})=>{Et(e)}),f.on(`call:accepted_by_other`,(e={})=>{Et(e)}),f.on(`call:rejected`,(e={})=>{Dt(e)}),f.on(`call:missed`,(e={})=>{Dt(e)}),f.on(`call:failed`,(e={})=>{Dt(e)}),f.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=it.current===e.callId,n=rt.current===e.callId,r=Ze.current?.callId===e.callId,i=W.current?.callId===e.callId;if(!t&&!n&&!r){i&&(Pe(null),Re(`idle`));return}ot.current=!0,it.current=null,rt.current=e.callId,Ie(e.callId),Pe(null),Re(`connected`),Be(e.connectedAt||new Date().toISOString()),A(!0)}),f.on(`call:unavailable`,(e={})=>{wt(`socket:call_unavailable`),We(Zr(e,`This visitor is not available for a call right now.`)),A(!0)}),f.on(`call:error`,(e={})=>{wt(`socket:call_error`),We(Zr(e,`We couldn't connect the call right now.`)),A(!0)}),f.on(`visitor:navigate`,async({url:e,section:t,highlight:n}={})=>{e&&tt(e,{voiceActive:gt.current}).then(({navigated:e,reason:r})=>{if(!e){r===`not-found`?E():r===`already-on-page`&&te();return}let i=t||n;i&&setTimeout(()=>{let e=Xn(null,i);e&&Zn(e)},300)})}),f.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;let n=Xn(e||null,t||null);n&&Zn(n)}),f.on(`visitor:clear_highlight`,()=>{Qn()}),vt.current=ln({socket:f,chatId:l});let v=await u.loadHistory(l,r);if(!e)return;S(Yr(v.chat_history||[])),N(!!v.is_human_handled),j(v.is_human_handled?`agent`:se);let y=v?.visitor_email||v?.visitorEmail;if(y&&String(y).trim()&&Ct(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&&Ke(!1)}})(),()=>{e=!1,vt.current?.cleanup?.(),wt(),B.current?.disconnect()}},[i,r,a]),(0,d.useEffect)(()=>()=>{if(De&&!ht.current&&mt.current.length>0){let e=H.current,t=mt.current,n=V.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(()=>{}),ht.current=!0)}},[De,m]);let kt=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e=V.current;!e||!g||kt.current!==D&&(D&&kt.current!==null?e.updateChatStatus(g,`open`).catch(()=>{}):kt.current===!0&&e.updateChatStatus(g,`widget_closed`).catch(()=>{}),kt.current=D)},[D,g]),(0,d.useEffect)(()=>{let e=()=>{let e=H.current,t=V.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 At=async()=>{if(!(!z?.callId||!V.current||!B.current||!g)){xt(),it.current=z.callId,St();try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});Ye.current=e;let t=[{urls:`stun:stun.l.google.com:19302`}];try{let e=await V.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});Je.current=n,n.onconnectionstatechange=()=>{let e=n.connectionState;if(e===`connected`){let e=new Date().toISOString();Re(`connected`),Be(t=>t||e),Tt(e);return}if(e===`connecting`){Re(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&wt(`peer:connection_${e}`)},n.oniceconnectionstatechange=()=>{let e=n.iceConnectionState;if(e===`connected`||e===`completed`){let e=new Date().toISOString();Re(`connected`),Be(t=>t||e),Tt(e);return}if(e===`checking`||e===`new`){Re(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&wt(`peer:ice_${e}`)},n.onsignalingstatechange=()=>{},n.onicegatheringstatechange=()=>{},e.getTracks().forEach(t=>{n.addTrack(t,e)}),n.onicecandidate=e=>{if(!e.candidate||!B.current?.connected)return;let t=e.candidate;B.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(!Xe.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=>{},Xe.current=e,document.body.appendChild(e)}Xe.current.srcObject=e.streams[0];let r=z?.callId,i=r&&(it.current===r||rt.current===r);if(!ot.current&&i){let e=new Date().toISOString();Re(`connected`),Be(t=>t||e),rt.current=r,Ie(r),Tt(e)}Xe.current.srcObject=t||null;let a=Xe.current.play?.();a?.catch&&a.catch(e=>{})};let r=Ze.current;r&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:r.callId||z.callId,chatId:g}),await Ot({...r,callId:r.callId||z.callId})),await V.current.acceptCall(z.callId,g),B.current?.emit(`call:accepted`,{callId:z.callId,chatId:g}),rt.current=z.callId,Ie(z.callId),Re(e=>e===`connected`||ot.current?`connected`:`connecting`),Pe(null),A(!0)}catch(e){if(it.current=null,wt(`accept_call_failed`),e?.status===404||e?.status===409||e?.status===422){We(Zr(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await V.current.rejectCall(z.callId,g)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}We(`Microphone access was denied. Please allow microphone access to accept the call.`);return}We(`We couldn't connect the call right now. Please try again.`)}}},jt=async()=>{if(!z?.callId||!V.current||!g){wt(`reject_call_without_server_context`);return}let e=z.callId;St(),xt(),B.current?.emit(`call:rejected`,{callId:e,chatId:g,reason:`visitor_declined`});try{await V.current.rejectCall(e,g)}catch(e){We(Zr(e,`We couldn't decline the call cleanly.`))}finally{wt(`reject_call_finally`)}},Mt=(0,d.useRef)(jt);Mt.current=jt,(0,d.useEffect)(()=>{if(!z?.callId||Fe){St();return}let e=z.callId;return St(),at.current=window.setTimeout(()=>{W.current?.callId===e&&it.current!==e&&rt.current!==e&&Mt.current()},b),()=>{at.current&&=(window.clearTimeout(at.current),null)}},[Fe,St,z?.callId]);let Nt=async()=>{if(!Fe||!V.current||!g){wt(`end_call_without_server_context`);return}xt();try{await V.current.endWebRTCCall(Fe,g)}catch(e){We(Zr(e,`The call ended locally, but the server could not be updated.`))}finally{wt(`end_call_finally`)}},Pt=()=>{let e=Ye.current?.getAudioTracks?.()||[],t=Je.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0)return;let r=!Ve;n.forEach(e=>{e.enabled=!r}),He(r)},Ft=async(e={})=>{let t=e.notifyChatInitiated===!0;if(A(!0),!(!t||!V.current||!g||typeof window>`u`)){try{await V.current.trackVisitor({chatId:g,currentPagePath:window.location.pathname||`/`})}catch{}try{await V.current.updateChatStatus(g,`open`)}catch{}}},It=async e=>{let t=Ct(e);if(!t||!V.current||!H.current)return t;try{await V.current.trackVisitor({chatId:H.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Lt=()=>{!g||!B.current?.connected||st.current||(st.current=!0,B.current.emit(`typing:start`,{chatId:g,sender:`user`}))},Rt=()=>{!g||!B.current?.connected||!st.current||(st.current=!1,B.current.emit(`typing:stop`,{chatId:g,sender:`user`}))},zt=(e=``)=>{let t=typeof e==`string`?e:``;!g||!B.current?.connected||t!==``&&ct.current===t||(ct.current=t,B.current.emit(`typing:update`,{chatId:g,sender:`user`,text:t}))};function Bt(){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 Vt=async(e,t=``,n=null,i={})=>{let a=typeof e==`string`?e.trim():``;if(!a||!V.current||!g||s!==`ready`||Me)return;Rt(),$e.current=!1;let o=/^\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,c=/^\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,l=/\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(Qe.current&&o.test(a)&&!c.test(a)){let{url:e,section:t}=Qe.current;Qe.current=null,$e.current=!0,console.log(`[FWH Nav] Client-side nav firing →`,e),tt(e,{voiceActive:gt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?E():n===`already-on-page`&&te();return}!t||!gt.current||setTimeout(()=>{let e=Xn(null,t);e&&Zn(e)},300)})}else o.test(a)||(Qe.current=null);let d=`pending-user-${Date.now()}`,f={id:d,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,type:i?.type||`text`,metadata:i?.metadata||void 0,...n||{}};S(e=>[...e,f]);let p=M;if(p)try{p=yt(await V.current.checkHumanHandled(g))}catch{}if(p&&B.current?.connected){B.current.emit(`customer:message`,{chatId:g,content:e,sender:`user`,email:fe||void 0,type:i?.type||`text`,metadata:i?.metadata||{},...n||{}});return}be(!0);try{let o=await Tr(),s=Cr(),c=`stream-preview-${Date.now().toString(36)}`,u=e=>{_e(!1),S(t=>{let n=t.findIndex(e=>e.id===c);if(n===-1)return[...t,{id:c,sender:`bot`,message:e,timestamp:new Date().toISOString(),isStreaming:!0}];let r=[...t];return r[n]={...r[n],message:r[n].message+e},r})},d=await V.current.sendAiMessage(g,e,r,t,{...n||{},...fe?{email:fe}:{}},{...i,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:Bt()||void 0,...o?{shopifyCart:o}:{},...s?{shopifyCustomerId:s}:{}},u),f=d.chat_history||[];if(console.log(`[FWH Nav Debug] API response fields:`,{has_navigate:!!d.navigate,navigate:d.navigate,has_pending_navigate:!!d.pending_navigate,pending_navigate:d.pending_navigate,last_bot_msg:[...f].reverse().find(e=>e.sender===`bot`)?.message?.substring(0,80)}),d.pending_navigate?.url){let e={url:d.pending_navigate.url,section:d.pending_navigate.section||null};l.test(a)?(console.log(`[FWH Nav] Auto-navigating (intent detected) →`,e.url),tt(e.url,{voiceActive:gt.current}).then(({navigated:t,reason:n})=>{if(!t){n===`not-found`?E():n===`already-on-page`&&te();return}e.section&&setTimeout(()=>{let t=Xn(null,e.section);t&&Zn(t)},300)})):(Qe.current=e,console.log(`[FWH Nav] Stored pending nav →`,Qe.current))}if(d.navigate?.url)if($e.current)$e.current=!1;else{let{url:e,section:t}=d.navigate;tt(e,{voiceActive:gt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?E():n===`already-on-page`&&te();return}t&&setTimeout(()=>{let e=Xn(null,t);e&&Zn(e)},300)})}else if(d.highlight?.section){let e=d.highlight.section;setTimeout(()=>{let t=Xn(null,e);t&&Zn(t)},150)}else{let e=[...f].reverse().find(e=>e.sender===`bot`||e.sender===`assistant`);if(e?.message){let t=Xr(e.message);t&&tr(t.url,{siteId:_t.current?.siteId,apiBaseUrl:_t.current?.apiBaseUrl}).then(({allowed:e,correctedUrl:n})=>{if(!e){E();return}tt(n||t.url,{voiceActive:gt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?E():n===`already-on-page`&&te();return}!t.section||!gt.current||setTimeout(()=>{let e=Xn(null,t.section);e&&Zn(e)},300)})})}}S(Yr(f)),Array.isArray(d.cart_actions)&&d.cart_actions.length&&ee(d.cart_actions),N(!!d.is_human_handled),j(d.is_human_handled?`agent`:`ai`),_e(!1),be(!1),await V.current.updateChatStatus(g,`messageSent`)}catch(e){S(e=>e.filter(e=>e.id!==d&&!e.isStreaming)),_e(!1),be(!1),e.status===429?(Se(!0),Ee(e.message),window.setTimeout(()=>{Se(!1),Ee(``)},v)):u(e)}},Ht=async e=>{if(!V.current||!e)throw Error(`Upload is unavailable right now.`);return V.current.uploadChatFile(e)},Ut=async e=>{if(!(!V.current||!g)){try{let t=e?`voice`:`text`;await V.current.setChatMode(g,t)}catch{}Oe(e),e&&(ht.current=!1)}},Wt=async e=>{if(ht.current)return;if(ht.current=!0,!V.current||!g||!e?.length){Oe(!1);return}let t=()=>{let t=Yr(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 V.current.syncVoice(g,e);if(n?.chat_history?.length)S(Yr(n.chat_history));else if(n?.success)try{let e=await V.current.loadHistory(g,r);e?.chat_history?.length?S(Yr(e.chat_history)):t()}catch{t()}else t()}catch{t()}finally{Oe(!1)}},G=async()=>{if(!(!V.current||!g)){De&&!ht.current&&mt.current.length>0&&await Wt(mt.current);try{await V.current.endConversation(g)}catch{try{await V.current.updateChatStatus(g,`ended`)}catch{}}Ne(!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(Le!==`connected`||!Fe||!g||!ze||!bt)return;let e=new Date(ze).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,bt*1e3-t),r=window.setTimeout(()=>{We(`The call ended because it reached the time limit.`),Nt()},n);return()=>window.clearTimeout(r)},[Fe,ze,Le,g,Nt,bt]),(0,d.useEffect)(()=>{let e=()=>{let e=H.current,t=V.current;if(!t||!e)return;if(gt.current&&mt.current.length>0&&me(),!ht.current&&mt.current.length>0&&(t.beaconSyncVoice(e,mt.current)||t.syncVoice(e,mt.current).catch(()=>{}),ht.current=!0),rt.current){t.beaconEndWebRTCCall(rt.current,e);return}let n=it.current||W.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 Gt=(0,d.useCallback)(()=>{let e=i?.siteId;re(e),qe.current=!0,U.current=null,B.current?.disconnect(),S([]),_(``),H.current=``,Ne(!1),N(!1),le(null),de(null),Ke(!0),o(e=>e+1)},[i?.siteId]),Kt=(0,d.useCallback)(e=>{i?.siteId,qe.current=!1,U.current=e,B.current?.disconnect(),S([]),_(``),H.current=``,Ne(!1),N(!1),le(null),de(null),Ke(!0),o(e=>e+1)},[i?.siteId]),qt=(0,d.useMemo)(()=>({status:s,error:l,runtimeConfig:m,resolvedConfig:i,chatId:g,chatHistory:x,isOpen:D,activeScreen:se,isHumanHandled:M,agentName:P,agentHeadshot:ue,visitorEmail:fe,isAgentTyping:he,isAiTyping:ge,connectionStatus:ve,isLoading:I,isVoiceMode:De,isRateLimited:xe,rateLimitMessage:L,isConversationEnded:Me,isSessionRestoring:Ge,openToChatCounter:ke,voiceEndCounter:Ae,incomingCall:z,activeCallId:Fe,callConnectionState:Le,callConnectedAt:ze,isCallMuted:Ve,webRTCError:Ue,language:r,historyRef:mt,hasSyncedRef:ht,dismissCallError:xt,captureVisitorEmail:It,startTyping:Lt,stopTyping:Rt,updateTypingDraft:zt,notifyRouteChange:()=>vt.current?.notifyRouteChange?.(),openWidget:Ft,closeWidget:()=>A(!1),toggleWidget:()=>{if(D){A(!1);return}Ft({notifyChatInitiated:!0})},sendMessage:Vt,uploadChatFile:Ht,setVoiceMode:Ut,onMessageSync:Wt,endConversation:G,startNewChat:Gt,resumeChat:Kt,getVisitorChatHistory:()=>V.current?.getVisitorChatHistory?.(),getVisitorChatThread:e=>V.current?.getVisitorChatThread?.(e),acceptCall:At,rejectCall:jt,endWebRTCCall:Nt,toggleCallMute:Pt}),[s,l,m,i,g,x,D,se,M,P,ue,fe,he,ge,ve,I,De,xe,L,Me,Ge,ke,Ae,z,Fe,Le,ze,Ve,Ue,r,It,Lt,Rt,zt,At,jt,Nt,Pt,Ft,Vt,Ht,Ut,Wt,G,Gt,xt]);return(0,f.jsx)(un.Provider,{value:qt,children:n})}var ni=(0,d.createContext)({});function ri(e){let t=(0,d.useRef)(null);return t.current===null&&(t.current=e()),t.current}var ii=typeof window<`u`?d.useLayoutEffect:d.useEffect,ai=(0,d.createContext)(null);function oi(e,t){e.indexOf(t)===-1&&e.push(t)}function si(e,t){let n=e.indexOf(t);n>-1&&e.splice(n,1)}var ci=(e,t,n)=>n>t?t:n<e?e:n;function li(e,t){return t?`${e}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${t}`:e}var ui=()=>{},di=()=>{};typeof process<`u`&&process.env.NODE_ENV!==`production`&&(ui=(e,t,n)=>{!e&&typeof console<`u`&&console.warn(li(t,n))},di=(e,t,n)=>{if(!e)throw Error(li(t,n))});var fi={},pi=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function mi(e){return typeof e==`object`&&!!e}var hi=e=>/^0[^.\s]+$/u.test(e);function gi(e){let t;return()=>(t===void 0&&(t=e()),t)}var _i=e=>e,vi=(e,t)=>n=>t(e(n)),yi=(...e)=>e.reduce(vi),bi=(e,t,n)=>{let r=t-e;return r===0?1:(n-e)/r},xi=class{constructor(){this.subscriptions=[]}add(e){return oi(this.subscriptions,e),()=>si(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}},Si=e=>e*1e3,Ci=e=>e/1e3;function wi(e,t){return t?1e3/t*e:0}var Ti=new Set;function Ei(e,t,n){e||Ti.has(t)||(console.warn(li(t,n)),Ti.add(t))}var Di=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Oi=1e-7,ki=12;function Ai(e,t,n,r,i){let a,o,s=0;do o=t+(n-t)/2,a=Di(o,r,i)-e,a>0?n=o:t=o;while(Math.abs(a)>Oi&&++s<ki);return o}function ji(e,t,n,r){if(e===t&&n===r)return _i;let i=t=>Ai(t,0,1,e,n);return e=>e===0||e===1?e:Di(i(e),t,r)}var Mi=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Ni=e=>t=>1-e(1-t),Pi=ji(.33,1.53,.69,.99),Fi=Ni(Pi),Ii=Mi(Fi),Li=e=>e>=1?1:(e*=2)<1?.5*Fi(e):.5*(2-2**(-10*(e-1))),Ri=e=>1-Math.sin(Math.acos(e)),zi=Ni(Ri),Bi=Mi(Ri),Vi=ji(.42,0,1,1),Hi=ji(0,0,.58,1),Ui=ji(.42,0,.58,1),Wi=e=>Array.isArray(e)&&typeof e[0]!=`number`,Gi=e=>Array.isArray(e)&&typeof e[0]==`number`,Ki={linear:_i,easeIn:Vi,easeInOut:Ui,easeOut:Hi,circIn:Ri,circInOut:Bi,circOut:zi,backIn:Fi,backInOut:Ii,backOut:Pi,anticipate:Li},qi=e=>typeof e==`string`,Ji=e=>{if(Gi(e)){di(e.length===4,`Cubic bezier arrays must contain four numerical values.`,`cubic-bezier-length`);let[t,n,r,i]=e;return ji(t,n,r,i)}else if(qi(e))return di(Ki[e]!==void 0,`Invalid easing type '${e}'`,`invalid-easing-type`),Ki[e];return e},Yi=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`],Xi={value:null,addProjectionMetrics:null};function Zi(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&&Xi.value&&Xi.value.frameloop[t].push(c),c=0,n.clear(),i=!1,a&&(a=!1,u.process(e))}};return u}var Qi=40;function $i(e,t){let n=!1,r=!0,i={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,o=Yi.reduce((e,n)=>(e[n]=Zi(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=fi.useManualTiming,o=a?i.timestamp:performance.now();n=!1,a||(i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,Qi),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:Yi.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<Yi.length;t++)o[Yi[t]].cancel(e)},state:i,steps:o}}var{schedule:q,cancel:ea,state:ta,steps:na}=$i(typeof requestAnimationFrame<`u`?requestAnimationFrame:_i,!0),ra;function ia(){ra=void 0}var aa={now:()=>(ra===void 0&&aa.set(ta.isProcessing||fi.useManualTiming?ta.timestamp:performance.now()),ra),set:e=>{ra=e,queueMicrotask(ia)}},oa={layout:0,mainThread:0,waapi:0},sa=e=>t=>typeof t==`string`&&t.startsWith(e),ca=sa(`--`),la=sa(`var(--`),ua=e=>la(e)?da.test(e.split(`/*`)[0].trim()):!1,da=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function fa(e){return typeof e==`string`?e.split(`/*`)[0].includes(`var(--`):!1}var pa={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},ma={...pa,transform:e=>ci(0,1,e)},ha={...pa,default:1},ga=e=>Math.round(e*1e5)/1e5,_a=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function va(e){return e==null}var ya=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ba=(e,t)=>n=>!!(typeof n==`string`&&ya.test(n)&&n.startsWith(e)||t&&!va(n)&&Object.prototype.hasOwnProperty.call(n,t)),xa=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(_a);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},Sa=e=>ci(0,255,e),Ca={...pa,transform:e=>Math.round(Sa(e))},wa={test:ba(`rgb`,`red`),parse:xa(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Ca.transform(e)+`, `+Ca.transform(t)+`, `+Ca.transform(n)+`, `+ga(ma.transform(r))+`)`};function Ta(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 Ea={test:ba(`#`),parse:Ta,transform:wa.transform},Da=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Oa=Da(`deg`),ka=Da(`%`),J=Da(`px`),Aa=Da(`vh`),ja=Da(`vw`),Ma={...ka,parse:e=>ka.parse(e)/100,transform:e=>ka.transform(e*100)},Na={test:ba(`hsl`,`hue`),parse:xa(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+ka.transform(ga(t))+`, `+ka.transform(ga(n))+`, `+ga(ma.transform(r))+`)`},Y={test:e=>wa.test(e)||Ea.test(e)||Na.test(e),parse:e=>wa.test(e)?wa.parse(e):Na.test(e)?Na.parse(e):Ea.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?wa.transform(e):Na.transform(e),getAnimatableNone:e=>{let t=Y.parse(e);return t.alpha=0,Y.transform(t)}},Pa=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Fa(e){return isNaN(e)&&typeof e==`string`&&(e.match(_a)?.length||0)+(e.match(Pa)?.length||0)>0}var Ia=`number`,La=`color`,Ra=`var`,za=`var(`,Ba="${}",Va=/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 Ha(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(Va,e=>(Y.test(e)?(r.color.push(a),i.push(La),n.push(Y.parse(e))):e.startsWith(za)?(r.var.push(a),i.push(Ra),n.push(e)):(r.number.push(a),i.push(Ia),n.push(parseFloat(e))),++a,Ba)).split(Ba),indexes:r,types:i}}function Ua(e){return Ha(e).values}function Wa({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===Ia?i+=ga(r[a]):e===La?i+=Y.transform(r[a]):i+=r[a]}return i}}function Ga(e){return Wa(Ha(e))}var Ka=e=>typeof e==`number`?0:Y.test(e)?Y.getAnimatableNone(e):e,qa=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:Ka(e);function Ja(e){let t=Ha(e);return Wa(t)(t.values.map((e,n)=>qa(e,t.split[n])))}var Ya={test:Fa,parse:Ua,createTransformer:Ga,getAnimatableNone:Ja};function Xa(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 Za({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=Xa(s,r,e+1/3),a=Xa(s,r,e),o=Xa(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function Qa(e,t){return n=>n>0?t:e}var X=(e,t,n)=>e+(t-e)*n,$a=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},eo=[Ea,wa,Na],to=e=>eo.find(t=>t.test(e));function no(e){let t=to(e);if(ui(!!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===Na&&(n=Za(n)),n}var ro=(e,t)=>{let n=no(e),r=no(t);if(!n||!r)return Qa(e,t);let i={...n};return e=>(i.red=$a(n.red,r.red,e),i.green=$a(n.green,r.green,e),i.blue=$a(n.blue,r.blue,e),i.alpha=X(n.alpha,r.alpha,e),wa.transform(i))},io=new Set([`none`,`hidden`]);function ao(e,t){return io.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function oo(e,t){return n=>X(e,t,n)}function so(e){return typeof e==`number`?oo:typeof e==`string`?ua(e)?Qa:Y.test(e)?ro:fo:Array.isArray(e)?co:typeof e==`object`?Y.test(e)?ro:lo:Qa}function co(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>so(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function lo(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=so(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function uo(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=Ya.createTransformer(t),r=Ha(e),i=Ha(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?io.has(e)&&!i.values.length||io.has(t)&&!r.values.length?ao(e,t):yi(co(uo(r,i),i.values),n):(ui(!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`),Qa(e,t))};function po(e,t,n){return typeof e==`number`&&typeof t==`number`&&typeof n==`number`?X(e,t,n):so(e)(e,t)}var mo=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>q.update(t,e),stop:()=>ea(t),now:()=>ta.isProcessing?ta.timestamp:aa.now()}},ho=(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)})`},go=2e4;function _o(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(_o(r),go);return{type:`keyframes`,ease:e=>r.next(i*e).value/t,duration:Ci(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 yo(e,t){return e*Math.sqrt(1-t*t)}var bo=12;function xo(e,t,n){let r=n;for(let n=1;n<bo;n++)r-=e(r)/t(r);return r}var So=.001;function Co({duration:e=Z.duration,bounce:t=Z.bounce,velocity:n=Z.velocity,mass:r=Z.mass}){let i,a;ui(e<=Si(Z.maxDuration),`Spring duration must be 10 seconds or less`,`spring-duration-limit`);let o=1-t;o=ci(Z.minDamping,Z.maxDamping,o),e=ci(Z.minDuration,Z.maxDuration,Ci(e)),o<1?(i=t=>{let r=t*o,i=r*e,a=r-n,s=yo(t,o),c=Math.exp(-i);return So-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=yo(t**2,o);return(-i(t)+So>0?-1:1)*((a-s)*c)/l}):(i=t=>{let r=Math.exp(-t*e),i=(t-n)*e+1;return-So+r*i},a=t=>Math.exp(-t*e)*((n-t)*(e*e)));let s=5/e,c=xo(i,a,s);if(e=Si(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 wo=[`duration`,`bounce`],To=[`stiffness`,`damping`,`mass`];function Eo(e,t){return t.some(t=>e[t]!==void 0)}function Do(e){let t={velocity:Z.velocity,stiffness:Z.stiffness,damping:Z.damping,mass:Z.mass,isResolvedFromDuration:!1,...e};if(!Eo(e,To)&&Eo(e,wo))if(t.velocity=0,e.visualDuration){let n=e.visualDuration,r=2*Math.PI/(n*1.2),i=r*r,a=2*ci(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:Z.mass,stiffness:i,damping:a}}else{let n=Co({...e,velocity:0});t={...t,...n,mass:Z.mass},t.isResolvedFromDuration=!0}return t}function Oo(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}=Do({...n,velocity:-Ci(n.velocity||0)}),m=f||0,h=l/(2*Math.sqrt(c*u)),g=o-a,_=Ci(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=yo(_,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=>Si(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=Si(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=Si(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(_o(T),go),t=ho(t=>T.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return T}Oo.applyToOptions=e=>{let t=vo(e,100,Oo);return e.ease=t.ease,e.duration=Si(t.duration),e.type=`keyframes`,e};var ko=5;function Ao(e,t,n){let r=Math.max(t-ko,0);return wi(n-e(r),t-r)}function jo({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=Oo({keyframes:[f.value,m(f.value)],velocity:Ao(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 Mo(e,t,n){let r=[],i=n||fi.mix||po,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=yi(Array.isArray(t)?t[n]||_i:t,a)),r.push(a)}return r}function No(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(di(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=Mo(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=bi(e[r],e[r+1],n);return s[r](i)};return n?t=>l(ci(e[0],e[a-1],t)):l}function Po(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=bi(0,t,r);e.push(X(n,1,i))}}function Fo(e){let t=[0];return Po(t,e.length-1),t}function Io(e,t){return e.map(e=>e*t)}function Lo(e,t){return e.map(()=>t||Ui).splice(0,e.length-1)}function Ro({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=Wi(r)?r.map(Ji):Ji(r),a={done:!1,value:t[0]},o=No(Io(n&&n.length===t.length?n:Fo(t),e),t,{ease:Array.isArray(i)?i:Lo(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var zo=e=>e!==null;function Bo(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(zo),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var Vo={decay:jo,inertia:jo,tween:Ro,keyframes:Ro,spring:Oo};function Ho(e){typeof e.type==`string`&&(e.type=Vo[e.type])}var Uo=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)}},Wo=e=>e/100,Go=class extends Uo{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!==aa.now()&&this.tick(aa.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;Ho(e);let{type:t=Ro,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||Ro;process.env.NODE_ENV!==`production`&&s!==Ro&&di(o.length<=2,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${o}`,`spring-two-frames`),s!==Ro&&typeof o[0]!=`number`&&(this.mixKeyframes=yi(Wo,po(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=_o(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=ci(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!==jo&&(b.value=Bo(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 Ci(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Ci(e)}get time(){return Ci(this.currentTime)}set time(e){e=Si(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 Ao(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(aa.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=Ci(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=mo,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(aa.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 Ko(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var qo=e=>e*180/Math.PI,Jo=e=>Xo(qo(Math.atan2(e[1],e[0]))),Yo={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Jo,rotateZ:Jo,skewX:e=>qo(Math.atan(e[1])),skewY:e=>qo(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Xo=e=>(e%=360,e<0&&(e+=360),e),Zo=Jo,Qo=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),$o=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),es={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Qo,scaleY:$o,scale:e=>(Qo(e)+$o(e))/2,rotateX:e=>Xo(qo(Math.atan2(e[6],e[5]))),rotateY:e=>Xo(qo(Math.atan2(-e[2],e[0]))),rotateZ:Zo,rotate:Zo,skewX:e=>qo(Math.atan(e[4])),skewY:e=>qo(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function ts(e){return e.includes(`scale`)?1:0}function ns(e,t){if(!e||e===`none`)return ts(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=es,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=Yo,i=t}if(!i)return ts(t);let a=r[t],o=i[1].split(`,`).map(is);return typeof a==`function`?a(o):o[a]}var rs=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return ns(n,t)};function is(e){return parseFloat(e.trim())}var as=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],os=new Set(as),ss=e=>e===pa||e===J,cs=new Set([`x`,`y`,`z`]),ls=as.filter(e=>!cs.has(e));function us(e){let t=[];return ls.forEach(n=>{let r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith(`scale`)?1:0))}),t}var ds={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})=>ns(t,`x`),y:(e,{transform:t})=>ns(t,`y`)};ds.translateX=ds.x,ds.translateY=ds.y;var fs=new Set,ps=!1,ms=!1,hs=!1;function gs(){if(ms){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=us(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)})}ms=!1,ps=!1,fs.forEach(e=>e.complete(hs)),fs.clear()}function _s(){fs.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(ms=!0)})}function vs(){hs=!0,_s(),gs(),hs=!1}var ys=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),ps||(ps=!0,q.read(_s),q.resolveKeyframes(gs))):(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])}Ko(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()}},bs=e=>e.startsWith(`--`);function xs(e,t,n){bs(t)?e.style.setProperty(t,n):e.style[t]=n}var Ss={};function Cs(e,t){let n=gi(e);return()=>Ss[t]??n()}var ws=Cs(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),Ts=Cs(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),Es=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,Ds={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:Es([0,.65,.55,1]),circOut:Es([.55,0,1,.45]),backIn:Es([.31,.01,.66,-.59]),backOut:Es([.33,1.53,.69,.99])};function Os(e,t){if(e)return typeof e==`function`?Ts()?ho(e,t):`ease-out`:Gi(e)?Es(e):Array.isArray(e)?e.map(e=>Os(e,t)||Ds.easeOut):Ds[e]}function ks(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=Os(s,i);Array.isArray(d)&&(u.easing=d),Xi.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 Xi.value&&p.finished.finally(()=>{oa.waapi--}),p}function As(e){return typeof e==`function`&&`applyToOptions`in e}function js({type:e,...t}){return As(e)&&Ts()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var Ms=class extends Uo{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,di(typeof e.type!=`string`,`Mini animate() doesn't support "type" as a string.`,`mini-spring`);let c=js(e);this.animation=ks(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=Bo(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),xs(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 Ci(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Ci(e)}get time(){return Ci(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Si(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&&ws()?(this.animation.timeline=e,t&&(this.animation.rangeStart=t),n&&(this.animation.rangeEnd=n),_i):r(this)}},Ns={anticipate:Li,backInOut:Ii,circInOut:Bi};function Ps(e){return e in Ns}function Fs(e){typeof e.ease==`string`&&Ps(e.ease)&&(e.ease=Ns[e.ease])}var Is=10,Ls=class extends Ms{constructor(e){Fs(e),Ho(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 Go({...a,autoplay:!1}),s=Math.max(Is,aa.now()-this.startTime),c=ci(0,Is,s-Is),l=o.sample(s).value,{name:u}=this.options;i&&u&&xs(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},Rs=(e,t)=>t===`zIndex`?!1:!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(Ya.test(e)||e===`0`)&&!e.startsWith(`url(`));function zs(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 Bs(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=Rs(i,t),s=Rs(a,t);return ui(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:zs(e)||(n===`spring`||As(n))&&r}function Vs(e){e.duration=0,e.type=`keyframes`}var Hs=new Set([`opacity`,`clipPath`,`filter`,`transform`]),Us=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function Ws(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&Us.test(e[t]))return!0;return!1}var Gs=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),Ks=gi(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function qs(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 Ks()&&n&&(Hs.has(n)||Gs.has(n)&&Ws(s))&&(n!==`transform`||!l)&&!c&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var Js=40,Ys=class extends Uo{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=aa.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||ys)(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=aa.now();let u=!0;Bs(e,i,a,o)||(u=!1,(fi.instantAnimations||!s)&&l?.(Bo(e,n,t)),e[0]=e[e.length-1],Vs(n),n.repeat=0);let d={startTime:r?this.resolvedAt&&this.resolvedAt-this.createdAt>Js?this.resolvedAt:this.createdAt:void 0,finalKeyframe:t,...n,keyframes:e},f=u&&!c&&qs(d),p=d.motionValue?.owner?.current,m;if(f)try{m=new Ls({...d,element:p})}catch{m=new Go(d)}else m=new Go(d);m.finished.then(()=>{this.notifyFinished()}).catch(_i),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 Xs(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 Zs=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Qs(e){let t=Zs.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}var $s=4;function ec(e,t,n=1){di(n<=$s,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`,`max-css-var-depth`);let[r,i]=Qs(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return pi(e)?parseFloat(e):e}return ua(i)?ec(i,t,n+1):i}var tc={type:`spring`,stiffness:500,damping:25,restSpeed:10},nc=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),rc={type:`keyframes`,duration:.8},ic={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},ac=(e,{keyframes:t})=>t.length>2?rc:os.has(e)?e.startsWith(`scale`)?nc(t[1]):tc:ic;function oc(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function sc(e,t){let n=e?.[t]??e?.default??e;return n===e?n:oc(n,e)}var cc=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function lc(e){for(let t in e)if(!cc.has(t))return!0;return!1}var uc=(e,t,n,r={},i,a)=>o=>{let s=sc(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=Si(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};lc(s)||Object.assign(u,ac(e,u)),u.duration&&=Si(u.duration),u.repeatDelay&&=Si(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(Vs(u),u.delay===0&&(d=!0)),(fi.instantAnimations||fi.skipAnimations||i?.shouldSkipAnimations)&&(d=!0,Vs(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=Bo(u.keyframes,s);if(e!==void 0){q.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new Go(u):new Ys(u)};function dc(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]=dc(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]=dc(r);t=t(n===void 0?e.custom:n,i,a)}return t}function pc(e,t,n){let r=e.getProps();return fc(r,t,n===void 0?r.custom:n,e)}var mc=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...as]),hc=30,gc=e=>!isNaN(parseFloat(e)),_c={current:void 0},vc=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=aa.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=aa.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=gc(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return process.env.NODE_ENV!==`production`&&Ei(!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 xi);let n=this.events[e].add(t);return e===`change`?()=>{n(),q.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 _c.current&&_c.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=aa.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>hc)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,hc);return wi(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 yc(e,t){return new vc(e,t)}var bc=e=>Array.isArray(e);function xc(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,yc(n))}function Sc(e){return bc(e)?e[e.length-1]||0:e}function Cc(e,t){let{transitionEnd:n={},transition:r={},...i}=pc(e,t)||{};i={...i,...n};for(let t in i)xc(e,t,Sc(i[t]))}var wc=e=>!!(e&&e.getVelocity);function Tc(e){return!!(wc(e)&&e.add)}function Ec(e,t){let n=e.getValue(`willChange`);if(Tc(n))return n.add(t);if(!n&&fi.WillChange){let n=new fi.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function Dc(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var Oc=`data-`+Dc(`framerAppearId`);function kc(e){return e.props[Oc]}function Ac({protectedKeys:e,needsAnimating:t},n){let r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function jc(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&&Ac(d,t))continue;let o={delay:n,...sc(a||{},t)},c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){q.update(()=>r.set(i));continue}let f=!1;if(window.MotionHandoffAnimation){let n=kc(e);if(n){let e=window.MotionHandoffAnimation(n,t,q);e!==null&&(o.startTime=e,f=!0)}}Ec(e,t);let p=l??e.shouldReduceMotion;r.start(uc(t,r,i,p&&mc.has(t)?{type:!1}:o,e,f));let m=r.animation;m&&u.push(m)}if(o){let t=()=>q.update(()=>{o&&Cc(e,o)});u.length?Promise.all(u).then(t):t()}return u}function Mc(e,t,n={}){let r=pc(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(jc(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{let{delayChildren:a=0,staggerChildren:o,staggerDirection:s}=i;return Nc(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 Nc(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(Mc(c,t,{...o,delay:n+(typeof r==`function`?0:r)+Xs(e.variantChildren,c,r,i,a)}).then(()=>c.notify(`AnimationComplete`,t)));return Promise.all(s)}function Pc(e,t,n={}){e.notify(`AnimationStart`,t);let r;if(Array.isArray(t)){let i=t.map(t=>Mc(e,t,n));r=Promise.all(i)}else if(typeof t==`string`)r=Mc(e,t,n);else{let i=typeof t==`function`?pc(e,t,n.custom):t;r=Promise.all(jc(e,i,n))}return r.then(()=>{e.notify(`AnimationComplete`,t)})}var Fc={test:e=>e===`auto`,parse:e=>e},Ic=e=>t=>t.test(e),Lc=[pa,J,ka,Oa,ja,Aa,Fc],Rc=e=>Lc.find(Ic(e));function zc(e){return typeof e==`number`?e===0:e===null?!0:e===`none`||e===`0`||hi(e)}var Bc=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function Vc(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(_a)||[];if(!r)return e;let i=n.replace(r,``),a=Bc.has(t)?1:0;return r!==n&&(a*=100),t+`(`+a+i+`)`}var Hc=/\b([a-z-]*)\(.*?\)/gu,Uc={...Ya,getAnimatableNone:e=>{let t=e.match(Hc);return t?t.map(Vc).join(` `):e}},Wc={...Ya,getAnimatableNone:e=>{let t=Ya.parse(e);return Ya.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},Gc={...pa,transform:Math.round},Kc={borderWidth:J,borderTopWidth:J,borderRightWidth:J,borderBottomWidth:J,borderLeftWidth:J,borderRadius:J,borderTopLeftRadius:J,borderTopRightRadius:J,borderBottomRightRadius:J,borderBottomLeftRadius:J,width:J,maxWidth:J,height:J,maxHeight:J,top:J,right:J,bottom:J,left:J,inset:J,insetBlock:J,insetBlockStart:J,insetBlockEnd:J,insetInline:J,insetInlineStart:J,insetInlineEnd:J,padding:J,paddingTop:J,paddingRight:J,paddingBottom:J,paddingLeft:J,paddingBlock:J,paddingBlockStart:J,paddingBlockEnd:J,paddingInline:J,paddingInlineStart:J,paddingInlineEnd:J,margin:J,marginTop:J,marginRight:J,marginBottom:J,marginLeft:J,marginBlock:J,marginBlockStart:J,marginBlockEnd:J,marginInline:J,marginInlineStart:J,marginInlineEnd:J,fontSize:J,backgroundPositionX:J,backgroundPositionY:J,rotate:Oa,rotateX:Oa,rotateY:Oa,rotateZ:Oa,scale:ha,scaleX:ha,scaleY:ha,scaleZ:ha,skew:Oa,skewX:Oa,skewY:Oa,distance:J,translateX:J,translateY:J,translateZ:J,x:J,y:J,z:J,perspective:J,transformPerspective:J,opacity:ma,originX:Ma,originY:Ma,originZ:J,zIndex:Gc,fillOpacity:ma,strokeOpacity:ma,numOctaves:Gc},qc={...Kc,color:Y,backgroundColor:Y,outlineColor:Y,fill:Y,stroke:Y,borderColor:Y,borderTopColor:Y,borderRightColor:Y,borderBottomColor:Y,borderLeftColor:Y,filter:Uc,WebkitFilter:Uc,mask:Wc,WebkitMask:Wc},Jc=e=>qc[e],Yc=new Set([Uc,Wc]);function Xc(e,t){let n=Jc(e);return Yc.has(n)||(n=Ya),n.getAnimatableNone?n.getAnimatableNone(t):void 0}var Zc=new Set([`auto`,`none`,`0`]);function Qc(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!Zc.has(t)&&Ha(t).values.length&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]=Xc(n,i)}var $c=class extends ys{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(),ua(r))){let i=ec(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!mc.has(n)||e.length!==2)return;let[r,i]=e,a=Rc(r),o=Rc(i);if(fa(r)!==fa(i)&&ds[n]){this.needsMeasurement=!0;return}if(a!==o)if(ss(a)&&ss(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else ds[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||zc(e[t]))&&n.push(t);n.length&&Qc(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=ds[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]=ds[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 el(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 tl=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function nl(e){return mi(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}var{schedule:rl,cancel:il}=$i(queueMicrotask,!1),al={x:!1,y:!1};function ol(){return al.x||al.y}function sl(e){return e===`x`||e===`y`?al[e]?null:(al[e]=!0,()=>{al[e]=!1}):al.x||al.y?null:(al.x=al.y=!0,()=>{al.x=al.y=!1})}function cl(e,t){let n=el(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function ll(e){return!(e.pointerType===`touch`||ol())}function ul(e,t,n={}){let[r,i,a]=cl(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(!ll(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 dl=(e,t)=>t?e===t?!0:dl(e,t.parentElement):!1,fl=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,pl=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function ml(e){return pl.has(e.tagName)||e.isContentEditable===!0}var hl=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function gl(e){return hl.has(e.tagName)||e.isContentEditable===!0}var _l=new WeakSet;function vl(e){return t=>{t.key===`Enter`&&e(t)}}function yl(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var bl=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=vl(()=>{if(_l.has(n))return;yl(n,`down`);let e=vl(()=>{yl(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>yl(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function xl(e){return fl(e)&&!ol()}var Sl=new WeakSet;function Cl(e,t,n={}){let[r,i,a]=cl(e,n),o=e=>{let r=e.currentTarget;if(!xl(e)||Sl.has(e))return;_l.add(r),n.stopPropagation&&Sl.add(e);let a=t(r,e),o=(e,t)=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c),_l.has(r)&&_l.delete(r),xl(e)&&typeof a==`function`&&a(e,{success:t})},s=e=>{o(e,r===window||r===document||n.useGlobalTarget||dl(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),nl(e)&&(e.addEventListener(`focus`,e=>bl(e,i)),!ml(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}function wl(e){return mi(e)&&`ownerSVGElement`in e}var Tl=new WeakMap,El,Dl=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:wl(r)&&`getBBox`in r?r.getBBox()[t]:r[n],Ol=Dl(`inline`,`width`,`offsetWidth`),kl=Dl(`block`,`height`,`offsetHeight`);function Al({target:e,borderBoxSize:t}){Tl.get(e)?.forEach(n=>{n(e,{get width(){return Ol(e,t)},get height(){return kl(e,t)}})})}function jl(e){e.forEach(Al)}function Ml(){typeof ResizeObserver>`u`||(El=new ResizeObserver(jl))}function Nl(e,t){El||Ml();let n=el(e);return n.forEach(e=>{let n=Tl.get(e);n||(n=new Set,Tl.set(e,n)),n.add(t),El?.observe(e)}),()=>{n.forEach(e=>{let n=Tl.get(e);n?.delete(t),n?.size||El?.unobserve(e)})}}var Pl=new Set,Fl;function Il(){Fl=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};Pl.forEach(t=>t(e))},window.addEventListener(`resize`,Fl)}function Ll(e){return Pl.add(e),Fl||Il(),()=>{Pl.delete(e),!Pl.size&&typeof Fl==`function`&&(window.removeEventListener(`resize`,Fl),Fl=void 0)}}function Rl(e,t){return typeof e==`function`?Ll(e):Nl(e,t)}function zl(e){return wl(e)&&e.tagName===`svg`}var Bl=[...Lc,Y,Ya],Vl=e=>Bl.find(Ic(e)),Hl=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ul=()=>({x:Hl(),y:Hl()}),Wl=()=>({min:0,max:0}),Gl=()=>({x:Wl(),y:Wl()}),Kl=new WeakMap;function ql(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function Jl(e){return typeof e==`string`||Array.isArray(e)}var Yl=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],Xl=[`initial`,...Yl];function Zl(e){return ql(e.animate)||Xl.some(t=>Jl(e[t]))}function Ql(e){return!!(Zl(e)||e.variants)}function $l(e,t,n){for(let r in t){let i=t[r],a=n[r];if(wc(i))e.addValue(r,i);else if(wc(a))e.addValue(r,yc(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,yc(t===void 0?i:t,{owner:e}))}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var eu={current:null},tu={current:!1},nu=typeof window<`u`;function ru(){if(tu.current=!0,nu)if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>eu.current=e.matches;e.addEventListener(`change`,t),t()}else eu.current=!1}var iu=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],au={};function ou(e){au=e}function su(){return au}var cu=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=ys,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=aa.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,q.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=Zl(t),this.isVariantNode=Ql(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&&wc(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,Kl.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:(tu.current||ru(),this.shouldReduceMotion=eu.current),process.env.NODE_ENV!==`production`&&Ei(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(),ea(this.notifyUpdate),ea(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&&Hs.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new Ms({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:Si(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&&q.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 au){let t=au[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):Gl()}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<iu.length;t++){let n=iu[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=$l(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=yc(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)||hi(n))?n=parseFloat(n):!Vl(n)&&Ya.test(t)&&(n=Xc(e,t)),this.setBaseTarget(e,wc(n)?n.get():n)),wc(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&&!wc(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 xi),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){rl.render(this.render)}},lu=class extends cu{constructor(){super(...arguments),this.KeyframeResolver=$c}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;wc(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},uu=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function du({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 pu(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 mu(e){return e===void 0||e===1}function hu({scale:e,scaleX:t,scaleY:n}){return!mu(e)||!mu(t)||!mu(n)}function gu(e){return hu(e)||_u(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function _u(e){return vu(e.x)||vu(e.y)}function vu(e){return e&&e!==`0%`}function yu(e,t,n){return n+t*(e-n)}function bu(e,t,n,r,i){return i!==void 0&&(e=yu(e,i,r)),yu(e,n,r)+t}function xu(e,t=0,n=1,r,i){e.min=bu(e.min,t,n,r,i),e.max=bu(e.max,t,n,r,i)}function Su(e,{x:t,y:n}){xu(e.x,t.translate,t.scale,t.originPoint),xu(e.y,n.translate,n.scale,n.originPoint)}var Cu=.999999999999,wu=1.0000000000001;function Tu(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&&(Eu(e.x,-a.scroll.offset.x),Eu(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Su(e,o)),r&&gu(a.latestValues)&&ku(e,a.latestValues,a.layout?.layoutBox))}t.x<wu&&t.x>Cu&&(t.x=1),t.y<wu&&t.y>Cu&&(t.y=1)}function Eu(e,t){e.min+=t,e.max+=t}function Du(e,t,n,r,i=.5){xu(e,t,n,X(e.min,e.max,i),r)}function Ou(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function ku(e,t,n){let r=n??e;Du(e.x,Ou(t.x,r.x),t.scaleX,t.scale,t.originX),Du(e.y,Ou(t.y,r.y),t.scaleY,t.scale,t.originY)}function Au(e,t){return du(pu(e.getBoundingClientRect(),t))}function ju(e,t,n){let r=Au(e,n),{scroll:i}=t;return i&&(Eu(r.x,i.offset.x),Eu(r.y,i.offset.y)),r}var Mu={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},Nu=as.length;function Pu(e,t,n){let r=``,i=!0;for(let a=0;a<Nu;a++){let o=as[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=tl(s,Kc[o]);if(!c){i=!1;let t=Mu[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}return r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function Fu(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(ca(e)){i[e]=n;continue}else{let t=tl(n,Kc[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=Pu(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 Iu(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 Lu(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var Ru={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`)if(J.test(e))e=parseFloat(e);else return e;return`${Lu(e,t.target.x)}% ${Lu(e,t.target.y)}%`}},zu={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=Ya.parse(e);if(i.length>5)return r;let a=Ya.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)}},Bu={borderRadius:{...Ru,applyTo:[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`]},borderTopLeftRadius:Ru,borderTopRightRadius:Ru,borderBottomLeftRadius:Ru,borderBottomRightRadius:Ru,boxShadow:zu};function Vu(e,{layout:t,layoutId:n}){return os.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!Bu[e]||e===`opacity`)}function Hu(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(wc(r[t])||i&&wc(i[t])||Vu(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function Uu(e){return window.getComputedStyle(e)}var Wu=class extends lu{constructor(){super(...arguments),this.type=`html`,this.renderInstance=Iu}readValueFromInstance(e,t){if(os.has(t))return this.projection?.isProjecting?ts(t):rs(e,t);{let n=Uu(e),r=(ca(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return Au(e,t)}build(e,t,n){Fu(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return Hu(e,t,n)}},Gu={offset:`stroke-dashoffset`,array:`stroke-dasharray`},Ku={offset:`strokeDashoffset`,array:`strokeDasharray`};function qu(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?Gu:Ku;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var Ju=[`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function Yu(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(Fu(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 Ju)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&&qu(d,i,a,o,!1)}var Xu=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`]),Zu=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function Qu(e,t,n,r){Iu(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(Xu.has(n)?n:Dc(n),t.attrs[n])}function $u(e,t,n){let r=Hu(e,t,n);for(let n in e)if(wc(e[n])||wc(t[n])){let t=as.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var ed=class extends lu{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=Gl}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(os.has(t)){let e=Jc(t);return e&&e.default||0}return t=Xu.has(t)?t:Dc(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return $u(e,t,n)}build(e,t,n){Yu(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){Qu(e,t,n,r)}mount(e){this.isSVGTag=Zu(e.tagName),super.mount(e)}},td=Xl.length;function nd(e){if(!e)return;if(!e.isControllingVariants){let t=e.parent&&nd(e.parent)||{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}let t={};for(let n=0;n<td;n++){let r=Xl[n],i=e.props[r];(Jl(i)||i===!1)&&(t[r]=i)}return t}function rd(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 id=[...Yl].reverse(),ad=Yl.length;function od(e){return t=>Promise.all(t.map(({animation:t,options:n})=>Pc(e,t,n)))}function sd(e){let t=od(e),n=ud(),r=!0,i=!1,a=t=>(n,r)=>{let i=pc(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=nd(e.parent)||{},l=[],u=new Set,d={},f=1/0;for(let t=0;t<ad;t++){let p=id[t],m=n[p],h=s[p]===void 0?c[p]:s[p],g=Jl(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||ql(h)||typeof h==`boolean`)continue;if(p===`exit`&&m.isActive&&_!==!0){m.prevResolvedValues&&(d={...d,...m.prevResolvedValues});continue}let y=cd(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=bc(t)&&bc(n)?!rd(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=pc(r,t);if(r.enteringChildren&&i){let{delayChildren:t}=i.transition||{};n.delay=Xs(r.enteringChildren,e,t)}}return{animation:t,options:n}}))}if(u.size){let t={};if(typeof s.initial!=`boolean`){let n=pc(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=ud(),i=!0}}}function cd(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!rd(t,e):!1}function ld(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ud(){return{animate:ld(!0),whileInView:ld(),whileHover:ld(),whileTap:ld(),whileDrag:ld(),whileFocus:ld(),exit:ld()}}function dd(e,t){e.min=t.min,e.max=t.max}function fd(e,t){dd(e.x,t.x),dd(e.y,t.y)}function pd(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var md=1e-4,hd=1-md,gd=1+md,_d=.01,vd=0-_d,yd=0+_d;function bd(e){return e.max-e.min}function xd(e,t,n){return Math.abs(e-t)<=n}function Sd(e,t,n,r=.5){e.origin=r,e.originPoint=X(t.min,t.max,e.origin),e.scale=bd(n)/bd(t),e.translate=X(n.min,n.max,e.origin)-e.originPoint,(e.scale>=hd&&e.scale<=gd||isNaN(e.scale))&&(e.scale=1),(e.translate>=vd&&e.translate<=yd||isNaN(e.translate))&&(e.translate=0)}function Cd(e,t,n,r){Sd(e.x,t.x,n.x,r?r.originX:void 0),Sd(e.y,t.y,n.y,r?r.originY:void 0)}function wd(e,t,n,r=0){e.min=(r?X(n.min,n.max,r):n.min)+t.min,e.max=e.min+bd(t)}function Td(e,t,n,r){wd(e.x,t.x,n.x,r?.x),wd(e.y,t.y,n.y,r?.y)}function Ed(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+bd(t)}function Dd(e,t,n,r){Ed(e.x,t.x,n.x,r?.x),Ed(e.y,t.y,n.y,r?.y)}function Od(e,t,n,r,i){return e-=t,e=yu(e,1/n,r),i!==void 0&&(e=yu(e,1/i,r)),e}function kd(e,t=0,n=1,r=.5,i,a=e,o=e){if(ka.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=Od(e.min,t,n,s,i),e.max=Od(e.max,t,n,s,i)}function Ad(e,t,[n,r,i],a,o){kd(e,t[n],t[r],t[i],t.scale,a,o)}var jd=[`x`,`scaleX`,`originX`],Md=[`y`,`scaleY`,`originY`];function Nd(e,t,n,r){Ad(e.x,t,jd,n?n.x:void 0,r?r.x:void 0),Ad(e.y,t,Md,n?n.y:void 0,r?r.y:void 0)}function Pd(e){return e.translate===0&&e.scale===1}function Fd(e){return Pd(e.x)&&Pd(e.y)}function Id(e,t){return e.min===t.min&&e.max===t.max}function Ld(e,t){return Id(e.x,t.x)&&Id(e.y,t.y)}function Rd(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function zd(e,t){return Rd(e.x,t.x)&&Rd(e.y,t.y)}function Bd(e){return bd(e.x)/bd(e.y)}function Vd(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function Hd(e){return[e(`x`),e(`y`)]}function Ud(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 Wd=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`],Gd=Wd.length,Kd=e=>typeof e==`string`?parseFloat(e):e,qd=e=>typeof e==`number`||J.test(e);function Jd(e,t,n,r,i,a){i?(e.opacity=X(0,n.opacity??1,Xd(r)),e.opacityExit=X(t.opacity??1,0,Zd(r))):a&&(e.opacity=X(t.opacity??1,n.opacity??1,r));for(let i=0;i<Gd;i++){let a=Wd[i],o=Yd(t,a),s=Yd(n,a);o===void 0&&s===void 0||(o||=0,s||=0,o===0||s===0||qd(o)===qd(s)?(e[a]=Math.max(X(Kd(o),Kd(s),r),0),(ka.test(s)||ka.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=X(t.rotate||0,n.rotate||0,r))}function Yd(e,t){return e[t]===void 0?e.borderRadius:e[t]}var Xd=Qd(0,.5,zi),Zd=Qd(.5,.95,_i);function Qd(e,t,n){return r=>r<e?0:r>t?1:n(bi(e,t,r))}function $d(e,t,n){let r=wc(e)?e:yc(e);return r.start(uc(``,r,t,n)),r.animation}function ef(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}var tf=(e,t)=>e.depth-t.depth,nf=class{constructor(){this.children=[],this.isDirty=!1}add(e){oi(this.children,e),this.isDirty=!0}remove(e){si(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(tf),this.isDirty=!1,this.children.forEach(e)}};function rf(e,t){let n=aa.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(ea(r),e(a-t))};return q.setup(r,!0),()=>ea(r)}function af(e){return wc(e)?e.get():e}var of=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&&(si(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(si(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)}},sf={hasAnimatedSinceResize:!0,hasEverUpdated:!1},cf={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},lf=[``,`X`,`Y`,`Z`],uf=1e3,df=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 pf(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=kc(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,q,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&pf(r)}function mf({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=df++,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,Xi.value&&(cf.nodes=cf.calculatedTargetDeltas=cf.calculatedProjections=0),this.nodes.forEach(_f),this.nodes.forEach(Ef),this.nodes.forEach(Df),this.nodes.forEach(vf),Xi.addProjectionMetrics&&Xi.addProjectionMetrics(cf)},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 nf)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new xi),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=wl(t)&&!zl(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;q.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=rf(i,250),sf.hasAnimatedSinceResize&&(sf.hasAnimatedSinceResize=!1,this.nodes.forEach(Tf)))})}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()||Pf,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!zd(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={...sc(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||Tf(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(),ea(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(Of),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&&pf(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(xf),this.nodes.forEach(bf);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Sf);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Cf),this.nodes.forEach(wf),this.nodes.forEach(hf),this.nodes.forEach(gf)):this.nodes.forEach(Sf),this.clearAllSnapshots();let e=aa.now();ta.delta=ci(0,1e3/60,e-ta.timestamp),ta.timestamp=e,ta.isProcessing=!0,na.update.process(ta),na.preRender.process(ta),na.render.process(ta),ta.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,rl.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(yf),this.sharedNodes.forEach(kf)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,q.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){q.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!bd(this.snapshot.measuredBox.x)&&!bd(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||=Gl(),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&&!Fd(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||gu(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)),Rf(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return Gl();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Bf))){let{scroll:e}=this.root;e&&(Eu(t.x,e.offset.x),Eu(t.y,e.offset.y))}return t}removeElementScroll(e){let t=Gl();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),Eu(t.x,i.offset.x),Eu(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||Gl();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&&(Eu(r.x,-n.scroll.offset.x),Eu(r.y,-n.scroll.offset.y)),gu(n.latestValues)&&ku(r,n.latestValues,n.layout?.layoutBox)}return gu(this.latestValues)&&ku(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=Gl();fd(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!gu(n.latestValues))continue;let r;n.instance&&(hu(n.latestValues)&&n.updateSnapshot(),r=Gl(),fd(r,n.measurePageBox())),Nd(t,n.latestValues,n.snapshot?.layoutBox,r)}return gu(this.latestValues)&&Nd(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!==ta.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=ta.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=Gl(),this.targetWithTransforms=Gl()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Td(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),Su(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),Xi.value&&cf.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||hu(this.parent.latestValues)||_u(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=Gl(),this.relativeTargetOrigin=Gl(),Dd(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===ta.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;Tu(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=Gl());let{target:s}=e;if(!s){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(pd(this.prevProjectionDelta.x,this.projectionDelta.x),pd(this.prevProjectionDelta.y,this.projectionDelta.y)),Cd(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!Vd(this.projectionDelta.x,this.prevProjectionDelta.x)||!Vd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),Xi.value&&cf.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=Ul(),this.projectionDelta=Ul(),this.projectionDeltaWithTransform=Ul()}setAnimationOrigin(e,t=!1){let n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},a=Ul();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let o=Gl(),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(Nf));this.animationProgress=0;let d;this.mixTargetDelta=t=>{let n=t/1e3;Af(a.x,e.x,n),Af(a.y,e.y,n),this.setTargetDelta(a),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Dd(o,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),Mf(this.relativeTarget,this.relativeTargetOrigin,o,n),d&&Ld(this.relativeTarget,d)&&(this.isProjectionDirty=!1),d||=Gl(),fd(d,this.relativeTarget)),s&&(this.animationValues=i,Jd(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&&=(ea(this.pendingAnimation),void 0),this.pendingAnimation=q.update(()=>{sf.hasAnimatedSinceResize=!0,oa.layout++,this.motionValue||=yc(0),this.motionValue.jump(0,!1),this.currentAnimation=$d(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(uf),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&&zf(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||Gl();let t=bd(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;let r=bd(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}fd(t,n),ku(t,i),Cd(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&&ff(`z`,e,r,this.animationValues);for(let t=0;t<lf.length;t++)ff(`rotate${lf[t]}`,e,r,this.animationValues),ff(`skew${lf[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=af(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=af(t?.pointerEvents)||``),this.hasProjected&&!gu(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=Ud(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 Bu){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=Bu[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?af(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(bf),this.root.sharedNodes.clear()}}}function hf(e){e.updateLayout()}function gf(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`)Hd(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=bd(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;dd(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else zf(i,t.layoutBox,n)&&Hd(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=bd(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=Ul();Cd(o,n,t.layoutBox);let s=Ul();a?Cd(s,e.applyTransform(r,!0),t.measuredBox):Cd(s,n,t.layoutBox);let c=!Fd(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=Gl();Dd(s,t.layoutBox,i.layoutBox,o);let c=Gl();Dd(c,n,a.layoutBox,o),zd(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 _f(e){Xi.value&&cf.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 yf(e){e.clearSnapshot()}function bf(e){e.clearMeasurements()}function xf(e){e.isLayoutDirty=!0,e.updateLayout()}function Sf(e){e.isLayoutDirty=!1}function Cf(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function wf(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function Tf(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Ef(e){e.resolveTargetDelta()}function Df(e){e.calcProjection()}function Of(e){e.resetSkewAndRotation()}function kf(e){e.removeLeadSnapshot()}function Af(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 jf(e,t,n,r){e.min=X(t.min,n.min,r),e.max=X(t.max,n.max,r)}function Mf(e,t,n,r){jf(e.x,t.x,n.x,r),jf(e.y,t.y,n.y,r)}function Nf(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var Pf={duration:.45,ease:[.4,0,.1,1]},Ff=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),If=Ff(`applewebkit/`)&&!Ff(`chrome/`)?Math.round:_i;function Lf(e){e.min=If(e.min),e.max=If(e.max)}function Rf(e){Lf(e.x),Lf(e.y)}function zf(e,t,n){return e===`position`||e===`preserve-aspect`&&!xd(Bd(t),Bd(n),.2)}function Bf(e){return e!==e.root&&e.scroll?.wasRoot}var Vf=mf({attachResizeListener:(e,t)=>ef(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),Hf={current:void 0},Uf=mf({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Hf.current){let e=new Vf({});e.mount(window),e.setOptions({layoutScroll:!0}),Hf.current=e}return Hf.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),Wf=(0,d.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function Gf(e=!0){let t=(0,d.useContext)(ai);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 Kf=(0,d.createContext)({strict:!1}),qf={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`]},Jf=!1;function Yf(){if(Jf)return;let e={};for(let t in qf)e[t]={isEnabled:e=>qf[t].some(t=>!!e[t])};ou(e),Jf=!0}function Xf(){return Yf(),su()}function Zf(e){let t=Xf();for(let n in e)t[n]={...t[n],...e[n]};ou(t)}var Qf=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 $f(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||Qf.has(e)}var ep=s({default:()=>tp}),tp,np=o((()=>{throw tp={},Error(`Could not resolve "@emotion/is-prop-valid" imported by "framer-motion". Is it installed?`)})),rp=e=>!$f(e);function ip(e){typeof e==`function`&&(rp=t=>t.startsWith(`on`)?!$f(t):e(t))}try{ip((np(),u(ep)).default)}catch{}function ap(e,t,n){let r={};for(let i in e)i===`values`&&typeof e.values==`object`||wc(e[i])||(rp(i)||n===!0&&$f(i)||!t&&!$f(i)||e.draggable&&i.startsWith(`onDrag`))&&(r[i]=e[i]);return r}var op=(0,d.createContext)({});function sp(e,t){if(Zl(e)){let{initial:t,animate:n}=e;return{initial:t===!1||Jl(t)?t:void 0,animate:Jl(n)?n:void 0}}return e.inherit===!1?{}:t}function cp(e){let{initial:t,animate:n}=sp(e,(0,d.useContext)(op));return(0,d.useMemo)(()=>({initial:t,animate:n}),[lp(t),lp(n)])}function lp(e){return Array.isArray(e)?e.join(` `):e}var up=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function dp(e,t,n){for(let r in t)!wc(t[r])&&!Vu(r,n)&&(e[r]=t[r])}function fp({transformTemplate:e},t){return(0,d.useMemo)(()=>{let n=up();return Fu(n,t,e),Object.assign({},n.vars,n.style)},[t])}function pp(e,t){let n=e.style||{},r={};return dp(r,n,e),Object.assign(r,fp(e,t)),r}function mp(e,t){let n={},r=pp(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 hp=()=>({...up(),attrs:{}});function gp(e,t,n,r){let i=(0,d.useMemo)(()=>{let n=hp();return Yu(n,t,Zu(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};dp(t,e.style,e),i.style={...t,...i.style}}return i}var _p=[`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:!!(_p.indexOf(e)>-1||/[A-Z]/u.test(e))}function yp(e,t,n,{latestValues:r},i,a=!1,o){let s=(o??vp(e)?gp:mp)(t,r,i,e),c=ap(t,typeof e==`string`,a),l=e===d.Fragment?{}:{...c,...s,ref:n},{children:u}=t,f=(0,d.useMemo)(()=>wc(u)?u.get():u,[u]);return(0,d.createElement)(e,{...l,children:f})}function bp({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:xp(n,r,i,e),renderState:t()}}function xp(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=af(a[e]);let{initial:o,animate:s}=e,c=Zl(e),l=Ql(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`&&!ql(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 Sp=e=>(t,n)=>{let r=(0,d.useContext)(op),i=(0,d.useContext)(ai),a=()=>bp(e,t,r,i);return n?a():ri(a)},Cp=Sp({scrapeMotionValuesFromProps:Hu,createRenderState:up}),wp=Sp({scrapeMotionValuesFromProps:$u,createRenderState:hp}),Tp=Symbol.for(`motionComponentSymbol`);function Ep(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 Dp=(0,d.createContext)({});function Op(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function kp(e,t,n,r,i,a){let{visualElement:o}=(0,d.useContext)(op),s=(0,d.useContext)(Kf),c=(0,d.useContext)(ai),l=(0,d.useContext)(Wf),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)(Dp);h&&!h.projection&&i&&(h.type===`html`||h.type===`svg`)&&Ap(p.current,n,i,g);let _=(0,d.useRef)(!1);(0,d.useInsertionEffect)(()=>{h&&_.current&&h.update(n,c)});let v=n[Oc],y=(0,d.useRef)(!!v&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(v)&&window.MotionHasOptimisedAnimation?.(v));return ii(()=>{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 Ap(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:jp(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&Op(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function jp(e){if(e)return e.options.allowProjection===!1?jp(e.parent):e.projection}function Mp(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&Zf(r);let a=n?n===`svg`:vp(e),o=a?wp:Cp;function s(n,s){let c,l={...(0,d.useContext)(Wf),...n,layoutId:Np(n)},{isStatic:u}=l,p=cp(n),m=o(n,u);if(!u&&typeof window<`u`){Pp(l,r);let t=Fp(l);c=t.MeasureLayout,p.visualElement=kp(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,yp(e,n,Ep(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[Tp]=e,c}function Np({layoutId:e}){let t=(0,d.useContext)(ni).id;return t&&e!==void 0?t+`-`+e:e}function Pp(e,t){let n=(0,d.useContext)(Kf).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?ui(!1,t,`lazy-strict-mode`):di(!1,t,`lazy-strict-mode`)}}function Fp(e){let{drag:t,layout:n}=Xf();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function Ip(e,t){if(typeof Proxy>`u`)return Mp;let n=new Map,r=(n,r)=>Mp(n,r,e,t);return new Proxy((e,t)=>(process.env.NODE_ENV!==`production`&&Ei(!1,`motion() is deprecated. Use motion.create() instead.`),r(e,t)),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,Mp(a,void 0,e,t)),n.get(a))})}var Lp=(e,t)=>t.isSVG??vp(e)?new ed(t):new Wu(t,{allowProjection:e!==d.Fragment}),Rp=class extends uu{constructor(e){super(e),e.animationState||=sd(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();ql(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?.()}},zp=0,Bp={animation:{Feature:Rp},exit:{Feature:class extends uu{constructor(){super(...arguments),this.id=zp++,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=pc(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 Vp(e){return{point:{x:e.pageX,y:e.pageY}}}var Hp=e=>t=>fl(t)&&e(t,Vp(t));function Up(e,t,n,r){return ef(e,t,Hp(n),r)}var Wp=({current:e})=>e?e.ownerDocument.defaultView:null,Gp=(e,t)=>Math.abs(e-t);function Kp(e,t){let n=Gp(e.x,t.x),r=Gp(e.y,t.y);return Math.sqrt(n**2+r**2)}var qp=new Set([`auto`,`scroll`]),Jp=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=Yp(this.lastRawMoveEventInfo,this.transformPagePoint));let e=Zp(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=Kp(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e,{timestamp:i}=ta;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=Yp(t,this.transformPagePoint),q.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=Zp(e.type===`pointercancel`?this.lastMoveEventInfo:Yp(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=Yp(Vp(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=ta;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,Zp(s,this.history)),this.removeListeners=yi(Up(this.contextWindow,`pointermove`,this.handlePointerMove),Up(this.contextWindow,`pointerup`,this.handlePointerUp),Up(this.contextWindow,`pointercancel`,this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let t=e.parentElement;for(;t;){let e=getComputedStyle(t);(qp.has(e.overflowX)||qp.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),q.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),ea(this.updatePoint)}};function Yp(e,t){return t?{point:t(e.point)}:e}function Xp(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Zp({point:e},t){return{point:e,delta:Xp(e,$p(t)),offset:Xp(e,Qp(t)),velocity:em(t,.1)}}function Qp(e){return e[0]}function $p(e){return e[e.length-1]}function em(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=$p(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>Si(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>Si(t)*2&&(r=e[1]);let a=Ci(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 tm(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 nm(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 rm(e,{top:t,left:n,bottom:r,right:i}){return{x:nm(e.x,n,i),y:nm(e.y,t,r)}}function im(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 am(e,t){return{x:im(e.x,t.x),y:im(e.y,t.y)}}function om(e,t){let n=.5,r=bd(e),i=bd(t);return i>r?n=bi(t.min,t.max-r,e.min):r>i&&(n=bi(e.min,e.max-i,t.min)),ci(0,1,n)}function sm(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 cm=.35;function lm(e=cm){return e===!1?e=0:e===!0&&(e=cm),{x:um(e,`left`,`right`),y:um(e,`top`,`bottom`)}}function um(e,t,n){return{min:dm(e,t),max:dm(e,n)}}function dm(e,t){return typeof e==`number`?e:e[t]||0}var fm=new WeakMap,pm=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=Gl(),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(Vp(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=sl(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),Hd(e=>{let t=this.getAxisMotionValue(e).get()||0;if(ka.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=bd(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&q.update(()=>i(e,t),!1,!0),Ec(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=_m(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&&q.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 Jp(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:Wp(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&&q.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||!gm(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=tm(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&&Op(e)?this.constraints||=this.resolveRefConstraints():e&&n?this.constraints=rm(n.layoutBox,e):this.constraints=!1,this.elastic=lm(t),r!==this.constraints&&!Op(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&Hd(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=sm(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Op(e))return!1;let n=e.current;di(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=ju(n,r.root,this.visualElement.getTransformPagePoint()),a=am(r.layout.layoutBox,i);if(t){let e=t(fu(a));this.hasMutatedConstraints=!!e,e&&(a=du(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=Hd(o=>{if(!gm(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 Ec(this.visualElement,e),n.start(uc(e,n,0,t,this.visualElement,!1))}stopAnimation(){Hd(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){Hd(t=>{let{drag:n}=this.getProps();if(!gm(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(!Op(t)||!n||!this.constraints)return;this.stopAnimation();let r={x:0,y:0};Hd(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(),Hd(t=>{if(!gm(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=Up(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&gl(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();Op(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=hm(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),q.read(r);let o=ef(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(Hd(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=cm,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function mm(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function hm(e,t,n){let r=Rl(e,mm(n)),i=Rl(t,mm(n));return()=>{r(),i()}}function gm(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function _m(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 uu{constructor(e){super(e),this.removeGroupControls=_i,this.removeListeners=_i,this.controls=new pm(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||_i}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()}},ym=e=>(t,n)=>{e&&q.update(()=>e(t,n),!1,!0)},bm=class extends uu{constructor(){super(...arguments),this.removePointerDownListener=_i}onPointerDown(e){this.session=new Jp(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Wp(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:ym(e),onStart:ym(t),onMove:ym(n),onEnd:(e,t)=>{delete this.session,r&&q.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=Up(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},xm=!1,Sm=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),xm&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),sf.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}),xm=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||q.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(),rl.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;xm=!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 Cm(e){let[t,n]=Gf(),r=(0,d.useContext)(ni);return(0,f.jsx)(Sm,{...e,layoutGroup:r,switchLayoutGroup:(0,d.useContext)(Dp),isPresent:t,safeToRemove:n})}var wm={pan:{Feature:bm},drag:{Feature:vm,ProjectionNode:Uf,MeasureLayout:Cm}};function Tm(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&q.postRender(()=>i(t,Vp(t)))}var Em=class extends uu{mount(){let{current:e}=this.node;e&&(this.unmount=ul(e,(e,t)=>(Tm(this.node,t,`Start`),e=>Tm(this.node,e,`End`))))}unmount(){}},Dm=class extends uu{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=yi(ef(this.node.current,`focus`,()=>this.onFocus()),ef(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function Om(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&&q.postRender(()=>i(t,Vp(t)))}var km=class extends uu{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=Cl(e,(e,t)=>(Om(this.node,t,`Start`),(e,{success:t})=>Om(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},Am=new WeakMap,jm=new WeakMap,Mm=e=>{let t=Am.get(e.target);t&&t(e)},Nm=e=>{e.forEach(Mm)};function Pm({root:e,...t}){let n=e||document;jm.has(n)||jm.set(n,{});let r=jm.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(Nm,{root:e,...t})),r[i]}function Fm(e,t,n){let r=Pm(t);return Am.set(e,n),r.observe(e),()=>{Am.delete(e),r.unobserve(e)}}var Im={some:0,all:1},Lm=class extends uu{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:Im[r]};this.stopObserver=Fm(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(Rm(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function Rm({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var zm={inView:{Feature:Lm},tap:{Feature:km},focus:{Feature:Dm},hover:{Feature:Em}},Bm={layout:{ProjectionNode:Uf,MeasureLayout:Cm}},Vm=Ip({...Bp,...zm,...wm,...Bm},Lp),Hm=24e3,Um=2048,Wm=1200,Gm=.05,Km=4,qm=.03,Jm=2,Ym=11;function Xm(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}function Zm(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 Qm(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]/32768;return t}var $m=.09,eh=[`audio/webm`,`audio/mp4`];function th(){return typeof window>`u`||window.MediaRecorder===void 0?null:eh.find(e=>window.MediaRecorder.isTypeSupported(e))||null}function nh(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))}function rh(e,t,n){let r=0,i=0,a=[],o=()=>{a.forEach(e=>{try{e.stop()}catch{}}),a=[],r=0},s=()=>r>e.currentTime;return{enqueue:o=>{let c=Qm(o),l=e.createBuffer(1,c.length,Hm);l.copyToChannel(c,0);let u=e.createBufferSource();u.buffer=l,u.connect(e.destination),n&&u.connect(n);let d=!s(),f=d?e.currentTime+$m:r;d&&(i=f),u.start(f),r=f+l.duration,a.push(u),u.onended=()=>{a=a.filter(e=>e!==u),!a.length&&!s()&&t?.()}},stop:o,isPlaying:s,playedMs:()=>Math.max(0,(e.currentTime-i)*1e3)}}async function ih(e,t,n){let r=new URLSearchParams({siteId:t||``});n&&r.set(`chatId`,n);let i=Cr();i&&r.set(`shopifyCustomerId`,String(i));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 ah(e){let{apiBaseUrl:t,siteId:n,chatId:r,clientTools:i={},onConnect:a,onDisconnect:o,onMessage:s,onModeChange:c,onError:l,onUnhandledClientToolCall:u,onAgentTurnEnd:d,onSessionInfo:f,onSessionEnding:p}=e,m=await ih(t,n,r);f?.({emailOnFile:!!m.emailOnFile});let h={type:`Start`};e.greeting!==void 0&&(h.greeting=e.greeting||null);let g=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),_=new(window.AudioContext||window.webkitAudioContext)({sampleRate:Hm});_.state===`suspended`&&await _.resume();let v=_.createMediaStreamDestination(),y=th(),b=[],x=null,S=r||n||null;y&&(x=new window.MediaRecorder(v.stream,{mimeType:y}),x.ondataavailable=e=>{e.data&&e.data.size>0&&b.push(e.data)},x.start());let C=new WebSocket(m.wsUrl);C.binaryType=`arraybuffer`;let w=new Set,T={role:null,text:``,timer:null,debug:null},E=``,ee=()=>{T.timer&&=(clearTimeout(T.timer),null);let e=T.text.trim(),t=T.role,n=T.debug;if(T.text=``,T.role=null,T.debug=null,!(!e||!t)){if(t===`agent`){if(e===E){console.debug(`[FlowEngage] duplicate agent turn suppressed`);return}E=e}s?.({role:t,message:e,debug:n})}},te=(e,t,n)=>{t&&(T.role&&T.role!==e&&ee(),T.role=e,T.text=T.text?`${T.text} ${t}`.replace(/\s+/g,` `):t,n&&(T.debug=n),T.timer&&clearTimeout(T.timer),T.timer=setTimeout(ee,Wm))},D=!1,ne=!1,re=!1,ie=!1,O=!0,k=0,ae=!1,oe=!1,A=Gm,se=Km,j=null,ce=!1,M=!1,N=()=>{j&&clearTimeout(j);let e=()=>{if(!D){if(P.isPlaying()){j=setTimeout(e,150);return}if(j=null,ce){p?.();return}!D&&C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:`PlaybackDrained`})),M&&(M=!1,d?.())}};j=setTimeout(e,150)},P=rh(_,()=>{ie&&(ie=!1,c?.({mode:`listening`}))},v);typeof window<`u`&&(window.__fe_agentAudioPlaying=()=>P.isPlaying());let le=_.createMediaStreamSource(g);le.connect(v);let ue=_.createScriptProcessor(Um,1,1),de=!1,fe=0,pe=0;ue.onaudioprocess=e=>{if(D||C.readyState!==WebSocket.OPEN)return;let t=e.inputBuffer.getChannelData(0),n=()=>C.send(new Int16Array(t.length).buffer);if(ne){re||(re=!0,console.debug(`[FlowEngage] mic held — streaming silence to keep socket alive`)),de=!1,fe=0,pe=0,n();return}let r=Xm(t);if(P.isPlaying()||oe?(de=!1,fe=0,pe=0):r>=qm?(pe=0,fe+=1,!de&&fe>=Jm&&(de=!0,c?.({mode:`user-speaking`}))):(fe=0,de&&++pe>=Ym&&(de=!1,pe=0,c?.({mode:`thinking`,tentative:!0}))),(P.isPlaying()||oe)&&!ae){if(r<A)k=0;else if(++k>=se){ae=!0,k=0;let e=P.playedMs();P.stop(),O=!1,oe=!1,j&&!ce&&(clearTimeout(j),j=null),M=!1,C.send(JSON.stringify({type:`VisitorInterrupted`,played_ms:Math.round(e)})),console.debug(`[FlowEngage] barge-in — visitor spoke over the agent`)}}C.send(Zm(t).buffer)},le.connect(ue),ue.connect(_.destination);let me=()=>{if(!D){D=!0,j&&=(clearTimeout(j),null),ee(),P.stop(),typeof window<`u`&&delete window.__fe_agentAudioPlaying;try{ue.disconnect(),le.disconnect()}catch{}if(g.getTracks().forEach(e=>e.stop()),x&&x.state!==`inactive`){x.onstop=()=>nh(t,n,S,b,y);try{x.stop()}catch{x.onstop=null}}else b.length&&nh(t,n,S,b,y);_.close().catch(()=>{}),(C.readyState===WebSocket.OPEN||C.readyState===WebSocket.CONNECTING)&&C.close()}},he=async e=>{let t=i[e.name];if(!t)return u?.({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`}}},F=async e=>{for(let t of e.functions||[]){if(!t.client_side)continue;let e=await he(t);if(D||C.readyState!==WebSocket.OPEN)return;C.send(JSON.stringify({type:`FunctionCallResponse`,id:t.id,name:t.name,content:typeof e==`string`?e:JSON.stringify(e??{})}))}},ge=e=>{switch(e.type){case`Welcome`:Number.isFinite(e.barge_in_rms)&&e.barge_in_rms>0&&(A=e.barge_in_rms),Number.isFinite(e.barge_in_frames)&&e.barge_in_frames>0&&(se=e.barge_in_frames),S=e.session_id||r||n||null,a?.({conversationId:S});break;case`ConversationText`:{let t=String(e.content||``);if(e.role===`user`){let e=t.trim();if(w.has(e)){w.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}}te(e.role===`user`?`user`:`agent`,t,e.debug);break}case`UserStartedSpeaking`:ee(),P.stop(),oe=!1,O=!1,ie=!1,j&&!ce&&(clearTimeout(j),j=null),M=!1,c?.({mode:`listening`});break;case`AgentStartedSpeaking`:O=!0,ie=!0,ae=!1,k=0,c?.({mode:`speaking`});break;case`AgentAudioDone`:oe=!1,ee(),N(),P.isPlaying()||(ie=!1,c?.({mode:`listening`}));break;case`FunctionCallRequest`:F(e);break;case`AgentPreparing`:oe=!0;break;case`AgentTurnComplete`:M=!0,N();break;case`SessionEnding`:console.debug(`[FlowEngage] server is ending the session:`,e.reason||`unspecified`),ce=!0;break;case`AgentThinking`:c?.({mode:`thinking`});break;case`PromptUpdated`:break;case`Error`:console.error(`[FlowEngage:Voice]`,e.code||``,e.description||e),l?.(Error(e.description||`Voice service error`));break;case`Warning`:console.warn(`[FlowEngage:Voice]`,e.code||``,e.description||``);break;default:break}};return C.onopen=()=>C.send(JSON.stringify(h)),C.onmessage=e=>{if(e.data instanceof ArrayBuffer){O&&P.enqueue(new Int16Array(e.data));return}try{ge(JSON.parse(e.data))}catch{}},C.onerror=()=>l?.(Error(`Voice connection failed`)),C.onclose=()=>{me(),o?.()},{endSession:async()=>me(),sendContextualUpdate:e=>{D||C.readyState!==WebSocket.OPEN||!e||C.send(JSON.stringify({type:`UpdatePrompt`,prompt:e}))},sendUserMessage:(e,{silent:t=!0,suppressQuestion:n=!1}={})=>{D||C.readyState!==WebSocket.OPEN||!e||(t&&w.add(e.trim()),C.send(JSON.stringify({type:`InjectUserMessage`,content:e,suppress_question:n})))},injectAgentSpeech:(e,t=`interrupt`)=>{D||C.readyState!==WebSocket.OPEN||!e||C.send(JSON.stringify({type:`InjectAgentMessage`,message:e,behavior:t}))},setWalkthroughActive:e=>{D||C.readyState!==WebSocket.OPEN||C.send(JSON.stringify({type:`WalkthroughActive`,active:!!e}))},setMicMuted:e=>{ne=!!e,!D&&C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:`MicHeld`,held:ne}))},get status(){return D?`disconnected`:`connected`}}}var oh={startSession:ah},sh=({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`})]}),ch=({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`})]}),lh=({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`})]}),uh=()=>(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`})]}),dh=()=>(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`})}),fh=({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`})]}),ph=({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`})]}),mh=({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`})]}),hh=({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})]}),gh=({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`})]}),_h=()=>(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`})}),vh=({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`})]}),yh=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),bh=(e=``)=>String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),xh=new Set([`p`,`br`,`ul`,`ol`,`li`,`strong`,`em`,`b`,`i`,`a`]),Sh=/^https?:\/\//i;function Ch(e){let t=Array.from(e.childNodes);for(let n of t)if(n.nodeType===Node.ELEMENT_NODE){let t=n.tagName.toLowerCase();if(!xh.has(t)){e.replaceChild(document.createTextNode(n.textContent),n);continue}let r={};if(t===`a`){let e=n.getAttribute(`href`)||``;Sh.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);Ch(n)}else n.nodeType!==Node.TEXT_NODE&&e.removeChild(n)}function wh(e){let t=document.createElement(`div`);return t.innerHTML=e,Ch(t),t.innerHTML}function Th(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 Eh=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return Th(wh(t));let n=t.replace(/\r\n/g,`
|
|
26
29
|
`).replace(/\n{3,}/g,`
|
|
27
30
|
|
|
28
31
|
`).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>bh(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 Th(n.map(e=>{let t=e.split(`
|
|
@@ -331,10 +334,10 @@
|
|
|
331
334
|
`));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(`
|
|
332
335
|
`).replace(/\n{3,}/g,`
|
|
333
336
|
|
|
334
|
-
`).trim()}function Ug(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={"fwh-navigate-mvp":async n=>{if($(`fwh-navigate-mvp ▶ raw parameters:`,n),e?.isWalkthroughActive?.())return $(`fwh-navigate-mvp ✖ blocked — walkthrough in progress`),`NAVIGATION_BLOCKED_DURING_WALKTHROUGH. A walkthrough of the current page is in progress, so navigation is not allowed. Do NOT tell the visitor you navigated or offer to. Describe the requested section using the CURRENT page's own content (fwh-read-content-mvp), then stop.`;let i=Rg(n),a=zg(i),o=i.section_text??i.sectionText??i.section,s=Array.isArray(i.expected_landmarks)?i.expected_landmarks:Array.isArray(i.expectedLandmarks)?i.expectedLandmarks:[];if($(`fwh-navigate-mvp · coerced:`,{url:a,sectionText:o,expectedLandmarks:s}),!a){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(a,window.location.href);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: The URL "${a}" points to an external site (${t}) that opens in a new tab. I cannot open new tabs or navigate to external sites. Tell the visitor exactly this: "That link opens an external app — I'm not able to open it for you, but you can click the link directly in the navigation header."`}}catch{}if(typeof window<`u`){try{let e=new URL(a,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. Do not navigate. Proceed directly with highlights, answering the question, or reading page content.`}catch{}let e=window.__fe_user_nav_during_speech;if(e&&Date.now()-e.ts<3e4)try{if(new URL(a,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}" and is now on "${e.toPageName}". Do NOT navigate them back. If they said "continue", resume verbally from where you left off — no navigation needed. If they want to return, they will navigate themselves.`}catch{}}let{allowed:c,correctedUrl:l}=await tr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl});if(!c){let e=`PAGE_NOT_IN_SITE: "${a}" is NOT a real page on this site — do NOT guess or invent URL paths. Do NOT tell the visitor you are taking them there. Instead, find the REAL page: look at your Popular Pages / Site Pages list for the closest actual match, or call fwh-list-nav-links-mvp (to read the site's real menu links) or fwh-search-mvp (to find the right page). If a close match exists (e.g. the visitor said "support" and the site has "Technical Support"), tell them the ACTUAL page name and ask "we don't have a page called that, but we do have [real page] — would you like me to take you there?" Then navigate only to that verified URL.`;return $(`fwh-navigate-mvp ✖ blocked`,e),e}l&&l!==a&&($(`fwh-navigate-mvp · corrected url:`,{requested:a,correctedUrl:l}),a=l);try{cg(`Navigating to ${a}...`,{spinner:!0}),pg(),gn();try{let e=r?r():``;if(e&&t){let n=rg([{sender:`user`,message:e}]);n&&ue(t,n)}}catch{}me();let e=a;try{e=new URL(a,typeof window<`u`?window.location.href:``).href}catch{}let n=`this`;try{let e=new URL(a,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`&&I(t,window.location.href,e,n),ir(e),$(`fwh-navigate-mvp → real navigation`,a);let i=typeof window<`u`&&!window.Shopify&&!!Fn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),i&&En(12e3),fr(a,{voiceActive:!0}).catch(()=>{}),i)try{let e=new URL(a,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:a;(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 o=[],s=null,c=``,l=Date.now()+12e3;for(;Date.now()<l&&(await new Promise(e=>setTimeout(e,300)),{headings:o,pageTitleHeading:s,introText:c}=Vg(),!(o.length>=1)););Bg(),$(`fwh-navigate-mvp → page headings collected:`,o,`titleHeading:`,s);let u=o.length?o.join(` | `):`none`,d=o.length?`Use ONLY these exact heading strings for fwh-highlight-mvp — never invent or abbreviate.`:`No headings collected yet — call fwh-get-current-page-mvp immediately (no speech) to get the live headings before speaking or highlighting.`,f=s?` "${s}" is the PAGE TITLE, not a content section — do not fwh-highlight-mvp it separately; if doing a walkthrough, just fold this intro into your opening line: "${c||`(no intro text found)`}"`:c?` No separate page-title heading detected, but this intro text precedes the first section — mention it briefly before covering sections: "${c}"`:``,p=``;try{if(o.length>0){let e=o.slice(0,3),t=[];for(let n of e){let e=Xn(null,n);if(e){let r=Hg(e).substring(0,800);r&&t.push(`[Section: ${n}] ${r}`)}}t.length>0&&(p=` CONTENT FOR FIRST FEW SECTIONS: ${t.join(` | `)}. Use this content to answer immediately if the visitor asks about one of these sections.`)}}catch{}if(sr())return ar(),$(`fwh-navigate-mvp ✖ landed on a not-found/404 page:`,i),`NAVIGATION_PAGE_NOT_FOUND. The page at ${i} does not exist — it shows a "not found"/404 error, not real content. Do NOT offer a page overview, do NOT describe or highlight any sections, do NOT claim the navigation succeeded. Tell the visitor EXACTLY: "It looks like that page doesn't exist — I couldn't find it. Would you like me to take you somewhere else?" Then STOP and wait for their reply.`;let m=Date.now()+4e3,h=typeof window<`u`?window.location.pathname:r;for(;Date.now()<m&&!Eg(h,e)&&Eg(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=Eg(h,e),y=!Eg(h,t),b=v||y;return $(`fwh-navigate-mvp settled:`,h,`target:`,e,`match:`,b),b?(ar(),`OK_NAVIGATE_SPA. Visitor is now on: ${g} (page: "${_}") | Section headings: ${u}.${f} ${d}${p} Now confirm the arrival in ONE short sentence phrased for what the visitor actually asked for — mention the page by name and what it lets them do (e.g. for a contact request: "I've taken you to the Contact Us page — filling in this form sends your query straight to our team."). Do NOT use a fixed template. Then, in the same breath, offer either a specific section or a full overview. Then STOP — wait for their reply.`):(ar(),`NAVIGATION_DID_NOT_HAPPEN. The visitor is STILL on ${g} (page: "${_}") — the navigation did not go through. Do NOT say "I have navigated you". Do NOT claim success. Tell the visitor EXACTLY: "Sorry, I couldn't open that page just now. Would you like me to try again, or is there something else I can help with?" Then STOP and wait for their reply.`)}catch{}let o=`this`;try{let e=new URL(a,window.location.href).pathname.split(`/`).filter(Boolean).pop()||``;o=e?e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()):`Home`}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, say EXACTLY: "I have navigated you on ${o} page. Do you want to know about any specific section or want a complete overview?" Then STOP — wait for the visitor's reply.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`fwh-navigate-mvp ✖`,t),cg(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{mg(),lg(900)}},"fwh-highlight-mvp":async e=>{$(`fwh-highlight-mvp ▶`,e);let t=Rg(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(En(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 navigated from "${e.fromPageName}" to "${e.toPageName}" (current path: ${t}) while you were speaking. STOP the current walkthrough immediately. DO NOT call fwh-highlight-mvp again. Say out loud: "I see you've navigated to the ${e.toPageName} page — do you want me to continue what I was explaining, or shall I guide you through this page?" Wait for the visitor's answer before doing anything else.`}Bg();let i=(e=>e&&e.replace(/^\d+\.\s*/,``).replace(/^["']|["']$/g,``).trim())(r),a=Xn(n||null,i||null);if(!a&&i){let e=Date.now()+600;for(;!a&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),Bg(),a=Xn(null,i)}if(!a){$(`fwh-highlight-mvp ✖ no element for:`,i||n);let{headings:e}=Vg(),t=e.length?`Page headings: ${e.map(e=>`"${e}"`).join(` | `)}. Use one of these EXACT strings for section_text — no numbers, no quotes around them.`:`No headings found — skip highlight and continue speaking.`;return`HIGHLIGHT_NOT_FOUND: "${i||n}" on the current page. ${t}`}return hn(a),$(`fwh-highlight-mvp ✓`,i||n),`OK_HIGHLIGHT: "${i||n}". Your NEXT response must be speech only (no tool call) describing THIS section — "${i||n}" — using its own content. Do not ask whether to continue.`},"fwh-read-content-mvp":async e=>{$(`fwh-read-content-mvp ▶`,e);let t=Rg(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=Xn(null,n);if(!t)return`Could not find section "${n}" on the page.`;e=Hg(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=Rg(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=Rg(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(`
|
|
337
|
+
`).trim()}function Ug(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={"fwh-navigate-mvp":async n=>{if($(`fwh-navigate-mvp ▶ raw parameters:`,n),e?.isWalkthroughActive?.())return $(`fwh-navigate-mvp ✖ blocked — walkthrough in progress`),`NAVIGATION_BLOCKED_DURING_WALKTHROUGH. A walkthrough of the current page is in progress, so navigation is not allowed. Do NOT tell the visitor you navigated or offer to. Describe the requested section using the CURRENT page's own content (fwh-read-content-mvp), then stop.`;let i=Rg(n),a=zg(i),o=i.section_text??i.sectionText??i.section,s=Array.isArray(i.expected_landmarks)?i.expected_landmarks:Array.isArray(i.expectedLandmarks)?i.expectedLandmarks:[];if($(`fwh-navigate-mvp · coerced:`,{url:a,sectionText:o,expectedLandmarks:s}),!a){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(a,window.location.href);if(e.hostname===window.location.hostname&&e.origin!==window.location.origin)a=e.pathname+e.search+e.hash,$(`fwh-navigate-mvp · cross-protocol same-host URL normalized →`,a);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: The URL "${a}" points to an external site (${t}) that opens in a new tab. I cannot open new tabs or navigate to external sites. Tell the visitor exactly this: "That link opens an external app — I'm not able to open it for you, but you can click the link directly in the navigation header."`}}catch{}if(typeof window<`u`){try{let e=new URL(a,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. Do not navigate. Proceed directly with highlights, answering the question, or reading page content.`}catch{}let e=window.__fe_user_nav_during_speech;if(e&&Date.now()-e.ts<3e4)try{if(new URL(a,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}" and is now on "${e.toPageName}". Do NOT navigate them back. If they said "continue", resume verbally from where you left off — no navigation needed. If they want to return, they will navigate themselves.`}catch{}}let{allowed:c,correctedUrl:l}=await tr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl});if(!c){let e=`PAGE_NOT_IN_SITE: "${a}" is NOT a real page on this site — do NOT guess or invent URL paths. Do NOT tell the visitor you are taking them there. Instead, find the REAL page: look at your Popular Pages / Site Pages list for the closest actual match, or call fwh-list-nav-links-mvp (to read the site's real menu links) or fwh-search-mvp (to find the right page). If a close match exists (e.g. the visitor said "support" and the site has "Technical Support"), tell them the ACTUAL page name and ask "we don't have a page called that, but we do have [real page] — would you like me to take you there?" Then navigate only to that verified URL.`;return $(`fwh-navigate-mvp ✖ blocked`,e),e}l&&l!==a&&($(`fwh-navigate-mvp · corrected url:`,{requested:a,correctedUrl:l}),a=l);try{cg(`Navigating to ${a}...`,{spinner:!0}),pg(),gn();try{let e=r?r():``;if(e&&t){let n=rg([{sender:`user`,message:e}]);n&&ue(t,n)}}catch{}me();let e=a;try{e=new URL(a,typeof window<`u`?window.location.href:``).href}catch{}let n=`this`;try{let e=new URL(a,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`&&I(t,window.location.href,e,n),ir(e);try{window.__fe_agent_nav={path:new URL(e,window.location.href).pathname,ts:Date.now()}}catch{}$(`fwh-navigate-mvp → real navigation`,a);let i=typeof window<`u`&&!window.Shopify&&!!Fn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),i&&En(12e3),fr(a,{voiceActive:!0}).catch(()=>{}),i)try{let e=new URL(a,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:a;(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 o=[],s=null,c=``,l=Date.now()+12e3;for(;Date.now()<l&&(await new Promise(e=>setTimeout(e,300)),{headings:o,pageTitleHeading:s,introText:c}=Vg(),!(o.length>=1)););Bg(),$(`fwh-navigate-mvp → page headings collected:`,o,`titleHeading:`,s);let u=o.length?o.join(` | `):`none`,d=o.length?`Use ONLY these exact heading strings for fwh-highlight-mvp — never invent or abbreviate.`:`No headings collected yet — call fwh-get-current-page-mvp immediately (no speech) to get the live headings before speaking or highlighting.`,f=s?` "${s}" is the PAGE TITLE, not a content section — do not fwh-highlight-mvp it separately; if doing a walkthrough, just fold this intro into your opening line: "${c||`(no intro text found)`}"`:c?` No separate page-title heading detected, but this intro text precedes the first section — mention it briefly before covering sections: "${c}"`:``,p=``;try{if(o.length>0){let e=o.slice(0,3),t=[];for(let n of e){let e=Xn(null,n);if(e){let r=Hg(e).substring(0,800);r&&t.push(`[Section: ${n}] ${r}`)}}t.length>0&&(p=` CONTENT FOR FIRST FEW SECTIONS: ${t.join(` | `)}. Use this content to answer immediately if the visitor asks about one of these sections.`)}}catch{}if(sr())return ar(),$(`fwh-navigate-mvp ✖ landed on a not-found/404 page:`,i),`NAVIGATION_PAGE_NOT_FOUND. The page at ${i} does not exist — it shows a "not found"/404 error, not real content. Do NOT offer a page overview, do NOT describe or highlight any sections, do NOT claim the navigation succeeded. Tell the visitor EXACTLY: "It looks like that page doesn't exist — I couldn't find it. Would you like me to take you somewhere else?" Then STOP and wait for their reply.`;let m=Date.now()+4e3,h=typeof window<`u`?window.location.pathname:r;for(;Date.now()<m&&!Eg(h,e)&&Eg(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=Eg(h,e),y=!Eg(h,t),b=v||y;return $(`fwh-navigate-mvp settled:`,h,`target:`,e,`match:`,b),b?(ar(),`OK_NAVIGATE_SPA. Visitor is now on: ${g} (page: "${_}") | Section headings: ${u}.${f} ${d}${p} Now confirm the arrival in ONE short sentence phrased for what the visitor actually asked for — mention the page by name and what it lets them do (e.g. for a contact request: "I've taken you to the Contact Us page — filling in this form sends your query straight to our team."). Do NOT use a fixed template. Then, in the same breath, offer either a specific section or a full overview. Then STOP — wait for their reply.`):(ar(),`NAVIGATION_DID_NOT_HAPPEN. The visitor is STILL on ${g} (page: "${_}") — the navigation did not go through. Do NOT say "I have navigated you". Do NOT claim success. Tell the visitor EXACTLY: "Sorry, I couldn't open that page just now. Would you like me to try again, or is there something else I can help with?" Then STOP and wait for their reply.`)}catch{}return`OK_NAVIGATE_RELOADING. The page is reloading now and this session is ending. Say NOTHING further — do not confirm the navigation, do not describe the page. The arrival greeting is spoken automatically on the new page; you resume from the visitor's next reply.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`fwh-navigate-mvp ✖`,t),cg(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{mg(),lg(900)}},"fwh-highlight-mvp":async e=>{$(`fwh-highlight-mvp ▶`,e);let t=Rg(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(En(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 navigated from "${e.fromPageName}" to "${e.toPageName}" (current path: ${t}) while you were speaking. STOP the current walkthrough immediately. DO NOT call fwh-highlight-mvp again. Say out loud: "I see you've navigated to the ${e.toPageName} page — do you want me to continue what I was explaining, or shall I guide you through this page?" Wait for the visitor's answer before doing anything else.`}Bg();let i=(e=>e&&e.replace(/^\d+\.\s*/,``).replace(/^["']|["']$/g,``).trim())(r),a=Xn(n||null,i||null);if(!a&&i){let e=Date.now()+600;for(;!a&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),Bg(),a=Xn(null,i)}if(!a){$(`fwh-highlight-mvp ✖ no element for:`,i||n);let{headings:e}=Vg(),t=e.length?`Page headings: ${e.map(e=>`"${e}"`).join(` | `)}. Use one of these EXACT strings for section_text — no numbers, no quotes around them.`:`No headings found — skip highlight and continue speaking.`;return`HIGHLIGHT_NOT_FOUND: "${i||n}" on the current page. ${t}`}return hn(a),$(`fwh-highlight-mvp ✓`,i||n),`OK_HIGHLIGHT: "${i||n}". Your NEXT response must be speech only (no tool call) describing THIS section — "${i||n}" — using its own content. Do not ask whether to continue.`},"fwh-read-content-mvp":async e=>{$(`fwh-read-content-mvp ▶`,e);let t=Rg(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=Xn(null,n);if(!t)return`Could not find section "${n}" on the page.`;e=Hg(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=Rg(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=Rg(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(`
|
|
335
338
|
`);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(Og(t=>{for(let r of n)try{t.querySelectorAll(r).forEach(t=>{if(vn(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&&Dg(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(vn(t))return;let n=Ag(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(`
|
|
336
|
-
`);return $(`fwh-list-nav-links-mvp ✓`,`${t.length} links`),`NAV_LINKS (${t.length} total, showing up to 50):\n${r}\n\nIMPORTANT: Use the EXACT text shown above when reading link names to the visitor. Do NOT rename, abbreviate, or invent options not listed here. To navigate, call fwh-navigate-mvp with the href value.`},"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. An email input text box is now visible to the visitor. Say EXACTLY: "Please enter your email in the text box to continue." Then stop and wait silently — do NOT ask them to say it aloud, do NOT repeat, and do NOT answer any other question until you receive the EMAIL_SAVED message.`),"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(sr())return $(`fwh-get-current-page-mvp ✓ 404 detected`,{url:e}),`CURRENT_PAGE_NOT_FOUND. The visitor is currently on a 404 / page-not-found error page (${e}). There is no real content here. Do NOT describe this page, do NOT list sections, do NOT offer a walkthrough, and do NOT describe it from your own knowledge. Tell the visitor plainly that the page they are on doesn't exist, and offer to take them somewhere that does.`;let{headings:r,pageTitleHeading:i,introText:a}=Vg();$(`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?` NOTE: "${i}" is the PAGE TITLE, not a content section — do NOT fwh-highlight-mvp it or list it as a separate section in a walkthrough. Instead, open with a brief 1-2 sentence summary of this intro text before covering the real sections: "${a||`(no intro text captured)`}"`:a?` NOTE: no separate page-title heading was detected, but this intro text appears before the first section — open your walkthrough with a brief 1-2 sentence summary of it before covering sections: "${a}"`:``;if(!r.length)return`CURRENT_PAGE. URL: ${e} | Title: ${n} |${o} No structured section headings found on this page. If there is intro text above, describe it; otherwise describe the page from your knowledge. Do not call this tool again.`;let s=r.map(e=>`"${e}"`).join(` | `);return`CURRENT_PAGE. URL: ${e} | Title: ${n} | Page sections (${r.length} total): ${s}.${o} *** WALKTHROUGH: do NOT drive it yourself. Do not call fwh-highlight-mvp and do not decide the order — highlighting and section order are handled for you. You will be told which section to describe, one at a time. When told, describe ONLY that section in 3-4 sentences and then stop; never announce another section, never ask whether to continue. ***`},"fwh-list-forms-mvp":async()=>{let e=Mg(),t=Ng();$(`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: Form filling is not available at this time. Tell the visitor what fields are present (use fwh-list-forms-mvp) and ask them to fill the form themselves.`,"fwh-click-button-mvp":async e=>{let t=Rg(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 a=Lg(n,i,r);if(!a)return $(`fwh-click-button-mvp ✖ no match`),`Could not find a button matching "${n}". Call fwh-list-forms-mvp to see button texts.`;try{cg(`Clicking ${n}...`,{spinner:!0});try{a.scrollIntoView({block:`center`,inline:`nearest`})}catch{a.scrollIntoView(!0)}await yg(a),a.focus?.(),await xg(a),Sg(a),a.click();let e=(a.textContent||a.value||a.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`fwh-click-button-mvp ✓`,t),cg(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`fwh-click-button-mvp ✖`,t),cg(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{bg(),lg(700)}},"fwh-cart-get-mvp":async()=>{$(`fwh-cart-get-mvp ▶`);try{let e=await Tr();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 Mr(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 Er(n,r);await Dr(e.id,i);let a=await Sr(),s=await o(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}`:``}.${s}`;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 Sr(),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 Or(n,r),a=await o(i),s=`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 ✓`,s),s}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 Sr(),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 Or(t,0),i=await o(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 ▶`),s(kr(),`Cart`)),"fwh-checkout-mvp":async()=>{$(`fwh-checkout-mvp ▶`);try{if(!(await Sr()).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 s(Ar(),`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?s(jr(n),n.replace(/[-_]/g,` `)):`Missing product_handle: search the product first with fwh-shop-search-mvp.`}};async function o(e){try{let{sectionsSwapped:t}=await Br(e);if(!t&&Nr())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 s(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&&I(t,window.location.href,r,n),ir(r),dr().then(()=>{window.location.assign(r)}),`OK_NAVIGATING to ${n}. The page is loading — say one short phrase like "Here you go." and nothing more.`}return{...a,highlightOnPage:a[`fwh-highlight-mvp`],getPageContent:a[`fwh-page-content-mvp`],endVoiceSession:a[`fwh-end-session-mvp`],listPageForms:a[`fwh-list-forms-mvp`],fillFormFields:a[`fwh-fill-form-mvp`],clickPageButton:a[`fwh-click-button-mvp`]}}var Wg=/^(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 Gg(){try{let{headings:e,pageTitleHeading:t}=Vg();return(e||[]).map(e=>typeof e==`string`?e:e?.text||``).filter(Boolean).filter(e=>!t||e.trim()!==t.trim()).filter(e=>!Wg.test(e.trim()))}catch{return[]}}function Kg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=fn();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 qg={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function Jg(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 Yg(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 Xg(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 Zg({logo:e,style:t}){let n=Xg(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 Qg({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 $g(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)||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 e_({orbColors:e,...t}){return(0,f.jsx)(Jh,{colors:e,...t})}function t_({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||qg.green,c=Yg(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)(Vm.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)(Vm.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)(Vm.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)(e_,{size:l,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(Vm.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 n_({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||qg.green,l=Yg(c);return(0,f.jsxs)(Vm.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)(e_,{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 r_({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l,websiteName:u,voiceFirstMessage:p,captureVisitorEmail:m,emailRequired:h,emailCaptureEnabled:g=!0,listeningLabel:_=`Listening...`,thinkingLabel:v=`Thinking...`,enterChatModeLabel:y=`Enter Chat Mode`,endConversationLabel:b=`End Conversation`}){(0,d.useEffect)(()=>(console.log(`[FlowEngage:VoiceDebug] 🔵 VoiceMode MOUNTED`),()=>console.log(`[FlowEngage:VoiceDebug] 🔴 VoiceMode UNMOUNTED`)),[]);let[x,S]=(0,d.useState)(`idle`),[C,w]=(0,d.useState)(!1),[T,E]=(0,d.useState)(!1),[ee,te]=(0,d.useState)(!1),[D,ne]=(0,d.useState)(``),[re,ie]=(0,d.useState)(``),O=(0,d.useRef)(!1),k=(0,d.useRef)(!1),ae=(0,d.useRef)(null),oe=(0,d.useRef)(0),A=(0,d.useRef)(``),se=(0,d.useRef)(!1),j=(0,d.useRef)(0),ce=(0,d.useRef)(!1),M=(0,d.useRef)(!1),N=(0,d.useRef)(!1),P=(0,d.useRef)([]),le=(0,d.useRef)(null),pe=e=>{ce.current=e,e||(M.current=!1),F.current?.setWalkthroughActive?.(e)};le.current=async()=>{if(M.current)return;let e=P.current;he.current+=1;let t=he.current,n=e[t];if(!n){pe(!1),e.length&&F.current?.sendUserMessage?.(`That was the last section. Say so in one short sentence and ask if they want to explore any section further.`);return}try{await ge.current?.highlightOnPage?.({section_text:n})}catch(e){console.warn(`[FlowEngage] walkthrough highlight failed:`,e?.message||e)}console.debug(`[FlowEngage] walkthrough step ${t+1}/${e.length}: ${n}`),F.current?.sendUserMessage?.(`Describe the section titled "${n}" in 3-4 sentences, starting with ${t===0?`Starting with`:`Next —`} ${n}. Describe ONLY this section. If this section contains named sub-items (steps, checklist entries, cards, plans, FAQs, team members), name EVERY one of them in order with a short phrase each — never skip or collapse them into a summary; read the section's content silently first (fwh-read-content-mvp) if you don't already have it. This section is ON THE PAGE THE VISITOR IS ALREADY ON — do NOT call fwh-navigate-mvp, do not go to a product/detail page, and do not offer to, even if this section's name also matches a page name. Do not mention any other section, do not ask whether to continue, then stop.`,{suppressQuestion:!0})};let he=(0,d.useRef)(0),F=(0,d.useRef)(null),ge=(0,d.useRef)(null),_e=(0,d.useRef)(``),ye=(0,d.useRef)(async()=>{}),I=(0,d.useRef)(!1),xe=(0,d.useRef)(!1),Se=(0,d.useRef)(!1),Ce=(0,d.useRef)(!1),we=(0,d.useRef)(`minimized`),Te=(0,d.useRef)(null),L=(0,d.useRef)(null),Ee=(0,d.useRef)(null),De=(0,d.useRef)(0),Oe=(0,d.useRef)(!1),ke=(0,d.useRef)(`idle`),R=(0,d.useRef)(null),Ae=(0,d.useRef)(!1),je=(0,d.useRef)(null),Me=(0,d.useCallback)((e=`minimized`)=>{console.warn(`[FlowEngage:VoiceDebug] 🛑 requestSessionShutdown called`,{destination:e,stack:Error().stack?.split(`
|
|
337
|
-
`).slice(1,4).join(` | `)}),we.current=e,Ce.current=!0,queueMicrotask(()=>{I.current||(I.current=!0,ye.current?.())})},[s]),Ne=(0,d.useCallback)(()=>{ae.current&&=(clearTimeout(ae.current),null)},[]);(0,d.useEffect)(()=>{if(h){O.current=!1;return}if(O.current=!0,k.current=!1,te(!1),Ne(),se.current){se.current=!1,F.current?.setMicMuted?.(!1);let e=A.current;A.current=``,F.current?.injectAgentSpeech?.(`Thanks — I already have your email on file.`,`interrupt`),e&&F.current?.sendUserMessage?.(`The visitor's email is already on file — do not ask for it. Answer their question now: "${e}"`)}F.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.`)},[h,Ne]);let z=/(walk\s*(me\s*)?through|walkthrough|take me through|(complete|full|detailed) (overview|understanding|walkthrough|picture|breakdown|explanation)|give me (a|an|the) (overview|tour|walk)|tell me about (each|all)|go through (it|them|each|all)|overview of|one by one|tell me everything|explain (me )?(this|the) (whole |entire |full )?page|everything (about|on) this page|show me (each|all|around))/i,Pe=/(that covers everything|that was all|covered everything|that(?:'|’)?s everything)/i,Fe=/^((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,Ie=(0,d.useCallback)(()=>{Ne(),ae.current=setTimeout(()=>{if(!(!k.current||O.current))if(oe.current<3){oe.current+=1;try{F.current?.injectAgentSpeech?.(`I still need your email in the box below to continue — could you enter it, please?`,`queue`)}catch{}Ie()}else{try{F.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{}k.current=!1,te(!1),Ne(),Oe.current=!0}},1e4)},[Ne]),Le=(0,d.useCallback)(async e=>{Ce.current=!0;try{gn()}catch{}if(i)try{be(i)}catch{}try{await F.current?.endSession?.()}catch{}let t=Te.current,n=L.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(Te.current=null,L.current=null,F.current=null,S(`idle`),w(!1),I.current=!1,gr(),i)try{fe(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);ye.current=()=>Le(we.current===`chat`?t:n),(0,d.useEffect)(()=>{xe.current=C},[C]),(0,d.useEffect)(()=>{l&&Me(`chat`)},[l]),(0,d.useEffect)(()=>{let e=!1,l=null,d=null,f=null;return(async()=>{if(!i){S(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],_e.current=``,I.current=!1,Se.current=!1,Ce.current=!1,we.current=`minimized`,hr({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=rg(s.current);e&&ue(i,e)}catch{}if(!Fn()){let e=Te.current,t=L.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(()=>{}),Te.current=null,L.current=null}catch{}}me()}});let t=Kg(Ug({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>_e.current,isWalkthroughActive:()=>ce.current&&!M.current,requestEndSession:()=>{Oe.current=!0},requestEmailCollection:()=>{g&&(O.current||k.current||(k.current=!0,oe.current=0,te(!0),Ie()))}})),n=i?de(i):null,r=!!n?.transcript,c=i?be(i):null,m=!!c,_=typeof window<`u`?window.location.pathname:`/`,v=typeof document<`u`?document.title:``,y=_.replace(/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i,``)||`/`,b=y===`/`||y===``,x={apiBaseUrl:a,siteId:i,chatId:o,clientTools:t};ge.current=t;let C=(_.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),T=``;v&&v.includes(`|`)&&(T=v.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let E=T||C||``,ee=E?`the ${E} page`:`this page`,D=(()=>{if(!c?.targetUrl)return!0;try{return new URL(c.targetUrl,window.location.href).pathname.replace(/\/$/,``)===window.location.pathname.replace(/\/$/,``)}catch{return!0}})(),ne=(()=>{if(!c?.targetUrl)return null;try{return new URL(c.targetUrl,window.location.href).pathname}catch{return null}})();if(m&&!D)x.greeting=`You're on ${ee}. What would you like to know?`,console.warn(`[FlowEngage] nav target "${c?.pageName}" not reached — on "${E}" instead; not claiming navigation`);else if(m){let e=c?.pageName?`the ${c.pageName} page`:ee;x.greeting=`I have navigated you to ${e}. Do you want to know about any specific section or want a complete overview?`,console.log(`[FlowEngage] 🔄 Agent-nav resume: greeting set for "${e}" (${_})`)}else if(r)x.greeting=`Welcome back! I see you're now on ${ee}. Would you like me to continue what I was explaining before, or would you like to know about this page instead?`;else{let e=u||``;x.greeting=p||(b?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to ${ee}! How may I help you?`),b||console.log(`[FlowEngage] 🏠 Page-context greeting: "${E}" for ${_}`)}let re=!1,ie=m?`NAVIGATION COMPLETE — The exact phrase "I have navigated you to the [page] page. Do you want to know about any specific section or want a complete overview?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until the visitor responds. When they reply: if they name a specific section → call fwh-get-current-page-mvp then answer immediately; if they say "overview" or anything non-specific → call fwh-get-current-page-mvp (zero speech) then do a full highlighted walkthrough.`:null,ae=!1,fe=!m&&!r?`Your greeting has been spoken. Wait for the visitor to ask a question or tell you what they need. Do NOT auto-start a walkthrough or highlight any sections — let the visitor lead.`:null,ye=r&&!m,Ee=!1,Le=ye?`The question "Would you like me to continue what I was explaining before, or would you like to know about this page instead?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript, or the visitor navigated before saying much)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until they respond. When they reply: if they want you to CONTINUE the previous topic → resume verbally from the prior transcript above, do NOT call fwh-get-current-page-mvp or describe the new page unless they ask. If they want to know about THIS page → call fwh-get-current-page-mvp (zero speech) then proceed as a normal fresh-page walkthrough/description. If their reply is ambiguous, ask them to clarify which they'd prefer rather than guessing.`:null,Re=!1,ze=!1,Be=g&&!!h&&!N.current,Ve=await oh.startSession({...x,onConnect:({conversationId:e})=>{Te.current=e,L.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&&(O.current=!0,k.current=!1,te(!1),Ne(),console.log(`[FlowEngage] email already on file per server — gate disabled`))},onAgentTurnEnd:()=>{e||ce.current&&(M.current||se.current||setTimeout(()=>le.current?.(),250))},onSessionEnding:()=>{e||Me(`minimized`)},onModeChange:({mode:t,tentative:n})=>{if(!e){if(t===`speaking`){R.current&&=(clearTimeout(R.current),null),je.current&&=(clearTimeout(je.current),null),S(`speaking`),ke.current=`speaking`,Ae.current=!1;return}if(t===`user-speaking`){if(je.current&&=(clearTimeout(je.current),null),ke.current===`speaking`)return;try{gn()}catch{}R.current&&=(clearTimeout(R.current),null),ke.current!==`listening`&&(S(`listening`),ke.current=`listening`);return}if(t===`thinking`){if(R.current&&=(clearTimeout(R.current),null),je.current&&=(clearTimeout(je.current),null),ke.current===`speaking`)return;S(`thinking`),ke.current=`thinking`,n&&(je.current=setTimeout(()=>{je.current=null,!(e||ke.current!==`thinking`)&&(ke.current=`listening`,S(`listening`))},4e3));return}if(ke.current=`listening`,Oe.current){Oe.current=!1,Me();return}if(Be&&!ze&&!O.current&&!N.current){ze=!0,re=!0,ae=!0;try{F.current?.sendContextualUpdate?.(`CRITICAL — EMAIL REQUIRED BEFORE ANYTHING ELSE. The visitor has not provided their email. Do NOT speak right now. Wait silently for the visitor to speak first. The MOMENT the visitor says ANYTHING — a question, a request, or just a greeting — your ENTIRE next response must be EXACTLY this one sentence: "Before I answer that, could you please enter your email in the text box below?" Do NOT answer their question. Do NOT say anything about the topic. Do NOT begin an answer and then switch — your first word must be "Before". After you say that sentence, stay completely silent until you receive an EMAIL_SAVED message, then thank them briefly and answer their question in full.`)}catch{}}if(ie&&!re){re=!0;try{F.current?.sendContextualUpdate?.(ie)}catch{}}if(Le&&!Ee){Ee=!0;try{F.current?.sendContextualUpdate?.(Le)}catch{}}if(fe&&!ae){ae=!0;try{F.current?.sendContextualUpdate?.(fe)}catch{}}R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{e||ke.current!==`speaking`&&(Ae.current||(R.current=null,ke.current=`listening`,S(`listening`)))},1200)}},onMessage:t=>{if(e||se.current&&t.role!==`user`&&!/email/i.test(String(t.message||``)))return;if(t.role===`user`&&z.test(String(t.message||``)))typeof window<`u`&&(window.__fe_user_nav_during_speech=null),pe(!0),M.current=!1,j.current=0,he.current=-1,P.current=Gg(),setTimeout(()=>le.current?.(),400),console.log(`[FlowEngage] walkthrough armed — ${P.current.length} sections on this page`);else if(t.role===`user`&&ce.current){let e=String(t.message||``).trim();Fe.test(e)?M.current&&(M.current=!1,console.debug(`[FlowEngage] walkthrough resumed by visitor`),setTimeout(()=>le.current?.(),300)):(M.current=!0,console.debug(`[FlowEngage] walkthrough paused — visitor interjected`))}if(t.role!==`user`&&Pe.test(String(t.message||``))){let e=P.current.length;!e||he.current>=e-1?pe(!1):console.debug(`[FlowEngage] agent claimed completion at step ${he.current+1}/${e} — ignoring, tour continues`)}let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(r){if(n===`user`&&(_e.current=r,typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Ae.current=!0,R.current&&=(clearTimeout(R.current),null),ke.current!==`speaking`&&(S(`thinking`),ke.current=`thinking`),Be&&!Re&&!O.current&&!N.current&&(Re=!0,A.current=r,se.current=!0,F.current?.injectAgentSpeech?.(`Before I answer that, could you please enter your email in the text box below?`,`interrupt`),F.current?.setMicMuted?.(!0),k.current||(k.current=!0,oe.current=0,te(!0),Ie()))),s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString(),debug:t.debug}],i)try{let e=rg(s.current);e&&ue(i,e)}catch{}if($g(n,r)){Oe.current=!0;return}if(xe.current&&n===`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(r))if(De.current+=1,De.current===2)try{F.current?.sendContextualUpdate?.(`IMPORTANT: The visitor is muted and has not responded to your last 2 checks. Make exactly ONE more check. If there is still no response, say: 'I feel like you are not active, so I'm ending this session. You can connect with me anytime.' then immediately call the fwh-end-session-mvp tool to end the voice session. Do NOT ask again after that.`)}catch{}else De.current>=5&&Me(`minimized`)}},onError:t=>{if(!e&&!Ce.current&&!Se.current&&!ve()){Se.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{F.current?.setMicMuted?.(!0)}catch{}w(!0),S(`error`),Me(`chat`)}},onDisconnect:t=>{if(e||Ce.current||Se.current||ve())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:_e.current||``,wasMuted:xe.current}),Se.current=!0;try{F.current?.setMicMuted?.(!0)}catch{}w(!0),Me(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),Ve.endSession().catch(()=>{});return}l=Ve,F.current=Ve,S(`listening`);try{sessionStorage.setItem(`el_conv_${i}`,Ve.getId())}catch{}parent.postMessage({type:`AGENT_EXPAND`},`*`);try{let e=typeof window<`u`?window.location.href:``,a=`[]`;try{a=await t[`fwh-list-forms-mvp`]()}catch{}let o=`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&&(o=[...new Set(n)].slice(0,15).join(` | `))}catch{}let s=r&&!m?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${n?.transcript||``}\n\n`:``;Ve.sendContextualUpdate(`${s}SESSION_CONTEXT (NOT a tool result — do NOT treat as CURRENT_PAGE): Visitor is on: ${e} | Approx headings for awareness only: ${o}. SiteId: ${i||`unknown`}. Forms: ${a}. ${h?``:`Visitor's email is already on file from a prior session — do NOT ask for it again. `}The visitor is ALREADY on this page — do NOT offer to navigate there. WALKTHROUGH RULE: When the visitor asks for a walkthrough or overview of this page, you MUST IMMEDIATELY call fwh-get-current-page-mvp (zero speech — call it silently with NO words before it) to get the exact highlightable headings. The approximate headings above are for routing awareness ONLY — they are NOT precise enough for fwh-highlight-mvp. Do NOT skip fwh-get-current-page-mvp. Voice: call end_voice_session or say you are ending the session to stop.`)}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(ne&&r(i)===r(ne)){t=i;return}if(Date.now()-n<8e3){t=i;return}if(Dn()){t=i;return}let a=t;t=i;let o=window.location.href,s=typeof document<`u`?document.title:``,c=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{gn()}catch{}let l=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,u=l(a),d=l(i);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:a,toPath:i,fromPageName:u,toPageName:d,ts:Date.now()}),console.log(`[FlowEngage] visitor navigation detected: "${a}" → "${i}" (agent target: ${ne||`none`})`);try{F.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${d}" page (${o}). Page title: "${s}". Sections: ${JSON.stringify(c)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${d} page — would you like me to continue what I was explaining, or shall I walk you through this page?" Then wait for my answer. IF I say continue/yes/carry on: resume speaking verbally from where you left off — do NOT call fwh-navigate-mvp, do NOT call fwh-highlight-mvp, the visitor will navigate themselves if needed. IF I want to hear about this page: call fwh-highlight-mvp for sections of "${d}" only.]`)}catch{}};d=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{d(...e),setTimeout(i,50)},f=()=>setTimeout(i,50),window.addEventListener(`popstate`,f)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(S(`error`),we.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,Ce.current=!0;try{gn()}catch{}if(i)try{be(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),gr(),R.current&&=(clearTimeout(R.current),null),je.current&&=(clearTimeout(je.current),null),ae.current&&=(clearTimeout(ae.current),null),Ae.current=!1,ke.current=`idle`,d&&typeof window<`u`&&(window.history.pushState=d),f&&typeof window<`u`&&window.removeEventListener(`popstate`,f);let t=l||F.current,n=Te.current,u=L.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=u?Math.round((Date.now()-u)/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(()=>{}),Te.current=null,L.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Me]),(0,d.useEffect)(()=>{if(!T)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Ee.current&&!Ee.current.contains(t)&&E(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[T]);let Re=async()=>{if(F.current)try{if(C){De.current=0,await F.current.setMicMuted?.(!1),w(!1);try{F.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{De.current=0,await F.current.setMicMuted?.(!0),w(!0);try{F.current.sendContextualUpdate?.(`The visitor has muted their microphone. Do NOT speak, ask if they are there, or prompt them in any way. Stay completely silent until they unmute.`)}catch{}}}catch{}},ze=(0,d.useCallback)(async e=>{e?.preventDefault?.();let t=D.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){ie(`Please enter a valid email address.`);return}ie(``),O.current=!0,k.current=!1,Ne(),te(!1),ne(``),se.current=!1;try{typeof m==`function`&&await m(t)}catch{}F.current?.setMicMuted?.(!1);let n=A.current;A.current=``;try{F.current?.injectAgentSpeech?.(`Thank you for submitting your email.`),F.current?.sendUserMessage?.(n||`The visitor's email is on file. Carry on helping them and never ask for it again.`)}catch{}},[D,m,Ne]),Be=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,f.jsxs)(`div`,{ref:Ee,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:[ee&&(0,f.jsxs)(`form`,{onSubmit:ze,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:D,onChange:e=>{ne(e.target.value),re&&ie(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:re?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),re&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:re}),(0,f.jsx)(`button`,{type:`submit`,disabled:!D.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:D.trim()?Be:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:D.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,f.jsxs)(`div`,{style:{position:`relative`},children:[(x===`listening`||x===`thinking`)&&!C&&(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:x===`thinking`?v:_}),C&&(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)(e_,{size:72,voiceState:x,isMuted:C,orbColors:e})]}),x===`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:Re,title:C?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:C?`#7f1d1d`:`#1f2937`,border:C?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:C?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:C?(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)(sh,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>E(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)(hh,{size:16,color:`currentColor`})})]}),T&&(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:()=>{E(!1),we.current=`chat`,Le(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)(gh,{}),y]}),(0,f.jsxs)(`button`,{onClick:()=>{E(!1),we.current=`minimized`,Le(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)(_h,{}),b]}),(0,f.jsx)(`button`,{onClick:()=>E(!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 i_({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:`
|
|
339
|
+
`);return $(`fwh-list-nav-links-mvp ✓`,`${t.length} links`),`NAV_LINKS (${t.length} total, showing up to 50):\n${r}\n\nIMPORTANT: Use the EXACT text shown above when reading link names to the visitor. Do NOT rename, abbreviate, or invent options not listed here. To navigate, call fwh-navigate-mvp with the href value.`},"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. An email input text box is now visible to the visitor. Say EXACTLY: "Please enter your email in the text box to continue." Then stop and wait silently — do NOT ask them to say it aloud, do NOT repeat, and do NOT answer any other question until you receive the EMAIL_SAVED message.`),"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(sr())return $(`fwh-get-current-page-mvp ✓ 404 detected`,{url:e}),`CURRENT_PAGE_NOT_FOUND. The visitor is currently on a 404 / page-not-found error page (${e}). There is no real content here. Do NOT describe this page, do NOT list sections, do NOT offer a walkthrough, and do NOT describe it from your own knowledge. Tell the visitor plainly that the page they are on doesn't exist, and offer to take them somewhere that does.`;let{headings:r,pageTitleHeading:i,introText:a}=Vg();$(`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?` NOTE: "${i}" is the PAGE TITLE, not a content section — do NOT fwh-highlight-mvp it or list it as a separate section in a walkthrough. Instead, open with a brief 1-2 sentence summary of this intro text before covering the real sections: "${a||`(no intro text captured)`}"`:a?` NOTE: no separate page-title heading was detected, but this intro text appears before the first section — open your walkthrough with a brief 1-2 sentence summary of it before covering sections: "${a}"`:``;if(!r.length)return`CURRENT_PAGE. URL: ${e} | Title: ${n} |${o} No structured section headings found on this page. If there is intro text above, describe it; otherwise describe the page from your knowledge. Do not call this tool again.`;let s=r.map(e=>`"${e}"`).join(` | `);return`CURRENT_PAGE. URL: ${e} | Title: ${n} | Page sections (${r.length} total): ${s}.${o} *** WALKTHROUGH: do NOT drive it yourself. Do not call fwh-highlight-mvp and do not decide the order — highlighting and section order are handled for you. You will be told which section to describe, one at a time. When told, describe ONLY that section in 3-4 sentences and then stop; never announce another section, never ask whether to continue. ***`},"fwh-list-forms-mvp":async()=>{let e=Mg(),t=Ng();$(`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: Form filling is not available at this time. Tell the visitor what fields are present (use fwh-list-forms-mvp) and ask them to fill the form themselves.`,"fwh-click-button-mvp":async e=>{let t=Rg(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 a=Lg(n,i,r);if(!a)return $(`fwh-click-button-mvp ✖ no match`),`Could not find a button matching "${n}". Call fwh-list-forms-mvp to see button texts.`;try{cg(`Clicking ${n}...`,{spinner:!0});try{a.scrollIntoView({block:`center`,inline:`nearest`})}catch{a.scrollIntoView(!0)}await yg(a),a.focus?.(),await xg(a),Sg(a),a.click();let e=(a.textContent||a.value||a.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`fwh-click-button-mvp ✓`,t),cg(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`fwh-click-button-mvp ✖`,t),cg(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{bg(),lg(700)}},"fwh-cart-get-mvp":async()=>{$(`fwh-cart-get-mvp ▶`);try{let e=await Tr();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 Mr(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 Er(n,r);await Dr(e.id,i);let a=await Sr(),s=await o(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}`:``}.${s}`;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 Sr(),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 Or(n,r),a=await o(i),s=`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 ✓`,s),s}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 Sr(),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 Or(t,0),i=await o(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 ▶`),s(kr(),`Cart`)),"fwh-checkout-mvp":async()=>{$(`fwh-checkout-mvp ▶`);try{if(!(await Sr()).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 s(Ar(),`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?s(jr(n),n.replace(/[-_]/g,` `)):`Missing product_handle: search the product first with fwh-shop-search-mvp.`}};async function o(e){try{let{sectionsSwapped:t}=await Br(e);if(!t&&Nr())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 s(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&&I(t,window.location.href,r,n),ir(r),dr().then(()=>{window.location.assign(r)}),`OK_NAVIGATING to ${n}. The page is loading — say one short phrase like "Here you go." and nothing more.`}return{...a,highlightOnPage:a[`fwh-highlight-mvp`],getPageContent:a[`fwh-page-content-mvp`],endVoiceSession:a[`fwh-end-session-mvp`],listPageForms:a[`fwh-list-forms-mvp`],fillFormFields:a[`fwh-fill-form-mvp`],clickPageButton:a[`fwh-click-button-mvp`]}}var Wg=/^(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 Gg(){try{let{headings:e,pageTitleHeading:t}=Vg();return(e||[]).map(e=>typeof e==`string`?e:e?.text||``).filter(Boolean).filter(e=>!t||e.trim()!==t.trim()).filter(e=>!Wg.test(e.trim()))}catch{return[]}}function Kg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=fn();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 qg={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function Jg(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 Yg(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 Xg(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 Zg({logo:e,style:t}){let n=Xg(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 Qg({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 $g(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)||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 e_({orbColors:e,...t}){return(0,f.jsx)(Jh,{colors:e,...t})}function t_({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||qg.green,c=Yg(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)(Vm.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)(Vm.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)(Vm.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)(e_,{size:l,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(Vm.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 n_({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||qg.green,l=Yg(c);return(0,f.jsxs)(Vm.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)(e_,{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 r_({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l,websiteName:u,voiceFirstMessage:p,captureVisitorEmail:m,emailRequired:h,emailCaptureEnabled:g=!0,listeningLabel:_=`Listening...`,thinkingLabel:v=`Thinking...`,enterChatModeLabel:y=`Enter Chat Mode`,endConversationLabel:b=`End Conversation`}){(0,d.useEffect)(()=>(console.log(`[FlowEngage:VoiceDebug] 🔵 VoiceMode MOUNTED`),()=>console.log(`[FlowEngage:VoiceDebug] 🔴 VoiceMode UNMOUNTED`)),[]);let[x,S]=(0,d.useState)(`idle`),[C,w]=(0,d.useState)(!1),[T,E]=(0,d.useState)(!1),[ee,te]=(0,d.useState)(!1),[D,ne]=(0,d.useState)(``),[re,ie]=(0,d.useState)(``),O=(0,d.useRef)(!1),k=(0,d.useRef)(!1),ae=(0,d.useRef)(null),oe=(0,d.useRef)(0),A=(0,d.useRef)(``),se=(0,d.useRef)(!1),j=(0,d.useRef)(0),ce=(0,d.useRef)(!1),M=(0,d.useRef)(!1),N=(0,d.useRef)(!1),P=(0,d.useRef)([]),le=(0,d.useRef)(null),pe=e=>{ce.current=e,e||(M.current=!1),F.current?.setWalkthroughActive?.(e)};le.current=async()=>{if(M.current)return;let e=P.current;he.current+=1;let t=he.current,n=e[t];if(!n){if(pe(!1),e.length)F.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(t===0){let e=``;try{let t=await ge.current?.[`fwh-read-content-mvp`]?.({});typeof t==`string`&&t&&!/^Could not/i.test(t)&&(e=t.slice(0,2800))}catch{}F.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 ge.current?.highlightOnPage?.({section_text:n})}catch(e){console.warn(`[FlowEngage] walkthrough highlight failed:`,e?.message||e)}console.debug(`[FlowEngage] walkthrough step ${t+1}/${e.length}: ${n}`);let r=``;try{let e=await ge.current?.[`fwh-read-content-mvp`]?.({section_text:n});typeof e==`string`&&e&&!/^Could not/i.test(e)&&(r=e.slice(0,2500))}catch{}let i=r?`Here is this section's full content — describe it from THIS text only, and do not call any tool:\n"""${r}"""\n`:`read the section's content silently first (fwh-read-content-mvp) if you don't already have it. `;F.current?.sendUserMessage?.(`Describe the section titled "${n}" in 3-4 sentences, starting with ${t===0?`Starting with`:`Next —`} ${n}. Describe ONLY this section. If this section contains named sub-items (steps, checklist entries, cards, plans, FAQs, team members), name EVERY one of them in order with a short phrase each — never skip or collapse them into a summary; `+i+`This section is ON THE PAGE THE VISITOR IS ALREADY ON — do NOT call fwh-navigate-mvp, do not go to a product/detail page, and do not offer to, even if this section's name also matches a page name. Do not mention any other section, do not ask whether to continue, then stop.`,{suppressQuestion:!0})};let he=(0,d.useRef)(0),F=(0,d.useRef)(null),ge=(0,d.useRef)(null),_e=(0,d.useRef)(``),ye=(0,d.useRef)(async()=>{}),I=(0,d.useRef)(!1),xe=(0,d.useRef)(!1),Se=(0,d.useRef)(!1),Ce=(0,d.useRef)(!1),we=(0,d.useRef)(`minimized`),Te=(0,d.useRef)(null),L=(0,d.useRef)(null),Ee=(0,d.useRef)(null),De=(0,d.useRef)(0),Oe=(0,d.useRef)(!1),ke=(0,d.useRef)(`idle`),R=(0,d.useRef)(null),Ae=(0,d.useRef)(!1),je=(0,d.useRef)(null),Me=(0,d.useCallback)((e=`minimized`)=>{console.warn(`[FlowEngage:VoiceDebug] 🛑 requestSessionShutdown called`,{destination:e,stack:Error().stack?.split(`
|
|
340
|
+
`).slice(1,4).join(` | `)}),we.current=e,Ce.current=!0,queueMicrotask(()=>{I.current||(I.current=!0,ye.current?.())})},[s]),Ne=(0,d.useCallback)(()=>{ae.current&&=(clearTimeout(ae.current),null)},[]);(0,d.useEffect)(()=>{if(h){O.current=!1;return}if(O.current=!0,k.current=!1,te(!1),Ne(),se.current){se.current=!1,F.current?.setMicMuted?.(!1);let e=A.current;A.current=``,F.current?.injectAgentSpeech?.(`Thanks — I already have your email on file.`,`interrupt`),e&&F.current?.sendUserMessage?.(`The visitor's email is already on file — do not ask for it. Answer their question now: "${e}"`)}F.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.`)},[h,Ne]);let z=/(walk\s*(me\s*)?through|walkthrough|take me through|(complete|full|detailed) (overview|understanding|walkthrough|picture|breakdown|explanation)|give me (a|an|the) (overview|tour|walk)|tell me about (each|all)|go through (it|them|each|all)|overview of|one by one|tell me everything|explain (me )?(this|the) (whole |entire |full )?page|everything (about|on) this page|show me (each|all|around))/i,Pe=/(that covers everything|that was all|covered everything|that(?:'|’)?s everything)/i,Fe=/^((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,Ie=(0,d.useCallback)(()=>{Ne(),ae.current=setTimeout(()=>{if(!(!k.current||O.current))if(oe.current<3){oe.current+=1;try{F.current?.injectAgentSpeech?.(`I still need your email in the box below to continue — could you enter it, please?`,`queue`)}catch{}Ie()}else{try{F.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{}k.current=!1,te(!1),Ne(),Oe.current=!0}},1e4)},[Ne]),Le=(0,d.useCallback)(async e=>{Ce.current=!0;try{gn()}catch{}if(i)try{be(i)}catch{}try{await F.current?.endSession?.()}catch{}let t=Te.current,n=L.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(Te.current=null,L.current=null,F.current=null,S(`idle`),w(!1),I.current=!1,gr(),i)try{fe(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);ye.current=()=>Le(we.current===`chat`?t:n),(0,d.useEffect)(()=>{xe.current=C},[C]),(0,d.useEffect)(()=>{l&&Me(`chat`)},[l]),(0,d.useEffect)(()=>{let e=!1,l=null,d=null,f=null;return(async()=>{if(!i){S(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],_e.current=``,I.current=!1,Se.current=!1,Ce.current=!1,we.current=`minimized`,hr({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=rg(s.current);e&&ue(i,e)}catch{}if(!Fn()){let e=Te.current,t=L.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(()=>{}),Te.current=null,L.current=null}catch{}}me()}});let t=Kg(Ug({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>_e.current,isWalkthroughActive:()=>ce.current&&!M.current,requestEndSession:()=>{Oe.current=!0},requestEmailCollection:()=>{g&&(O.current||k.current||(k.current=!0,oe.current=0,te(!0),Ie()))}})),n=i?de(i):null,r=!!n?.transcript,c=i?be(i):null,m=!!c,_=typeof window<`u`?window.location.pathname:`/`,v=typeof document<`u`?document.title:``,y=_.replace(/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i,``)||`/`,b=y===`/`||y===``,x={apiBaseUrl:a,siteId:i,chatId:o,clientTools:t};ge.current=t;let C=(_.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),T=``;v&&v.includes(`|`)&&(T=v.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let E=T||C||``,ee=E?`the ${E} page`:`this page`,D=(()=>{if(!c?.targetUrl)return!0;try{return new URL(c.targetUrl,window.location.href).pathname.replace(/\/$/,``)===window.location.pathname.replace(/\/$/,``)}catch{return!0}})(),ne=(()=>{if(!c?.targetUrl)return null;try{return new URL(c.targetUrl,window.location.href).pathname}catch{return null}})();if(m&&!D)x.greeting=`You're on ${ee}. What would you like to know?`,console.warn(`[FlowEngage] nav target "${c?.pageName}" not reached — on "${E}" instead; not claiming navigation`);else if(m){let e=c?.pageName?`the ${c.pageName} page`:ee;x.greeting=`I have navigated you to ${e}. Do you want to know about any specific section or want a complete overview?`,console.log(`[FlowEngage] 🔄 Agent-nav resume: greeting set for "${e}" (${_})`)}else if(r)x.greeting=`Welcome back! I see you're now on ${ee}. Would you like me to continue what I was explaining before, or would you like to know about this page instead?`;else{let e=u||``;x.greeting=p||(b?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to ${ee}! How may I help you?`),b||console.log(`[FlowEngage] 🏠 Page-context greeting: "${E}" for ${_}`)}let re=!1,ie=m?`NAVIGATION COMPLETE — The exact phrase "I have navigated you to the [page] page. Do you want to know about any specific section or want a complete overview?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until the visitor responds. When they reply: if they name a specific section → call fwh-get-current-page-mvp then answer immediately; if they say "overview" or anything non-specific → call fwh-get-current-page-mvp (zero speech) then do a full highlighted walkthrough.`:null,ae=!1,fe=!m&&!r?`Your greeting has been spoken. Wait for the visitor to ask a question or tell you what they need. Do NOT auto-start a walkthrough or highlight any sections — let the visitor lead.`:null,ye=r&&!m,Ee=!1,Le=ye?`The question "Would you like me to continue what I was explaining before, or would you like to know about this page instead?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript, or the visitor navigated before saying much)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until they respond. When they reply: if they want you to CONTINUE the previous topic → resume verbally from the prior transcript above, do NOT call fwh-get-current-page-mvp or describe the new page unless they ask. If they want to know about THIS page → call fwh-get-current-page-mvp (zero speech) then proceed as a normal fresh-page walkthrough/description. If their reply is ambiguous, ask them to clarify which they'd prefer rather than guessing.`:null,Re=!1,ze=!1,Be=g&&!!h&&!N.current,Ve=await oh.startSession({...x,onConnect:({conversationId:e})=>{Te.current=e,L.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&&(O.current=!0,k.current=!1,te(!1),Ne(),console.log(`[FlowEngage] email already on file per server — gate disabled`))},onAgentTurnEnd:()=>{e||ce.current&&(M.current||se.current||setTimeout(()=>le.current?.(),250))},onSessionEnding:()=>{e||Me(`minimized`)},onModeChange:({mode:t,tentative:n})=>{if(!e){if(t===`speaking`){R.current&&=(clearTimeout(R.current),null),je.current&&=(clearTimeout(je.current),null),S(`speaking`),ke.current=`speaking`,Ae.current=!1;return}if(t===`user-speaking`){if(je.current&&=(clearTimeout(je.current),null),ke.current===`speaking`)return;try{gn()}catch{}R.current&&=(clearTimeout(R.current),null),ke.current!==`listening`&&(S(`listening`),ke.current=`listening`);return}if(t===`thinking`){if(R.current&&=(clearTimeout(R.current),null),je.current&&=(clearTimeout(je.current),null),ke.current===`speaking`)return;S(`thinking`),ke.current=`thinking`,n&&(je.current=setTimeout(()=>{je.current=null,!(e||ke.current!==`thinking`)&&(ke.current=`listening`,S(`listening`))},4e3));return}if(ke.current=`listening`,Oe.current){Oe.current=!1,Me();return}if(Be&&!ze&&!O.current&&!N.current){ze=!0,re=!0,ae=!0;try{F.current?.sendContextualUpdate?.(`CRITICAL — EMAIL REQUIRED BEFORE ANYTHING ELSE. The visitor has not provided their email. Do NOT speak right now. Wait silently for the visitor to speak first. The MOMENT the visitor says ANYTHING — a question, a request, or just a greeting — your ENTIRE next response must be EXACTLY this one sentence: "Before I answer that, could you please enter your email in the text box below?" Do NOT answer their question. Do NOT say anything about the topic. Do NOT begin an answer and then switch — your first word must be "Before". After you say that sentence, stay completely silent until you receive an EMAIL_SAVED message, then thank them briefly and answer their question in full.`)}catch{}}if(ie&&!re){re=!0;try{F.current?.sendContextualUpdate?.(ie)}catch{}}if(Le&&!Ee){Ee=!0;try{F.current?.sendContextualUpdate?.(Le)}catch{}}if(fe&&!ae){ae=!0;try{F.current?.sendContextualUpdate?.(fe)}catch{}}R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{e||ke.current!==`speaking`&&(Ae.current||(R.current=null,ke.current=`listening`,S(`listening`)))},1200)}},onMessage:t=>{if(e||se.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()),r=/\b(?:this|that|the)\s+(?:case\s*stud(?:y|ies)|product|article|blog|post|item|service)\b/i.test(String(t.message||``));if(!n&&!r&&t.role===`user`&&z.test(String(t.message||``)))typeof window<`u`&&(window.__fe_user_nav_during_speech=null),pe(!0),M.current=!1,j.current=0,he.current=-1,P.current=Gg(),setTimeout(()=>le.current?.(),400),console.log(`[FlowEngage] walkthrough armed — ${P.current.length} sections on this page`);else if(!n&&t.role===`user`&&ce.current){let e=String(t.message||``).trim();Fe.test(e)?M.current&&(M.current=!1,console.debug(`[FlowEngage] walkthrough resumed by visitor`),setTimeout(()=>le.current?.(),300)):(M.current=!0,console.debug(`[FlowEngage] walkthrough paused — visitor interjected`))}if(t.role!==`user`&&Pe.test(String(t.message||``))){let e=P.current.length;!e||he.current>=e-1?pe(!1):console.debug(`[FlowEngage] agent claimed completion at step ${he.current+1}/${e} — ignoring, tour continues`)}let a=t.role===`user`?`user`:`bot`,o=t.message||t.text||t.content||``;if(o){if(a===`user`&&(_e.current=o,typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Ae.current=!0,R.current&&=(clearTimeout(R.current),null),ke.current!==`speaking`&&(S(`thinking`),ke.current=`thinking`),Be&&!Re&&!O.current&&!N.current&&(Re=!0,A.current=o,se.current=!0,F.current?.injectAgentSpeech?.(`Before I answer that, could you please enter your email in the text box below?`,`interrupt`),F.current?.setMicMuted?.(!0),k.current||(k.current=!0,oe.current=0,te(!0),Ie()))),s.current=[...s.current,{sender:a,message:o,timestamp:new Date().toISOString(),debug:t.debug}],i)try{let e=rg(s.current);e&&ue(i,e)}catch{}if($g(a,o)){Oe.current=!0;return}if(xe.current&&a===`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(o))if(De.current+=1,De.current===2)try{F.current?.sendContextualUpdate?.(`IMPORTANT: The visitor is muted and has not responded to your last 2 checks. Make exactly ONE more check. If there is still no response, say: 'I feel like you are not active, so I'm ending this session. You can connect with me anytime.' then immediately call the fwh-end-session-mvp tool to end the voice session. Do NOT ask again after that.`)}catch{}else De.current>=5&&Me(`minimized`)}},onError:t=>{if(!e&&!Ce.current&&!Se.current&&!ve()){Se.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{F.current?.setMicMuted?.(!0)}catch{}w(!0),S(`error`),Me(`chat`)}},onDisconnect:t=>{if(e||Ce.current||Se.current||ve())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:_e.current||``,wasMuted:xe.current}),Se.current=!0;try{F.current?.setMicMuted?.(!0)}catch{}w(!0),Me(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),Ve.endSession().catch(()=>{});return}l=Ve,F.current=Ve,S(`listening`);try{sessionStorage.setItem(`el_conv_${i}`,Ve.getId())}catch{}parent.postMessage({type:`AGENT_EXPAND`},`*`);try{let e=typeof window<`u`?window.location.href:``,a=`[]`;try{a=await t[`fwh-list-forms-mvp`]()}catch{}let o=`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&&(o=[...new Set(n)].slice(0,15).join(` | `))}catch{}let s=r&&!m?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${n?.transcript||``}\n\n`:``;Ve.sendContextualUpdate(`${s}SESSION_CONTEXT (NOT a tool result — do NOT treat as CURRENT_PAGE): Visitor is on: ${e} | Approx headings for awareness only: ${o}. SiteId: ${i||`unknown`}. Forms: ${a}. ${h?``:`Visitor's email is already on file from a prior session — do NOT ask for it again. `}The visitor is ALREADY on this page — do NOT offer to navigate there. WALKTHROUGH RULE: When the visitor asks for a walkthrough or overview of this page, you MUST IMMEDIATELY call fwh-get-current-page-mvp (zero speech — call it silently with NO words before it) to get the exact highlightable headings. The approximate headings above are for routing awareness ONLY — they are NOT precise enough for fwh-highlight-mvp. Do NOT skip fwh-get-current-page-mvp. Voice: call end_voice_session or say you are ending the session to stop.`)}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=ne&&r(i)===r(ne)||Dn()||a&&Date.now()-a.ts<15e3&&r(a.path)===r(i),s=t;t=i;let c=window.location.href,l=typeof document<`u`?document.title:``,u=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{gn()}catch{}let 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{F.current?.sendUserMessage?.(`[SYSTEM: YOU just navigated the visitor to the "${p}" page (${c}) at their request — this was YOUR action, not theirs. Page title: "${l}". Sections: ${JSON.stringify(u)}. Say: "Here we are on the ${p} page." Then introduce this page in 2-3 sentences, and finish by asking: "Would you like me to walk you through it section by section?" NEVER say "I see you've navigated" — the visitor did not navigate, you did. Do NOT call fwh-navigate-mvp again. Wait for their answer before describing sections.]`,{suppressQuestion:!0})}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: ${ne||`none`})`);try{F.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${p}" page (${c}). Page title: "${l}". Sections: ${JSON.stringify(u)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${p} page — would you like me to continue what I was explaining, or shall I walk you through this page?" Then wait for my answer. IF I say continue/yes/carry on: resume speaking verbally from where you left off — do NOT call fwh-navigate-mvp, do NOT call fwh-highlight-mvp, the visitor will navigate themselves if needed. IF I want to hear about this page: call fwh-highlight-mvp for sections of "${p}" only.]`)}catch{}};d=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{d(...e),setTimeout(i,50)},f=()=>setTimeout(i,50),window.addEventListener(`popstate`,f)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(S(`error`),we.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,Ce.current=!0;try{gn()}catch{}if(i)try{be(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),gr(),R.current&&=(clearTimeout(R.current),null),je.current&&=(clearTimeout(je.current),null),ae.current&&=(clearTimeout(ae.current),null),Ae.current=!1,ke.current=`idle`,d&&typeof window<`u`&&(window.history.pushState=d),f&&typeof window<`u`&&window.removeEventListener(`popstate`,f);let t=l||F.current,n=Te.current,u=L.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=u?Math.round((Date.now()-u)/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(()=>{}),Te.current=null,L.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Me]),(0,d.useEffect)(()=>{if(!T)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Ee.current&&!Ee.current.contains(t)&&E(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[T]);let Re=async()=>{if(F.current)try{if(C){De.current=0,await F.current.setMicMuted?.(!1),w(!1);try{F.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{De.current=0,await F.current.setMicMuted?.(!0),w(!0);try{F.current.sendContextualUpdate?.(`The visitor has muted their microphone. Do NOT speak, ask if they are there, or prompt them in any way. Stay completely silent until they unmute.`)}catch{}}}catch{}},ze=(0,d.useCallback)(async e=>{e?.preventDefault?.();let t=D.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){ie(`Please enter a valid email address.`);return}ie(``),O.current=!0,k.current=!1,Ne(),te(!1),ne(``),se.current=!1;try{typeof m==`function`&&await m(t)}catch{}F.current?.setMicMuted?.(!1);let n=A.current;A.current=``;try{F.current?.injectAgentSpeech?.(`Thank you for submitting your email.`),F.current?.sendUserMessage?.(n||`The visitor's email is on file. Carry on helping them and never ask for it again.`)}catch{}},[D,m,Ne]),Be=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,f.jsxs)(`div`,{ref:Ee,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:[ee&&(0,f.jsxs)(`form`,{onSubmit:ze,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:D,onChange:e=>{ne(e.target.value),re&&ie(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:re?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),re&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:re}),(0,f.jsx)(`button`,{type:`submit`,disabled:!D.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:D.trim()?Be:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:D.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,f.jsxs)(`div`,{style:{position:`relative`},children:[(x===`listening`||x===`thinking`)&&!C&&(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:x===`thinking`?v:_}),C&&(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)(e_,{size:72,voiceState:x,isMuted:C,orbColors:e})]}),x===`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:Re,title:C?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:C?`#7f1d1d`:`#1f2937`,border:C?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:C?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:C?(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)(sh,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>E(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)(hh,{size:16,color:`currentColor`})})]}),T&&(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:()=>{E(!1),we.current=`chat`,Le(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)(gh,{}),y]}),(0,f.jsxs)(`button`,{onClick:()=>{E(!1),we.current=`minimized`,Le(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)(_h,{}),b]}),(0,f.jsx)(`button`,{onClick:()=>E(!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 i_({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:`
|
|
338
341
|
radial-gradient(circle at 18% 50%, ${n} 0%, ${n}99 35%, transparent 65%),
|
|
339
342
|
radial-gradient(circle at 82% 50%, ${r} 0%, ${r}99 35%, transparent 65%),
|
|
340
343
|
radial-gradient(circle at 50% 82%, ${i} 0%, ${i}99 30%, transparent 58%),
|