@flowengage/react-chatbot 8.0.109 → 8.0.110
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.
|
@@ -33,18 +33,18 @@ Error generating stack: `+e.message+`
|
|
|
33
33
|
box-shadow: none !important;
|
|
34
34
|
transition: outline-color 0.25s ease, box-shadow 0.25s ease !important;
|
|
35
35
|
}
|
|
36
|
-
`,document.head.appendChild(e)};function ur(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(jn(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(Mn(e).toLowerCase()===n)return e;for(let e of i){let t=Mn(e).toLowerCase();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=Mn(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=Mn(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=Mn(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=>!jn(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(jn(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(jn(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(jn(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=>!jn(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(jn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function dr(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;lr();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 fr(){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`)),kn())}function pr(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 mr(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 hr(e,{siteId:t,apiBaseUrl:n}){if(!e)return{allowed:!1,correctedUrl:null};let r=!1;try{r=!!Yn()}catch{r=!1}let i=async()=>({allowed:r?!1:await mr(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 gr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Pn,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function _r(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}or();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 sr(),!1;let o=await a.text(),s=new DOMParser().parseFromString(o,`text/html`),c=document.getElementById(`flowengage-root`);if(!c)return sr(),!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()}),Zn();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(Xn,`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(Xn,`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,Nn(`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){Nn(`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,Nn(`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){Nn(`trySpaNavigate: blocked location.assign from replayed script:`,e);return}return d(e)},window.location.replace=e=>{if(p){Nn(`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;Nn(`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)){Nn(`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:`)&&(Nn(`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`)||``}),Nn(`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),Nn(`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(Wn(),Kn(),n){try{er()}catch{}try{rr()}catch{}}else window.scrollTo(0,0);sr(),ir(e);try{sessionStorage.removeItem(Pn)}catch{}try{sessionStorage.removeItem(In)}catch{}try{Un=new URL(e,window.location.origin).pathname}catch{}return Nn(`trySpaNavigate: succeeded →`,e),!0}catch{return clearTimeout(i),sr(),!1}}function vr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(In,JSON.stringify({voiceWasActive:!0,targetUrl:String(e),ts:Date.now()}))}catch{}}function yr(){if(!(typeof sessionStorage>`u`))try{sessionStorage.removeItem(In)}catch{}}function br(){if(typeof window>`u`||typeof sessionStorage>`u`)return{shouldResumeVoice:!1,targetUrl:null};let e;try{e=JSON.parse(sessionStorage.getItem(In)||`null`)}catch{return{shouldResumeVoice:!1,targetUrl:null}}if(!e)return{shouldResumeVoice:!1,targetUrl:null};try{sessionStorage.removeItem(In)}catch{}return e.voiceWasActive?Date.now()-e.ts>Ln?(Nn(`initVoiceNavResume: state expired, skipping`),{shouldResumeVoice:!1,targetUrl:null}):(Nn(`initVoiceNavResume: voice was active during navigation to`,e.targetUrl),{shouldResumeVoice:!0,targetUrl:e.targetUrl||null}):{shouldResumeVoice:!1,targetUrl:null}}function xr(){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 Sr=6e3,Cr=250,wr=700;async function Tr(){if(typeof window>`u`)return;let e=window.__fe_agentAudioPlaying;if(typeof e!=`function`){await new Promise(e=>setTimeout(e,wr));return}let t=Date.now()+Sr;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,Cr))}async function Er(e,t={}){if(typeof window>`u`)return{navigated:!1};let{sectionText:n,voiceActive:r=!1}=t;try{let t=pr(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&&gr(n),r||we(),r?Tr().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(Yn()){n&&gr(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)),xr()){try{window.history.pushState({},``,e),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}}))}catch{}return n&&gr(n),r||we(),window.location.assign(i.href),{navigated:!0}}return{navigated:!0}}return n&&gr(n),r||we(),window.location.assign(i.href),{navigated:!0}}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&gr(n);try{window.location.href=pr(e)}catch{window.location.href=e}return{navigated:!0}}}var Dr=!1,Or=null;function kr(e){Or=e,typeof window<`u`&&(window.__fe_triggerVoiceNavHooks=()=>{try{e.onBeforeNavigate()}catch{}}),!Dr&&(Dr=!0,!(typeof document>`u`)&&(document.addEventListener(`click`,e=>{if(!Or)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)){Nn(`voice-link-hook: saving state before navigation →`,r.href);try{Or.onBeforeNavigate()}catch{}}},!0),document.addEventListener(`submit`,e=>{if(Or&&!e.target?.closest?.(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)){Nn(`voice-form-hook: saving state before form submit`);try{Or.onBeforeNavigate()}catch{}}},!0)))}function Ar(){Or=null,Nn(`voice-nav-hooks: deactivated`)}var jr=4e3,Mr=null;function Nr(){let e=typeof window<`u`&&window.Shopify?.routes?.root||`/`;return e.endsWith(`/`)?e:`${e}/`}async function Pr(e,t={}){let n=new AbortController,r=setTimeout(()=>n.abort(),jr);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 Fr(){if(Mr!==null)return Mr;if(typeof window>`u`)return Mr=!1;if(window.Shopify)return Mr=!0;try{let e=await Pr(`${Nr()}cart.js`);Mr=e&&typeof e.item_count==`number`}catch{Mr=!1}return Mr}async function Ir(){return Pr(`${Nr()}cart.js`)}function Lr(){return typeof window>`u`?null:window.__flowengageCustomer?.id||null}function Rr(e){return typeof e!=`number`||Number.isNaN(e)?null:(e/100).toFixed(2)}async function zr(){try{if(!await Fr())return null;let e=await Ir();return{itemCount:e.item_count,subtotal:Rr(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:Rr(e.final_line_price??e.line_price),handle:e.handle||null}))}}catch{return null}}async function Br(e,t=null){let n=await Pr(`${Nr()}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 Vr(e,t=1){return Pr(`${Nr()}cart/add.js`,{method:`POST`,body:JSON.stringify({items:[{id:e,quantity:t}]})})}async function Hr(e,t){return Pr(`${Nr()}cart/change.js`,{method:`POST`,body:JSON.stringify({line:e,quantity:t})})}function Ur(){return`${Nr()}cart`}function Wr(){return`${Nr()}checkout`}function Gr(e){return`${Nr()}products/${encodeURIComponent(e)}`}async function Kr(e,t=6){let n=new URLSearchParams({q:e,"resources[type]":`product`,"resources[limit]":String(t)});try{return((await Pr(`${Nr()}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 qr(){return typeof window>`u`?!1:/\/cart\/?$/.test(window.location.pathname)}var Jr=[`form[action*="/cart"]`,`cart-items`,`cart-drawer-items`,`.cart-items`,`.cart__items`,`#main-cart-items`,`[data-cart-items]`].join(`, `);function Yr(e){if(/cart/i.test(e.id))return!0;try{return!!e.querySelector(Jr)}catch{return!1}}async function Xr(){if(typeof document>`u`)return!1;let e=Array.from(document.querySelectorAll(`[id^="shopify-section-"]`)).filter(Yr);if(!e.length)return!1;let t=e.map(e=>e.id.replace(/^shopify-section-/,``));try{let e=await Pr(`${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 Zr=[`[data-cart-count]`,`.cart-count-bubble`,`.cart-count`,`#CartCount`,`.cart-link__bubble`,`.site-header__cart-count`,`#cart-icon-bubble`];function Qr(e){if(typeof document>`u`)return;let t=String(e);for(let e of Zr)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 $r(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 ei(e){let t=await Xr();return!t&&qr()&&(await new Promise(e=>setTimeout(e,600)),t=await Xr()),e&&typeof e.item_count==`number`&&Qr(e.item_count),$r(e||null),{sectionsSwapped:t}}async function ti(e){try{let{sectionsSwapped:t}=await ei(e);if(!t&&qr())return` (The list on this page may need a quick refresh to show it.)`}catch{}return``}function ni(e){let t=Rr(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 ri(e,t){let n=t.title&&t.title!==`Default Title`;return`${e.title}${n?` (${t.title})`:``}`}function ii(e,t){return e?.userMessage||t}var ai={async add(e){let{variant:t,product:n}=await Br(e.productHandle,e.variantTitle||null);await Vr(t.id,e.quantity||1);let r=await Ir(),i=await ti(r);return{message:`✅ Added ${e.quantity||1} × ${ri(n,t)} to your cart.${ni(r)}${i}`}},async update(e){let t=(await Ir()).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 Hr(e.line,e.quantity),r=await ti(n);return{message:`✅ Updated ${t.product_title||t.title} to quantity ${e.quantity}.${ni(n)}${r}`}},async remove(e){let t=(await Ir()).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 Hr(e.line,0),r=await ti(n);return{message:`🗑️ Removed ${t.product_title||t.title} from your cart.${ni(n)}${r}`}},async view_cart(){return{message:`Opening your cart…`,navigateTo:Ur()}},async checkout(){return(await Ir()).item_count?{message:`Taking you to checkout…`,navigateTo:Wr()}:{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:Gr(e.productHandle)}}},oi={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 si(e){let t={messages:[],navigateTo:null};if(!Array.isArray(e)||e.length===0)return t;if(!await Fr())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=ai[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(ii(e,oi[n.type]))}}return t}var ci=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),H=s(((e,t)=>{t.exports=ci()}))(),li=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(),ui=(e=[])=>e.filter(e=>e.type!==`call_recording`&&!(typeof e.message==`string`&&e.message.includes(`AI chat recording`))).map(e=>({...e,message:li(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`}));function di(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 fi=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,pi=(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}:{}}},mi=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},hi=(e=[],t,n=6)=>!t?.message||e.slice(-n).some(e=>e.sender===`system`&&e.message===t.message)?e:[...e,t];function gi({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,b.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),[a,o]=(0,b.useState)(0),[s,c]=(0,b.useState)(`booting`),[l,u]=(0,b.useState)(null),[d,f]=(0,b.useState)(null),[p,m]=(0,b.useState)(``),[h,g]=(0,b.useState)([]),_=(0,b.useCallback)(()=>{g(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()}])},[]),v=(0,b.useCallback)(e=>{si(e).then(({messages:e,navigateTo:t})=>{e.length&&g(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)})},[]),y=(0,b.useCallback)(()=>{g(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()}])},[]),[x,C]=(0,b.useState)(N().isOpen),[w,T]=(0,b.useState)(N().activeScreen),[E,k]=(0,b.useState)(N().isHumanHandled),[A,ie]=(0,b.useState)(N().agentName),[j,M]=(0,b.useState)(N().agentHeadshot),[ae,de]=(0,b.useState)(()=>le(i?.siteId)),[F,fe]=(0,b.useState)(!1),[me,I]=(0,b.useState)(!1),[he,ge]=(0,b.useState)(`idle`),[_e,ve]=(0,b.useState)(!1),[ye,be]=(0,b.useState)(!1),[Se,Ce]=(0,b.useState)(``),[we,Te]=(0,b.useState)(!1),[Ee,De]=(0,b.useState)(0),[Oe,ke]=(0,b.useState)(0),[Ae,L]=(0,b.useState)(!1),[R,Pe]=(0,b.useState)(null),[Fe,Ie]=(0,b.useState)(null),[Le,Re]=(0,b.useState)(`idle`),[ze,Be]=(0,b.useState)(null),[Ve,He]=(0,b.useState)(!1),[Ue,We]=(0,b.useState)(``),[Ge,Ke]=(0,b.useState)(!1),qe=(0,b.useRef)(null),z=(0,b.useRef)(null),Je=(0,b.useRef)(``),Ye=(0,b.useRef)(!1),Xe=(0,b.useRef)(null),Ze=(0,b.useRef)(null),Qe=(0,b.useRef)(null),$e=(0,b.useRef)(null),et=(0,b.useRef)(null),tt=(0,b.useRef)(null),nt=(0,b.useRef)(null),rt=(0,b.useRef)(!1),it=(0,b.useRef)({url:null,at:0}),at=(0,b.useCallback)((e,t)=>{Bn(6e3);let n=e;try{n=new URL(e,window.location.origin).href}catch{}let r=it.current;return r.url===n&&Date.now()-r.at<4e3?Promise.resolve({navigated:!0,deduped:!0}):(it.current={url:n,at:Date.now()},Er(e,t))},[]),ot=(0,b.useRef)([]),B=(0,b.useRef)(null),st=(0,b.useRef)(null),ct=(0,b.useRef)(null),lt=(0,b.useRef)(!1),ut=(0,b.useRef)(!1),dt=(0,b.useRef)(``),ft=(0,b.useRef)(null),pt=(0,b.useRef)(null),mt=(0,b.useRef)([]),ht=(0,b.useRef)(0),gt=(0,b.useRef)(A),_t=(0,b.useRef)([]),vt=(0,b.useRef)(!1),yt=(0,b.useRef)(!1),bt=(0,b.useRef)(i),xt=(0,b.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),St=(0,b.useCallback)((e={})=>{let t=!!e.is_human_handled;return k(t),t?(T(`agent`),e.agent_info?.name&&ie(e.agent_info.name),e.agent_info?.headshot&&M(e.agent_info.headshot),t):(T(`ai`),t)},[]),Ct=(0,b.useMemo)(()=>{let e=d?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:D},[i,d]);(0,b.useEffect)(()=>{Ze.current=R},[R]),(0,b.useEffect)(()=>{gt.current=A},[A]),(0,b.useEffect)(()=>{yt.current=we},[we]),(0,b.useEffect)(()=>{bt.current=i},[i]);let wt=()=>{We(``)},Tt=(0,b.useCallback)(()=>{ct.current&&=(window.clearTimeout(ct.current),null)},[]),Et=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return de(t),ue(t,i?.siteId),t};(0,b.useEffect)(()=>{let e=i?.siteId;if(!e)return;let t=le(e);if(t){de(t);return}de(t=>(t&&ue(t,e),t))},[i?.siteId]);let Dt=(e=`unspecified`)=>{let t=B.current||tt.current?.callId,n=ht.current,r=ft.current;if(ft.current=null,ht.current=0,r&&r.state!==`inactive`){r.onstop=()=>{let e=mt.current;if(mt.current=[],e.length>0&&t&&z.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;z.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,mt.current=[]}}else if(r&&r.state===`inactive`){let e=mt.current;if(mt.current=[],e.length>0&&t&&z.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;z.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}}else mt.current=[];if(pt.current){try{pt.current.close()}catch{}pt.current=null}Qe.current&&=(Qe.current.close(),null),$e.current&&=($e.current.getTracks().forEach(e=>e.stop()),null),et.current&&=(et.current.srcObject=null,et.current.remove(),null),Tt(),tt.current=null,ot.current=[],B.current=null,st.current=null,lt.current=!1,He(!1),Pe(null),Ie(null),Re(`idle`),Be(null)},Ot=(e=new Date().toISOString())=>{let t=qe.current,n=B.current||tt.current?.callId;if(!(!t?.connected||!n||lt.current)){lt.current=!0,t.emit(`call:connected`,{callId:n,chatId:Je.current,connectedAt:e});try{let e=$e.current,t=et.current?.srcObject;if(e&&t&&!ft.current){mt.current=[];let n=new(window.AudioContext||window.webkitAudioContext);pt.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&&mt.current.push(e.data)},ft.current=a,ht.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{}}},kt=(e={})=>{if(!e.callId)return;let t=st.current===e.callId,n=B.current===e.callId,r=Ze.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(Tt(),Pe(null),t||n){B.current=e.callId,Ie(e.callId),Re(e=>e===`connected`?e:`connecting`),C(!0);return}Re(`idle`)}},At=(e={})=>{if(!e.callId)return;let t=st.current===e.callId,n=B.current===e.callId,r=Ze.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(Tt(),n){Dt();return}st.current=null,tt.current=null,ot.current=[],Pe(null),Re(`idle`)}},jt=async(e={})=>{let t=Qe.current,n=qe.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:Je.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),tt.current=e;return}if(await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),ot.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:Je.current,queuedCount:ot.current.length});for(let e of ot.current)await t.addIceCandidate(new RTCIceCandidate(e));ot.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:Je.current})};(0,b.useEffect)(()=>{P({isOpen:x,activeScreen:w,isHumanHandled:E,agentName:A,agentHeadshot:j})},[x,w,E,A,j]),(0,b.useEffect)(()=>{let e=!0;return(async()=>{Ke(!0);try{let t=S(i),n=await Me(t);if(!e)return;let a=t.siteId,o=oe(a),s=pe(a),l=``;try{let e=Ye.current,r=Xe.current;if(Ye.current=!1,Xe.current=null,l=(await je({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:a,priorChatId:e||r?null:o||te(),forceNew:e,resumeChatId:r,visitorId:s}))?.data?.chatId,!l)throw Error(`resolve-session returned no chatId`);ne(),ce(a,l)}catch(e){console.warn(`[FlowEngageProvider] resolve-session failed, reusing persisted or ephemeral chat id`,e?.message||e),l=o||re(),ce(a,l)}Je.current=l;let u=Ne({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId,visitorId:s});z.current=u,f({...n,apiBaseUrl:t.apiBaseUrl}),m(l);let d=n?.widgetSettings?.branding?.fallbackAgentName||`Agent`,p=xn({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:l,siteId:t.siteId});qe.current=p,p.on(`connect`,async()=>{ge(`connected`);let e=Je.current;if(e&&z.current)try{St(await z.current.checkHumanHandled(e))}catch{}}),p.on(`disconnect`,()=>{ge(`disconnected`)}),p.on(`aiTyping`,()=>{I(!0)}),p.on(`ai:typing`,()=>{I(!0)}),p.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:li(t.message)};I(!1),fe(!1),!(n.type===`call_recording`||typeof n.message==`string`&&n.message.includes(`AI chat recording`))&&g(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),p.on(`conversationStarted`,e=>{e?.message&&g(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),p.on(`message:new`,e=>{let t=e.message||e,n={...t,message:li(t.message)};I(!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`)&&fe(!1),g(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)&&(k(!0),T(`agent`),ie(mi([n.agent_name,n.agentName,n.metadata?.agentName],d)),n.sender_headshot&&M(n.sender_headshot),C(!0),De(e=>e+1)))});let h=(e={})=>{let t=mi([e.agent?.name,e.agentName,e.agent_name,gt.current],d);k(!0),T(`agent`),ie(t),M(e.agent?.headshot||null),C(!0),De(e=>e+1),g(e=>hi(e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}))},v=(e={})=>{let t=mi([e.agent?.name,e.agentName,e.agent_name,gt.current],d);k(!1),T(`ai`),g(e=>hi(e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}))};p.on(`agent:joined`,h),p.on(`agentJoined`,h),p.on(`agent:left`,v),p.on(`agentLeft`,v),p.on(`conversationEnded`,e=>{L(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;g(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),p.on(`chat:history_update`,e=>{let t=ui(e.chat_history||[]);g(t),t.length===0&&(L(!1),k(!1),T(`ai`),I(!1),fe(!1))}),p.on(`conversation:reset`,()=>{g([]),L(!1),k(!1),T(`ai`),I(!1),fe(!1)}),p.on(`voice:end_session`,(e={})=>{console.log(`[FlowEngageProvider] voice:end_session received — ending voice session`),ke(e=>e+1),C(!0),De(e=>e+1)}),p.on(`typing:start`,e=>{e.sender===`agent`&&fe(!0)}),p.on(`typing:stop`,e=>{e.sender===`agent`&&fe(!1)}),p.on(`call:incoming`,(e={})=>{let t=mi([e.agentName,e.ownerName,e.agent?.name,gt.current],`Agent`);wt(),Tt(),lt.current=!1,Pe({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ie(e=>mi([t,e],`Agent`)),Re(`incoming`),Be(null),C(!0)}),p.on(`call:offer`,async(e={})=>{tt.current=e;try{await jt(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),p.on(`call:ice-candidate-from-agent`,async(e={})=>{if(e.candidate)try{let t=pi(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(!Qe.current||!Qe.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||Je.current,queueSize:ot.current.length+1}),ot.current.push(t);return}await Qe.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),p.on(`call:ended`,()=>{wt(),Dt(`socket:call_ended`)}),p.on(`call:accepted`,(e={})=>{kt(e)}),p.on(`call:accepted_by_other`,(e={})=>{kt(e)}),p.on(`call:rejected`,(e={})=>{At(e)}),p.on(`call:missed`,(e={})=>{At(e)}),p.on(`call:failed`,(e={})=>{At(e)}),p.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=st.current===e.callId,n=B.current===e.callId,r=tt.current?.callId===e.callId,i=Ze.current?.callId===e.callId;if(!t&&!n&&!r){i&&(Pe(null),Re(`idle`));return}lt.current=!0,st.current=null,B.current=e.callId,Ie(e.callId),Pe(null),Re(`connected`),Be(e.connectedAt||new Date().toISOString()),C(!0)}),p.on(`call:unavailable`,(e={})=>{Dt(`socket:call_unavailable`),We(fi(e,`This visitor is not available for a call right now.`)),C(!0)}),p.on(`call:error`,(e={})=>{Dt(`socket:call_error`),We(fi(e,`We couldn't connect the call right now.`)),C(!0)}),p.on(`visitor:navigate`,async({url:e,section:t,highlight:n}={})=>{e&&at(e,{voiceActive:yt.current}).then(({navigated:e,reason:r})=>{if(!e){r===`not-found`?_():r===`already-on-page`&&y();return}let i=t||n;i&&setTimeout(()=>{let e=ur(null,i);e&&dr(e)},300)})}),p.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;let n=ur(e||null,t||null);n&&dr(n)}),p.on(`visitor:clear_highlight`,()=>{fr()}),xt.current=Sn({socket:p,chatId:l});let b=await u.loadHistory(l,r);if(!e)return;g(ui(b.chat_history||[])),k(!!b.is_human_handled),T(b.is_human_handled?`agent`:w);let x=b?.visitor_email||b?.visitorEmail;if(x&&String(x).trim()&&Et(String(x).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,xt.current?.cleanup?.(),Dt(),qe.current?.disconnect()}},[i,r,a]),(0,b.useEffect)(()=>()=>{if(we&&!vt.current&&_t.current.length>0){let e=Je.current,t=_t.current,n=z.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(()=>{}),vt.current=!0)}},[we,d]);let Mt=(0,b.useRef)(null);(0,b.useEffect)(()=>{let e=z.current;!e||!p||Mt.current!==x&&(x&&Mt.current!==null?e.updateChatStatus(p,`open`).catch(()=>{}):Mt.current===!0&&e.updateChatStatus(p,`widget_closed`).catch(()=>{}),Mt.current=x)},[x,p]),(0,b.useEffect)(()=>{let e=()=>{let e=Je.current,t=z.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 Nt=async()=>{if(!(!R?.callId||!z.current||!qe.current||!p)){wt(),st.current=R.callId,Tt();try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});$e.current=e;let t=[{urls:`stun:stun.l.google.com:19302`}];try{let e=await z.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});Qe.current=n,n.onconnectionstatechange=()=>{let e=n.connectionState;if(e===`connected`){let e=new Date().toISOString();Re(`connected`),Be(t=>t||e),Ot(e);return}if(e===`connecting`){Re(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&Dt(`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),Ot(e);return}if(e===`checking`||e===`new`){Re(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&Dt(`peer:ice_${e}`)},n.onsignalingstatechange=()=>{},n.onicegatheringstatechange=()=>{},e.getTracks().forEach(t=>{n.addTrack(t,e)}),n.onicecandidate=e=>{if(!e.candidate||!qe.current?.connected)return;let t=e.candidate;qe.current.emit(`call:ice-candidate`,{callId:R.callId,candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,chatId:p,from:`customer`})},n.ontrack=e=>{let[t]=e.streams||[],[n]=t?.getAudioTracks?.()||[];if(!et.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=>{},et.current=e,document.body.appendChild(e)}et.current.srcObject=e.streams[0];let r=R?.callId,i=r&&(st.current===r||B.current===r);if(!lt.current&&i){let e=new Date().toISOString();Re(`connected`),Be(t=>t||e),B.current=r,Ie(r),Ot(e)}et.current.srcObject=t||null;let a=et.current.play?.();a?.catch&&a.catch(e=>{})};let r=tt.current;r&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:r.callId||R.callId,chatId:p}),await jt({...r,callId:r.callId||R.callId})),await z.current.acceptCall(R.callId,p),qe.current?.emit(`call:accepted`,{callId:R.callId,chatId:p}),B.current=R.callId,Ie(R.callId),Re(e=>e===`connected`||lt.current?`connected`:`connecting`),Pe(null),C(!0)}catch(e){if(st.current=null,Dt(`accept_call_failed`),e?.status===404||e?.status===409||e?.status===422){We(fi(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await z.current.rejectCall(R.callId,p)}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.`)}}},Pt=async()=>{if(!R?.callId||!z.current||!p){Dt(`reject_call_without_server_context`);return}let e=R.callId;Tt(),wt(),qe.current?.emit(`call:rejected`,{callId:e,chatId:p,reason:`visitor_declined`});try{await z.current.rejectCall(e,p)}catch(e){We(fi(e,`We couldn't decline the call cleanly.`))}finally{Dt(`reject_call_finally`)}},Ft=(0,b.useRef)(Pt);Ft.current=Pt,(0,b.useEffect)(()=>{if(!R?.callId||Fe){Tt();return}let e=R.callId;return Tt(),ct.current=window.setTimeout(()=>{Ze.current?.callId===e&&st.current!==e&&B.current!==e&&Ft.current()},O),()=>{ct.current&&=(window.clearTimeout(ct.current),null)}},[Fe,Tt,R?.callId]);let It=async()=>{if(!Fe||!z.current||!p){Dt(`end_call_without_server_context`);return}wt();try{await z.current.endWebRTCCall(Fe,p)}catch(e){We(fi(e,`The call ended locally, but the server could not be updated.`))}finally{Dt(`end_call_finally`)}},Lt=()=>{let e=$e.current?.getAudioTracks?.()||[],t=Qe.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)},Rt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(C(!0),!(!t||!z.current||!p||typeof window>`u`)){try{await z.current.trackVisitor({chatId:p,currentPagePath:window.location.pathname||`/`})}catch{}try{await z.current.updateChatStatus(p,`open`)}catch{}}},zt=async e=>{let t=Et(e);if(!t||!z.current||!Je.current)return t;try{await z.current.trackVisitor({chatId:Je.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Bt=()=>{!p||!qe.current?.connected||ut.current||(ut.current=!0,qe.current.emit(`typing:start`,{chatId:p,sender:`user`}))},Vt=()=>{!p||!qe.current?.connected||!ut.current||(ut.current=!1,qe.current.emit(`typing:stop`,{chatId:p,sender:`user`}))},Ht=(e=``)=>{let t=typeof e==`string`?e:``;!p||!qe.current?.connected||t!==``&&dt.current===t||(dt.current=t,qe.current.emit(`typing:update`,{chatId:p,sender:`user`,text:t}))};function Ut(){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 Wt=async(e,t=``,n=null,i={})=>{let a=typeof e==`string`?e.trim():``;if(!a||!z.current||!p||s!==`ready`||Ae)return;Vt(),rt.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(nt.current&&o.test(a)&&!c.test(a)){let{url:e,section:t}=nt.current;nt.current=null,rt.current=!0,console.log(`[FWH Nav] Client-side nav firing →`,e),at(e,{voiceActive:yt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?_():n===`already-on-page`&&y();return}!t||!yt.current||setTimeout(()=>{let e=ur(null,t);e&&dr(e)},300)})}else o.test(a)||(nt.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||{}};g(e=>[...e,f]);let m=E;if(m)try{m=St(await z.current.checkHumanHandled(p))}catch{}if(m&&qe.current?.connected){qe.current.emit(`customer:message`,{chatId:p,content:e,sender:`user`,email:ae||void 0,type:i?.type||`text`,metadata:i?.metadata||{},...n||{}});return}ve(!0);try{let o=await zr(),s=Lr(),c=`stream-preview-${Date.now().toString(36)}`,u=e=>{I(!1),g(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 z.current.sendAiMessage(p,e,r,t,{...n||{},...ae?{email:ae}:{}},{...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:Ut()||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),at(e.url,{voiceActive:yt.current}).then(({navigated:t,reason:n})=>{if(!t){n===`not-found`?_():n===`already-on-page`&&y();return}e.section&&setTimeout(()=>{let t=ur(null,e.section);t&&dr(t)},300)})):(nt.current=e,console.log(`[FWH Nav] Stored pending nav →`,nt.current))}if(d.navigate?.url)if(rt.current)rt.current=!1;else{let{url:e,section:t}=d.navigate;at(e,{voiceActive:yt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?_():n===`already-on-page`&&y();return}t&&setTimeout(()=>{let e=ur(null,t);e&&dr(e)},300)})}else if(d.highlight?.section){let e=d.highlight.section;setTimeout(()=>{let t=ur(null,e);t&&dr(t)},150)}else{let e=[...f].reverse().find(e=>e.sender===`bot`||e.sender===`assistant`);if(e?.message){let t=di(e.message);t&&hr(t.url,{siteId:bt.current?.siteId,apiBaseUrl:bt.current?.apiBaseUrl}).then(({allowed:e,correctedUrl:n})=>{if(!e){_();return}at(n||t.url,{voiceActive:yt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?_():n===`already-on-page`&&y();return}!t.section||!yt.current||setTimeout(()=>{let e=ur(null,t.section);e&&dr(e)},300)})})}}g(ui(f)),Array.isArray(d.cart_actions)&&d.cart_actions.length&&v(d.cart_actions),k(!!d.is_human_handled),T(d.is_human_handled?`agent`:`ai`),I(!1),ve(!1),await z.current.updateChatStatus(p,`messageSent`)}catch(e){g(e=>e.filter(e=>e.id!==d&&!e.isStreaming)),I(!1),ve(!1),e.status===429?(be(!0),Ce(e.message),window.setTimeout(()=>{be(!1),Ce(``)},ee)):u(e)}},Gt=async e=>{if(!z.current||!e)throw Error(`Upload is unavailable right now.`);return z.current.uploadChatFile(e)},Kt=async e=>{if(!(!z.current||!p)){try{let t=e?`voice`:`text`;await z.current.setChatMode(p,t)}catch{}Te(e),e&&(vt.current=!1)}},qt=async e=>{if(vt.current)return;if(vt.current=!0,!z.current||!p||!e?.length){Te(!1);return}let t=()=>{let t=ui(e);g(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 z.current.syncVoice(p,e);if(n?.chat_history?.length)g(ui(n.chat_history));else if(n?.success)try{let e=await z.current.loadHistory(p,r);e?.chat_history?.length?g(ui(e.chat_history)):t()}catch{t()}else t()}catch{t()}finally{Te(!1)}},Jt=async()=>{if(!(!z.current||!p)){we&&!vt.current&&_t.current.length>0&&await qt(_t.current);try{await z.current.endConversation(p)}catch{try{await z.current.updateChatStatus(p,`ended`)}catch{}}L(!0),g(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,b.useEffect)(()=>{if(Le!==`connected`||!Fe||!p||!ze||!Ct)return;let e=new Date(ze).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,Ct*1e3-t),r=window.setTimeout(()=>{We(`The call ended because it reached the time limit.`),It()},n);return()=>window.clearTimeout(r)},[Fe,ze,Le,p,It,Ct]),(0,b.useEffect)(()=>{let e=()=>{let e=Je.current,t=z.current;if(!t||!e)return;if(yt.current&&_t.current.length>0&&xe(),!vt.current&&_t.current.length>0&&(t.beaconSyncVoice(e,_t.current)||t.syncVoice(e,_t.current).catch(()=>{}),vt.current=!0),B.current){t.beaconEndWebRTCCall(B.current,e);return}let n=st.current||Ze.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 Yt=(0,b.useCallback)(()=>{let e=i?.siteId;se(e),Ye.current=!0,Xe.current=null,qe.current?.disconnect(),g([]),m(``),Je.current=``,L(!1),k(!1),ie(null),M(null),Ke(!0),o(e=>e+1)},[i?.siteId]),Xt=(0,b.useCallback)(e=>{i?.siteId,Ye.current=!1,Xe.current=e,qe.current?.disconnect(),g([]),m(``),Je.current=``,L(!1),k(!1),ie(null),M(null),Ke(!0),o(e=>e+1)},[i?.siteId]),Zt=(0,b.useMemo)(()=>({status:s,error:l,runtimeConfig:d,resolvedConfig:i,chatId:p,chatHistory:h,isOpen:x,activeScreen:w,isHumanHandled:E,agentName:A,agentHeadshot:j,visitorEmail:ae,isAgentTyping:F,isAiTyping:me,connectionStatus:he,isLoading:_e,isVoiceMode:we,isRateLimited:ye,rateLimitMessage:Se,isConversationEnded:Ae,isSessionRestoring:Ge,openToChatCounter:Ee,voiceEndCounter:Oe,incomingCall:R,activeCallId:Fe,callConnectionState:Le,callConnectedAt:ze,isCallMuted:Ve,webRTCError:Ue,language:r,historyRef:_t,hasSyncedRef:vt,dismissCallError:wt,captureVisitorEmail:zt,startTyping:Bt,stopTyping:Vt,updateTypingDraft:Ht,notifyRouteChange:()=>xt.current?.notifyRouteChange?.(),openWidget:Rt,closeWidget:()=>C(!1),toggleWidget:()=>{if(x){C(!1);return}Rt({notifyChatInitiated:!0})},sendMessage:Wt,uploadChatFile:Gt,setVoiceMode:Kt,onMessageSync:qt,endConversation:Jt,startNewChat:Yt,resumeChat:Xt,getVisitorChatHistory:()=>z.current?.getVisitorChatHistory?.(),getVisitorChatThread:e=>z.current?.getVisitorChatThread?.(e),acceptCall:Nt,rejectCall:Pt,endWebRTCCall:It,toggleCallMute:Lt}),[s,l,d,i,p,h,x,w,E,A,j,ae,F,me,he,_e,we,ye,Se,Ae,Ge,Ee,Oe,R,Fe,Le,ze,Ve,Ue,r,zt,Bt,Vt,Ht,Nt,Pt,It,Lt,Rt,Wt,Gt,Kt,qt,Jt,Yt,wt]);return(0,H.jsx)(Cn.Provider,{value:Zt,children:n})}var _i=(0,b.createContext)({});function vi(e){let t=(0,b.useRef)(null);return t.current===null&&(t.current=e()),t.current}var yi=typeof window<`u`?b.useLayoutEffect:b.useEffect,bi=(0,b.createContext)(null);function xi(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,wi={},Ti=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Ei(e){return typeof e==`object`&&!!e}var Di=e=>/^0[^.\s]+$/u.test(e);function Oi(e){let t;return()=>(t===void 0&&(t=e()),t)}var ki=e=>e,Ai=(e,t)=>n=>t(e(n)),U=(...e)=>e.reduce(Ai),ji=(e,t,n)=>{let r=t-e;return r===0?1:(n-e)/r},Mi=class{constructor(){this.subscriptions=[]}add(e){return xi(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}},Ni=e=>e*1e3,Pi=e=>e/1e3;function Fi(e,t){return t?1e3/t*e:0}var Ii=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Li=1e-7,Ri=12;function zi(e,t,n,r,i){let a,o,s=0;do o=t+(n-t)/2,a=Ii(o,r,i)-e,a>0?n=o:t=o;while(Math.abs(a)>Li&&++s<Ri);return o}function Bi(e,t,n,r){if(e===t&&n===r)return ki;let i=t=>zi(t,0,1,e,n);return e=>e===0||e===1?e:Ii(i(e),t,r)}var Vi=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Hi=e=>t=>1-e(1-t),Ui=Bi(.33,1.53,.69,.99),Wi=Hi(Ui),Gi=Vi(Wi),Ki=e=>e>=1?1:(e*=2)<1?.5*Wi(e):.5*(2-2**(-10*(e-1))),qi=e=>1-Math.sin(Math.acos(e)),Ji=Hi(qi),Yi=Vi(qi),Xi=Bi(.42,0,1,1),Zi=Bi(0,0,.58,1),Qi=Bi(.42,0,.58,1),$i=e=>Array.isArray(e)&&typeof e[0]!=`number`,ea=e=>Array.isArray(e)&&typeof e[0]==`number`,ta={linear:ki,easeIn:Xi,easeInOut:Qi,easeOut:Zi,circIn:qi,circInOut:Yi,circOut:Ji,backIn:Wi,backInOut:Gi,backOut:Ui,anticipate:Ki},na=e=>typeof e==`string`,ra=e=>{if(ea(e)){e.length;let[t,n,r,i]=e;return Bi(t,n,r,i)}else if(na(e))return ta[e],`${e}`,ta[e];return e},ia=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`],aa={value:null,addProjectionMetrics:null};function oa(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&&aa.value&&aa.value.frameloop[t].push(c),c=0,n.clear(),i=!1,a&&(a=!1,u.process(e))}};return u}var sa=40;function ca(e,t){let n=!1,r=!0,i={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,o=ia.reduce((e,n)=>(e[n]=oa(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=wi.useManualTiming,o=a?i.timestamp:performance.now();n=!1,a||(i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,sa),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:ia.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<ia.length;t++)o[ia[t]].cancel(e)},state:i,steps:o}}var{schedule:W,cancel:la,state:ua,steps:da}=ca(typeof requestAnimationFrame<`u`?requestAnimationFrame:ki,!0),fa;function pa(){fa=void 0}var ma={now:()=>(fa===void 0&&ma.set(ua.isProcessing||wi.useManualTiming?ua.timestamp:performance.now()),fa),set:e=>{fa=e,queueMicrotask(pa)}},ha={layout:0,mainThread:0,waapi:0},ga=e=>t=>typeof t==`string`&&t.startsWith(e),_a=ga(`--`),va=ga(`var(--`),ya=e=>va(e)?ba.test(e.split(`/*`)[0].trim()):!1,ba=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function xa(e){return typeof e==`string`?e.split(`/*`)[0].includes(`var(--`):!1}var Sa={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},Ca={...Sa,transform:e=>Ci(0,1,e)},wa={...Sa,default:1},Ta=e=>Math.round(e*1e5)/1e5,Ea=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Da(e){return e==null}var Oa=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ka=(e,t)=>n=>!!(typeof n==`string`&&Oa.test(n)&&n.startsWith(e)||t&&!Da(n)&&Object.prototype.hasOwnProperty.call(n,t)),Aa=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(Ea);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},ja=e=>Ci(0,255,e),Ma={...Sa,transform:e=>Math.round(ja(e))},Na={test:ka(`rgb`,`red`),parse:Aa(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Ma.transform(e)+`, `+Ma.transform(t)+`, `+Ma.transform(n)+`, `+Ta(Ca.transform(r))+`)`};function Pa(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 Fa={test:ka(`#`),parse:Pa,transform:Na.transform},Ia=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),La=Ia(`deg`),Ra=Ia(`%`),G=Ia(`px`),za=Ia(`vh`),Ba=Ia(`vw`),Va={...Ra,parse:e=>Ra.parse(e)/100,transform:e=>Ra.transform(e*100)},Ha={test:ka(`hsl`,`hue`),parse:Aa(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+Ra.transform(Ta(t))+`, `+Ra.transform(Ta(n))+`, `+Ta(Ca.transform(r))+`)`},Ua={test:e=>Na.test(e)||Fa.test(e)||Ha.test(e),parse:e=>Na.test(e)?Na.parse(e):Ha.test(e)?Ha.parse(e):Fa.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?Na.transform(e):Ha.transform(e),getAnimatableNone:e=>{let t=Ua.parse(e);return t.alpha=0,Ua.transform(t)}},Wa=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Ga(e){return isNaN(e)&&typeof e==`string`&&(e.match(Ea)?.length||0)+(e.match(Wa)?.length||0)>0}var Ka=`number`,qa=`color`,Ja=`var`,Ya=`var(`,Xa="${}",Za=/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 Qa(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(Za,e=>(Ua.test(e)?(r.color.push(a),i.push(qa),n.push(Ua.parse(e))):e.startsWith(Ya)?(r.var.push(a),i.push(Ja),n.push(e)):(r.number.push(a),i.push(Ka),n.push(parseFloat(e))),++a,Xa)).split(Xa),indexes:r,types:i}}function $a(e){return Qa(e).values}function eo({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===Ka?i+=Ta(r[a]):e===qa?i+=Ua.transform(r[a]):i+=r[a]}return i}}function to(e){return eo(Qa(e))}var no=e=>typeof e==`number`?0:Ua.test(e)?Ua.getAnimatableNone(e):e,ro=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:no(e);function io(e){let t=Qa(e);return eo(t)(t.values.map((e,n)=>ro(e,t.split[n])))}var ao={test:Ga,parse:$a,createTransformer:to,getAnimatableNone:io};function oo(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 K({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=oo(s,r,e+1/3),a=oo(s,r,e),o=oo(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function so(e,t){return n=>n>0?t:e}var q=(e,t,n)=>e+(t-e)*n,co=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},lo=[Fa,Na,Ha],uo=e=>lo.find(t=>t.test(e));function fo(e){let t=uo(e);if(`${e}`,!t)return!1;let n=t.parse(e);return t===Ha&&(n=K(n)),n}var po=(e,t)=>{let n=fo(e),r=fo(t);if(!n||!r)return so(e,t);let i={...n};return e=>(i.red=co(n.red,r.red,e),i.green=co(n.green,r.green,e),i.blue=co(n.blue,r.blue,e),i.alpha=q(n.alpha,r.alpha,e),Na.transform(i))},mo=new Set([`none`,`hidden`]);function ho(e,t){return mo.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function go(e,t){return n=>q(e,t,n)}function _o(e){return typeof e==`number`?go:typeof e==`string`?ya(e)?so:Ua.test(e)?po:xo:Array.isArray(e)?vo:typeof e==`object`?Ua.test(e)?po:yo:so}function vo(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>_o(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function yo(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=_o(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function bo(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 xo=(e,t)=>{let n=ao.createTransformer(t),r=Qa(e),i=Qa(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?mo.has(e)&&!i.values.length||mo.has(t)&&!r.values.length?ho(e,t):U(vo(bo(r,i),i.values),n):(`${e}${t}`,so(e,t))};function So(e,t,n){return typeof e==`number`&&typeof t==`number`&&typeof n==`number`?q(e,t,n):_o(e)(e,t)}var Co=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>W.update(t,e),stop:()=>la(t),now:()=>ua.isProcessing?ua.timestamp:ma.now()}},wo=(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)})`},To=2e4;function Eo(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 Do(e,t=100,n){let r=n({...e,keyframes:[0,t]}),i=Math.min(Eo(r),To);return{type:`keyframes`,ease:e=>r.next(i*e).value/t,duration:Pi(i)}}var Oo={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 ko(e,t){return e*Math.sqrt(1-t*t)}var Ao=12;function jo(e,t,n){let r=n;for(let n=1;n<Ao;n++)r-=e(r)/t(r);return r}var Mo=.001;function No({duration:e=Oo.duration,bounce:t=Oo.bounce,velocity:n=Oo.velocity,mass:r=Oo.mass}){let i,a;Oo.maxDuration;let o=1-t;o=Ci(Oo.minDamping,Oo.maxDamping,o),e=Ci(Oo.minDuration,Oo.maxDuration,Pi(e)),o<1?(i=t=>{let r=t*o,i=r*e,a=r-n,s=ko(t,o),c=Math.exp(-i);return Mo-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=ko(t**2,o);return(-i(t)+Mo>0?-1:1)*((a-s)*c)/l}):(i=t=>{let r=Math.exp(-t*e),i=(t-n)*e+1;return-Mo+r*i},a=t=>Math.exp(-t*e)*((n-t)*(e*e)));let s=5/e,c=jo(i,a,s);if(e=Ni(e),isNaN(c))return{stiffness:Oo.stiffness,damping:Oo.damping,duration:e};{let t=c**2*r;return{stiffness:t,damping:o*2*Math.sqrt(r*t),duration:e}}}var Po=[`duration`,`bounce`],Fo=[`stiffness`,`damping`,`mass`];function Io(e,t){return t.some(t=>e[t]!==void 0)}function Lo(e){let t={velocity:Oo.velocity,stiffness:Oo.stiffness,damping:Oo.damping,mass:Oo.mass,isResolvedFromDuration:!1,...e};if(!Io(e,Fo)&&Io(e,Po))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:Oo.mass,stiffness:i,damping:a}}else{let n=No({...e,velocity:0});t={...t,...n,mass:Oo.mass},t.isResolvedFromDuration=!0}return t}function Ro(e=Oo.visualDuration,t=Oo.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}=Lo({...n,velocity:-Pi(n.velocity||0)}),m=f||0,h=l/(2*Math.sqrt(c*u)),g=o-a,_=Pi(Math.sqrt(c/u)),v=Math.abs(g)<5;r||=v?Oo.restSpeed.granular:Oo.restSpeed.default,i||=v?Oo.restDelta.granular:Oo.restDelta.default;let y,b,x,S,C,w;if(h<1)x=ko(_,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=>Ni(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=Ni(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=Ni(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(Eo(T),To),t=wo(t=>T.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return T}Ro.applyToOptions=e=>{let t=Do(e,100,Ro);return e.ease=t.ease,e.duration=Ni(t.duration),e.type=`keyframes`,e};var zo=5;function Bo(e,t,n){let r=Math.max(t-zo,0);return Fi(n-e(r),t-r)}function Vo({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=Ro({keyframes:[f.value,m(f.value)],velocity:Bo(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 Ho(e,t,n){let r=[],i=n||wi.mix||So,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=U(Array.isArray(t)?t[n]||ki:t,a)),r.push(a)}return r}function Uo(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(t.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=Ho(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=ji(e[r],e[r+1],n);return s[r](i)};return n?t=>l(Ci(e[0],e[a-1],t)):l}function Wo(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=ji(0,t,r);e.push(q(n,1,i))}}function Go(e){let t=[0];return Wo(t,e.length-1),t}function Ko(e,t){return e.map(e=>e*t)}function qo(e,t){return e.map(()=>t||Qi).splice(0,e.length-1)}function Jo({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=$i(r)?r.map(ra):ra(r),a={done:!1,value:t[0]},o=Uo(Ko(n&&n.length===t.length?n:Go(t),e),t,{ease:Array.isArray(i)?i:qo(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var Yo=e=>e!==null;function Xo(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(Yo),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var Zo={decay:Vo,inertia:Vo,tween:Jo,keyframes:Jo,spring:Ro};function Qo(e){typeof e.type==`string`&&(e.type=Zo[e.type])}var $o=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)}},es=e=>e/100,ts=class extends $o{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!==ma.now()&&this.tick(ma.now()),this.isStopped=!0,this.state!==`idle`&&(this.teardown(),this.options.onStop?.())},ha.mainThread++,this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){let{options:e}=this;Qo(e);let{type:t=Jo,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||Jo;s!==Jo&&typeof o[0]!=`number`&&(this.mixKeyframes=U(es,So(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=Eo(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!==Vo&&(b.value=Xo(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 Pi(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Pi(e)}get time(){return Pi(this.currentTime)}set time(e){e=Ni(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 Bo(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(ma.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=Pi(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=Co,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(ma.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,ha.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 ns(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var rs=e=>e*180/Math.PI,is=e=>os(rs(Math.atan2(e[1],e[0]))),as={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:is,rotateZ:is,skewX:e=>rs(Math.atan(e[1])),skewY:e=>rs(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},os=e=>(e%=360,e<0&&(e+=360),e),ss=is,cs=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),ls=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),us={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:cs,scaleY:ls,scale:e=>(cs(e)+ls(e))/2,rotateX:e=>os(rs(Math.atan2(e[6],e[5]))),rotateY:e=>os(rs(Math.atan2(-e[2],e[0]))),rotateZ:ss,rotate:ss,skewX:e=>rs(Math.atan(e[4])),skewY:e=>rs(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function ds(e){return e.includes(`scale`)?1:0}function fs(e,t){if(!e||e===`none`)return ds(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=us,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=as,i=t}if(!i)return ds(t);let a=r[t],o=i[1].split(`,`).map(ms);return typeof a==`function`?a(o):o[a]}var ps=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return fs(n,t)};function ms(e){return parseFloat(e.trim())}var hs=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],gs=new Set(hs),_s=e=>e===Sa||e===G,vs=new Set([`x`,`y`,`z`]),ys=hs.filter(e=>!vs.has(e));function bs(e){let t=[];return ys.forEach(n=>{let r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith(`scale`)?1:0))}),t}var xs={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})=>fs(t,`x`),y:(e,{transform:t})=>fs(t,`y`)};xs.translateX=xs.x,xs.translateY=xs.y;var Ss=new Set,Cs=!1,ws=!1,Ts=!1;function Es(){if(ws){let e=Array.from(Ss).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),n=new Map;t.forEach(e=>{let t=bs(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)})}ws=!1,Cs=!1,Ss.forEach(e=>e.complete(Ts)),Ss.clear()}function Ds(){Ss.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(ws=!0)})}function Os(){Ts=!0,Ds(),Es(),Ts=!1}var ks=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?(Ss.add(this),Cs||(Cs=!0,W.read(Ds),W.resolveKeyframes(Es))):(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])}ns(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Ss.delete(this)}cancel(){this.state===`scheduled`&&(Ss.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},As=e=>e.startsWith(`--`);function js(e,t,n){As(t)?e.style.setProperty(t,n):e.style[t]=n}var Ms={};function Ns(e,t){let n=Oi(e);return()=>Ms[t]??n()}var Ps=Ns(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),Fs=Ns(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),Is=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,Ls={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:Is([0,.65,.55,1]),circOut:Is([.55,0,1,.45]),backIn:Is([.31,.01,.66,-.59]),backOut:Is([.33,1.53,.69,.99])};function Rs(e,t){if(e)return typeof e==`function`?Fs()?wo(e,t):`ease-out`:ea(e)?Is(e):Array.isArray(e)?e.map(e=>Rs(e,t)||Ls.easeOut):Ls[e]}function zs(e,t,n,{delay:r=0,duration:i=300,repeat:a=0,repeatType:o=`loop`,ease:s=`easeOut`,times:c}={},l=void 0){let u={[t]:n};c&&(u.offset=c);let d=Rs(s,i);Array.isArray(d)&&(u.easing=d),aa.value&&ha.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 aa.value&&p.finished.finally(()=>{ha.waapi--}),p}function Bs(e){return typeof e==`function`&&`applyToOptions`in e}function Vs({type:e,...t}){return Bs(e)&&Fs()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var Hs=class extends $o{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,e.type;let c=Vs(e);this.animation=zs(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=Xo(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),js(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 Pi(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Pi(e)}get time(){return Pi(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Ni(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&&Ps()?(this.animation.timeline=e,t&&(this.animation.rangeStart=t),n&&(this.animation.rangeEnd=n),ki):r(this)}},Us={anticipate:Ki,backInOut:Gi,circInOut:Yi};function Ws(e){return e in Us}function Gs(e){typeof e.ease==`string`&&Ws(e.ease)&&(e.ease=Us[e.ease])}var Ks=10,qs=class extends Hs{constructor(e){Gs(e),Qo(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 ts({...a,autoplay:!1}),s=Math.max(Ks,ma.now()-this.startTime),c=Ci(0,Ks,s-Ks),l=o.sample(s).value,{name:u}=this.options;i&&u&&js(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},Js=(e,t)=>t===`zIndex`?!1:!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(ao.test(e)||e===`0`)&&!e.startsWith(`url(`));function Ys(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 Xs(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=Js(i,t),s=Js(a,t);return`${t}${i}${a}${o?a:i}`,!o||!s?!1:Ys(e)||(n===`spring`||Bs(n))&&r}function Zs(e){e.duration=0,e.type=`keyframes`}var Qs=new Set([`opacity`,`clipPath`,`filter`,`transform`]),$s=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function ec(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&$s.test(e[t]))return!0;return!1}var tc=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),nc=Oi(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function rc(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 nc()&&n&&(Qs.has(n)||tc.has(n)&&ec(s))&&(n!==`transform`||!l)&&!c&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var ic=40,ac=class extends $o{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=ma.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||ks)(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=ma.now();let u=!0;Xs(e,i,a,o)||(u=!1,(wi.instantAnimations||!s)&&l?.(Xo(e,n,t)),e[0]=e[e.length-1],Zs(n),n.repeat=0);let d={startTime:r?this.resolvedAt&&this.resolvedAt-this.createdAt>ic?this.resolvedAt:this.createdAt:void 0,finalKeyframe:t,...n,keyframes:e},f=u&&!c&&rc(d),p=d.motionValue?.owner?.current,m;if(f)try{m=new qs({...d,element:p})}catch{m=new ts(d)}else m=new ts(d);m.finished.then(()=>{this.notifyFinished()}).catch(ki),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(),Os()),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 oc(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 sc=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function cc(e){let t=sc.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}function lc(e,t,n=1){`${e}`;let[r,i]=cc(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return Ti(e)?parseFloat(e):e}return ya(i)?lc(i,t,n+1):i}var uc={type:`spring`,stiffness:500,damping:25,restSpeed:10},dc=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),fc={type:`keyframes`,duration:.8},pc={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},mc=(e,{keyframes:t})=>t.length>2?fc:gs.has(e)?e.startsWith(`scale`)?dc(t[1]):uc:pc;function hc(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function gc(e,t){let n=e?.[t]??e?.default??e;return n===e?n:hc(n,e)}var _c=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function vc(e){for(let t in e)if(!_c.has(t))return!0;return!1}var yc=(e,t,n,r={},i,a)=>o=>{let s=gc(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=Ni(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};vc(s)||Object.assign(u,mc(e,u)),u.duration&&=Ni(u.duration),u.repeatDelay&&=Ni(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(Zs(u),u.delay===0&&(d=!0)),(wi.instantAnimations||wi.skipAnimations||i?.shouldSkipAnimations)&&(d=!0,Zs(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=Xo(u.keyframes,s);if(e!==void 0){W.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new ts(u):new ac(u)};function bc(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function xc(e,t,n,r){if(typeof t==`function`){let[i,a]=bc(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]=bc(r);t=t(n===void 0?e.custom:n,i,a)}return t}function Sc(e,t,n){let r=e.getProps();return xc(r,t,n===void 0?r.custom:n,e)}var Cc=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...hs]),wc=30,Tc=e=>!isNaN(parseFloat(e)),Ec={current:void 0},Dc=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=ma.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=ma.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Tc(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on(`change`,e)}on(e,t){this.events[e]||(this.events[e]=new Mi);let n=this.events[e].add(t);return e===`change`?()=>{n(),W.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 Ec.current&&Ec.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=ma.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>wc)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,wc);return Fi(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 Oc(e,t){return new Dc(e,t)}var kc=e=>Array.isArray(e);function Ac(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Oc(n))}function jc(e){return kc(e)?e[e.length-1]||0:e}function Mc(e,t){let{transitionEnd:n={},transition:r={},...i}=Sc(e,t)||{};i={...i,...n};for(let t in i)Ac(e,t,jc(i[t]))}var Nc=e=>!!(e&&e.getVelocity);function Pc(e){return!!(Nc(e)&&e.add)}function Fc(e,t){let n=e.getValue(`willChange`);if(Pc(n))return n.add(t);if(!n&&wi.WillChange){let n=new wi.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function Ic(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var Lc=`data-`+Ic(`framerAppearId`);function Rc(e){return e.props[Lc]}function zc({protectedKeys:e,needsAnimating:t},n){let r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function Bc(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:a,transitionEnd:o,...s}=t,c=e.getDefaultTransition();a=a?hc(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&&zc(d,t))continue;let o={delay:n,...gc(a||{},t)},c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){W.update(()=>r.set(i));continue}let f=!1;if(window.MotionHandoffAnimation){let n=Rc(e);if(n){let e=window.MotionHandoffAnimation(n,t,W);e!==null&&(o.startTime=e,f=!0)}}Fc(e,t);let p=l??e.shouldReduceMotion;r.start(yc(t,r,i,p&&Cc.has(t)?{type:!1}:o,e,f));let m=r.animation;m&&u.push(m)}if(o){let t=()=>W.update(()=>{o&&Mc(e,o)});u.length?Promise.all(u).then(t):t()}return u}function Vc(e,t,n={}){let r=Sc(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(Bc(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{let{delayChildren:a=0,staggerChildren:o,staggerDirection:s}=i;return Hc(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 Hc(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(Vc(c,t,{...o,delay:n+(typeof r==`function`?0:r)+oc(e.variantChildren,c,r,i,a)}).then(()=>c.notify(`AnimationComplete`,t)));return Promise.all(s)}function Uc(e,t,n={}){e.notify(`AnimationStart`,t);let r;if(Array.isArray(t)){let i=t.map(t=>Vc(e,t,n));r=Promise.all(i)}else if(typeof t==`string`)r=Vc(e,t,n);else{let i=typeof t==`function`?Sc(e,t,n.custom):t;r=Promise.all(Bc(e,i,n))}return r.then(()=>{e.notify(`AnimationComplete`,t)})}var Wc={test:e=>e===`auto`,parse:e=>e},Gc=e=>t=>t.test(e),Kc=[Sa,G,Ra,La,Ba,za,Wc],qc=e=>Kc.find(Gc(e));function Jc(e){return typeof e==`number`?e===0:e===null?!0:e===`none`||e===`0`||Di(e)}var Yc=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function Xc(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(Ea)||[];if(!r)return e;let i=n.replace(r,``),a=Yc.has(t)?1:0;return r!==n&&(a*=100),t+`(`+a+i+`)`}var Zc=/\b([a-z-]*)\(.*?\)/gu,Qc={...ao,getAnimatableNone:e=>{let t=e.match(Zc);return t?t.map(Xc).join(` `):e}},$c={...ao,getAnimatableNone:e=>{let t=ao.parse(e);return ao.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},el={...Sa,transform:Math.round},tl={borderWidth:G,borderTopWidth:G,borderRightWidth:G,borderBottomWidth:G,borderLeftWidth:G,borderRadius:G,borderTopLeftRadius:G,borderTopRightRadius:G,borderBottomRightRadius:G,borderBottomLeftRadius:G,width:G,maxWidth:G,height:G,maxHeight:G,top:G,right:G,bottom:G,left:G,inset:G,insetBlock:G,insetBlockStart:G,insetBlockEnd:G,insetInline:G,insetInlineStart:G,insetInlineEnd:G,padding:G,paddingTop:G,paddingRight:G,paddingBottom:G,paddingLeft:G,paddingBlock:G,paddingBlockStart:G,paddingBlockEnd:G,paddingInline:G,paddingInlineStart:G,paddingInlineEnd:G,margin:G,marginTop:G,marginRight:G,marginBottom:G,marginLeft:G,marginBlock:G,marginBlockStart:G,marginBlockEnd:G,marginInline:G,marginInlineStart:G,marginInlineEnd:G,fontSize:G,backgroundPositionX:G,backgroundPositionY:G,rotate:La,rotateX:La,rotateY:La,rotateZ:La,scale:wa,scaleX:wa,scaleY:wa,scaleZ:wa,skew:La,skewX:La,skewY:La,distance:G,translateX:G,translateY:G,translateZ:G,x:G,y:G,z:G,perspective:G,transformPerspective:G,opacity:Ca,originX:Va,originY:Va,originZ:G,zIndex:el,fillOpacity:Ca,strokeOpacity:Ca,numOctaves:el},nl={...tl,color:Ua,backgroundColor:Ua,outlineColor:Ua,fill:Ua,stroke:Ua,borderColor:Ua,borderTopColor:Ua,borderRightColor:Ua,borderBottomColor:Ua,borderLeftColor:Ua,filter:Qc,WebkitFilter:Qc,mask:$c,WebkitMask:$c},rl=e=>nl[e],il=new Set([Qc,$c]);function al(e,t){let n=rl(e);return il.has(n)||(n=ao),n.getAnimatableNone?n.getAnimatableNone(t):void 0}var ol=new Set([`auto`,`none`,`0`]);function sl(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!ol.has(t)&&Qa(t).values.length&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]=al(n,i)}var cl=class extends ks{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(),ya(r))){let i=lc(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!Cc.has(n)||e.length!==2)return;let[r,i]=e,a=qc(r),o=qc(i);if(xa(r)!==xa(i)&&xs[n]){this.needsMeasurement=!0;return}if(a!==o)if(_s(a)&&_s(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else xs[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||Jc(e[t]))&&n.push(t);n.length&&sl(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=xs[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]=xs[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 ll(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 ul=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function dl(e){return Ei(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}var{schedule:fl,cancel:pl}=ca(queueMicrotask,!1),ml={x:!1,y:!1};function hl(){return ml.x||ml.y}function gl(e){return e===`x`||e===`y`?ml[e]?null:(ml[e]=!0,()=>{ml[e]=!1}):ml.x||ml.y?null:(ml.x=ml.y=!0,()=>{ml.x=ml.y=!1})}function _l(e,t){let n=ll(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function vl(e){return!(e.pointerType===`touch`||hl())}function yl(e,t,n={}){let[r,i,a]=_l(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(!vl(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 bl=(e,t)=>t?e===t?!0:bl(e,t.parentElement):!1,xl=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,Sl=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function Cl(e){return Sl.has(e.tagName)||e.isContentEditable===!0}var wl=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function Tl(e){return wl.has(e.tagName)||e.isContentEditable===!0}var El=new WeakSet;function Dl(e){return t=>{t.key===`Enter`&&e(t)}}function Ol(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var kl=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=Dl(()=>{if(El.has(n))return;Ol(n,`down`);let e=Dl(()=>{Ol(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>Ol(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function Al(e){return xl(e)&&!hl()}var jl=new WeakSet;function Ml(e,t,n={}){let[r,i,a]=_l(e,n),o=e=>{let r=e.currentTarget;if(!Al(e)||jl.has(e))return;El.add(r),n.stopPropagation&&jl.add(e);let a=t(r,e),o=(e,t)=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c),El.has(r)&&El.delete(r),Al(e)&&typeof a==`function`&&a(e,{success:t})},s=e=>{o(e,r===window||r===document||n.useGlobalTarget||bl(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),dl(e)&&(e.addEventListener(`focus`,e=>kl(e,i)),!Cl(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}function Nl(e){return Ei(e)&&`ownerSVGElement`in e}var Pl=new WeakMap,Fl,Il=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:Nl(r)&&`getBBox`in r?r.getBBox()[t]:r[n],Ll=Il(`inline`,`width`,`offsetWidth`),Rl=Il(`block`,`height`,`offsetHeight`);function J({target:e,borderBoxSize:t}){Pl.get(e)?.forEach(n=>{n(e,{get width(){return Ll(e,t)},get height(){return Rl(e,t)}})})}function Y(e){e.forEach(J)}function zl(){typeof ResizeObserver>`u`||(Fl=new ResizeObserver(Y))}function Bl(e,t){Fl||zl();let n=ll(e);return n.forEach(e=>{let n=Pl.get(e);n||(n=new Set,Pl.set(e,n)),n.add(t),Fl?.observe(e)}),()=>{n.forEach(e=>{let n=Pl.get(e);n?.delete(t),n?.size||Fl?.unobserve(e)})}}var Vl=new Set,Hl;function Ul(){Hl=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};Vl.forEach(t=>t(e))},window.addEventListener(`resize`,Hl)}function Wl(e){return Vl.add(e),Hl||Ul(),()=>{Vl.delete(e),!Vl.size&&typeof Hl==`function`&&(window.removeEventListener(`resize`,Hl),Hl=void 0)}}function Gl(e,t){return typeof e==`function`?Wl(e):Bl(e,t)}function Kl(e){return Nl(e)&&e.tagName===`svg`}var ql=[...Kc,Ua,ao],Jl=e=>ql.find(Gc(e)),Yl=()=>({translate:0,scale:1,origin:0,originPoint:0}),Xl=()=>({x:Yl(),y:Yl()}),Zl=()=>({min:0,max:0}),X=()=>({x:Zl(),y:Zl()}),Ql=new WeakMap;function $l(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function eu(e){return typeof e==`string`||Array.isArray(e)}var tu=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],nu=[`initial`,...tu];function ru(e){return $l(e.animate)||nu.some(t=>eu(e[t]))}function iu(e){return!!(ru(e)||e.variants)}function au(e,t,n){for(let r in t){let i=t[r],a=n[r];if(Nc(i))e.addValue(r,i);else if(Nc(a))e.addValue(r,Oc(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,Oc(t===void 0?i:t,{owner:e}))}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var ou={current:null},su={current:!1},cu=typeof window<`u`;function lu(){if(su.current=!0,cu)if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>ou.current=e.matches;e.addEventListener(`change`,t),t()}else ou.current=!1}var uu=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],du={};function fu(e){du=e}function pu(){return du}var mu=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=ks,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=ma.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,W.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=ru(t),this.isVariantNode=iu(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&&Nc(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,Ql.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:(su.current||lu(),this.shouldReduceMotion=ou.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),la(this.notifyUpdate),la(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&&Qs.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new Hs({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:Ni(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=gs.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&W.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()}),i;typeof window<`u`&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i&&i(),t.owner&&t.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e=`animation`;for(e in du){let t=du[e];if(!t)continue;let{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(this)),this.features[e]){let t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):X()}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<uu.length;t++){let n=uu[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=au(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=Oc(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`&&(Ti(n)||Di(n))?n=parseFloat(n):!Jl(n)&&ao.test(t)&&(n=al(e,t)),this.setBaseTarget(e,Nc(n)?n.get():n)),Nc(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=xc(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&&!Nc(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 Mi),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){fl.render(this.render)}},hu=class extends mu{constructor(){super(...arguments),this.KeyframeResolver=cl}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;Nc(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},gu=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function _u({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function vu({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function yu(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 bu(e){return e===void 0||e===1}function xu({scale:e,scaleX:t,scaleY:n}){return!bu(e)||!bu(t)||!bu(n)}function Su(e){return xu(e)||Cu(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Cu(e){return wu(e.x)||wu(e.y)}function wu(e){return e&&e!==`0%`}function Tu(e,t,n){return n+t*(e-n)}function Eu(e,t,n,r,i){return i!==void 0&&(e=Tu(e,i,r)),Tu(e,n,r)+t}function Du(e,t=0,n=1,r,i){e.min=Eu(e.min,t,n,r,i),e.max=Eu(e.max,t,n,r,i)}function Ou(e,{x:t,y:n}){Du(e.x,t.translate,t.scale,t.originPoint),Du(e.y,n.translate,n.scale,n.originPoint)}var ku=.999999999999,Au=1.0000000000001;function ju(e,t,n,r=!1){let i=n.length;if(!i)return;t.x=t.y=1;let a,o;for(let s=0;s<i;s++){a=n[s],o=a.projectionDelta;let{visualElement:i}=a.options;i&&i.props.style&&i.props.style.display===`contents`||(r&&a.options.layoutScroll&&a.scroll&&a!==a.root&&(Mu(e.x,-a.scroll.offset.x),Mu(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Ou(e,o)),r&&Su(a.latestValues)&&Fu(e,a.latestValues,a.layout?.layoutBox))}t.x<Au&&t.x>ku&&(t.x=1),t.y<Au&&t.y>ku&&(t.y=1)}function Mu(e,t){e.min+=t,e.max+=t}function Nu(e,t,n,r,i=.5){Du(e,t,n,q(e.min,e.max,i),r)}function Pu(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function Fu(e,t,n){let r=n??e;Nu(e.x,Pu(t.x,r.x),t.scaleX,t.scale,t.originX),Nu(e.y,Pu(t.y,r.y),t.scaleY,t.scale,t.originY)}function Iu(e,t){return _u(yu(e.getBoundingClientRect(),t))}function Lu(e,t,n){let r=Iu(e,n),{scroll:i}=t;return i&&(Mu(r.x,i.offset.x),Mu(r.y,i.offset.y)),r}var Ru={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},zu=hs.length;function Bu(e,t,n){let r=``,i=!0;for(let a=0;a<zu;a++){let o=hs[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=ul(s,tl[o]);if(!c){i=!1;let t=Ru[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}return r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function Vu(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(gs.has(e)){o=!0;continue}else if(_a(e)){i[e]=n;continue}else{let t=ul(n,tl[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=Bu(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 Hu(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 Uu(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var Wu={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`)if(G.test(e))e=parseFloat(e);else return e;return`${Uu(e,t.target.x)}% ${Uu(e,t.target.y)}%`}},Gu={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=ao.parse(e);if(i.length>5)return r;let a=ao.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=q(s,c,.5);return typeof i[2+o]==`number`&&(i[2+o]/=l),typeof i[3+o]==`number`&&(i[3+o]/=l),a(i)}},Ku={borderRadius:{...Wu,applyTo:[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`]},borderTopLeftRadius:Wu,borderTopRightRadius:Wu,borderBottomLeftRadius:Wu,borderBottomRightRadius:Wu,boxShadow:Gu};function qu(e,{layout:t,layoutId:n}){return gs.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!Ku[e]||e===`opacity`)}function Ju(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(Nc(r[t])||i&&Nc(i[t])||qu(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function Yu(e){return window.getComputedStyle(e)}var Xu=class extends hu{constructor(){super(...arguments),this.type=`html`,this.renderInstance=Hu}readValueFromInstance(e,t){if(gs.has(t))return this.projection?.isProjecting?ds(t):ps(e,t);{let n=Yu(e),r=(_a(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return Iu(e,t)}build(e,t,n){Vu(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return Ju(e,t,n)}},Zu={offset:`stroke-dashoffset`,array:`stroke-dasharray`},Qu={offset:`strokeDashoffset`,array:`strokeDasharray`};function $u(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?Zu:Qu;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var ed=[`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function td(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(Vu(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 ed)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&&$u(d,i,a,o,!1)}var nd=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`]),rd=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function id(e,t,n,r){Hu(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(nd.has(n)?n:Ic(n),t.attrs[n])}function ad(e,t,n){let r=Ju(e,t,n);for(let n in e)if(Nc(e[n])||Nc(t[n])){let t=hs.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var od=class extends hu{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=X}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(gs.has(t)){let e=rl(t);return e&&e.default||0}return t=nd.has(t)?t:Ic(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return ad(e,t,n)}build(e,t,n){td(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){id(e,t,n,r)}mount(e){this.isSVGTag=rd(e.tagName),super.mount(e)}},sd=nu.length;function cd(e){if(!e)return;if(!e.isControllingVariants){let t=e.parent&&cd(e.parent)||{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}let t={};for(let n=0;n<sd;n++){let r=nu[n],i=e.props[r];(eu(i)||i===!1)&&(t[r]=i)}return t}function ld(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 ud=[...tu].reverse(),dd=tu.length;function fd(e){return t=>Promise.all(t.map(({animation:t,options:n})=>Uc(e,t,n)))}function pd(e){let t=fd(e),n=gd(),r=!0,i=!1,a=t=>(n,r)=>{let i=Sc(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=cd(e.parent)||{},l=[],u=new Set,d={},f=1/0;for(let t=0;t<dd;t++){let p=ud[t],m=n[p],h=s[p]===void 0?c[p]:s[p],g=eu(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||$l(h)||typeof h==`boolean`)continue;if(p===`exit`&&m.isActive&&_!==!0){m.prevResolvedValues&&(d={...d,...m.prevResolvedValues});continue}let y=md(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=kc(t)&&kc(n)?!ld(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=Sc(r,t);if(r.enteringChildren&&i){let{delayChildren:t}=i.transition||{};n.delay=oc(r.enteringChildren,e,t)}}return{animation:t,options:n}}))}if(u.size){let t={};if(typeof s.initial!=`boolean`){let n=Sc(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=gd(),i=!0}}}function md(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!ld(t,e):!1}function hd(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function gd(){return{animate:hd(!0),whileInView:hd(),whileHover:hd(),whileTap:hd(),whileDrag:hd(),whileFocus:hd(),exit:hd()}}function _d(e,t){e.min=t.min,e.max=t.max}function vd(e,t){_d(e.x,t.x),_d(e.y,t.y)}function yd(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var bd=1e-4,Z=1-bd,xd=1+bd,Sd=.01,Cd=0-Sd,wd=0+Sd;function Td(e){return e.max-e.min}function Ed(e,t,n){return Math.abs(e-t)<=n}function Dd(e,t,n,r=.5){e.origin=r,e.originPoint=q(t.min,t.max,e.origin),e.scale=Td(n)/Td(t),e.translate=q(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Z&&e.scale<=xd||isNaN(e.scale))&&(e.scale=1),(e.translate>=Cd&&e.translate<=wd||isNaN(e.translate))&&(e.translate=0)}function Od(e,t,n,r){Dd(e.x,t.x,n.x,r?r.originX:void 0),Dd(e.y,t.y,n.y,r?r.originY:void 0)}function kd(e,t,n,r=0){e.min=(r?q(n.min,n.max,r):n.min)+t.min,e.max=e.min+Td(t)}function Ad(e,t,n,r){kd(e.x,t.x,n.x,r?.x),kd(e.y,t.y,n.y,r?.y)}function jd(e,t,n,r=0){let i=r?q(n.min,n.max,r):n.min;e.min=t.min-i,e.max=e.min+Td(t)}function Md(e,t,n,r){jd(e.x,t.x,n.x,r?.x),jd(e.y,t.y,n.y,r?.y)}function Nd(e,t,n,r,i){return e-=t,e=Tu(e,1/n,r),i!==void 0&&(e=Tu(e,1/i,r)),e}function Pd(e,t=0,n=1,r=.5,i,a=e,o=e){if(Ra.test(t)&&(t=parseFloat(t),t=q(o.min,o.max,t/100)-o.min),typeof t!=`number`)return;let s=q(a.min,a.max,r);e===a&&(s-=t),e.min=Nd(e.min,t,n,s,i),e.max=Nd(e.max,t,n,s,i)}function Fd(e,t,[n,r,i],a,o){Pd(e,t[n],t[r],t[i],t.scale,a,o)}var Id=[`x`,`scaleX`,`originX`],Ld=[`y`,`scaleY`,`originY`];function Rd(e,t,n,r){Fd(e.x,t,Id,n?n.x:void 0,r?r.x:void 0),Fd(e.y,t,Ld,n?n.y:void 0,r?r.y:void 0)}function zd(e){return e.translate===0&&e.scale===1}function Bd(e){return zd(e.x)&&zd(e.y)}function Vd(e,t){return e.min===t.min&&e.max===t.max}function Hd(e,t){return Vd(e.x,t.x)&&Vd(e.y,t.y)}function Ud(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Wd(e,t){return Ud(e.x,t.x)&&Ud(e.y,t.y)}function Gd(e){return Td(e.x)/Td(e.y)}function Kd(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function qd(e){return[e(`x`),e(`y`)]}function Jd(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 Yd=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`],Xd=Yd.length,Zd=e=>typeof e==`string`?parseFloat(e):e,Qd=e=>typeof e==`number`||G.test(e);function $d(e,t,n,r,i,a){i?(e.opacity=q(0,n.opacity??1,tf(r)),e.opacityExit=q(t.opacity??1,0,nf(r))):a&&(e.opacity=q(t.opacity??1,n.opacity??1,r));for(let i=0;i<Xd;i++){let a=Yd[i],o=ef(t,a),s=ef(n,a);o===void 0&&s===void 0||(o||=0,s||=0,o===0||s===0||Qd(o)===Qd(s)?(e[a]=Math.max(q(Zd(o),Zd(s),r),0),(Ra.test(s)||Ra.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=q(t.rotate||0,n.rotate||0,r))}function ef(e,t){return e[t]===void 0?e.borderRadius:e[t]}var tf=rf(0,.5,Ji),nf=rf(.5,.95,ki);function rf(e,t,n){return r=>r<e?0:r>t?1:n(ji(e,t,r))}function af(e,t,n){let r=Nc(e)?e:Oc(e);return r.start(yc(``,r,t,n)),r.animation}function of(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}var sf=(e,t)=>e.depth-t.depth,cf=class{constructor(){this.children=[],this.isDirty=!1}add(e){xi(this.children,e),this.isDirty=!0}remove(e){Si(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(sf),this.isDirty=!1,this.children.forEach(e)}};function lf(e,t){let n=ma.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(la(r),e(a-t))};return W.setup(r,!0),()=>la(r)}function uf(e){return Nc(e)?e.get():e}var df=class{constructor(){this.members=[]}add(e){xi(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)}},ff={hasAnimatedSinceResize:!0,hasEverUpdated:!1},pf={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},mf=[``,`X`,`Y`,`Z`],hf=1e3,gf=0;function _f(e,t,n,r){let{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function vf(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=Rc(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,W,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&vf(r)}function yf({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=gf++,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,aa.value&&(pf.nodes=pf.calculatedTargetDeltas=pf.calculatedProjections=0),this.nodes.forEach(Sf),this.nodes.forEach(jf),this.nodes.forEach(Mf),this.nodes.forEach(Cf),aa.addProjectionMetrics&&aa.addProjectionMetrics(pf)},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 cf)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new Mi),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=Nl(t)&&!Kl(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;W.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=lf(i,250),ff.hasAnimatedSinceResize&&(ff.hasAnimatedSinceResize=!1,this.nodes.forEach(Af)))})}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()||zf,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!Wd(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={...gc(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||Af(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(),la(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(Nf),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&&vf(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(Ef),this.nodes.forEach(Tf);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Df);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Of),this.nodes.forEach(kf),this.nodes.forEach(bf),this.nodes.forEach(xf)):this.nodes.forEach(Df),this.clearAllSnapshots();let e=ma.now();ua.delta=Ci(0,1e3/60,e-ua.timestamp),ua.timestamp=e,ua.isProcessing=!0,da.update.process(ua),da.preRender.process(ua),da.render.process(ua),ua.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,fl.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(wf),this.sharedNodes.forEach(Pf)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,W.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){W.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Td(this.snapshot.measuredBox.x)&&!Td(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||=X(),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&&!Bd(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||Su(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)),Uf(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return X();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Gf))){let{scroll:e}=this.root;e&&(Mu(t.x,e.offset.x),Mu(t.y,e.offset.y))}return t}removeElementScroll(e){let t=X();if(vd(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&&vd(t,e),Mu(t.x,i.offset.x),Mu(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||X();vd(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&&(Mu(r.x,-n.scroll.offset.x),Mu(r.y,-n.scroll.offset.y)),Su(n.latestValues)&&Fu(r,n.latestValues,n.layout?.layoutBox)}return Su(this.latestValues)&&Fu(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=X();vd(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!Su(n.latestValues))continue;let r;n.instance&&(xu(n.latestValues)&&n.updateSnapshot(),r=X(),vd(r,n.measurePageBox())),Rd(t,n.latestValues,n.snapshot?.layoutBox,r)}return Su(this.latestValues)&&Rd(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!==ua.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=ua.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=X(),this.targetWithTransforms=X()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Ad(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):vd(this.target,this.layout.layoutBox),Ou(this.target,this.targetDelta)):vd(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),aa.value&&pf.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||xu(this.parent.latestValues)||Cu(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=X(),this.relativeTargetOrigin=X(),Md(this.relativeTargetOrigin,t,n,this.options.layoutAnchor||void 0),vd(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===ua.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;vd(this.layoutCorrected,this.layout.layoutBox);let a=this.treeScale.x,o=this.treeScale.y;ju(this.layoutCorrected,this.treeScale,this.path,t),e.layout&&!e.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(e.target=e.layout.layoutBox,e.targetWithTransforms=X());let{target:s}=e;if(!s){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(yd(this.prevProjectionDelta.x,this.projectionDelta.x),yd(this.prevProjectionDelta.y,this.projectionDelta.y)),Od(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!Kd(this.projectionDelta.x,this.prevProjectionDelta.x)||!Kd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),aa.value&&pf.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=Xl(),this.projectionDelta=Xl(),this.projectionDeltaWithTransform=Xl()}setAnimationOrigin(e,t=!1){let n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},a=Xl();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let o=X(),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(Rf));this.animationProgress=0;let d;this.mixTargetDelta=t=>{let n=t/1e3;Ff(a.x,e.x,n),Ff(a.y,e.y,n),this.setTargetDelta(a),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Md(o,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),Lf(this.relativeTarget,this.relativeTargetOrigin,o,n),d&&Hd(this.relativeTarget,d)&&(this.isProjectionDirty=!1),d||=X(),vd(d,this.relativeTarget)),s&&(this.animationValues=i,$d(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&&=(la(this.pendingAnimation),void 0),this.pendingAnimation=W.update(()=>{ff.hasAnimatedSinceResize=!0,ha.layout++,this.motionValue||=Oc(0),this.motionValue.jump(0,!1),this.currentAnimation=af(this.motionValue,[0,1e3],{...e,velocity:0,isSync:!0,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onStop:()=>{ha.layout--},onComplete:()=>{ha.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(hf),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&&Wf(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||X();let t=Td(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;let r=Td(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}vd(t,n),Fu(t,i),Od(this.projectionDeltaWithTransform,this.layoutCorrected,t,i)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new df),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&&_f(`z`,e,r,this.animationValues);for(let t=0;t<mf.length;t++)_f(`rotate${mf[t]}`,e,r,this.animationValues),_f(`skew${mf[t]}`,e,r,this.animationValues);e.render();for(let t in r)e.setStaticValue(t,r[t]),this.animationValues&&(this.animationValues[t]=r[t]);e.scheduleRender()}applyProjectionStyles(e,t){if(!this.instance||this.isSVG)return;if(!this.isVisible){e.visibility=`hidden`;return}let n=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,e.visibility=``,e.opacity=``,e.pointerEvents=uf(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=uf(t?.pointerEvents)||``),this.hasProjected&&!Su(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=Jd(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 Ku){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=Ku[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?uf(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(Tf),this.root.sharedNodes.clear()}}}function bf(e){e.updateLayout()}function xf(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`)qd(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=Td(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;_d(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else Wf(i,t.layoutBox,n)&&qd(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=Td(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=Xl();Od(o,n,t.layoutBox);let s=Xl();a?Od(s,e.applyTransform(r,!0),t.measuredBox):Od(s,n,t.layoutBox);let c=!Bd(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=X();Md(s,t.layoutBox,i.layoutBox,o);let c=X();Md(c,n,a.layoutBox,o),Wd(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 Sf(e){aa.value&&pf.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 Cf(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function wf(e){e.clearSnapshot()}function Tf(e){e.clearMeasurements()}function Ef(e){e.isLayoutDirty=!0,e.updateLayout()}function Df(e){e.isLayoutDirty=!1}function Of(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function kf(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function Af(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function jf(e){e.resolveTargetDelta()}function Mf(e){e.calcProjection()}function Nf(e){e.resetSkewAndRotation()}function Pf(e){e.removeLeadSnapshot()}function Ff(e,t,n){e.translate=q(t.translate,0,n),e.scale=q(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function If(e,t,n,r){e.min=q(t.min,n.min,r),e.max=q(t.max,n.max,r)}function Lf(e,t,n,r){If(e.x,t.x,n.x,r),If(e.y,t.y,n.y,r)}function Rf(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var zf={duration:.45,ease:[.4,0,.1,1]},Bf=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Vf=Bf(`applewebkit/`)&&!Bf(`chrome/`)?Math.round:ki;function Hf(e){e.min=Vf(e.min),e.max=Vf(e.max)}function Uf(e){Hf(e.x),Hf(e.y)}function Wf(e,t,n){return e===`position`||e===`preserve-aspect`&&!Ed(Gd(t),Gd(n),.2)}function Gf(e){return e!==e.root&&e.scroll?.wasRoot}var Kf=yf({attachResizeListener:(e,t)=>of(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),qf={current:void 0},Jf=yf({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!qf.current){let e=new Kf({});e.mount(window),e.setOptions({layoutScroll:!0}),qf.current=e}return qf.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),Yf=(0,b.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function Xf(e=!0){let t=(0,b.useContext)(bi);if(t===null)return[!0,null];let{isPresent:n,onExitComplete:r,register:i}=t,a=(0,b.useId)();(0,b.useEffect)(()=>{if(e)return i(a)},[e]);let o=(0,b.useCallback)(()=>e&&r&&r(a),[a,r,e]);return!n&&r?[!1,o]:[!0]}var Zf=(0,b.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`]},$f=!1;function ep(){if($f)return;let e={};for(let t in Qf)e[t]={isEnabled:e=>Qf[t].some(t=>!!e[t])};fu(e),$f=!0}function tp(){return ep(),pu()}function np(e){let t=tp();for(let n in e)t[n]={...t[n],...e[n]};fu(t)}var rp=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 ip(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||rp.has(e)}var ap=c({default:()=>op}),op,sp=o((()=>{throw op={},Error(`Could not resolve "@emotion/is-prop-valid" imported by "framer-motion". Is it installed?`)})),cp=e=>!ip(e);function lp(e){typeof e==`function`&&(cp=t=>t.startsWith(`on`)?!ip(t):e(t))}try{lp((sp(),d(ap)).default)}catch{}function up(e,t,n){let r={};for(let i in e)i===`values`&&typeof e.values==`object`||Nc(e[i])||(cp(i)||n===!0&&ip(i)||!t&&!ip(i)||e.draggable&&i.startsWith(`onDrag`))&&(r[i]=e[i]);return r}var dp=(0,b.createContext)({});function fp(e,t){if(ru(e)){let{initial:t,animate:n}=e;return{initial:t===!1||eu(t)?t:void 0,animate:eu(n)?n:void 0}}return e.inherit===!1?{}:t}function pp(e){let{initial:t,animate:n}=fp(e,(0,b.useContext)(dp));return(0,b.useMemo)(()=>({initial:t,animate:n}),[mp(t),mp(n)])}function mp(e){return Array.isArray(e)?e.join(` `):e}var hp=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function gp(e,t,n){for(let r in t)!Nc(t[r])&&!qu(r,n)&&(e[r]=t[r])}function _p({transformTemplate:e},t){return(0,b.useMemo)(()=>{let n=hp();return Vu(n,t,e),Object.assign({},n.vars,n.style)},[t])}function vp(e,t){let n=e.style||{},r={};return gp(r,n,e),Object.assign(r,_p(e,t)),r}function yp(e,t){let n={},r=vp(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 bp=()=>({...hp(),attrs:{}});function xp(e,t,n,r){let i=(0,b.useMemo)(()=>{let n=bp();return td(n,t,rd(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};gp(t,e.style,e),i.style={...t,...i.style}}return i}var Sp=[`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 Cp(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(Sp.indexOf(e)>-1||/[A-Z]/u.test(e))}function wp(e,t,n,{latestValues:r},i,a=!1,o){let s=(o??Cp(e)?xp:yp)(t,r,i,e),c=up(t,typeof e==`string`,a),l=e===b.Fragment?{}:{...c,...s,ref:n},{children:u}=t,d=(0,b.useMemo)(()=>Nc(u)?u.get():u,[u]);return(0,b.createElement)(e,{...l,children:d})}function Tp({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:Ep(n,r,i,e),renderState:t()}}function Ep(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=uf(a[e]);let{initial:o,animate:s}=e,c=ru(e),l=iu(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`&&!$l(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=xc(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 Dp=e=>(t,n)=>{let r=(0,b.useContext)(dp),i=(0,b.useContext)(bi),a=()=>Tp(e,t,r,i);return n?a():vi(a)},Op=Dp({scrapeMotionValuesFromProps:Ju,createRenderState:hp}),kp=Dp({scrapeMotionValuesFromProps:ad,createRenderState:bp}),Ap=Symbol.for(`motionComponentSymbol`);function jp(e,t,n){let r=(0,b.useRef)(n);(0,b.useInsertionEffect)(()=>{r.current=n});let i=(0,b.useRef)(null);return(0,b.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 Mp=(0,b.createContext)({});function Np(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function Pp(e,t,n,r,i,a){let{visualElement:o}=(0,b.useContext)(dp),s=(0,b.useContext)(Zf),c=(0,b.useContext)(bi),l=(0,b.useContext)(Yf),u=l.reducedMotion,d=l.skipAnimations,f=(0,b.useRef)(null),p=(0,b.useRef)(!1);r||=s.renderer,!f.current&&r&&(f.current=r(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:d,isSVG:a}),p.current&&f.current&&(f.current.manuallyAnimateOnMount=!0));let m=f.current,h=(0,b.useContext)(Mp);m&&!m.projection&&i&&(m.type===`html`||m.type===`svg`)&&Fp(f.current,n,i,h);let g=(0,b.useRef)(!1);(0,b.useInsertionEffect)(()=>{m&&g.current&&m.update(n,c)});let _=n[Lc],v=(0,b.useRef)(!!_&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(_)&&window.MotionHasOptimisedAnimation?.(_));return yi(()=>{p.current=!0,m&&(g.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),v.current&&m.animationState&&m.animationState.animateChanges())}),(0,b.useEffect)(()=>{m&&(!v.current&&m.animationState&&m.animationState.animateChanges(),v.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(_)}),!1),m.enteringChildren=void 0)}),m}function Fp(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:Ip(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&Np(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function Ip(e){if(e)return e.options.allowProjection===!1?Ip(e.parent):e.projection}function Lp(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&np(r);let a=n?n===`svg`:Cp(e),o=a?kp:Op;function s(n,s){let c,l={...(0,b.useContext)(Yf),...n,layoutId:Rp(n)},{isStatic:u}=l,d=pp(n),f=o(n,u);if(!u&&typeof window<`u`){zp(l,r);let t=Bp(l);c=t.MeasureLayout,d.visualElement=Pp(e,f,l,i,t.ProjectionNode,a)}return(0,H.jsxs)(dp.Provider,{value:d,children:[c&&d.visualElement?(0,H.jsx)(c,{visualElement:d.visualElement,...l}):null,wp(e,n,jp(f,d.visualElement,s),f,u,t,a)]})}s.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let c=(0,b.forwardRef)(s);return c[Ap]=e,c}function Rp({layoutId:e}){let t=(0,b.useContext)(_i).id;return t&&e!==void 0?t+`-`+e:e}function zp(e,t){(0,b.useContext)(Zf).strict}function Bp(e){let{drag:t,layout:n}=tp();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function Vp(e,t){if(typeof Proxy>`u`)return Lp;let n=new Map,r=(n,r)=>Lp(n,r,e,t);return new Proxy((e,t)=>r(e,t),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,Lp(a,void 0,e,t)),n.get(a))})}var Hp=(e,t)=>t.isSVG??Cp(e)?new od(t):new Xu(t,{allowProjection:e!==b.Fragment}),Up=class extends gu{constructor(e){super(e),e.animationState||=pd(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();$l(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?.()}},Wp=0,Gp={animation:{Feature:Up},exit:{Feature:class extends gu{constructor(){super(...arguments),this.id=Wp++,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=Sc(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 Kp(e){return{point:{x:e.pageX,y:e.pageY}}}var qp=e=>t=>xl(t)&&e(t,Kp(t));function Jp(e,t,n,r){return of(e,t,qp(n),r)}var Yp=({current:e})=>e?e.ownerDocument.defaultView:null,Xp=(e,t)=>Math.abs(e-t);function Zp(e,t){let n=Xp(e.x,t.x),r=Xp(e.y,t.y);return Math.sqrt(n**2+r**2)}var Qp=new Set([`auto`,`scroll`]),$p=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=em(this.lastRawMoveEventInfo,this.transformPagePoint));let e=nm(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=Zp(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e,{timestamp:i}=ua;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=em(t,this.transformPagePoint),W.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=nm(e.type===`pointercancel`?this.lastMoveEventInfo:em(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,a),r&&r(e,a)},!xl(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.distanceThreshold=a,this.contextWindow=r||window;let s=em(Kp(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=ua;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,nm(s,this.history)),this.removeListeners=U(Jp(this.contextWindow,`pointermove`,this.handlePointerMove),Jp(this.contextWindow,`pointerup`,this.handlePointerUp),Jp(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),W.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),la(this.updatePoint)}};function em(e,t){return t?{point:t(e.point)}:e}function tm(e,t){return{x:e.x-t.x,y:e.y-t.y}}function nm({point:e},t){return{point:e,delta:tm(e,im(t)),offset:tm(e,rm(t)),velocity:am(t,.1)}}function rm(e){return e[0]}function im(e){return e[e.length-1]}function am(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=im(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>Ni(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>Ni(t)*2&&(r=e[1]);let a=Pi(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 om(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?q(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?q(n,e,r.max):Math.min(e,n)),e}function sm(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 cm(e,{top:t,left:n,bottom:r,right:i}){return{x:sm(e.x,n,i),y:sm(e.y,t,r)}}function lm(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 um(e,t){return{x:lm(e.x,t.x),y:lm(e.y,t.y)}}function dm(e,t){let n=.5,r=Td(e),i=Td(t);return i>r?n=ji(t.min,t.max-r,e.min):r>i&&(n=ji(e.min,e.max-i,t.min)),Ci(0,1,n)}function fm(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 pm=.35;function mm(e=pm){return e===!1?e=0:e===!0&&(e=pm),{x:hm(e,`left`,`right`),y:hm(e,`top`,`bottom`)}}function hm(e,t,n){return{min:gm(e,t),max:gm(e,n)}}function gm(e,t){return typeof e==`number`?e:e[t]||0}var _m=new WeakMap,vm=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=X(),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(Kp(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=gl(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),qd(e=>{let t=this.getAxisMotionValue(e).get()||0;if(Ra.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=Td(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&W.update(()=>i(e,t),!1,!0),Fc(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=Sm(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&&W.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 $p(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:Yp(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&&W.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||!xm(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=om(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&&Np(e)?this.constraints||=this.resolveRefConstraints():e&&n?this.constraints=cm(n.layoutBox,e):this.constraints=!1,this.elastic=mm(t),r!==this.constraints&&!Np(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&qd(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=fm(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Np(e))return!1;let n=e.current,{projection:r}=this.visualElement;if(!r||!r.layout)return!1;let i=Lu(n,r.root,this.visualElement.getTransformPagePoint()),a=um(r.layout.layoutBox,i);if(t){let e=t(vu(a));this.hasMutatedConstraints=!!e,e&&(a=_u(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=qd(o=>{if(!xm(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 Fc(this.visualElement,e),n.start(yc(e,n,0,t,this.visualElement,!1))}stopAnimation(){qd(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){qd(t=>{let{drag:n}=this.getProps();if(!xm(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]-q(n,a,.5)+o)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!Np(t)||!n||!this.constraints)return;this.stopAnimation();let r={x:0,y:0};qd(e=>{let t=this.getAxisMotionValue(e);if(t&&this.constraints!==!1){let n=t.get();r[e]=dm({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(),qd(t=>{if(!xm(t,e,null))return;let n=this.getAxisMotionValue(t),{min:i,max:a}=this.constraints[t];n.set(q(i,a,r[t]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;_m.set(this.visualElement,this);let e=this.visualElement.current,t=Jp(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&Tl(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();Np(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=bm(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),W.read(r);let o=of(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(qd(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=pm,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function ym(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function bm(e,t,n){let r=Gl(e,ym(n)),i=Gl(t,ym(n));return()=>{r(),i()}}function xm(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Sm(e,t=10){let n=null;return Math.abs(e.y)>t?n=`y`:Math.abs(e.x)>t&&(n=`x`),n}var Cm=class extends gu{constructor(e){super(e),this.removeGroupControls=ki,this.removeListeners=ki,this.controls=new vm(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ki}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()}},wm=e=>(t,n)=>{e&&W.update(()=>e(t,n),!1,!0)},Tm=class extends gu{constructor(){super(...arguments),this.removePointerDownListener=ki}onPointerDown(e){this.session=new $p(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Yp(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:wm(e),onStart:wm(t),onMove:wm(n),onEnd:(e,t)=>{delete this.session,r&&W.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=Jp(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},Em=!1,Dm=class extends b.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),Em&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),ff.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}),Em=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||W.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(),fl.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;Em=!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 Om(e){let[t,n]=Xf(),r=(0,b.useContext)(_i);return(0,H.jsx)(Dm,{...e,layoutGroup:r,switchLayoutGroup:(0,b.useContext)(Mp),isPresent:t,safeToRemove:n})}var km={pan:{Feature:Tm},drag:{Feature:Cm,ProjectionNode:Jf,MeasureLayout:Om}};function Am(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&W.postRender(()=>i(t,Kp(t)))}var jm=class extends gu{mount(){let{current:e}=this.node;e&&(this.unmount=yl(e,(e,t)=>(Am(this.node,t,`Start`),e=>Am(this.node,e,`End`))))}unmount(){}},Mm=class extends gu{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=U(of(this.node.current,`focus`,()=>this.onFocus()),of(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function Nm(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&&W.postRender(()=>i(t,Kp(t)))}var Pm=class extends gu{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=Ml(e,(e,t)=>(Nm(this.node,t,`Start`),(e,{success:t})=>Nm(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},Fm=new WeakMap,Im=new WeakMap,Lm=e=>{let t=Fm.get(e.target);t&&t(e)},Rm=e=>{e.forEach(Lm)};function zm({root:e,...t}){let n=e||document;Im.has(n)||Im.set(n,{});let r=Im.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(Rm,{root:e,...t})),r[i]}function Bm(e,t,n){let r=zm(t);return Fm.set(e,n),r.observe(e),()=>{Fm.delete(e),r.unobserve(e)}}var Vm={some:0,all:1},Hm=class extends gu{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:Vm[r]};this.stopObserver=Bm(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(Um(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function Um({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var Wm={inView:{Feature:Hm},tap:{Feature:Pm},focus:{Feature:Mm},hover:{Feature:jm}},Gm={layout:{ProjectionNode:Jf,MeasureLayout:Om}},Km=Vp({...Gp,...Wm,...km,...Gm},Hp),qm=24e3,Jm=2048,Ym=1200,Xm=.05,Zm=4,Qm=.03,$m=2,eh=11;function th(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}function nh(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 rh(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]/32768;return t}var ih=.13,ah=[`audio/webm`,`audio/mp4`];function oh(){return typeof window>`u`||window.MediaRecorder===void 0?null:ah.find(e=>window.MediaRecorder.isTypeSupported(e))||null}function sh(e,t,n,r,i){if(!r.length||!n||!e)return;let a=new Blob(r,{type:i}),o=new FormData;o.append(`audio`,a,`aichat-${n}.webm`),o.append(`voiceSessionId`,n),o.append(`siteId`,t||``),fetch(`${e}/api/voice/upload-chat-recording`,{method:`POST`,body:o}).then(e=>{if(!e.ok)throw Error(`HTTP ${e.status}`)}).catch(e=>console.warn(`[FlowEngage] voice recording upload failed:`,e.message))}var ch=.02;function lh(e,t,n){let r=0,i=0,a=[],o=()=>{let t=e.currentTime;a.forEach(({source:e,gain:n})=>{try{n.gain.cancelScheduledValues(t),n.gain.setValueAtTime(n.gain.value,t),n.gain.linearRampToValueAtTime(0,t+ch),e.stop(t+ch)}catch{}}),a=[],r=0,i=0},s=()=>r>e.currentTime;return{enqueue:o=>{let c=rh(o),l=e.createBuffer(1,c.length,qm);l.copyToChannel(c,0);let u=e.createBufferSource();u.buffer=l;let d=e.createGain();u.connect(d),d.connect(e.destination),n&&d.connect(n);let f=s()?r:e.currentTime+ih;i||=f,u.start(f),r=f+l.duration;let p={source:u,gain:d};a.push(p),u.onended=()=>{a=a.filter(e=>e!==p),!a.length&&!s()&&t?.()}},stop:o,isPlaying:s,playedMs:()=>Math.max(0,(e.currentTime-i)*1e3)}}async function uh(e,t,n){let r=new URLSearchParams({siteId:t||``});n&&r.set(`chatId`,n);let i=Lr();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 dh(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 uh(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:qm});_.state===`suspended`&&await _.resume();let v=_.createMediaStreamDestination(),y=oh(),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})}},D=(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,Ym))},O=!1,k=!1,A=!1,te=!1,ne=!0,re=0,ie=!1,j=!1,M=Xm,ae=Zm,oe=null,se=!1,ce=!1,N=()=>{oe&&clearTimeout(oe);let e=()=>{if(!O){if(P.isPlaying()){oe=setTimeout(e,150);return}if(oe=null,se){p?.();return}!O&&C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:`PlaybackDrained`})),ce&&(ce=!1,d?.())}};oe=setTimeout(e,150)},P=lh(_,()=>{te&&(te=!1,c?.({mode:`listening`}))},v);typeof window<`u`&&(window.__fe_agentAudioPlaying=()=>P.isPlaying());let le=_.createMediaStreamSource(g);le.connect(v);let ue=_.createScriptProcessor(Jm,1,1),de=!1,F=0,fe=0;ue.onaudioprocess=e=>{if(O||C.readyState!==WebSocket.OPEN)return;let t=e.inputBuffer.getChannelData(0),n=()=>C.send(new Int16Array(t.length).buffer);if(k){A||(A=!0,console.debug(`[FlowEngage] mic held — streaming silence to keep socket alive`)),de=!1,F=0,fe=0,n();return}let r=th(t);if(P.isPlaying()||j?(de=!1,F=0,fe=0):r>=Qm?(fe=0,F+=1,!de&&F>=$m&&(de=!0,c?.({mode:`user-speaking`}))):(F=0,de&&++fe>=eh&&(de=!1,fe=0,c?.({mode:`thinking`,tentative:!0}))),(P.isPlaying()||j)&&!ie){if(r<M)re=0;else if(++re>=ae){ie=!0,re=0;let e=P.playedMs();P.stop(),ne=!1,j=!1,oe&&!se&&(clearTimeout(oe),oe=null),ce=!1,C.send(JSON.stringify({type:`VisitorInterrupted`,played_ms:Math.round(e)})),console.debug(`[FlowEngage] barge-in — visitor spoke over the agent`)}}C.send(nh(t).buffer)},le.connect(ue),ue.connect(_.destination);let pe=()=>{if(!O){O=!0,oe&&=(clearTimeout(oe),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=()=>sh(t,n,S,b,y);try{x.stop()}catch{x.onstop=null}}else b.length&&sh(t,n,S,b,y);_.close().catch(()=>{}),(C.readyState===WebSocket.OPEN||C.readyState===WebSocket.CONNECTING)&&C.close()}},me=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`}}},I=async e=>{for(let t of e.functions||[]){if(!t.client_side)continue;let e=await me(t);if(O||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??{})}))}},he=e=>{switch(e.type){case`Welcome`:Number.isFinite(e.barge_in_rms)&&e.barge_in_rms>0&&(M=e.barge_in_rms),Number.isFinite(e.barge_in_frames)&&e.barge_in_frames>0&&(ae=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}}D(e.role===`user`?`user`:`agent`,t,e.debug);break}case`UserStartedSpeaking`:ee(),P.stop(),j=!1,ne=!1,te=!1,oe&&!se&&(clearTimeout(oe),oe=null),ce=!1,c?.({mode:`listening`});break;case`AgentStartedSpeaking`:ne=!0,te=!0,ie=!1,re=0,c?.({mode:`speaking`});break;case`AgentAudioDone`:j=!1,ee(),N(),P.isPlaying()||(te=!1,c?.({mode:`listening`}));break;case`FunctionCallRequest`:I(e);break;case`AgentPreparing`:j=!0;break;case`AgentTurnComplete`:ce=!0,N();break;case`SessionEnding`:console.debug(`[FlowEngage] server is ending the session:`,e.reason||`unspecified`),se=!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){ne&&P.enqueue(new Int16Array(e.data));return}try{he(JSON.parse(e.data))}catch{}},C.onerror=()=>l?.(Error(`Voice connection failed`)),C.onclose=()=>{pe(),o?.()},{endSession:async()=>pe(),sendContextualUpdate:e=>{O||C.readyState!==WebSocket.OPEN||!e||C.send(JSON.stringify({type:`UpdatePrompt`,prompt:e}))},sendUserMessage:(e,{silent:t=!0,suppressQuestion:n=!1}={})=>{O||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`)=>{O||C.readyState!==WebSocket.OPEN||!e||C.send(JSON.stringify({type:`InjectAgentMessage`,message:e,behavior:t}))},setWalkthroughActive:e=>{O||C.readyState!==WebSocket.OPEN||C.send(JSON.stringify({type:`WalkthroughActive`,active:!!e}))},setMicMuted:e=>{k=!!e,!O&&C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:`MicHeld`,held:k}))},get status(){return O?`disconnected`:`connected`}}}var fh={startSession:dh},ph=({size:e=18,color:t=`currentColor`})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,H.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,H.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),mh=({size:e=20})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.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,H.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),hh=({size:e=18})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,H.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),gh=()=>(0,H.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,H.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),_h=()=>(0,H.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.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`})}),vh=({className:e=``})=>(0,H.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,H.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,H.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,H.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),yh=({size:e=14})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`path`,{d:`M12 8V4H8`}),(0,H.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,H.jsx)(`path`,{d:`M2 14h2`}),(0,H.jsx)(`path`,{d:`M20 14h2`}),(0,H.jsx)(`path`,{d:`M15 13v2`}),(0,H.jsx)(`path`,{d:`M9 13v2`})]}),bh=({size:e=20,strokeWidth:t=2,color:n=`currentColor`})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:n,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`12`,y1:`5`,x2:`12`,y2:`19`}),(0,H.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`})]}),xh=({size:e=20,color:t=`currentColor`})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,H.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`,fill:t}),(0,H.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`,fill:t}),(0,H.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`,fill:t})]}),Sh=({size:e=20,color:t=`currentColor`})=>(0,H.jsxs)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,H.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,H.jsx)(`path`,{d:`M11.9955 12H12.0045M15.991 12H16M8 12H8.00897`,stroke:`white`,"stroke-width":`2`,"stroke-linecap":`round`,"stroke-linejoin":`round`})]}),Ch=()=>(0,H.jsx)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,H.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`})}),wh=({size:e=24})=>(0,H.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,H.jsx)(`path`,{d:`M12 19v3`}),(0,H.jsx)(`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`}),(0,H.jsx)(`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`}),(0,H.jsx)(`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`}),(0,H.jsx)(`path`,{d:`m2 2 20 20`}),(0,H.jsx)(`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`})]}),Th=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Eh=(e=``)=>String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),Dh=new Set([`p`,`br`,`ul`,`ol`,`li`,`strong`,`em`,`b`,`i`,`a`]),Oh=/^https?:\/\//i;function kh(e){let t=Array.from(e.childNodes);for(let n of t)if(n.nodeType===Node.ELEMENT_NODE){let t=n.tagName.toLowerCase();if(!Dh.has(t)){e.replaceChild(document.createTextNode(n.textContent),n);continue}let r={};if(t===`a`){let e=n.getAttribute(`href`)||``;Oh.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);kh(n)}else n.nodeType!==Node.TEXT_NODE&&e.removeChild(n)}function Ah(e){let t=document.createElement(`div`);return t.innerHTML=e,kh(t),t.innerHTML}function jh(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 Mh=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return jh(Ah(t));let n=t.replace(/\r\n/g,`
|
|
36
|
+
`,document.head.appendChild(e)};function ur(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(jn(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(Mn(e).toLowerCase()===n)return e;for(let e of i){let t=Mn(e).toLowerCase();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=Mn(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=Mn(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=Mn(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=>!jn(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(jn(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(jn(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(jn(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=>!jn(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(jn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function dr(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;lr();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 fr(){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`)),kn())}function pr(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 mr(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 hr(e,{siteId:t,apiBaseUrl:n}){if(!e)return{allowed:!1,correctedUrl:null};let r=!1;try{r=!!Yn()}catch{r=!1}let i=async()=>({allowed:r?!1:await mr(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 gr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(Pn,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function _r(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}or();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 sr(),!1;let o=await a.text(),s=new DOMParser().parseFromString(o,`text/html`),c=document.getElementById(`flowengage-root`);if(!c)return sr(),!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()}),Zn();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(Xn,`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(Xn,`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,Nn(`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){Nn(`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,Nn(`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){Nn(`trySpaNavigate: blocked location.assign from replayed script:`,e);return}return d(e)},window.location.replace=e=>{if(p){Nn(`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;Nn(`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)){Nn(`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:`)&&(Nn(`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`)||``}),Nn(`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),Nn(`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(Wn(),Kn(),n){try{er()}catch{}try{rr()}catch{}}else window.scrollTo(0,0);sr(),ir(e);try{sessionStorage.removeItem(Pn)}catch{}try{sessionStorage.removeItem(In)}catch{}try{Un=new URL(e,window.location.origin).pathname}catch{}return Nn(`trySpaNavigate: succeeded →`,e),!0}catch{return clearTimeout(i),sr(),!1}}function vr(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(In,JSON.stringify({voiceWasActive:!0,targetUrl:String(e),ts:Date.now()}))}catch{}}function yr(){if(!(typeof sessionStorage>`u`))try{sessionStorage.removeItem(In)}catch{}}function br(){if(typeof window>`u`||typeof sessionStorage>`u`)return{shouldResumeVoice:!1,targetUrl:null};let e;try{e=JSON.parse(sessionStorage.getItem(In)||`null`)}catch{return{shouldResumeVoice:!1,targetUrl:null}}if(!e)return{shouldResumeVoice:!1,targetUrl:null};try{sessionStorage.removeItem(In)}catch{}return e.voiceWasActive?Date.now()-e.ts>Ln?(Nn(`initVoiceNavResume: state expired, skipping`),{shouldResumeVoice:!1,targetUrl:null}):(Nn(`initVoiceNavResume: voice was active during navigation to`,e.targetUrl),{shouldResumeVoice:!0,targetUrl:e.targetUrl||null}):{shouldResumeVoice:!1,targetUrl:null}}function xr(){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 Sr=6e3,Cr=250,wr=700;async function Tr(){if(typeof window>`u`)return;let e=window.__fe_agentAudioPlaying;if(typeof e!=`function`){await new Promise(e=>setTimeout(e,wr));return}let t=Date.now()+Sr;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,Cr))}async function Er(e,t={}){if(typeof window>`u`)return{navigated:!1};let{sectionText:n,voiceActive:r=!1}=t;try{let t=pr(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&&gr(n),r||we(),r?Tr().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(Yn()){n&&gr(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)),xr()){try{window.history.pushState({},``,e),window.dispatchEvent(new PopStateEvent(`popstate`,{state:{}}))}catch{}return n&&gr(n),r||we(),window.location.assign(i.href),{navigated:!0}}return{navigated:!0}}return n&&gr(n),r||we(),window.location.assign(i.href),{navigated:!0}}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&gr(n);try{window.location.href=pr(e)}catch{window.location.href=e}return{navigated:!0}}}var Dr=!1,Or=null;function kr(e){Or=e,typeof window<`u`&&(window.__fe_triggerVoiceNavHooks=()=>{try{e.onBeforeNavigate()}catch{}}),!Dr&&(Dr=!0,!(typeof document>`u`)&&(document.addEventListener(`click`,e=>{if(!Or)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)){Nn(`voice-link-hook: saving state before navigation →`,r.href);try{Or.onBeforeNavigate()}catch{}}},!0),document.addEventListener(`submit`,e=>{if(Or&&!e.target?.closest?.(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)){Nn(`voice-form-hook: saving state before form submit`);try{Or.onBeforeNavigate()}catch{}}},!0)))}function Ar(){Or=null,Nn(`voice-nav-hooks: deactivated`)}var jr=4e3,Mr=null;function Nr(){let e=typeof window<`u`&&window.Shopify?.routes?.root||`/`;return e.endsWith(`/`)?e:`${e}/`}async function Pr(e,t={}){let n=new AbortController,r=setTimeout(()=>n.abort(),jr);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 Fr(){if(Mr!==null)return Mr;if(typeof window>`u`)return Mr=!1;if(window.Shopify)return Mr=!0;try{let e=await Pr(`${Nr()}cart.js`);Mr=e&&typeof e.item_count==`number`}catch{Mr=!1}return Mr}async function Ir(){return Pr(`${Nr()}cart.js`)}function Lr(){return typeof window>`u`?null:window.__flowengageCustomer?.id||null}function Rr(e){return typeof e!=`number`||Number.isNaN(e)?null:(e/100).toFixed(2)}async function zr(){try{if(!await Fr())return null;let e=await Ir();return{itemCount:e.item_count,subtotal:Rr(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:Rr(e.final_line_price??e.line_price),handle:e.handle||null}))}}catch{return null}}async function Br(e,t=null){let n=await Pr(`${Nr()}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 Vr(e,t=1){return Pr(`${Nr()}cart/add.js`,{method:`POST`,body:JSON.stringify({items:[{id:e,quantity:t}]})})}async function Hr(e,t){return Pr(`${Nr()}cart/change.js`,{method:`POST`,body:JSON.stringify({line:e,quantity:t})})}function Ur(){return`${Nr()}cart`}function Wr(){return`${Nr()}checkout`}function Gr(e){return`${Nr()}products/${encodeURIComponent(e)}`}async function Kr(e,t=6){let n=new URLSearchParams({q:e,"resources[type]":`product`,"resources[limit]":String(t)});try{return((await Pr(`${Nr()}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 qr(){return typeof window>`u`?!1:/\/cart\/?$/.test(window.location.pathname)}var Jr=[`form[action*="/cart"]`,`cart-items`,`cart-drawer-items`,`.cart-items`,`.cart__items`,`#main-cart-items`,`[data-cart-items]`].join(`, `);function Yr(e){if(/cart/i.test(e.id))return!0;try{return!!e.querySelector(Jr)}catch{return!1}}async function Xr(){if(typeof document>`u`)return!1;let e=Array.from(document.querySelectorAll(`[id^="shopify-section-"]`)).filter(Yr);if(!e.length)return!1;let t=e.map(e=>e.id.replace(/^shopify-section-/,``));try{let e=await Pr(`${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 Zr=[`[data-cart-count]`,`.cart-count-bubble`,`.cart-count`,`#CartCount`,`.cart-link__bubble`,`.site-header__cart-count`,`#cart-icon-bubble`];function Qr(e){if(typeof document>`u`)return;let t=String(e);for(let e of Zr)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 $r(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 ei(e){let t=await Xr();return!t&&qr()&&(await new Promise(e=>setTimeout(e,600)),t=await Xr()),e&&typeof e.item_count==`number`&&Qr(e.item_count),$r(e||null),{sectionsSwapped:t}}async function ti(e){try{let{sectionsSwapped:t}=await ei(e);if(!t&&qr())return` (The list on this page may need a quick refresh to show it.)`}catch{}return``}function ni(e){let t=Rr(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 ri(e,t){let n=t.title&&t.title!==`Default Title`;return`${e.title}${n?` (${t.title})`:``}`}function ii(e,t){return e?.userMessage||t}var ai={async add(e){let{variant:t,product:n}=await Br(e.productHandle,e.variantTitle||null);await Vr(t.id,e.quantity||1);let r=await Ir(),i=await ti(r);return{message:`✅ Added ${e.quantity||1} × ${ri(n,t)} to your cart.${ni(r)}${i}`}},async update(e){let t=(await Ir()).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 Hr(e.line,e.quantity),r=await ti(n);return{message:`✅ Updated ${t.product_title||t.title} to quantity ${e.quantity}.${ni(n)}${r}`}},async remove(e){let t=(await Ir()).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 Hr(e.line,0),r=await ti(n);return{message:`🗑️ Removed ${t.product_title||t.title} from your cart.${ni(n)}${r}`}},async view_cart(){return{message:`Opening your cart…`,navigateTo:Ur()}},async checkout(){return(await Ir()).item_count?{message:`Taking you to checkout…`,navigateTo:Wr()}:{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:Gr(e.productHandle)}}},oi={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 si(e){let t={messages:[],navigateTo:null};if(!Array.isArray(e)||e.length===0)return t;if(!await Fr())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=ai[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(ii(e,oi[n.type]))}}return t}var ci=s((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),H=s(((e,t)=>{t.exports=ci()}))(),li=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(),ui=(e=[])=>e.filter(e=>e.type!==`call_recording`&&!(typeof e.message==`string`&&e.message.includes(`AI chat recording`))).map(e=>({...e,message:li(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`}));function di(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 fi=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,pi=(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}:{}}},mi=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t},hi=(e=[],t,n=6)=>!t?.message||e.slice(-n).some(e=>e.sender===`system`&&e.message===t.message)?e:[...e,t];function gi({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,b.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),[a,o]=(0,b.useState)(0),[s,c]=(0,b.useState)(`booting`),[l,u]=(0,b.useState)(null),[d,f]=(0,b.useState)(null),[p,m]=(0,b.useState)(``),[h,g]=(0,b.useState)([]),_=(0,b.useCallback)(()=>{g(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()}])},[]),v=(0,b.useCallback)(e=>{si(e).then(({messages:e,navigateTo:t})=>{e.length&&g(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)})},[]),y=(0,b.useCallback)(()=>{g(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()}])},[]),[x,C]=(0,b.useState)(N().isOpen),[w,T]=(0,b.useState)(N().activeScreen),[E,k]=(0,b.useState)(N().isHumanHandled),[A,ie]=(0,b.useState)(N().agentName),[j,M]=(0,b.useState)(N().agentHeadshot),[ae,de]=(0,b.useState)(()=>le(i?.siteId)),[F,fe]=(0,b.useState)(!1),[me,I]=(0,b.useState)(!1),[he,ge]=(0,b.useState)(`idle`),[_e,ve]=(0,b.useState)(!1),[ye,be]=(0,b.useState)(!1),[Se,Ce]=(0,b.useState)(``),[we,Te]=(0,b.useState)(!1),[Ee,De]=(0,b.useState)(0),[Oe,ke]=(0,b.useState)(0),[Ae,L]=(0,b.useState)(!1),[R,Pe]=(0,b.useState)(null),[Fe,Ie]=(0,b.useState)(null),[Le,Re]=(0,b.useState)(`idle`),[ze,Be]=(0,b.useState)(null),[Ve,He]=(0,b.useState)(!1),[Ue,We]=(0,b.useState)(``),[Ge,Ke]=(0,b.useState)(!1),qe=(0,b.useRef)(null),z=(0,b.useRef)(null),Je=(0,b.useRef)(``),Ye=(0,b.useRef)(!1),Xe=(0,b.useRef)(null),Ze=(0,b.useRef)(null),Qe=(0,b.useRef)(null),$e=(0,b.useRef)(null),et=(0,b.useRef)(null),tt=(0,b.useRef)(null),nt=(0,b.useRef)(null),rt=(0,b.useRef)(!1),it=(0,b.useRef)({url:null,at:0}),at=(0,b.useCallback)((e,t)=>{Bn(6e3);let n=e;try{n=new URL(e,window.location.origin).href}catch{}let r=it.current;return r.url===n&&Date.now()-r.at<4e3?Promise.resolve({navigated:!0,deduped:!0}):(it.current={url:n,at:Date.now()},Er(e,t))},[]),ot=(0,b.useRef)([]),B=(0,b.useRef)(null),st=(0,b.useRef)(null),ct=(0,b.useRef)(null),lt=(0,b.useRef)(!1),ut=(0,b.useRef)(!1),dt=(0,b.useRef)(``),ft=(0,b.useRef)(null),pt=(0,b.useRef)(null),mt=(0,b.useRef)([]),ht=(0,b.useRef)(0),gt=(0,b.useRef)(A),_t=(0,b.useRef)([]),vt=(0,b.useRef)(!1),yt=(0,b.useRef)(!1),bt=(0,b.useRef)(i),xt=(0,b.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),St=(0,b.useCallback)((e={})=>{let t=!!e.is_human_handled;return k(t),t?(T(`agent`),e.agent_info?.name&&ie(e.agent_info.name),e.agent_info?.headshot&&M(e.agent_info.headshot),t):(T(`ai`),t)},[]),Ct=(0,b.useMemo)(()=>{let e=d?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:D},[i,d]);(0,b.useEffect)(()=>{Ze.current=R},[R]),(0,b.useEffect)(()=>{gt.current=A},[A]),(0,b.useEffect)(()=>{yt.current=we},[we]),(0,b.useEffect)(()=>{bt.current=i},[i]);let wt=()=>{We(``)},Tt=(0,b.useCallback)(()=>{ct.current&&=(window.clearTimeout(ct.current),null)},[]),Et=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return de(t),ue(t,i?.siteId),t};(0,b.useEffect)(()=>{let e=i?.siteId;if(!e)return;let t=le(e);if(t){de(t);return}de(t=>(t&&ue(t,e),t))},[i?.siteId]);let Dt=(e=`unspecified`)=>{let t=B.current||tt.current?.callId,n=ht.current,r=ft.current;if(ft.current=null,ht.current=0,r&&r.state!==`inactive`){r.onstop=()=>{let e=mt.current;if(mt.current=[],e.length>0&&t&&z.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;z.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,mt.current=[]}}else if(r&&r.state===`inactive`){let e=mt.current;if(mt.current=[],e.length>0&&t&&z.current){let r=new Blob(e,{type:e[0].type}),i=n>0?Math.round((Date.now()-n)/1e3):0;z.current.uploadRecording(t,r,i).then(e=>console.log(`[FlowEngageCall] recording upload success`,e)).catch(e=>console.warn(`[FlowEngageCall] recording upload failed`,e))}}else mt.current=[];if(pt.current){try{pt.current.close()}catch{}pt.current=null}Qe.current&&=(Qe.current.close(),null),$e.current&&=($e.current.getTracks().forEach(e=>e.stop()),null),et.current&&=(et.current.srcObject=null,et.current.remove(),null),Tt(),tt.current=null,ot.current=[],B.current=null,st.current=null,lt.current=!1,He(!1),Pe(null),Ie(null),Re(`idle`),Be(null)},Ot=(e=new Date().toISOString())=>{let t=qe.current,n=B.current||tt.current?.callId;if(!(!t?.connected||!n||lt.current)){lt.current=!0,t.emit(`call:connected`,{callId:n,chatId:Je.current,connectedAt:e});try{let e=$e.current,t=et.current?.srcObject;if(e&&t&&!ft.current){mt.current=[];let n=new(window.AudioContext||window.webkitAudioContext);pt.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&&mt.current.push(e.data)},ft.current=a,ht.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{}}},kt=(e={})=>{if(!e.callId)return;let t=st.current===e.callId,n=B.current===e.callId,r=Ze.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(Tt(),Pe(null),t||n){B.current=e.callId,Ie(e.callId),Re(e=>e===`connected`?e:`connecting`),C(!0);return}Re(`idle`)}},At=(e={})=>{if(!e.callId)return;let t=st.current===e.callId,n=B.current===e.callId,r=Ze.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(Tt(),n){Dt();return}st.current=null,tt.current=null,ot.current=[],Pe(null),Re(`idle`)}},jt=async(e={})=>{let t=Qe.current,n=qe.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:Je.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),tt.current=e;return}if(await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),ot.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:Je.current,queuedCount:ot.current.length});for(let e of ot.current)await t.addIceCandidate(new RTCIceCandidate(e));ot.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:Je.current})};(0,b.useEffect)(()=>{P({isOpen:x,activeScreen:w,isHumanHandled:E,agentName:A,agentHeadshot:j})},[x,w,E,A,j]),(0,b.useEffect)(()=>{let e=!0;return(async()=>{Ke(!0);try{let t=S(i),n=await Me(t);if(!e)return;let a=t.siteId,o=oe(a),s=pe(a),l=``;try{let e=Ye.current,r=Xe.current;if(Ye.current=!1,Xe.current=null,l=(await je({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:a,priorChatId:e||r?null:o||te(),forceNew:e,resumeChatId:r,visitorId:s}))?.data?.chatId,!l)throw Error(`resolve-session returned no chatId`);ne(),ce(a,l)}catch(e){console.warn(`[FlowEngageProvider] resolve-session failed, reusing persisted or ephemeral chat id`,e?.message||e),l=o||re(),ce(a,l)}Je.current=l;let u=Ne({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId,visitorId:s});z.current=u,f({...n,apiBaseUrl:t.apiBaseUrl}),m(l);let d=n?.widgetSettings?.branding?.fallbackAgentName||`Agent`,p=xn({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:l,siteId:t.siteId});qe.current=p,p.on(`connect`,async()=>{ge(`connected`);let e=Je.current;if(e&&z.current)try{St(await z.current.checkHumanHandled(e))}catch{}}),p.on(`disconnect`,()=>{ge(`disconnected`)}),p.on(`aiTyping`,()=>{I(!0)}),p.on(`ai:typing`,()=>{I(!0)}),p.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:li(t.message)};I(!1),fe(!1),!(n.type===`call_recording`||typeof n.message==`string`&&n.message.includes(`AI chat recording`))&&g(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),p.on(`conversationStarted`,e=>{e?.message&&g(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),p.on(`message:new`,e=>{let t=e.message||e,n={...t,message:li(t.message)};I(!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`)&&fe(!1),g(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)&&(k(!0),T(`agent`),ie(mi([n.agent_name,n.agentName,n.metadata?.agentName],d)),n.sender_headshot&&M(n.sender_headshot),C(!0),De(e=>e+1)))});let h=(e={})=>{let t=mi([e.agent?.name,e.agentName,e.agent_name,gt.current],d);k(!0),T(`agent`),ie(t),M(e.agent?.headshot||null),C(!0),De(e=>e+1),g(e=>hi(e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}))},v=(e={})=>{let t=mi([e.agent?.name,e.agentName,e.agent_name,gt.current],d);k(!1),T(`ai`),g(e=>hi(e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}))};p.on(`agent:joined`,h),p.on(`agentJoined`,h),p.on(`agent:left`,v),p.on(`agentLeft`,v),p.on(`conversationEnded`,e=>{L(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;g(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),p.on(`chat:history_update`,e=>{let t=ui(e.chat_history||[]);g(t),t.length===0&&(L(!1),k(!1),T(`ai`),I(!1),fe(!1))}),p.on(`conversation:reset`,()=>{g([]),L(!1),k(!1),T(`ai`),I(!1),fe(!1)}),p.on(`voice:end_session`,(e={})=>{console.log(`[FlowEngageProvider] voice:end_session received — ending voice session`),ke(e=>e+1),C(!0),De(e=>e+1)}),p.on(`typing:start`,e=>{e.sender===`agent`&&fe(!0)}),p.on(`typing:stop`,e=>{e.sender===`agent`&&fe(!1)}),p.on(`call:incoming`,(e={})=>{let t=mi([e.agentName,e.ownerName,e.agent?.name,gt.current],`Agent`);wt(),Tt(),lt.current=!1,Pe({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ie(e=>mi([t,e],`Agent`)),Re(`incoming`),Be(null),C(!0)}),p.on(`call:offer`,async(e={})=>{tt.current=e;try{await jt(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),p.on(`call:ice-candidate-from-agent`,async(e={})=>{if(e.candidate)try{let t=pi(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(!Qe.current||!Qe.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||Je.current,queueSize:ot.current.length+1}),ot.current.push(t);return}await Qe.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),p.on(`call:ended`,()=>{wt(),Dt(`socket:call_ended`)}),p.on(`call:accepted`,(e={})=>{kt(e)}),p.on(`call:accepted_by_other`,(e={})=>{kt(e)}),p.on(`call:rejected`,(e={})=>{At(e)}),p.on(`call:missed`,(e={})=>{At(e)}),p.on(`call:failed`,(e={})=>{At(e)}),p.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=st.current===e.callId,n=B.current===e.callId,r=tt.current?.callId===e.callId,i=Ze.current?.callId===e.callId;if(!t&&!n&&!r){i&&(Pe(null),Re(`idle`));return}lt.current=!0,st.current=null,B.current=e.callId,Ie(e.callId),Pe(null),Re(`connected`),Be(e.connectedAt||new Date().toISOString()),C(!0)}),p.on(`call:unavailable`,(e={})=>{Dt(`socket:call_unavailable`),We(fi(e,`This visitor is not available for a call right now.`)),C(!0)}),p.on(`call:error`,(e={})=>{Dt(`socket:call_error`),We(fi(e,`We couldn't connect the call right now.`)),C(!0)}),p.on(`visitor:navigate`,async({url:e,section:t,highlight:n}={})=>{e&&at(e,{voiceActive:yt.current}).then(({navigated:e,reason:r})=>{if(!e){r===`not-found`?_():r===`already-on-page`&&y();return}let i=t||n;i&&setTimeout(()=>{let e=ur(null,i);e&&dr(e)},300)})}),p.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;let n=ur(e||null,t||null);n&&dr(n)}),p.on(`visitor:clear_highlight`,()=>{fr()}),xt.current=Sn({socket:p,chatId:l});let b=await u.loadHistory(l,r);if(!e)return;g(ui(b.chat_history||[])),k(!!b.is_human_handled),T(b.is_human_handled?`agent`:w);let x=b?.visitor_email||b?.visitorEmail;if(x&&String(x).trim()&&Et(String(x).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,xt.current?.cleanup?.(),Dt(),qe.current?.disconnect()}},[i,r,a]),(0,b.useEffect)(()=>()=>{if(we&&!vt.current&&_t.current.length>0){let e=Je.current,t=_t.current,n=z.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(()=>{}),vt.current=!0)}},[we,d]);let Mt=(0,b.useRef)(null);(0,b.useEffect)(()=>{let e=z.current;!e||!p||Mt.current!==x&&(x&&Mt.current!==null?e.updateChatStatus(p,`open`).catch(()=>{}):Mt.current===!0&&e.updateChatStatus(p,`widget_closed`).catch(()=>{}),Mt.current=x)},[x,p]),(0,b.useEffect)(()=>{let e=()=>{let e=Je.current,t=z.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 Nt=async()=>{if(!(!R?.callId||!z.current||!qe.current||!p)){wt(),st.current=R.callId,Tt();try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});$e.current=e;let t=[{urls:`stun:stun.l.google.com:19302`}];try{let e=await z.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});Qe.current=n,n.onconnectionstatechange=()=>{let e=n.connectionState;if(e===`connected`){let e=new Date().toISOString();Re(`connected`),Be(t=>t||e),Ot(e);return}if(e===`connecting`){Re(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&Dt(`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),Ot(e);return}if(e===`checking`||e===`new`){Re(e=>e===`connected`?e:`connecting`);return}(e===`failed`||e===`closed`)&&Dt(`peer:ice_${e}`)},n.onsignalingstatechange=()=>{},n.onicegatheringstatechange=()=>{},e.getTracks().forEach(t=>{n.addTrack(t,e)}),n.onicecandidate=e=>{if(!e.candidate||!qe.current?.connected)return;let t=e.candidate;qe.current.emit(`call:ice-candidate`,{callId:R.callId,candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,chatId:p,from:`customer`})},n.ontrack=e=>{let[t]=e.streams||[],[n]=t?.getAudioTracks?.()||[];if(!et.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=>{},et.current=e,document.body.appendChild(e)}et.current.srcObject=e.streams[0];let r=R?.callId,i=r&&(st.current===r||B.current===r);if(!lt.current&&i){let e=new Date().toISOString();Re(`connected`),Be(t=>t||e),B.current=r,Ie(r),Ot(e)}et.current.srcObject=t||null;let a=et.current.play?.();a?.catch&&a.catch(e=>{})};let r=tt.current;r&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:r.callId||R.callId,chatId:p}),await jt({...r,callId:r.callId||R.callId})),await z.current.acceptCall(R.callId,p),qe.current?.emit(`call:accepted`,{callId:R.callId,chatId:p}),B.current=R.callId,Ie(R.callId),Re(e=>e===`connected`||lt.current?`connected`:`connecting`),Pe(null),C(!0)}catch(e){if(st.current=null,Dt(`accept_call_failed`),e?.status===404||e?.status===409||e?.status===422){We(fi(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await z.current.rejectCall(R.callId,p)}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.`)}}},Pt=async()=>{if(!R?.callId||!z.current||!p){Dt(`reject_call_without_server_context`);return}let e=R.callId;Tt(),wt(),qe.current?.emit(`call:rejected`,{callId:e,chatId:p,reason:`visitor_declined`});try{await z.current.rejectCall(e,p)}catch(e){We(fi(e,`We couldn't decline the call cleanly.`))}finally{Dt(`reject_call_finally`)}},Ft=(0,b.useRef)(Pt);Ft.current=Pt,(0,b.useEffect)(()=>{if(!R?.callId||Fe){Tt();return}let e=R.callId;return Tt(),ct.current=window.setTimeout(()=>{Ze.current?.callId===e&&st.current!==e&&B.current!==e&&Ft.current()},O),()=>{ct.current&&=(window.clearTimeout(ct.current),null)}},[Fe,Tt,R?.callId]);let It=async()=>{if(!Fe||!z.current||!p){Dt(`end_call_without_server_context`);return}wt();try{await z.current.endWebRTCCall(Fe,p)}catch(e){We(fi(e,`The call ended locally, but the server could not be updated.`))}finally{Dt(`end_call_finally`)}},Lt=()=>{let e=$e.current?.getAudioTracks?.()||[],t=Qe.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)},Rt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(C(!0),!(!t||!z.current||!p||typeof window>`u`)){try{await z.current.trackVisitor({chatId:p,currentPagePath:window.location.pathname||`/`})}catch{}try{await z.current.updateChatStatus(p,`open`)}catch{}}},zt=async e=>{let t=Et(e);if(!t||!z.current||!Je.current)return t;try{await z.current.trackVisitor({chatId:Je.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Bt=()=>{!p||!qe.current?.connected||ut.current||(ut.current=!0,qe.current.emit(`typing:start`,{chatId:p,sender:`user`}))},Vt=()=>{!p||!qe.current?.connected||!ut.current||(ut.current=!1,qe.current.emit(`typing:stop`,{chatId:p,sender:`user`}))},Ht=(e=``)=>{let t=typeof e==`string`?e:``;!p||!qe.current?.connected||t!==``&&dt.current===t||(dt.current=t,qe.current.emit(`typing:update`,{chatId:p,sender:`user`,text:t}))};function Ut(){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 Wt=async(e,t=``,n=null,i={})=>{let a=typeof e==`string`?e.trim():``;if(!a||!z.current||!p||s!==`ready`||Ae)return;Vt(),rt.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(nt.current&&o.test(a)&&!c.test(a)){let{url:e,section:t}=nt.current;nt.current=null,rt.current=!0,console.log(`[FWH Nav] Client-side nav firing →`,e),at(e,{voiceActive:yt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?_():n===`already-on-page`&&y();return}!t||!yt.current||setTimeout(()=>{let e=ur(null,t);e&&dr(e)},300)})}else o.test(a)||(nt.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||{}};g(e=>[...e,f]);let m=E;if(m)try{m=St(await z.current.checkHumanHandled(p))}catch{}if(m&&qe.current?.connected){qe.current.emit(`customer:message`,{chatId:p,content:e,sender:`user`,email:ae||void 0,type:i?.type||`text`,metadata:i?.metadata||{},...n||{}});return}ve(!0);try{let o=await zr(),s=Lr(),c=`stream-preview-${Date.now().toString(36)}`,u=e=>{I(!1),g(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 z.current.sendAiMessage(p,e,r,t,{...n||{},...ae?{email:ae}:{}},{...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:Ut()||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),at(e.url,{voiceActive:yt.current}).then(({navigated:t,reason:n})=>{if(!t){n===`not-found`?_():n===`already-on-page`&&y();return}e.section&&setTimeout(()=>{let t=ur(null,e.section);t&&dr(t)},300)})):(nt.current=e,console.log(`[FWH Nav] Stored pending nav →`,nt.current))}if(d.navigate?.url)if(rt.current)rt.current=!1;else{let{url:e,section:t}=d.navigate;at(e,{voiceActive:yt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?_():n===`already-on-page`&&y();return}t&&setTimeout(()=>{let e=ur(null,t);e&&dr(e)},300)})}else if(d.highlight?.section){let e=d.highlight.section;setTimeout(()=>{let t=ur(null,e);t&&dr(t)},150)}else{let e=[...f].reverse().find(e=>e.sender===`bot`||e.sender===`assistant`);if(e?.message){let t=di(e.message);t&&hr(t.url,{siteId:bt.current?.siteId,apiBaseUrl:bt.current?.apiBaseUrl}).then(({allowed:e,correctedUrl:n})=>{if(!e){_();return}at(n||t.url,{voiceActive:yt.current}).then(({navigated:e,reason:n})=>{if(!e){n===`not-found`?_():n===`already-on-page`&&y();return}!t.section||!yt.current||setTimeout(()=>{let e=ur(null,t.section);e&&dr(e)},300)})})}}g(ui(f)),Array.isArray(d.cart_actions)&&d.cart_actions.length&&v(d.cart_actions),k(!!d.is_human_handled),T(d.is_human_handled?`agent`:`ai`),I(!1),ve(!1),await z.current.updateChatStatus(p,`messageSent`)}catch(e){g(e=>e.filter(e=>e.id!==d&&!e.isStreaming)),I(!1),ve(!1),e.status===429?(be(!0),Ce(e.message),window.setTimeout(()=>{be(!1),Ce(``)},ee)):u(e)}},Gt=async e=>{if(!z.current||!e)throw Error(`Upload is unavailable right now.`);return z.current.uploadChatFile(e)},Kt=async e=>{if(!(!z.current||!p)){try{let t=e?`voice`:`text`;await z.current.setChatMode(p,t)}catch{}Te(e),e&&(vt.current=!1)}},qt=async e=>{if(vt.current)return;if(vt.current=!0,!z.current||!p||!e?.length){Te(!1);return}let t=()=>{let t=ui(e);g(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 z.current.syncVoice(p,e);if(n?.chat_history?.length)g(ui(n.chat_history));else if(n?.success)try{let e=await z.current.loadHistory(p,r);e?.chat_history?.length?g(ui(e.chat_history)):t()}catch{t()}else t()}catch{t()}finally{Te(!1)}},Jt=async()=>{if(!(!z.current||!p)){we&&!vt.current&&_t.current.length>0&&await qt(_t.current);try{await z.current.endConversation(p)}catch{try{await z.current.updateChatStatus(p,`ended`)}catch{}}L(!0),g(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,b.useEffect)(()=>{if(Le!==`connected`||!Fe||!p||!ze||!Ct)return;let e=new Date(ze).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,Ct*1e3-t),r=window.setTimeout(()=>{We(`The call ended because it reached the time limit.`),It()},n);return()=>window.clearTimeout(r)},[Fe,ze,Le,p,It,Ct]),(0,b.useEffect)(()=>{let e=()=>{let e=Je.current,t=z.current;if(!t||!e)return;if(yt.current&&_t.current.length>0&&xe(),!vt.current&&_t.current.length>0&&(t.beaconSyncVoice(e,_t.current)||t.syncVoice(e,_t.current).catch(()=>{}),vt.current=!0),B.current){t.beaconEndWebRTCCall(B.current,e);return}let n=st.current||Ze.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 Yt=(0,b.useCallback)(()=>{let e=i?.siteId;se(e),Ye.current=!0,Xe.current=null,qe.current?.disconnect(),g([]),m(``),Je.current=``,L(!1),k(!1),ie(null),M(null),Ke(!0),o(e=>e+1)},[i?.siteId]),Xt=(0,b.useCallback)(e=>{i?.siteId,Ye.current=!1,Xe.current=e,qe.current?.disconnect(),g([]),m(``),Je.current=``,L(!1),k(!1),ie(null),M(null),Ke(!0),o(e=>e+1)},[i?.siteId]),Zt=(0,b.useMemo)(()=>({status:s,error:l,runtimeConfig:d,resolvedConfig:i,chatId:p,chatHistory:h,isOpen:x,activeScreen:w,isHumanHandled:E,agentName:A,agentHeadshot:j,visitorEmail:ae,isAgentTyping:F,isAiTyping:me,connectionStatus:he,isLoading:_e,isVoiceMode:we,isRateLimited:ye,rateLimitMessage:Se,isConversationEnded:Ae,isSessionRestoring:Ge,openToChatCounter:Ee,voiceEndCounter:Oe,incomingCall:R,activeCallId:Fe,callConnectionState:Le,callConnectedAt:ze,isCallMuted:Ve,webRTCError:Ue,language:r,historyRef:_t,hasSyncedRef:vt,dismissCallError:wt,captureVisitorEmail:zt,startTyping:Bt,stopTyping:Vt,updateTypingDraft:Ht,notifyRouteChange:()=>xt.current?.notifyRouteChange?.(),openWidget:Rt,closeWidget:()=>C(!1),toggleWidget:()=>{if(x){C(!1);return}Rt({notifyChatInitiated:!0})},sendMessage:Wt,uploadChatFile:Gt,setVoiceMode:Kt,onMessageSync:qt,endConversation:Jt,startNewChat:Yt,resumeChat:Xt,getVisitorChatHistory:()=>z.current?.getVisitorChatHistory?.(),getVisitorChatThread:e=>z.current?.getVisitorChatThread?.(e),acceptCall:Nt,rejectCall:Pt,endWebRTCCall:It,toggleCallMute:Lt}),[s,l,d,i,p,h,x,w,E,A,j,ae,F,me,he,_e,we,ye,Se,Ae,Ge,Ee,Oe,R,Fe,Le,ze,Ve,Ue,r,zt,Bt,Vt,Ht,Nt,Pt,It,Lt,Rt,Wt,Gt,Kt,qt,Jt,Yt,wt]);return(0,H.jsx)(Cn.Provider,{value:Zt,children:n})}var _i=(0,b.createContext)({});function vi(e){let t=(0,b.useRef)(null);return t.current===null&&(t.current=e()),t.current}var yi=typeof window<`u`?b.useLayoutEffect:b.useEffect,bi=(0,b.createContext)(null);function xi(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,wi={},Ti=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e);function Ei(e){return typeof e==`object`&&!!e}var Di=e=>/^0[^.\s]+$/u.test(e);function Oi(e){let t;return()=>(t===void 0&&(t=e()),t)}var ki=e=>e,Ai=(e,t)=>n=>t(e(n)),U=(...e)=>e.reduce(Ai),ji=(e,t,n)=>{let r=t-e;return r===0?1:(n-e)/r},Mi=class{constructor(){this.subscriptions=[]}add(e){return xi(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}},Ni=e=>e*1e3,Pi=e=>e/1e3;function Fi(e,t){return t?1e3/t*e:0}var Ii=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Li=1e-7,Ri=12;function zi(e,t,n,r,i){let a,o,s=0;do o=t+(n-t)/2,a=Ii(o,r,i)-e,a>0?n=o:t=o;while(Math.abs(a)>Li&&++s<Ri);return o}function Bi(e,t,n,r){if(e===t&&n===r)return ki;let i=t=>zi(t,0,1,e,n);return e=>e===0||e===1?e:Ii(i(e),t,r)}var Vi=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Hi=e=>t=>1-e(1-t),Ui=Bi(.33,1.53,.69,.99),Wi=Hi(Ui),Gi=Vi(Wi),Ki=e=>e>=1?1:(e*=2)<1?.5*Wi(e):.5*(2-2**(-10*(e-1))),qi=e=>1-Math.sin(Math.acos(e)),Ji=Hi(qi),Yi=Vi(qi),Xi=Bi(.42,0,1,1),Zi=Bi(0,0,.58,1),Qi=Bi(.42,0,.58,1),$i=e=>Array.isArray(e)&&typeof e[0]!=`number`,ea=e=>Array.isArray(e)&&typeof e[0]==`number`,ta={linear:ki,easeIn:Xi,easeInOut:Qi,easeOut:Zi,circIn:qi,circInOut:Yi,circOut:Ji,backIn:Wi,backInOut:Gi,backOut:Ui,anticipate:Ki},na=e=>typeof e==`string`,ra=e=>{if(ea(e)){e.length;let[t,n,r,i]=e;return Bi(t,n,r,i)}else if(na(e))return ta[e],`${e}`,ta[e];return e},ia=[`setup`,`read`,`resolveKeyframes`,`preUpdate`,`update`,`preRender`,`render`,`postRender`],aa={value:null,addProjectionMetrics:null};function oa(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&&aa.value&&aa.value.frameloop[t].push(c),c=0,n.clear(),i=!1,a&&(a=!1,u.process(e))}};return u}var sa=40;function ca(e,t){let n=!1,r=!0,i={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,o=ia.reduce((e,n)=>(e[n]=oa(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=wi.useManualTiming,o=a?i.timestamp:performance.now();n=!1,a||(i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,sa),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:ia.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<ia.length;t++)o[ia[t]].cancel(e)},state:i,steps:o}}var{schedule:W,cancel:la,state:ua,steps:da}=ca(typeof requestAnimationFrame<`u`?requestAnimationFrame:ki,!0),fa;function pa(){fa=void 0}var ma={now:()=>(fa===void 0&&ma.set(ua.isProcessing||wi.useManualTiming?ua.timestamp:performance.now()),fa),set:e=>{fa=e,queueMicrotask(pa)}},ha={layout:0,mainThread:0,waapi:0},ga=e=>t=>typeof t==`string`&&t.startsWith(e),_a=ga(`--`),va=ga(`var(--`),ya=e=>va(e)?ba.test(e.split(`/*`)[0].trim()):!1,ba=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function xa(e){return typeof e==`string`?e.split(`/*`)[0].includes(`var(--`):!1}var Sa={test:e=>typeof e==`number`,parse:parseFloat,transform:e=>e},Ca={...Sa,transform:e=>Ci(0,1,e)},wa={...Sa,default:1},Ta=e=>Math.round(e*1e5)/1e5,Ea=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Da(e){return e==null}var Oa=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ka=(e,t)=>n=>!!(typeof n==`string`&&Oa.test(n)&&n.startsWith(e)||t&&!Da(n)&&Object.prototype.hasOwnProperty.call(n,t)),Aa=(e,t,n)=>r=>{if(typeof r!=`string`)return r;let[i,a,o,s]=r.match(Ea);return{[e]:parseFloat(i),[t]:parseFloat(a),[n]:parseFloat(o),alpha:s===void 0?1:parseFloat(s)}},ja=e=>Ci(0,255,e),Ma={...Sa,transform:e=>Math.round(ja(e))},Na={test:ka(`rgb`,`red`),parse:Aa(`red`,`green`,`blue`),transform:({red:e,green:t,blue:n,alpha:r=1})=>`rgba(`+Ma.transform(e)+`, `+Ma.transform(t)+`, `+Ma.transform(n)+`, `+Ta(Ca.transform(r))+`)`};function Pa(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 Fa={test:ka(`#`),parse:Pa,transform:Na.transform},Ia=e=>({test:t=>typeof t==`string`&&t.endsWith(e)&&t.split(` `).length===1,parse:parseFloat,transform:t=>`${t}${e}`}),La=Ia(`deg`),Ra=Ia(`%`),G=Ia(`px`),za=Ia(`vh`),Ba=Ia(`vw`),Va={...Ra,parse:e=>Ra.parse(e)/100,transform:e=>Ra.transform(e*100)},Ha={test:ka(`hsl`,`hue`),parse:Aa(`hue`,`saturation`,`lightness`),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>`hsla(`+Math.round(e)+`, `+Ra.transform(Ta(t))+`, `+Ra.transform(Ta(n))+`, `+Ta(Ca.transform(r))+`)`},Ua={test:e=>Na.test(e)||Fa.test(e)||Ha.test(e),parse:e=>Na.test(e)?Na.parse(e):Ha.test(e)?Ha.parse(e):Fa.parse(e),transform:e=>typeof e==`string`?e:e.hasOwnProperty(`red`)?Na.transform(e):Ha.transform(e),getAnimatableNone:e=>{let t=Ua.parse(e);return t.alpha=0,Ua.transform(t)}},Wa=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Ga(e){return isNaN(e)&&typeof e==`string`&&(e.match(Ea)?.length||0)+(e.match(Wa)?.length||0)>0}var Ka=`number`,qa=`color`,Ja=`var`,Ya=`var(`,Xa="${}",Za=/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 Qa(e){let t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[],a=0;return{values:n,split:t.replace(Za,e=>(Ua.test(e)?(r.color.push(a),i.push(qa),n.push(Ua.parse(e))):e.startsWith(Ya)?(r.var.push(a),i.push(Ja),n.push(e)):(r.number.push(a),i.push(Ka),n.push(parseFloat(e))),++a,Xa)).split(Xa),indexes:r,types:i}}function $a(e){return Qa(e).values}function eo({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===Ka?i+=Ta(r[a]):e===qa?i+=Ua.transform(r[a]):i+=r[a]}return i}}function to(e){return eo(Qa(e))}var no=e=>typeof e==`number`?0:Ua.test(e)?Ua.getAnimatableNone(e):e,ro=(e,t)=>typeof e==`number`?t?.trim().endsWith(`/`)?e:0:no(e);function io(e){let t=Qa(e);return eo(t)(t.values.map((e,n)=>ro(e,t.split[n])))}var ao={test:Ga,parse:$a,createTransformer:to,getAnimatableNone:io};function oo(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 K({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=oo(s,r,e+1/3),a=oo(s,r,e),o=oo(s,r,e-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(o*255),alpha:r}}function so(e,t){return n=>n>0?t:e}var q=(e,t,n)=>e+(t-e)*n,co=(e,t,n)=>{let r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},lo=[Fa,Na,Ha],uo=e=>lo.find(t=>t.test(e));function fo(e){let t=uo(e);if(`${e}`,!t)return!1;let n=t.parse(e);return t===Ha&&(n=K(n)),n}var po=(e,t)=>{let n=fo(e),r=fo(t);if(!n||!r)return so(e,t);let i={...n};return e=>(i.red=co(n.red,r.red,e),i.green=co(n.green,r.green,e),i.blue=co(n.blue,r.blue,e),i.alpha=q(n.alpha,r.alpha,e),Na.transform(i))},mo=new Set([`none`,`hidden`]);function ho(e,t){return mo.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function go(e,t){return n=>q(e,t,n)}function _o(e){return typeof e==`number`?go:typeof e==`string`?ya(e)?so:Ua.test(e)?po:xo:Array.isArray(e)?vo:typeof e==`object`?Ua.test(e)?po:yo:so}function vo(e,t){let n=[...e],r=n.length,i=e.map((e,n)=>_o(e)(e,t[n]));return e=>{for(let t=0;t<r;t++)n[t]=i[t](e);return n}}function yo(e,t){let n={...e,...t},r={};for(let i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=_o(e[i])(e[i],t[i]));return e=>{for(let t in r)n[t]=r[t](e);return n}}function bo(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 xo=(e,t)=>{let n=ao.createTransformer(t),r=Qa(e),i=Qa(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?mo.has(e)&&!i.values.length||mo.has(t)&&!r.values.length?ho(e,t):U(vo(bo(r,i),i.values),n):(`${e}${t}`,so(e,t))};function So(e,t,n){return typeof e==`number`&&typeof t==`number`&&typeof n==`number`?q(e,t,n):_o(e)(e,t)}var Co=e=>{let t=({timestamp:t})=>e(t);return{start:(e=!0)=>W.update(t,e),stop:()=>la(t),now:()=>ua.isProcessing?ua.timestamp:ma.now()}},wo=(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)})`},To=2e4;function Eo(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 Do(e,t=100,n){let r=n({...e,keyframes:[0,t]}),i=Math.min(Eo(r),To);return{type:`keyframes`,ease:e=>r.next(i*e).value/t,duration:Pi(i)}}var Oo={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 ko(e,t){return e*Math.sqrt(1-t*t)}var Ao=12;function jo(e,t,n){let r=n;for(let n=1;n<Ao;n++)r-=e(r)/t(r);return r}var Mo=.001;function No({duration:e=Oo.duration,bounce:t=Oo.bounce,velocity:n=Oo.velocity,mass:r=Oo.mass}){let i,a;Oo.maxDuration;let o=1-t;o=Ci(Oo.minDamping,Oo.maxDamping,o),e=Ci(Oo.minDuration,Oo.maxDuration,Pi(e)),o<1?(i=t=>{let r=t*o,i=r*e,a=r-n,s=ko(t,o),c=Math.exp(-i);return Mo-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=ko(t**2,o);return(-i(t)+Mo>0?-1:1)*((a-s)*c)/l}):(i=t=>{let r=Math.exp(-t*e),i=(t-n)*e+1;return-Mo+r*i},a=t=>Math.exp(-t*e)*((n-t)*(e*e)));let s=5/e,c=jo(i,a,s);if(e=Ni(e),isNaN(c))return{stiffness:Oo.stiffness,damping:Oo.damping,duration:e};{let t=c**2*r;return{stiffness:t,damping:o*2*Math.sqrt(r*t),duration:e}}}var Po=[`duration`,`bounce`],Fo=[`stiffness`,`damping`,`mass`];function Io(e,t){return t.some(t=>e[t]!==void 0)}function Lo(e){let t={velocity:Oo.velocity,stiffness:Oo.stiffness,damping:Oo.damping,mass:Oo.mass,isResolvedFromDuration:!1,...e};if(!Io(e,Fo)&&Io(e,Po))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:Oo.mass,stiffness:i,damping:a}}else{let n=No({...e,velocity:0});t={...t,...n,mass:Oo.mass},t.isResolvedFromDuration=!0}return t}function Ro(e=Oo.visualDuration,t=Oo.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}=Lo({...n,velocity:-Pi(n.velocity||0)}),m=f||0,h=l/(2*Math.sqrt(c*u)),g=o-a,_=Pi(Math.sqrt(c/u)),v=Math.abs(g)<5;r||=v?Oo.restSpeed.granular:Oo.restSpeed.default,i||=v?Oo.restDelta.granular:Oo.restDelta.default;let y,b,x,S,C,w;if(h<1)x=ko(_,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=>Ni(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=Ni(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=Ni(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(Eo(T),To),t=wo(t=>T.next(e*t).value,e,30);return e+`ms `+t},toTransition:()=>{}};return T}Ro.applyToOptions=e=>{let t=Do(e,100,Ro);return e.ease=t.ease,e.duration=Ni(t.duration),e.type=`keyframes`,e};var zo=5;function Bo(e,t,n){let r=Math.max(t-zo,0);return Fi(n-e(r),t-r)}function Vo({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=Ro({keyframes:[f.value,m(f.value)],velocity:Bo(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 Ho(e,t,n){let r=[],i=n||wi.mix||So,a=e.length-1;for(let n=0;n<a;n++){let a=i(e[n],e[n+1]);t&&(a=U(Array.isArray(t)?t[n]||ki:t,a)),r.push(a)}return r}function Uo(e,t,{clamp:n=!0,ease:r,mixer:i}={}){let a=e.length;if(t.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=Ho(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=ji(e[r],e[r+1],n);return s[r](i)};return n?t=>l(Ci(e[0],e[a-1],t)):l}function Wo(e,t){let n=e[e.length-1];for(let r=1;r<=t;r++){let i=ji(0,t,r);e.push(q(n,1,i))}}function Go(e){let t=[0];return Wo(t,e.length-1),t}function Ko(e,t){return e.map(e=>e*t)}function qo(e,t){return e.map(()=>t||Qi).splice(0,e.length-1)}function Jo({duration:e=300,keyframes:t,times:n,ease:r=`easeInOut`}){let i=$i(r)?r.map(ra):ra(r),a={done:!1,value:t[0]},o=Uo(Ko(n&&n.length===t.length?n:Go(t),e),t,{ease:Array.isArray(i)?i:qo(t,i)});return{calculatedDuration:e,next:t=>(a.value=o(t),a.done=t>=e,a)}}var Yo=e=>e!==null;function Xo(e,{repeat:t,repeatType:n=`loop`},r,i=1){let a=e.filter(Yo),o=i<0||t&&n!==`loop`&&t%2==1?0:a.length-1;return!o||r===void 0?a[o]:r}var Zo={decay:Vo,inertia:Vo,tween:Jo,keyframes:Jo,spring:Ro};function Qo(e){typeof e.type==`string`&&(e.type=Zo[e.type])}var $o=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)}},es=e=>e/100,ts=class extends $o{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!==ma.now()&&this.tick(ma.now()),this.isStopped=!0,this.state!==`idle`&&(this.teardown(),this.options.onStop?.())},ha.mainThread++,this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){let{options:e}=this;Qo(e);let{type:t=Jo,repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:a=0}=e,{keyframes:o}=e,s=t||Jo;s!==Jo&&typeof o[0]!=`number`&&(this.mixKeyframes=U(es,So(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=Eo(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!==Vo&&(b.value=Xo(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 Pi(this.calculatedDuration)}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Pi(e)}get time(){return Pi(this.currentTime)}set time(e){e=Ni(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 Bo(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(ma.now()),this.playbackSpeed=e,t&&this.driver&&(this.time=Pi(this.currentTime))}play(){if(this.isStopped)return;let{driver:e=Co,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(ma.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,ha.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 ns(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}var rs=e=>e*180/Math.PI,is=e=>os(rs(Math.atan2(e[1],e[0]))),as={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:is,rotateZ:is,skewX:e=>rs(Math.atan(e[1])),skewY:e=>rs(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},os=e=>(e%=360,e<0&&(e+=360),e),ss=is,cs=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),ls=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),us={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:cs,scaleY:ls,scale:e=>(cs(e)+ls(e))/2,rotateX:e=>os(rs(Math.atan2(e[6],e[5]))),rotateY:e=>os(rs(Math.atan2(-e[2],e[0]))),rotateZ:ss,rotate:ss,skewX:e=>rs(Math.atan(e[4])),skewY:e=>rs(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function ds(e){return e.includes(`scale`)?1:0}function fs(e,t){if(!e||e===`none`)return ds(t);let n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u),r,i;if(n)r=us,i=n;else{let t=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=as,i=t}if(!i)return ds(t);let a=r[t],o=i[1].split(`,`).map(ms);return typeof a==`function`?a(o):o[a]}var ps=(e,t)=>{let{transform:n=`none`}=getComputedStyle(e);return fs(n,t)};function ms(e){return parseFloat(e.trim())}var hs=[`transformPerspective`,`x`,`y`,`z`,`translateX`,`translateY`,`translateZ`,`scale`,`scaleX`,`scaleY`,`rotate`,`rotateX`,`rotateY`,`rotateZ`,`skew`,`skewX`,`skewY`],gs=new Set(hs),_s=e=>e===Sa||e===G,vs=new Set([`x`,`y`,`z`]),ys=hs.filter(e=>!vs.has(e));function bs(e){let t=[];return ys.forEach(n=>{let r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith(`scale`)?1:0))}),t}var xs={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})=>fs(t,`x`),y:(e,{transform:t})=>fs(t,`y`)};xs.translateX=xs.x,xs.translateY=xs.y;var Ss=new Set,Cs=!1,ws=!1,Ts=!1;function Es(){if(ws){let e=Array.from(Ss).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),n=new Map;t.forEach(e=>{let t=bs(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)})}ws=!1,Cs=!1,Ss.forEach(e=>e.complete(Ts)),Ss.clear()}function Ds(){Ss.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(ws=!0)})}function Os(){Ts=!0,Ds(),Es(),Ts=!1}var ks=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?(Ss.add(this),Cs||(Cs=!0,W.read(Ds),W.resolveKeyframes(Es))):(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])}ns(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state=`complete`,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Ss.delete(this)}cancel(){this.state===`scheduled`&&(Ss.delete(this),this.state=`pending`)}resume(){this.state===`pending`&&this.scheduleResolve()}},As=e=>e.startsWith(`--`);function js(e,t,n){As(t)?e.style.setProperty(t,n):e.style[t]=n}var Ms={};function Ns(e,t){let n=Oi(e);return()=>Ms[t]??n()}var Ps=Ns(()=>window.ScrollTimeline!==void 0,`scrollTimeline`),Fs=Ns(()=>{try{document.createElement(`div`).animate({opacity:0},{easing:`linear(0, 1)`})}catch{return!1}return!0},`linearEasing`),Is=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,Ls={linear:`linear`,ease:`ease`,easeIn:`ease-in`,easeOut:`ease-out`,easeInOut:`ease-in-out`,circIn:Is([0,.65,.55,1]),circOut:Is([.55,0,1,.45]),backIn:Is([.31,.01,.66,-.59]),backOut:Is([.33,1.53,.69,.99])};function Rs(e,t){if(e)return typeof e==`function`?Fs()?wo(e,t):`ease-out`:ea(e)?Is(e):Array.isArray(e)?e.map(e=>Rs(e,t)||Ls.easeOut):Ls[e]}function zs(e,t,n,{delay:r=0,duration:i=300,repeat:a=0,repeatType:o=`loop`,ease:s=`easeOut`,times:c}={},l=void 0){let u={[t]:n};c&&(u.offset=c);let d=Rs(s,i);Array.isArray(d)&&(u.easing=d),aa.value&&ha.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 aa.value&&p.finished.finally(()=>{ha.waapi--}),p}function Bs(e){return typeof e==`function`&&`applyToOptions`in e}function Vs({type:e,...t}){return Bs(e)&&Fs()?e.applyToOptions(t):(t.duration??=300,t.ease??=`easeOut`,t)}var Hs=class extends $o{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,e.type;let c=Vs(e);this.animation=zs(t,n,r,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){let e=Xo(r,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(e),js(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 Pi(Number(e))}get iterationDuration(){let{delay:e=0}=this.options||{};return this.duration+Pi(e)}get time(){return Pi(Number(this.animation.currentTime)||0)}set time(e){let t=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Ni(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&&Ps()?(this.animation.timeline=e,t&&(this.animation.rangeStart=t),n&&(this.animation.rangeEnd=n),ki):r(this)}},Us={anticipate:Ki,backInOut:Gi,circInOut:Yi};function Ws(e){return e in Us}function Gs(e){typeof e.ease==`string`&&Ws(e.ease)&&(e.ease=Us[e.ease])}var Ks=10,qs=class extends Hs{constructor(e){Gs(e),Qo(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 ts({...a,autoplay:!1}),s=Math.max(Ks,ma.now()-this.startTime),c=Ci(0,Ks,s-Ks),l=o.sample(s).value,{name:u}=this.options;i&&u&&js(i,u,l),t.setWithVelocity(o.sample(Math.max(0,s-c)).value,l,c),o.stop()}},Js=(e,t)=>t===`zIndex`?!1:!!(typeof e==`number`||Array.isArray(e)||typeof e==`string`&&(ao.test(e)||e===`0`)&&!e.startsWith(`url(`));function Ys(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 Xs(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=Js(i,t),s=Js(a,t);return`${t}${i}${a}${o?a:i}`,!o||!s?!1:Ys(e)||(n===`spring`||Bs(n))&&r}function Zs(e){e.duration=0,e.type=`keyframes`}var Qs=new Set([`opacity`,`clipPath`,`filter`,`transform`]),$s=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function ec(e){for(let t=0;t<e.length;t++)if(typeof e[t]==`string`&&$s.test(e[t]))return!0;return!1}var tc=new Set([`color`,`backgroundColor`,`outlineColor`,`fill`,`stroke`,`borderColor`,`borderTopColor`,`borderRightColor`,`borderBottomColor`,`borderLeftColor`]),nc=Oi(()=>Object.hasOwnProperty.call(Element.prototype,`animate`));function rc(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 nc()&&n&&(Qs.has(n)||tc.has(n)&&ec(s))&&(n!==`transform`||!l)&&!c&&!r&&i!==`mirror`&&a!==0&&o!==`inertia`}var ic=40,ac=class extends $o{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=ma.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||ks)(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=ma.now();let u=!0;Xs(e,i,a,o)||(u=!1,(wi.instantAnimations||!s)&&l?.(Xo(e,n,t)),e[0]=e[e.length-1],Zs(n),n.repeat=0);let d={startTime:r?this.resolvedAt&&this.resolvedAt-this.createdAt>ic?this.resolvedAt:this.createdAt:void 0,finalKeyframe:t,...n,keyframes:e},f=u&&!c&&rc(d),p=d.motionValue?.owner?.current,m;if(f)try{m=new qs({...d,element:p})}catch{m=new ts(d)}else m=new ts(d);m.finished.then(()=>{this.notifyFinished()}).catch(ki),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(),Os()),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 oc(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 sc=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function cc(e){let t=sc.exec(e);if(!t)return[,];let[,n,r,i]=t;return[`--${n??r}`,i]}function lc(e,t,n=1){`${e}`;let[r,i]=cc(e);if(!r)return;let a=window.getComputedStyle(t).getPropertyValue(r);if(a){let e=a.trim();return Ti(e)?parseFloat(e):e}return ya(i)?lc(i,t,n+1):i}var uc={type:`spring`,stiffness:500,damping:25,restSpeed:10},dc=e=>({type:`spring`,stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),fc={type:`keyframes`,duration:.8},pc={type:`keyframes`,ease:[.25,.1,.35,1],duration:.3},mc=(e,{keyframes:t})=>t.length>2?fc:gs.has(e)?e.startsWith(`scale`)?dc(t[1]):uc:pc;function hc(e,t){if(e?.inherit&&t){let{inherit:n,...r}=e;return{...t,...r}}return e}function gc(e,t){let n=e?.[t]??e?.default??e;return n===e?n:hc(n,e)}var _c=new Set([`when`,`delay`,`delayChildren`,`staggerChildren`,`staggerDirection`,`repeat`,`repeatType`,`repeatDelay`,`from`,`elapsed`]);function vc(e){for(let t in e)if(!_c.has(t))return!0;return!1}var yc=(e,t,n,r={},i,a)=>o=>{let s=gc(r,e)||{},c=s.delay||r.delay||0,{elapsed:l=0}=r;l-=Ni(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};vc(s)||Object.assign(u,mc(e,u)),u.duration&&=Ni(u.duration),u.repeatDelay&&=Ni(u.repeatDelay),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(Zs(u),u.delay===0&&(d=!0)),(wi.instantAnimations||wi.skipAnimations||i?.shouldSkipAnimations)&&(d=!0,Zs(u),u.delay=0),u.allowFlatten=!s.type&&!s.ease,d&&!a&&t.get()!==void 0){let e=Xo(u.keyframes,s);if(e!==void 0){W.update(()=>{u.onUpdate(e),u.onComplete()});return}}return s.isSync?new ts(u):new ac(u)};function bc(e){let t=[{},{}];return e?.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function xc(e,t,n,r){if(typeof t==`function`){let[i,a]=bc(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]=bc(r);t=t(n===void 0?e.custom:n,i,a)}return t}function Sc(e,t,n){let r=e.getProps();return xc(r,t,n===void 0?r.custom:n,e)}var Cc=new Set([`width`,`height`,`top`,`left`,`right`,`bottom`,...hs]),wc=30,Tc=e=>!isNaN(parseFloat(e)),Ec={current:void 0},Dc=class{constructor(e,t={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=e=>{let t=ma.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=ma.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Tc(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on(`change`,e)}on(e,t){this.events[e]||(this.events[e]=new Mi);let n=this.events[e].add(t);return e===`change`?()=>{n(),W.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 Ec.current&&Ec.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){let e=ma.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>wc)return 0;let t=Math.min(this.updatedAt-this.prevUpdatedAt,wc);return Fi(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 Oc(e,t){return new Dc(e,t)}var kc=e=>Array.isArray(e);function Ac(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Oc(n))}function jc(e){return kc(e)?e[e.length-1]||0:e}function Mc(e,t){let{transitionEnd:n={},transition:r={},...i}=Sc(e,t)||{};i={...i,...n};for(let t in i)Ac(e,t,jc(i[t]))}var Nc=e=>!!(e&&e.getVelocity);function Pc(e){return!!(Nc(e)&&e.add)}function Fc(e,t){let n=e.getValue(`willChange`);if(Pc(n))return n.add(t);if(!n&&wi.WillChange){let n=new wi.WillChange(`auto`);e.addValue(`willChange`,n),n.add(t)}}function Ic(e){return e.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}var Lc=`data-`+Ic(`framerAppearId`);function Rc(e){return e.props[Lc]}function zc({protectedKeys:e,needsAnimating:t},n){let r=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function Bc(e,t,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:a,transitionEnd:o,...s}=t,c=e.getDefaultTransition();a=a?hc(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&&zc(d,t))continue;let o={delay:n,...gc(a||{},t)},c=r.get();if(c!==void 0&&!r.isAnimating()&&!Array.isArray(i)&&i===c&&!o.velocity){W.update(()=>r.set(i));continue}let f=!1;if(window.MotionHandoffAnimation){let n=Rc(e);if(n){let e=window.MotionHandoffAnimation(n,t,W);e!==null&&(o.startTime=e,f=!0)}}Fc(e,t);let p=l??e.shouldReduceMotion;r.start(yc(t,r,i,p&&Cc.has(t)?{type:!1}:o,e,f));let m=r.animation;m&&u.push(m)}if(o){let t=()=>W.update(()=>{o&&Mc(e,o)});u.length?Promise.all(u).then(t):t()}return u}function Vc(e,t,n={}){let r=Sc(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(Bc(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(r=0)=>{let{delayChildren:a=0,staggerChildren:o,staggerDirection:s}=i;return Hc(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 Hc(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(Vc(c,t,{...o,delay:n+(typeof r==`function`?0:r)+oc(e.variantChildren,c,r,i,a)}).then(()=>c.notify(`AnimationComplete`,t)));return Promise.all(s)}function Uc(e,t,n={}){e.notify(`AnimationStart`,t);let r;if(Array.isArray(t)){let i=t.map(t=>Vc(e,t,n));r=Promise.all(i)}else if(typeof t==`string`)r=Vc(e,t,n);else{let i=typeof t==`function`?Sc(e,t,n.custom):t;r=Promise.all(Bc(e,i,n))}return r.then(()=>{e.notify(`AnimationComplete`,t)})}var Wc={test:e=>e===`auto`,parse:e=>e},Gc=e=>t=>t.test(e),Kc=[Sa,G,Ra,La,Ba,za,Wc],qc=e=>Kc.find(Gc(e));function Jc(e){return typeof e==`number`?e===0:e===null?!0:e===`none`||e===`0`||Di(e)}var Yc=new Set([`brightness`,`contrast`,`saturate`,`opacity`]);function Xc(e){let[t,n]=e.slice(0,-1).split(`(`);if(t===`drop-shadow`)return e;let[r]=n.match(Ea)||[];if(!r)return e;let i=n.replace(r,``),a=Yc.has(t)?1:0;return r!==n&&(a*=100),t+`(`+a+i+`)`}var Zc=/\b([a-z-]*)\(.*?\)/gu,Qc={...ao,getAnimatableNone:e=>{let t=e.match(Zc);return t?t.map(Xc).join(` `):e}},$c={...ao,getAnimatableNone:e=>{let t=ao.parse(e);return ao.createTransformer(e)(t.map(e=>typeof e==`number`?0:typeof e==`object`?{...e,alpha:1}:e))}},el={...Sa,transform:Math.round},tl={borderWidth:G,borderTopWidth:G,borderRightWidth:G,borderBottomWidth:G,borderLeftWidth:G,borderRadius:G,borderTopLeftRadius:G,borderTopRightRadius:G,borderBottomRightRadius:G,borderBottomLeftRadius:G,width:G,maxWidth:G,height:G,maxHeight:G,top:G,right:G,bottom:G,left:G,inset:G,insetBlock:G,insetBlockStart:G,insetBlockEnd:G,insetInline:G,insetInlineStart:G,insetInlineEnd:G,padding:G,paddingTop:G,paddingRight:G,paddingBottom:G,paddingLeft:G,paddingBlock:G,paddingBlockStart:G,paddingBlockEnd:G,paddingInline:G,paddingInlineStart:G,paddingInlineEnd:G,margin:G,marginTop:G,marginRight:G,marginBottom:G,marginLeft:G,marginBlock:G,marginBlockStart:G,marginBlockEnd:G,marginInline:G,marginInlineStart:G,marginInlineEnd:G,fontSize:G,backgroundPositionX:G,backgroundPositionY:G,rotate:La,rotateX:La,rotateY:La,rotateZ:La,scale:wa,scaleX:wa,scaleY:wa,scaleZ:wa,skew:La,skewX:La,skewY:La,distance:G,translateX:G,translateY:G,translateZ:G,x:G,y:G,z:G,perspective:G,transformPerspective:G,opacity:Ca,originX:Va,originY:Va,originZ:G,zIndex:el,fillOpacity:Ca,strokeOpacity:Ca,numOctaves:el},nl={...tl,color:Ua,backgroundColor:Ua,outlineColor:Ua,fill:Ua,stroke:Ua,borderColor:Ua,borderTopColor:Ua,borderRightColor:Ua,borderBottomColor:Ua,borderLeftColor:Ua,filter:Qc,WebkitFilter:Qc,mask:$c,WebkitMask:$c},rl=e=>nl[e],il=new Set([Qc,$c]);function al(e,t){let n=rl(e);return il.has(n)||(n=ao),n.getAnimatableNone?n.getAnimatableNone(t):void 0}var ol=new Set([`auto`,`none`,`0`]);function sl(e,t,n){let r=0,i;for(;r<e.length&&!i;){let t=e[r];typeof t==`string`&&!ol.has(t)&&Qa(t).values.length&&(i=e[r]),r++}if(i&&n)for(let r of t)e[r]=al(n,i)}var cl=class extends ks{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(),ya(r))){let i=lc(r,t.current);i!==void 0&&(e[n]=i),n===e.length-1&&(this.finalKeyframe=r)}}if(this.resolveNoneKeyframes(),!Cc.has(n)||e.length!==2)return;let[r,i]=e,a=qc(r),o=qc(i);if(xa(r)!==xa(i)&&xs[n]){this.needsMeasurement=!0;return}if(a!==o)if(_s(a)&&_s(o))for(let t=0;t<e.length;t++){let n=e[t];typeof n==`string`&&(e[t]=parseFloat(n))}else xs[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,n=[];for(let t=0;t<e.length;t++)(e[t]===null||Jc(e[t]))&&n.push(t);n.length&&sl(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=xs[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]=xs[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 ll(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 ul=(e,t)=>t&&typeof e==`number`?t.transform(e):e;function dl(e){return Ei(e)&&`offsetHeight`in e&&!(`ownerSVGElement`in e)}var{schedule:fl,cancel:pl}=ca(queueMicrotask,!1),ml={x:!1,y:!1};function hl(){return ml.x||ml.y}function gl(e){return e===`x`||e===`y`?ml[e]?null:(ml[e]=!0,()=>{ml[e]=!1}):ml.x||ml.y?null:(ml.x=ml.y=!0,()=>{ml.x=ml.y=!1})}function _l(e,t){let n=ll(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function vl(e){return!(e.pointerType===`touch`||hl())}function yl(e,t,n={}){let[r,i,a]=_l(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(!vl(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 bl=(e,t)=>t?e===t?!0:bl(e,t.parentElement):!1,xl=e=>e.pointerType===`mouse`?typeof e.button!=`number`||e.button<=0:e.isPrimary!==!1,Sl=new Set([`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`A`]);function Cl(e){return Sl.has(e.tagName)||e.isContentEditable===!0}var wl=new Set([`INPUT`,`SELECT`,`TEXTAREA`]);function Tl(e){return wl.has(e.tagName)||e.isContentEditable===!0}var El=new WeakSet;function Dl(e){return t=>{t.key===`Enter`&&e(t)}}function Ol(e,t){e.dispatchEvent(new PointerEvent(`pointer`+t,{isPrimary:!0,bubbles:!0}))}var kl=(e,t)=>{let n=e.currentTarget;if(!n)return;let r=Dl(()=>{if(El.has(n))return;Ol(n,`down`);let e=Dl(()=>{Ol(n,`up`)});n.addEventListener(`keyup`,e,t),n.addEventListener(`blur`,()=>Ol(n,`cancel`),t)});n.addEventListener(`keydown`,r,t),n.addEventListener(`blur`,()=>n.removeEventListener(`keydown`,r),t)};function Al(e){return xl(e)&&!hl()}var jl=new WeakSet;function Ml(e,t,n={}){let[r,i,a]=_l(e,n),o=e=>{let r=e.currentTarget;if(!Al(e)||jl.has(e))return;El.add(r),n.stopPropagation&&jl.add(e);let a=t(r,e),o=(e,t)=>{window.removeEventListener(`pointerup`,s),window.removeEventListener(`pointercancel`,c),El.has(r)&&El.delete(r),Al(e)&&typeof a==`function`&&a(e,{success:t})},s=e=>{o(e,r===window||r===document||n.useGlobalTarget||bl(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),dl(e)&&(e.addEventListener(`focus`,e=>kl(e,i)),!Cl(e)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=0))}),a}function Nl(e){return Ei(e)&&`ownerSVGElement`in e}var Pl=new WeakMap,Fl,Il=(e,t,n)=>(r,i)=>i&&i[0]?i[0][e+`Size`]:Nl(r)&&`getBBox`in r?r.getBBox()[t]:r[n],Ll=Il(`inline`,`width`,`offsetWidth`),Rl=Il(`block`,`height`,`offsetHeight`);function J({target:e,borderBoxSize:t}){Pl.get(e)?.forEach(n=>{n(e,{get width(){return Ll(e,t)},get height(){return Rl(e,t)}})})}function Y(e){e.forEach(J)}function zl(){typeof ResizeObserver>`u`||(Fl=new ResizeObserver(Y))}function Bl(e,t){Fl||zl();let n=ll(e);return n.forEach(e=>{let n=Pl.get(e);n||(n=new Set,Pl.set(e,n)),n.add(t),Fl?.observe(e)}),()=>{n.forEach(e=>{let n=Pl.get(e);n?.delete(t),n?.size||Fl?.unobserve(e)})}}var Vl=new Set,Hl;function Ul(){Hl=()=>{let e={get width(){return window.innerWidth},get height(){return window.innerHeight}};Vl.forEach(t=>t(e))},window.addEventListener(`resize`,Hl)}function Wl(e){return Vl.add(e),Hl||Ul(),()=>{Vl.delete(e),!Vl.size&&typeof Hl==`function`&&(window.removeEventListener(`resize`,Hl),Hl=void 0)}}function Gl(e,t){return typeof e==`function`?Wl(e):Bl(e,t)}function Kl(e){return Nl(e)&&e.tagName===`svg`}var ql=[...Kc,Ua,ao],Jl=e=>ql.find(Gc(e)),Yl=()=>({translate:0,scale:1,origin:0,originPoint:0}),Xl=()=>({x:Yl(),y:Yl()}),Zl=()=>({min:0,max:0}),X=()=>({x:Zl(),y:Zl()}),Ql=new WeakMap;function $l(e){return typeof e==`object`&&!!e&&typeof e.start==`function`}function eu(e){return typeof e==`string`||Array.isArray(e)}var tu=[`animate`,`whileInView`,`whileFocus`,`whileHover`,`whileTap`,`whileDrag`,`exit`],nu=[`initial`,...tu];function ru(e){return $l(e.animate)||nu.some(t=>eu(e[t]))}function iu(e){return!!(ru(e)||e.variants)}function au(e,t,n){for(let r in t){let i=t[r],a=n[r];if(Nc(i))e.addValue(r,i);else if(Nc(a))e.addValue(r,Oc(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,Oc(t===void 0?i:t,{owner:e}))}}for(let r in n)t[r]===void 0&&e.removeValue(r);return t}var ou={current:null},su={current:!1},cu=typeof window<`u`;function lu(){if(su.current=!0,cu)if(window.matchMedia){let e=window.matchMedia(`(prefers-reduced-motion)`),t=()=>ou.current=e.matches;e.addEventListener(`change`,t),t()}else ou.current=!1}var uu=[`AnimationStart`,`AnimationComplete`,`Update`,`BeforeLayoutMeasure`,`LayoutMeasure`,`LayoutAnimationStart`,`LayoutAnimationComplete`],du={};function fu(e){du=e}function pu(){return du}var mu=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=ks,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=ma.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,W.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=ru(t),this.isVariantNode=iu(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&&Nc(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,Ql.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:(su.current||lu(),this.shouldReduceMotion=ou.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),la(this.notifyUpdate),la(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&&Qs.has(e)&&this.current instanceof HTMLElement){let{factory:n,keyframes:r,times:i,ease:a,duration:o}=t.accelerate,s=new Hs({element:this.current,name:e,keyframes:r,times:i,ease:a,duration:Ni(o)}),c=n(s);this.valueSubscriptions.set(e,()=>{c(),s.cancel()});return}let n=gs.has(e);n&&this.onBindTransform&&this.onBindTransform();let r=t.on(`change`,t=>{this.latestValues[e]=t,this.props.onUpdate&&W.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()}),i;typeof window<`u`&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i&&i(),t.owner&&t.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e=`animation`;for(e in du){let t=du[e];if(!t)continue;let{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(this)),this.features[e]){let t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):X()}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<uu.length;t++){let n=uu[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=au(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=Oc(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`&&(Ti(n)||Di(n))?n=parseFloat(n):!Jl(n)&&ao.test(t)&&(n=al(e,t)),this.setBaseTarget(e,Nc(n)?n.get():n)),Nc(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=xc(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&&!Nc(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 Mi),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}scheduleRenderMicrotask(){fl.render(this.render)}},hu=class extends mu{constructor(){super(...arguments),this.KeyframeResolver=cl}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;Nc(e)&&(this.childSubscription=e.on(`change`,e=>{this.current&&(this.current.textContent=`${e}`)}))}},gu=class{constructor(e){this.isMounted=!1,this.node=e}update(){}};function _u({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function vu({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function yu(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 bu(e){return e===void 0||e===1}function xu({scale:e,scaleX:t,scaleY:n}){return!bu(e)||!bu(t)||!bu(n)}function Su(e){return xu(e)||Cu(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function Cu(e){return wu(e.x)||wu(e.y)}function wu(e){return e&&e!==`0%`}function Tu(e,t,n){return n+t*(e-n)}function Eu(e,t,n,r,i){return i!==void 0&&(e=Tu(e,i,r)),Tu(e,n,r)+t}function Du(e,t=0,n=1,r,i){e.min=Eu(e.min,t,n,r,i),e.max=Eu(e.max,t,n,r,i)}function Ou(e,{x:t,y:n}){Du(e.x,t.translate,t.scale,t.originPoint),Du(e.y,n.translate,n.scale,n.originPoint)}var ku=.999999999999,Au=1.0000000000001;function ju(e,t,n,r=!1){let i=n.length;if(!i)return;t.x=t.y=1;let a,o;for(let s=0;s<i;s++){a=n[s],o=a.projectionDelta;let{visualElement:i}=a.options;i&&i.props.style&&i.props.style.display===`contents`||(r&&a.options.layoutScroll&&a.scroll&&a!==a.root&&(Mu(e.x,-a.scroll.offset.x),Mu(e.y,-a.scroll.offset.y)),o&&(t.x*=o.x.scale,t.y*=o.y.scale,Ou(e,o)),r&&Su(a.latestValues)&&Fu(e,a.latestValues,a.layout?.layoutBox))}t.x<Au&&t.x>ku&&(t.x=1),t.y<Au&&t.y>ku&&(t.y=1)}function Mu(e,t){e.min+=t,e.max+=t}function Nu(e,t,n,r,i=.5){Du(e,t,n,q(e.min,e.max,i),r)}function Pu(e,t){return typeof e==`string`?parseFloat(e)/100*(t.max-t.min):e}function Fu(e,t,n){let r=n??e;Nu(e.x,Pu(t.x,r.x),t.scaleX,t.scale,t.originX),Nu(e.y,Pu(t.y,r.y),t.scaleY,t.scale,t.originY)}function Iu(e,t){return _u(yu(e.getBoundingClientRect(),t))}function Lu(e,t,n){let r=Iu(e,n),{scroll:i}=t;return i&&(Mu(r.x,i.offset.x),Mu(r.y,i.offset.y)),r}var Ru={x:`translateX`,y:`translateY`,z:`translateZ`,transformPerspective:`perspective`},zu=hs.length;function Bu(e,t,n){let r=``,i=!0;for(let a=0;a<zu;a++){let o=hs[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=ul(s,tl[o]);if(!c){i=!1;let t=Ru[o]||o;r+=`${t}(${e}) `}n&&(t[o]=e)}}return r=r.trim(),n?r=n(t,i?``:r):i&&(r=`none`),r}function Vu(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(gs.has(e)){o=!0;continue}else if(_a(e)){i[e]=n;continue}else{let t=ul(n,tl[e]);e.startsWith(`origin`)?(s=!0,a[e]=t):r[e]=t}}if(t.transform||(o||n?r.transform=Bu(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 Hu(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 Uu(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}var Wu={correct:(e,t)=>{if(!t.target)return e;if(typeof e==`string`)if(G.test(e))e=parseFloat(e);else return e;return`${Uu(e,t.target.x)}% ${Uu(e,t.target.y)}%`}},Gu={correct:(e,{treeScale:t,projectionDelta:n})=>{let r=e,i=ao.parse(e);if(i.length>5)return r;let a=ao.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=q(s,c,.5);return typeof i[2+o]==`number`&&(i[2+o]/=l),typeof i[3+o]==`number`&&(i[3+o]/=l),a(i)}},Ku={borderRadius:{...Wu,applyTo:[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`]},borderTopLeftRadius:Wu,borderTopRightRadius:Wu,borderBottomLeftRadius:Wu,borderBottomRightRadius:Wu,boxShadow:Gu};function qu(e,{layout:t,layoutId:n}){return gs.has(e)||e.startsWith(`origin`)||(t||n!==void 0)&&(!!Ku[e]||e===`opacity`)}function Ju(e,t,n){let r=e.style,i=t?.style,a={};if(!r)return a;for(let t in r)(Nc(r[t])||i&&Nc(i[t])||qu(t,e)||n?.getValue(t)?.liveStyle!==void 0)&&(a[t]=r[t]);return a}function Yu(e){return window.getComputedStyle(e)}var Xu=class extends hu{constructor(){super(...arguments),this.type=`html`,this.renderInstance=Hu}readValueFromInstance(e,t){if(gs.has(t))return this.projection?.isProjecting?ds(t):ps(e,t);{let n=Yu(e),r=(_a(t)?n.getPropertyValue(t):n[t])||0;return typeof r==`string`?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:t}){return Iu(e,t)}build(e,t,n){Vu(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return Ju(e,t,n)}},Zu={offset:`stroke-dashoffset`,array:`stroke-dasharray`},Qu={offset:`strokeDashoffset`,array:`strokeDasharray`};function $u(e,t,n=1,r=0,i=!0){e.pathLength=1;let a=i?Zu:Qu;e[a.offset]=`${-r}`,e[a.array]=`${t} ${n}`}var ed=[`offsetDistance`,`offsetPath`,`offsetRotate`,`offsetAnchor`];function td(e,{attrX:t,attrY:n,attrScale:r,pathLength:i,pathSpacing:a=1,pathOffset:o=0,...s},c,l,u){if(Vu(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 ed)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&&$u(d,i,a,o,!1)}var nd=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`]),rd=e=>typeof e==`string`&&e.toLowerCase()===`svg`;function id(e,t,n,r){Hu(e,t,void 0,r);for(let n in t.attrs)e.setAttribute(nd.has(n)?n:Ic(n),t.attrs[n])}function ad(e,t,n){let r=Ju(e,t,n);for(let n in e)if(Nc(e[n])||Nc(t[n])){let t=hs.indexOf(n)===-1?n:`attr`+n.charAt(0).toUpperCase()+n.substring(1);r[t]=e[n]}return r}var od=class extends hu{constructor(){super(...arguments),this.type=`svg`,this.isSVGTag=!1,this.measureInstanceViewportBox=X}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(gs.has(t)){let e=rl(t);return e&&e.default||0}return t=nd.has(t)?t:Ic(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return ad(e,t,n)}build(e,t,n){td(e,t,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,t,n,r){id(e,t,n,r)}mount(e){this.isSVGTag=rd(e.tagName),super.mount(e)}},sd=nu.length;function cd(e){if(!e)return;if(!e.isControllingVariants){let t=e.parent&&cd(e.parent)||{};return e.props.initial!==void 0&&(t.initial=e.props.initial),t}let t={};for(let n=0;n<sd;n++){let r=nu[n],i=e.props[r];(eu(i)||i===!1)&&(t[r]=i)}return t}function ld(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 ud=[...tu].reverse(),dd=tu.length;function fd(e){return t=>Promise.all(t.map(({animation:t,options:n})=>Uc(e,t,n)))}function pd(e){let t=fd(e),n=gd(),r=!0,i=!1,a=t=>(n,r)=>{let i=Sc(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=cd(e.parent)||{},l=[],u=new Set,d={},f=1/0;for(let t=0;t<dd;t++){let p=ud[t],m=n[p],h=s[p]===void 0?c[p]:s[p],g=eu(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||$l(h)||typeof h==`boolean`)continue;if(p===`exit`&&m.isActive&&_!==!0){m.prevResolvedValues&&(d={...d,...m.prevResolvedValues});continue}let y=md(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=kc(t)&&kc(n)?!ld(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=Sc(r,t);if(r.enteringChildren&&i){let{delayChildren:t}=i.transition||{};n.delay=oc(r.enteringChildren,e,t)}}return{animation:t,options:n}}))}if(u.size){let t={};if(typeof s.initial!=`boolean`){let n=Sc(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=gd(),i=!0}}}function md(e,t){return typeof t==`string`?t!==e:Array.isArray(t)?!ld(t,e):!1}function hd(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function gd(){return{animate:hd(!0),whileInView:hd(),whileHover:hd(),whileTap:hd(),whileDrag:hd(),whileFocus:hd(),exit:hd()}}function _d(e,t){e.min=t.min,e.max=t.max}function vd(e,t){_d(e.x,t.x),_d(e.y,t.y)}function yd(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}var bd=1e-4,Z=1-bd,xd=1+bd,Sd=.01,Cd=0-Sd,wd=0+Sd;function Td(e){return e.max-e.min}function Ed(e,t,n){return Math.abs(e-t)<=n}function Dd(e,t,n,r=.5){e.origin=r,e.originPoint=q(t.min,t.max,e.origin),e.scale=Td(n)/Td(t),e.translate=q(n.min,n.max,e.origin)-e.originPoint,(e.scale>=Z&&e.scale<=xd||isNaN(e.scale))&&(e.scale=1),(e.translate>=Cd&&e.translate<=wd||isNaN(e.translate))&&(e.translate=0)}function Od(e,t,n,r){Dd(e.x,t.x,n.x,r?r.originX:void 0),Dd(e.y,t.y,n.y,r?r.originY:void 0)}function kd(e,t,n,r=0){e.min=(r?q(n.min,n.max,r):n.min)+t.min,e.max=e.min+Td(t)}function Ad(e,t,n,r){kd(e.x,t.x,n.x,r?.x),kd(e.y,t.y,n.y,r?.y)}function jd(e,t,n,r=0){let i=r?q(n.min,n.max,r):n.min;e.min=t.min-i,e.max=e.min+Td(t)}function Md(e,t,n,r){jd(e.x,t.x,n.x,r?.x),jd(e.y,t.y,n.y,r?.y)}function Nd(e,t,n,r,i){return e-=t,e=Tu(e,1/n,r),i!==void 0&&(e=Tu(e,1/i,r)),e}function Pd(e,t=0,n=1,r=.5,i,a=e,o=e){if(Ra.test(t)&&(t=parseFloat(t),t=q(o.min,o.max,t/100)-o.min),typeof t!=`number`)return;let s=q(a.min,a.max,r);e===a&&(s-=t),e.min=Nd(e.min,t,n,s,i),e.max=Nd(e.max,t,n,s,i)}function Fd(e,t,[n,r,i],a,o){Pd(e,t[n],t[r],t[i],t.scale,a,o)}var Id=[`x`,`scaleX`,`originX`],Ld=[`y`,`scaleY`,`originY`];function Rd(e,t,n,r){Fd(e.x,t,Id,n?n.x:void 0,r?r.x:void 0),Fd(e.y,t,Ld,n?n.y:void 0,r?r.y:void 0)}function zd(e){return e.translate===0&&e.scale===1}function Bd(e){return zd(e.x)&&zd(e.y)}function Vd(e,t){return e.min===t.min&&e.max===t.max}function Hd(e,t){return Vd(e.x,t.x)&&Vd(e.y,t.y)}function Ud(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function Wd(e,t){return Ud(e.x,t.x)&&Ud(e.y,t.y)}function Gd(e){return Td(e.x)/Td(e.y)}function Kd(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function qd(e){return[e(`x`),e(`y`)]}function Jd(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 Yd=[`borderTopLeftRadius`,`borderTopRightRadius`,`borderBottomLeftRadius`,`borderBottomRightRadius`],Xd=Yd.length,Zd=e=>typeof e==`string`?parseFloat(e):e,Qd=e=>typeof e==`number`||G.test(e);function $d(e,t,n,r,i,a){i?(e.opacity=q(0,n.opacity??1,tf(r)),e.opacityExit=q(t.opacity??1,0,nf(r))):a&&(e.opacity=q(t.opacity??1,n.opacity??1,r));for(let i=0;i<Xd;i++){let a=Yd[i],o=ef(t,a),s=ef(n,a);o===void 0&&s===void 0||(o||=0,s||=0,o===0||s===0||Qd(o)===Qd(s)?(e[a]=Math.max(q(Zd(o),Zd(s),r),0),(Ra.test(s)||Ra.test(o))&&(e[a]+=`%`)):e[a]=s)}(t.rotate||n.rotate)&&(e.rotate=q(t.rotate||0,n.rotate||0,r))}function ef(e,t){return e[t]===void 0?e.borderRadius:e[t]}var tf=rf(0,.5,Ji),nf=rf(.5,.95,ki);function rf(e,t,n){return r=>r<e?0:r>t?1:n(ji(e,t,r))}function af(e,t,n){let r=Nc(e)?e:Oc(e);return r.start(yc(``,r,t,n)),r.animation}function of(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}var sf=(e,t)=>e.depth-t.depth,cf=class{constructor(){this.children=[],this.isDirty=!1}add(e){xi(this.children,e),this.isDirty=!0}remove(e){Si(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(sf),this.isDirty=!1,this.children.forEach(e)}};function lf(e,t){let n=ma.now(),r=({timestamp:i})=>{let a=i-n;a>=t&&(la(r),e(a-t))};return W.setup(r,!0),()=>la(r)}function uf(e){return Nc(e)?e.get():e}var df=class{constructor(){this.members=[]}add(e){xi(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)}},ff={hasAnimatedSinceResize:!0,hasEverUpdated:!1},pf={nodes:0,calculatedTargetDeltas:0,calculatedProjections:0},mf=[``,`X`,`Y`,`Z`],hf=1e3,gf=0;function _f(e,t,n,r){let{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function vf(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;let{visualElement:t}=e.options;if(!t)return;let n=Rc(t);if(window.MotionHasOptimisedAnimation(n,`transform`)){let{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,`transform`,W,!(t||r))}let{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&vf(r)}function yf({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=t?.()){this.id=gf++,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,aa.value&&(pf.nodes=pf.calculatedTargetDeltas=pf.calculatedProjections=0),this.nodes.forEach(Sf),this.nodes.forEach(jf),this.nodes.forEach(Mf),this.nodes.forEach(Cf),aa.addProjectionMetrics&&aa.addProjectionMetrics(pf)},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 cf)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new Mi),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=Nl(t)&&!Kl(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;W.read(()=>{r=window.innerWidth}),e(t,()=>{let e=window.innerWidth;e!==r&&(r=e,this.root.updateBlockedByResize=!0,n&&n(),n=lf(i,250),ff.hasAnimatedSinceResize&&(ff.hasAnimatedSinceResize=!1,this.nodes.forEach(Af)))})}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()||zf,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=i.getProps(),c=!this.targetLayout||!Wd(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={...gc(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||Af(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(),la(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(Nf),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&&vf(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(Ef),this.nodes.forEach(Tf);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Df);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Of),this.nodes.forEach(kf),this.nodes.forEach(bf),this.nodes.forEach(xf)):this.nodes.forEach(Df),this.clearAllSnapshots();let e=ma.now();ua.delta=Ci(0,1e3/60,e-ua.timestamp),ua.timestamp=e,ua.isProcessing=!0,da.update.process(ua),da.preRender.process(ua),da.render.process(ua),ua.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,fl.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(wf),this.sharedNodes.forEach(Pf)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,W.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){W.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Td(this.snapshot.measuredBox.x)&&!Td(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||=X(),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&&!Bd(this.projectionDelta),n=this.getTransformTemplate(),r=n?n(this.latestValues,``):void 0,a=r!==this.prevTransformTemplateValue;e&&this.instance&&(t||Su(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)),Uf(n),{animationId:this.root.animationId,measuredBox:t,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){let{visualElement:e}=this.options;if(!e)return X();let t=e.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(Gf))){let{scroll:e}=this.root;e&&(Mu(t.x,e.offset.x),Mu(t.y,e.offset.y))}return t}removeElementScroll(e){let t=X();if(vd(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&&vd(t,e),Mu(t.x,i.offset.x),Mu(t.y,i.offset.y))}return t}applyTransform(e,t=!1,n){let r=n||X();vd(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&&(Mu(r.x,-n.scroll.offset.x),Mu(r.y,-n.scroll.offset.y)),Su(n.latestValues)&&Fu(r,n.latestValues,n.layout?.layoutBox)}return Su(this.latestValues)&&Fu(r,this.latestValues,this.layout?.layoutBox),r}removeTransform(e){let t=X();vd(t,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];if(!Su(n.latestValues))continue;let r;n.instance&&(xu(n.latestValues)&&n.updateSnapshot(),r=X(),vd(r,n.measurePageBox())),Rd(t,n.latestValues,n.snapshot?.layoutBox,r)}return Su(this.latestValues)&&Rd(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!==ua.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=ua.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=X(),this.targetWithTransforms=X()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Ad(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):vd(this.target,this.layout.layoutBox),Ou(this.target,this.targetDelta)):vd(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),aa.value&&pf.calculatedTargetDeltas++)}getClosestProjectingParent(){if(!(!this.parent||xu(this.parent.latestValues)||Cu(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=X(),this.relativeTargetOrigin=X(),Md(this.relativeTargetOrigin,t,n,this.options.layoutAnchor||void 0),vd(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===ua.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;vd(this.layoutCorrected,this.layout.layoutBox);let a=this.treeScale.x,o=this.treeScale.y;ju(this.layoutCorrected,this.treeScale,this.path,t),e.layout&&!e.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(e.target=e.layout.layoutBox,e.targetWithTransforms=X());let{target:s}=e;if(!s){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(yd(this.prevProjectionDelta.x,this.projectionDelta.x),yd(this.prevProjectionDelta.y,this.projectionDelta.y)),Od(this.projectionDelta,this.layoutCorrected,s,this.latestValues),(this.treeScale.x!==a||this.treeScale.y!==o||!Kd(this.projectionDelta.x,this.prevProjectionDelta.x)||!Kd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners(`projectionUpdate`,s)),aa.value&&pf.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=Xl(),this.projectionDelta=Xl(),this.projectionDeltaWithTransform=Xl()}setAnimationOrigin(e,t=!1){let n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},a=Xl();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let o=X(),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(Rf));this.animationProgress=0;let d;this.mixTargetDelta=t=>{let n=t/1e3;Ff(a.x,e.x,n),Ff(a.y,e.y,n),this.setTargetDelta(a),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Md(o,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),Lf(this.relativeTarget,this.relativeTargetOrigin,o,n),d&&Hd(this.relativeTarget,d)&&(this.isProjectionDirty=!1),d||=X(),vd(d,this.relativeTarget)),s&&(this.animationValues=i,$d(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&&=(la(this.pendingAnimation),void 0),this.pendingAnimation=W.update(()=>{ff.hasAnimatedSinceResize=!0,ha.layout++,this.motionValue||=Oc(0),this.motionValue.jump(0,!1),this.currentAnimation=af(this.motionValue,[0,1e3],{...e,velocity:0,isSync:!0,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onStop:()=>{ha.layout--},onComplete:()=>{ha.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(hf),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&&Wf(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||X();let t=Td(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;let r=Td(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}vd(t,n),Fu(t,i),Od(this.projectionDeltaWithTransform,this.layoutCorrected,t,i)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new df),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&&_f(`z`,e,r,this.animationValues);for(let t=0;t<mf.length;t++)_f(`rotate${mf[t]}`,e,r,this.animationValues),_f(`skew${mf[t]}`,e,r,this.animationValues);e.render();for(let t in r)e.setStaticValue(t,r[t]),this.animationValues&&(this.animationValues[t]=r[t]);e.scheduleRender()}applyProjectionStyles(e,t){if(!this.instance||this.isSVG)return;if(!this.isVisible){e.visibility=`hidden`;return}let n=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,e.visibility=``,e.opacity=``,e.pointerEvents=uf(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=uf(t?.pointerEvents)||``),this.hasProjected&&!Su(this.latestValues)&&(e.transform=n?n({},``):`none`,this.hasProjected=!1);return}e.visibility=``;let i=r.animationValues||r.latestValues;this.applyTransformsToTarget();let a=Jd(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 Ku){if(i[t]===void 0)continue;let{correct:n,applyTo:o,isCSSVariable:s}=Ku[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?uf(t?.pointerEvents)||``:`none`)}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>e.currentAnimation?.stop()),this.root.nodes.forEach(Tf),this.root.sharedNodes.clear()}}}function bf(e){e.updateLayout()}function xf(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`)qd(e=>{let r=a?t.measuredBox[e]:t.layoutBox[e],i=Td(r);r.min=n[e].min,r.max=r.min+i});else if(i===`x`||i===`y`){let e=i===`x`?`y`:`x`;_d(a?t.measuredBox[e]:t.layoutBox[e],n[e])}else Wf(i,t.layoutBox,n)&&qd(r=>{let i=a?t.measuredBox[r]:t.layoutBox[r],o=Td(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=Xl();Od(o,n,t.layoutBox);let s=Xl();a?Od(s,e.applyTransform(r,!0),t.measuredBox):Od(s,n,t.layoutBox);let c=!Bd(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=X();Md(s,t.layoutBox,i.layoutBox,o);let c=X();Md(c,n,a.layoutBox,o),Wd(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 Sf(e){aa.value&&pf.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 Cf(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function wf(e){e.clearSnapshot()}function Tf(e){e.clearMeasurements()}function Ef(e){e.isLayoutDirty=!0,e.updateLayout()}function Df(e){e.isLayoutDirty=!1}function Of(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function kf(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify(`BeforeLayoutMeasure`),e.resetTransform()}function Af(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function jf(e){e.resolveTargetDelta()}function Mf(e){e.calcProjection()}function Nf(e){e.resetSkewAndRotation()}function Pf(e){e.removeLeadSnapshot()}function Ff(e,t,n){e.translate=q(t.translate,0,n),e.scale=q(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function If(e,t,n,r){e.min=q(t.min,n.min,r),e.max=q(t.max,n.max,r)}function Lf(e,t,n,r){If(e.x,t.x,n.x,r),If(e.y,t.y,n.y,r)}function Rf(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}var zf={duration:.45,ease:[.4,0,.1,1]},Bf=e=>typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Vf=Bf(`applewebkit/`)&&!Bf(`chrome/`)?Math.round:ki;function Hf(e){e.min=Vf(e.min),e.max=Vf(e.max)}function Uf(e){Hf(e.x),Hf(e.y)}function Wf(e,t,n){return e===`position`||e===`preserve-aspect`&&!Ed(Gd(t),Gd(n),.2)}function Gf(e){return e!==e.root&&e.scroll?.wasRoot}var Kf=yf({attachResizeListener:(e,t)=>of(e,`resize`,t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),qf={current:void 0},Jf=yf({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!qf.current){let e=new Kf({});e.mount(window),e.setOptions({layoutScroll:!0}),qf.current=e}return qf.current},resetTransform:(e,t)=>{e.style.transform=t===void 0?`none`:t},checkIsScrollRoot:e=>window.getComputedStyle(e).position===`fixed`}),Yf=(0,b.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:`never`});function Xf(e=!0){let t=(0,b.useContext)(bi);if(t===null)return[!0,null];let{isPresent:n,onExitComplete:r,register:i}=t,a=(0,b.useId)();(0,b.useEffect)(()=>{if(e)return i(a)},[e]);let o=(0,b.useCallback)(()=>e&&r&&r(a),[a,r,e]);return!n&&r?[!1,o]:[!0]}var Zf=(0,b.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`]},$f=!1;function ep(){if($f)return;let e={};for(let t in Qf)e[t]={isEnabled:e=>Qf[t].some(t=>!!e[t])};fu(e),$f=!0}function tp(){return ep(),pu()}function np(e){let t=tp();for(let n in e)t[n]={...t[n],...e[n]};fu(t)}var rp=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 ip(e){return e.startsWith(`while`)||e.startsWith(`drag`)&&e!==`draggable`||e.startsWith(`layout`)||e.startsWith(`onTap`)||e.startsWith(`onPan`)||e.startsWith(`onLayout`)||rp.has(e)}var ap=c({default:()=>op}),op,sp=o((()=>{throw op={},Error(`Could not resolve "@emotion/is-prop-valid" imported by "framer-motion". Is it installed?`)})),cp=e=>!ip(e);function lp(e){typeof e==`function`&&(cp=t=>t.startsWith(`on`)?!ip(t):e(t))}try{lp((sp(),d(ap)).default)}catch{}function up(e,t,n){let r={};for(let i in e)i===`values`&&typeof e.values==`object`||Nc(e[i])||(cp(i)||n===!0&&ip(i)||!t&&!ip(i)||e.draggable&&i.startsWith(`onDrag`))&&(r[i]=e[i]);return r}var dp=(0,b.createContext)({});function fp(e,t){if(ru(e)){let{initial:t,animate:n}=e;return{initial:t===!1||eu(t)?t:void 0,animate:eu(n)?n:void 0}}return e.inherit===!1?{}:t}function pp(e){let{initial:t,animate:n}=fp(e,(0,b.useContext)(dp));return(0,b.useMemo)(()=>({initial:t,animate:n}),[mp(t),mp(n)])}function mp(e){return Array.isArray(e)?e.join(` `):e}var hp=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function gp(e,t,n){for(let r in t)!Nc(t[r])&&!qu(r,n)&&(e[r]=t[r])}function _p({transformTemplate:e},t){return(0,b.useMemo)(()=>{let n=hp();return Vu(n,t,e),Object.assign({},n.vars,n.style)},[t])}function vp(e,t){let n=e.style||{},r={};return gp(r,n,e),Object.assign(r,_p(e,t)),r}function yp(e,t){let n={},r=vp(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 bp=()=>({...hp(),attrs:{}});function xp(e,t,n,r){let i=(0,b.useMemo)(()=>{let n=bp();return td(n,t,rd(r),e.transformTemplate,e.style),{...n.attrs,style:{...n.style}}},[t]);if(e.style){let t={};gp(t,e.style,e),i.style={...t,...i.style}}return i}var Sp=[`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 Cp(e){return typeof e!=`string`||e.includes(`-`)?!1:!!(Sp.indexOf(e)>-1||/[A-Z]/u.test(e))}function wp(e,t,n,{latestValues:r},i,a=!1,o){let s=(o??Cp(e)?xp:yp)(t,r,i,e),c=up(t,typeof e==`string`,a),l=e===b.Fragment?{}:{...c,...s,ref:n},{children:u}=t,d=(0,b.useMemo)(()=>Nc(u)?u.get():u,[u]);return(0,b.createElement)(e,{...l,children:d})}function Tp({scrapeMotionValuesFromProps:e,createRenderState:t},n,r,i){return{latestValues:Ep(n,r,i,e),renderState:t()}}function Ep(e,t,n,r){let i={},a=r(e,{});for(let e in a)i[e]=uf(a[e]);let{initial:o,animate:s}=e,c=ru(e),l=iu(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`&&!$l(d)){let t=Array.isArray(d)?d:[d];for(let n=0;n<t.length;n++){let r=xc(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 Dp=e=>(t,n)=>{let r=(0,b.useContext)(dp),i=(0,b.useContext)(bi),a=()=>Tp(e,t,r,i);return n?a():vi(a)},Op=Dp({scrapeMotionValuesFromProps:Ju,createRenderState:hp}),kp=Dp({scrapeMotionValuesFromProps:ad,createRenderState:bp}),Ap=Symbol.for(`motionComponentSymbol`);function jp(e,t,n){let r=(0,b.useRef)(n);(0,b.useInsertionEffect)(()=>{r.current=n});let i=(0,b.useRef)(null);return(0,b.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 Mp=(0,b.createContext)({});function Np(e){return e&&typeof e==`object`&&Object.prototype.hasOwnProperty.call(e,`current`)}function Pp(e,t,n,r,i,a){let{visualElement:o}=(0,b.useContext)(dp),s=(0,b.useContext)(Zf),c=(0,b.useContext)(bi),l=(0,b.useContext)(Yf),u=l.reducedMotion,d=l.skipAnimations,f=(0,b.useRef)(null),p=(0,b.useRef)(!1);r||=s.renderer,!f.current&&r&&(f.current=r(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:d,isSVG:a}),p.current&&f.current&&(f.current.manuallyAnimateOnMount=!0));let m=f.current,h=(0,b.useContext)(Mp);m&&!m.projection&&i&&(m.type===`html`||m.type===`svg`)&&Fp(f.current,n,i,h);let g=(0,b.useRef)(!1);(0,b.useInsertionEffect)(()=>{m&&g.current&&m.update(n,c)});let _=n[Lc],v=(0,b.useRef)(!!_&&typeof window<`u`&&!window.MotionHandoffIsComplete?.(_)&&window.MotionHasOptimisedAnimation?.(_));return yi(()=>{p.current=!0,m&&(g.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),v.current&&m.animationState&&m.animationState.animateChanges())}),(0,b.useEffect)(()=>{m&&(!v.current&&m.animationState&&m.animationState.animateChanges(),v.current&&=(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(_)}),!1),m.enteringChildren=void 0)}),m}function Fp(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:Ip(e.parent)),e.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!o||s&&Np(s),visualElement:e,animationType:typeof a==`string`?a:`both`,initialPromotionConfig:r,crossfade:d,layoutScroll:c,layoutRoot:l,layoutAnchor:u})}function Ip(e){if(e)return e.options.allowProjection===!1?Ip(e.parent):e.projection}function Lp(e,{forwardMotionProps:t=!1,type:n}={},r,i){r&&np(r);let a=n?n===`svg`:Cp(e),o=a?kp:Op;function s(n,s){let c,l={...(0,b.useContext)(Yf),...n,layoutId:Rp(n)},{isStatic:u}=l,d=pp(n),f=o(n,u);if(!u&&typeof window<`u`){zp(l,r);let t=Bp(l);c=t.MeasureLayout,d.visualElement=Pp(e,f,l,i,t.ProjectionNode,a)}return(0,H.jsxs)(dp.Provider,{value:d,children:[c&&d.visualElement?(0,H.jsx)(c,{visualElement:d.visualElement,...l}):null,wp(e,n,jp(f,d.visualElement,s),f,u,t,a)]})}s.displayName=`motion.${typeof e==`string`?e:`create(${e.displayName??e.name??``})`}`;let c=(0,b.forwardRef)(s);return c[Ap]=e,c}function Rp({layoutId:e}){let t=(0,b.useContext)(_i).id;return t&&e!==void 0?t+`-`+e:e}function zp(e,t){(0,b.useContext)(Zf).strict}function Bp(e){let{drag:t,layout:n}=tp();if(!t&&!n)return{};let r={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function Vp(e,t){if(typeof Proxy>`u`)return Lp;let n=new Map,r=(n,r)=>Lp(n,r,e,t);return new Proxy((e,t)=>r(e,t),{get:(i,a)=>a===`create`?r:(n.has(a)||n.set(a,Lp(a,void 0,e,t)),n.get(a))})}var Hp=(e,t)=>t.isSVG??Cp(e)?new od(t):new Xu(t,{allowProjection:e!==b.Fragment}),Up=class extends gu{constructor(e){super(e),e.animationState||=pd(e)}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();$l(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?.()}},Wp=0,Gp={animation:{Feature:Up},exit:{Feature:class extends gu{constructor(){super(...arguments),this.id=Wp++,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=Sc(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 Kp(e){return{point:{x:e.pageX,y:e.pageY}}}var qp=e=>t=>xl(t)&&e(t,Kp(t));function Jp(e,t,n,r){return of(e,t,qp(n),r)}var Yp=({current:e})=>e?e.ownerDocument.defaultView:null,Xp=(e,t)=>Math.abs(e-t);function Zp(e,t){let n=Xp(e.x,t.x),r=Xp(e.y,t.y);return Math.sqrt(n**2+r**2)}var Qp=new Set([`auto`,`scroll`]),$p=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=em(this.lastRawMoveEventInfo,this.transformPagePoint));let e=nm(this.lastMoveEventInfo,this.history),t=this.startEvent!==null,n=Zp(e.offset,{x:0,y:0})>=this.distanceThreshold;if(!t&&!n)return;let{point:r}=e,{timestamp:i}=ua;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=em(t,this.transformPagePoint),W.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=nm(e.type===`pointercancel`?this.lastMoveEventInfo:em(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,a),r&&r(e,a)},!xl(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.distanceThreshold=a,this.contextWindow=r||window;let s=em(Kp(e),this.transformPagePoint),{point:c}=s,{timestamp:l}=ua;this.history=[{...c,timestamp:l}];let{onSessionStart:u}=t;u&&u(e,nm(s,this.history)),this.removeListeners=U(Jp(this.contextWindow,`pointermove`,this.handlePointerMove),Jp(this.contextWindow,`pointerup`,this.handlePointerUp),Jp(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),W.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),la(this.updatePoint)}};function em(e,t){return t?{point:t(e.point)}:e}function tm(e,t){return{x:e.x-t.x,y:e.y-t.y}}function nm({point:e},t){return{point:e,delta:tm(e,im(t)),offset:tm(e,rm(t)),velocity:am(t,.1)}}function rm(e){return e[0]}function im(e){return e[e.length-1]}function am(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null,i=im(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>Ni(t)));)n--;if(!r)return{x:0,y:0};r===e[0]&&e.length>2&&i.timestamp-r.timestamp>Ni(t)*2&&(r=e[1]);let a=Pi(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 om(e,{min:t,max:n},r){return t!==void 0&&e<t?e=r?q(t,e,r.min):Math.max(e,t):n!==void 0&&e>n&&(e=r?q(n,e,r.max):Math.min(e,n)),e}function sm(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 cm(e,{top:t,left:n,bottom:r,right:i}){return{x:sm(e.x,n,i),y:sm(e.y,t,r)}}function lm(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 um(e,t){return{x:lm(e.x,t.x),y:lm(e.y,t.y)}}function dm(e,t){let n=.5,r=Td(e),i=Td(t);return i>r?n=ji(t.min,t.max-r,e.min):r>i&&(n=ji(e.min,e.max-i,t.min)),Ci(0,1,n)}function fm(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 pm=.35;function mm(e=pm){return e===!1?e=0:e===!0&&(e=pm),{x:hm(e,`left`,`right`),y:hm(e,`top`,`bottom`)}}function hm(e,t,n){return{min:gm(e,t),max:gm(e,n)}}function gm(e,t){return typeof e==`number`?e:e[t]||0}var _m=new WeakMap,vm=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=X(),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(Kp(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=gl(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),qd(e=>{let t=this.getAxisMotionValue(e).get()||0;if(Ra.test(t)){let{projection:n}=this.visualElement;if(n&&n.layout){let r=n.layout.layoutBox[e];r&&(t=Td(r)*(parseFloat(t)/100))}}this.originPoint[e]=t}),i&&W.update(()=>i(e,t),!1,!0),Fc(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=Sm(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&&W.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 $p(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:s,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:l,distanceThreshold:n,contextWindow:Yp(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&&W.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||!xm(e,r,this.currentDirection))return;let i=this.getAxisMotionValue(e),a=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(a=om(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&&Np(e)?this.constraints||=this.resolveRefConstraints():e&&n?this.constraints=cm(n.layoutBox,e):this.constraints=!1,this.elastic=mm(t),r!==this.constraints&&!Np(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&qd(e=>{this.constraints!==!1&&this.getAxisMotionValue(e)&&(this.constraints[e]=fm(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){let{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!Np(e))return!1;let n=e.current,{projection:r}=this.visualElement;if(!r||!r.layout)return!1;let i=Lu(n,r.root,this.visualElement.getTransformPagePoint()),a=um(r.layout.layoutBox,i);if(t){let e=t(vu(a));this.hasMutatedConstraints=!!e,e&&(a=_u(e))}return a}startAnimation(e){let{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),s=this.constraints||{},c=qd(o=>{if(!xm(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 Fc(this.visualElement,e),n.start(yc(e,n,0,t,this.visualElement,!1))}stopAnimation(){qd(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){qd(t=>{let{drag:n}=this.getProps();if(!xm(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]-q(n,a,.5)+o)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!Np(t)||!n||!this.constraints)return;this.stopAnimation();let r={x:0,y:0};qd(e=>{let t=this.getAxisMotionValue(e);if(t&&this.constraints!==!1){let n=t.get();r[e]=dm({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(),qd(t=>{if(!xm(t,e,null))return;let n=this.getAxisMotionValue(t),{min:i,max:a}=this.constraints[t];n.set(q(i,a,r[t]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;_m.set(this.visualElement,this);let e=this.visualElement.current,t=Jp(e,`pointerdown`,t=>{let{drag:n,dragListener:r=!0}=this.getProps(),i=t.target,a=i!==e&&Tl(i);n&&r&&!a&&this.start(t)}),n,r=()=>{let{dragConstraints:t}=this.getProps();Np(t)&&t.current&&(this.constraints=this.resolveRefConstraints(),n||=bm(e,t.current,()=>this.scalePositionWithinConstraints()))},{projection:i}=this.visualElement,a=i.addEventListener(`measure`,r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),W.read(r);let o=of(window,`resize`,()=>this.scalePositionWithinConstraints()),s=i.addEventListener(`didUpdate`,(({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(qd(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=pm,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:o}}};function ym(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function bm(e,t,n){let r=Gl(e,ym(n)),i=Gl(t,ym(n));return()=>{r(),i()}}function xm(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Sm(e,t=10){let n=null;return Math.abs(e.y)>t?n=`y`:Math.abs(e.x)>t&&(n=`x`),n}var Cm=class extends gu{constructor(e){super(e),this.removeGroupControls=ki,this.removeListeners=ki,this.controls=new vm(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ki}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()}},wm=e=>(t,n)=>{e&&W.update(()=>e(t,n),!1,!0)},Tm=class extends gu{constructor(){super(...arguments),this.removePointerDownListener=ki}onPointerDown(e){this.session=new $p(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Yp(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:wm(e),onStart:wm(t),onMove:wm(n),onEnd:(e,t)=>{delete this.session,r&&W.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=Jp(this.node.current,`pointerdown`,e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}},Em=!1,Dm=class extends b.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),Em&&i.root.didUpdate(),i.addEventListener(`animationComplete`,()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),ff.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}),Em=!0,r||e.layoutDependency!==t||t===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||W.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(),fl.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;Em=!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 Om(e){let[t,n]=Xf(),r=(0,b.useContext)(_i);return(0,H.jsx)(Dm,{...e,layoutGroup:r,switchLayoutGroup:(0,b.useContext)(Mp),isPresent:t,safeToRemove:n})}var km={pan:{Feature:Tm},drag:{Feature:Cm,ProjectionNode:Jf,MeasureLayout:Om}};function Am(e,t,n){let{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive(`whileHover`,n===`Start`);let i=r[`onHover`+n];i&&W.postRender(()=>i(t,Kp(t)))}var jm=class extends gu{mount(){let{current:e}=this.node;e&&(this.unmount=yl(e,(e,t)=>(Am(this.node,t,`Start`),e=>Am(this.node,e,`End`))))}unmount(){}},Mm=class extends gu{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=U(of(this.node.current,`focus`,()=>this.onFocus()),of(this.node.current,`blur`,()=>this.onBlur()))}unmount(){}};function Nm(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&&W.postRender(()=>i(t,Kp(t)))}var Pm=class extends gu{mount(){let{current:e}=this.node;if(!e)return;let{globalTapTarget:t,propagate:n}=this.node.props;this.unmount=Ml(e,(e,t)=>(Nm(this.node,t,`Start`),(e,{success:t})=>Nm(this.node,e,t?`End`:`Cancel`)),{useGlobalTarget:t,stopPropagation:n?.tap===!1})}unmount(){}},Fm=new WeakMap,Im=new WeakMap,Lm=e=>{let t=Fm.get(e.target);t&&t(e)},Rm=e=>{e.forEach(Lm)};function zm({root:e,...t}){let n=e||document;Im.has(n)||Im.set(n,{});let r=Im.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(Rm,{root:e,...t})),r[i]}function Bm(e,t,n){let r=zm(t);return Fm.set(e,n),r.observe(e),()=>{Fm.delete(e),r.unobserve(e)}}var Vm={some:0,all:1},Hm=class extends gu{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:Vm[r]};this.stopObserver=Bm(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(Um(e,t))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}};function Um({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}var Wm={inView:{Feature:Hm},tap:{Feature:Pm},focus:{Feature:Mm},hover:{Feature:jm}},Gm={layout:{ProjectionNode:Jf,MeasureLayout:Om}},Km=Vp({...Gp,...Wm,...km,...Gm},Hp),qm=24e3,Jm=2048,Ym=1200,Xm=.03,Zm=2,Qm=11;function $m(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n]*e[n];return Math.sqrt(t/e.length)}function eh(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 th(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;n++)t[n]=e[n]/32768;return t}var nh=.13,rh=[`audio/webm`,`audio/mp4`];function ih(){return typeof window>`u`||window.MediaRecorder===void 0?null:rh.find(e=>window.MediaRecorder.isTypeSupported(e))||null}function ah(e,t,n,r,i){if(!r.length||!n||!e)return;let a=new Blob(r,{type:i}),o=new FormData;o.append(`audio`,a,`aichat-${n}.webm`),o.append(`voiceSessionId`,n),o.append(`siteId`,t||``),fetch(`${e}/api/voice/upload-chat-recording`,{method:`POST`,body:o}).then(e=>{if(!e.ok)throw Error(`HTTP ${e.status}`)}).catch(e=>console.warn(`[FlowEngage] voice recording upload failed:`,e.message))}var oh=.02;function sh(e,t,n){let r=0,i=0,a=[],o=()=>{let t=e.currentTime;a.forEach(({source:e,gain:n})=>{try{n.gain.cancelScheduledValues(t),n.gain.setValueAtTime(n.gain.value,t),n.gain.linearRampToValueAtTime(0,t+oh),e.stop(t+oh)}catch{}}),a=[],r=0,i=0},s=()=>r>e.currentTime;return{enqueue:o=>{let c=th(o),l=e.createBuffer(1,c.length,qm);l.copyToChannel(c,0);let u=e.createBufferSource();u.buffer=l;let d=e.createGain();u.connect(d),d.connect(e.destination),n&&d.connect(n);let f=s()?r:e.currentTime+nh;i||=f,u.start(f),r=f+l.duration;let p={source:u,gain:d};a.push(p),u.onended=()=>{a=a.filter(e=>e!==p),!a.length&&!s()&&t?.()}},stop:o,isPlaying:s,playedMs:()=>Math.max(0,(e.currentTime-i)*1e3)}}async function ch(e,t,n){let r=new URLSearchParams({siteId:t||``});n&&r.set(`chatId`,n);let i=Lr();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 lh(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 ch(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:qm});_.state===`suspended`&&await _.resume();let v=_.createMediaStreamDestination(),y=ih(),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})}},D=(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,Ym))},O=!1,k=!1,A=!1,te=!1,ne=!0,re=!1,ie=null,j=!1,M=!1,ae=()=>{ie&&clearTimeout(ie);let e=()=>{if(!O){if(oe.isPlaying()){ie=setTimeout(e,150);return}if(ie=null,j){p?.();return}!O&&C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:`PlaybackDrained`})),M&&(M=!1,d?.())}};ie=setTimeout(e,150)},oe=sh(_,()=>{te&&(te=!1,c?.({mode:`listening`}))},v);typeof window<`u`&&(window.__fe_agentAudioPlaying=()=>oe.isPlaying());let se=_.createMediaStreamSource(g);se.connect(v);let ce=_.createScriptProcessor(Jm,1,1),N=!1,P=0,le=0;ce.onaudioprocess=e=>{if(O||C.readyState!==WebSocket.OPEN)return;let t=e.inputBuffer.getChannelData(0),n=()=>C.send(new Int16Array(t.length).buffer);if(k){A||(A=!0,console.debug(`[FlowEngage] mic held — streaming silence to keep socket alive`)),N=!1,P=0,le=0,n();return}let r=$m(t);oe.isPlaying()||re?(N=!1,P=0,le=0):r>=Xm?(le=0,P+=1,!N&&P>=Zm&&(N=!0,c?.({mode:`user-speaking`}))):(P=0,N&&++le>=Qm&&(N=!1,le=0,c?.({mode:`thinking`,tentative:!0}))),C.send(eh(t).buffer)},se.connect(ce),ce.connect(_.destination);let ue=()=>{if(!O){O=!0,ie&&=(clearTimeout(ie),null),ee(),oe.stop(),typeof window<`u`&&delete window.__fe_agentAudioPlaying;try{ce.disconnect(),se.disconnect()}catch{}if(g.getTracks().forEach(e=>e.stop()),x&&x.state!==`inactive`){x.onstop=()=>ah(t,n,S,b,y);try{x.stop()}catch{x.onstop=null}}else b.length&&ah(t,n,S,b,y);_.close().catch(()=>{}),(C.readyState===WebSocket.OPEN||C.readyState===WebSocket.CONNECTING)&&C.close()}},de=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 de(t);if(O||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??{})}))}},fe=e=>{switch(e.type){case`Welcome`:Number.isFinite(e.barge_in_rms)&&e.barge_in_rms>0&&e.barge_in_rms,Number.isFinite(e.barge_in_frames)&&e.barge_in_frames>0&&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}}D(e.role===`user`?`user`:`agent`,t,e.debug);break}case`UserStartedSpeaking`:ee(),oe.stop(),re=!1,ne=!1,te=!1,ie&&!j&&(clearTimeout(ie),ie=null),M=!1,c?.({mode:`listening`});break;case`AgentStartedSpeaking`:ne=!0,te=!0,c?.({mode:`speaking`});break;case`AgentAudioDone`:re=!1,ee(),ae(),oe.isPlaying()||(te=!1,c?.({mode:`listening`}));break;case`FunctionCallRequest`:F(e);break;case`AgentPreparing`:re=!0;break;case`AgentTurnComplete`:M=!0,ae();break;case`SessionEnding`:console.debug(`[FlowEngage] server is ending the session:`,e.reason||`unspecified`),j=!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){ne&&oe.enqueue(new Int16Array(e.data));return}try{fe(JSON.parse(e.data))}catch{}},C.onerror=()=>l?.(Error(`Voice connection failed`)),C.onclose=()=>{ue(),o?.()},{endSession:async()=>ue(),sendContextualUpdate:e=>{O||C.readyState!==WebSocket.OPEN||!e||C.send(JSON.stringify({type:`UpdatePrompt`,prompt:e}))},sendUserMessage:(e,{silent:t=!0,suppressQuestion:n=!1}={})=>{O||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`)=>{O||C.readyState!==WebSocket.OPEN||!e||C.send(JSON.stringify({type:`InjectAgentMessage`,message:e,behavior:t}))},setWalkthroughActive:e=>{O||C.readyState!==WebSocket.OPEN||C.send(JSON.stringify({type:`WalkthroughActive`,active:!!e}))},setMicMuted:e=>{k=!!e,!O&&C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:`MicHeld`,held:k}))},get status(){return O?`disconnected`:`connected`}}}var uh={startSession:lh},dh=({size:e=18,color:t=`currentColor`})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,H.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,H.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),fh=({size:e=20})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.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,H.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),ph=({size:e=18})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,H.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),mh=()=>(0,H.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,H.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),hh=()=>(0,H.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.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`})}),gh=({className:e=``})=>(0,H.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,H.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,H.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,H.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),_h=({size:e=14})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`path`,{d:`M12 8V4H8`}),(0,H.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,H.jsx)(`path`,{d:`M2 14h2`}),(0,H.jsx)(`path`,{d:`M20 14h2`}),(0,H.jsx)(`path`,{d:`M15 13v2`}),(0,H.jsx)(`path`,{d:`M9 13v2`})]}),vh=({size:e=20,strokeWidth:t=2,color:n=`currentColor`})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:n,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`12`,y1:`5`,x2:`12`,y2:`19`}),(0,H.jsx)(`line`,{x1:`5`,y1:`12`,x2:`19`,y2:`12`})]}),yh=({size:e=20,color:t=`currentColor`})=>(0,H.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,H.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`,fill:t}),(0,H.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`,fill:t}),(0,H.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`,fill:t})]}),bh=({size:e=20,color:t=`currentColor`})=>(0,H.jsxs)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,H.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,H.jsx)(`path`,{d:`M11.9955 12H12.0045M15.991 12H16M8 12H8.00897`,stroke:`white`,"stroke-width":`2`,"stroke-linecap":`round`,"stroke-linejoin":`round`})]}),xh=()=>(0,H.jsx)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,H.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`})}),Sh=({size:e=24})=>(0,H.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,H.jsx)(`path`,{d:`M12 19v3`}),(0,H.jsx)(`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`}),(0,H.jsx)(`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`}),(0,H.jsx)(`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`}),(0,H.jsx)(`path`,{d:`m2 2 20 20`}),(0,H.jsx)(`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`})]}),Ch=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),wh=(e=``)=>String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),Th=new Set([`p`,`br`,`ul`,`ol`,`li`,`strong`,`em`,`b`,`i`,`a`]),Eh=/^https?:\/\//i;function Dh(e){let t=Array.from(e.childNodes);for(let n of t)if(n.nodeType===Node.ELEMENT_NODE){let t=n.tagName.toLowerCase();if(!Th.has(t)){e.replaceChild(document.createTextNode(n.textContent),n);continue}let r={};if(t===`a`){let e=n.getAttribute(`href`)||``;Eh.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);Dh(n)}else n.nodeType!==Node.TEXT_NODE&&e.removeChild(n)}function Oh(e){let t=document.createElement(`div`);return t.innerHTML=e,Dh(t),t.innerHTML}function kh(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 Ah=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return kh(Oh(t));let n=t.replace(/\r\n/g,`
|
|
37
37
|
`).replace(/\n{3,}/g,`
|
|
38
38
|
|
|
39
|
-
`).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>
|
|
40
|
-
`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``))},Nh=new Set([`application/pdf`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`]),Ph=new Set([`.pdf`,`.docx`,`.png`,`.jpg`,`.jpeg`]),Fh=`image/png,image/jpeg,.pdf,.docx`;function Ih(e){if(!e)return!1;let t=typeof e.name==`string`?e.name.toLowerCase():``,n=t.includes(`.`)?`.${t.split(`.`).pop()}`:``,r=typeof e.type==`string`?e.type.toLowerCase():``;return r===`image/png`||r===`image/jpeg`||Nh.has(r)||Ph.has(n)}function Lh(e){return e?Ih(e)?e.size>2097152?`File must be 2 MB or smaller.`:``:`Only PNG, JPEG, PDF, and DOCX files are allowed.`:`No file selected.`}function Rh(e=0){if(!Number.isFinite(e)||e<=0)return``;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=n>=10||r===0?0:1;return`${n.toFixed(i)} ${t[r]}`}function zh(e){return e?e.name||`Attachment`:``}function Bh(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function Vh({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,b.useState)(null),o=typeof e==`string`?e.trim():``;return(0,b.useEffect)(()=>{if(!o){a(null);return}a(null);let e=!1,t=new window.Image;return t.onload=()=>{e||a(o)},t.onerror=()=>{e||a(null)},t.src=o,()=>{e=!0}},[o]),i?(0,H.jsx)(`img`,{src:i,alt:``,style:n,onError:()=>a(null)}):(0,H.jsx)(`span`,{style:r,children:Bh(t)})}function Hh({chatHistory:e,isAiTyping:t,isLoading:n,isAgentTyping:r,setReplyContext:i,primaryColor:a=`#3B82F6`,agentHeadshot:o=null,agentDisplayName:s=`Agent`,botAvatarNode:c=null}){let{resolvedConfig:l}=wn(),u=(0,b.useRef)(null),[d,f]=(0,b.useState)(null),[p,m]=(0,b.useState)(null),h=(0,b.useRef)(e.length),g=(0,b.useRef)(!0),_=(0,b.useRef)(null),v=(0,b.useCallback)(e=>{let t=e.target.closest(`a[href]`);if(!t)return;let n=t.getAttribute(`href`)||``;if(!(!n||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||n.startsWith(`javascript:`)))try{let t=new URL(n,window.location.href);if(t.origin!==window.location.origin){e.preventDefault(),window.open(t.href,`_blank`,`noopener,noreferrer`);return}e.preventDefault(),hr(t.href,{siteId:l?.siteId,apiBaseUrl:l?.apiBaseUrl}).then(({allowed:e,correctedUrl:n})=>{e&&Er(n||t.href)})}catch{}},[l]),y=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i} min${i>1?`s`:``} ago`;let a=Math.floor(i/60);if(a<24)return`${a} hr${a>1?`s`:``} ago`;let o=Math.floor(a/24);return`${o} day${o>1?`s`:``} ago`};return(0,b.useEffect)(()=>{if(g.current){g.current=!1,h.current=e.length,_.current&&(_.current.scrollTop=_.current.scrollHeight);return}let n=e.length>h.current;h.current=e.length,(n||t||r)&&u.current?.scrollIntoView({behavior:`smooth`})},[e.length,t,n,r]),(0,H.jsxs)(`div`,{ref:_,style:{flex:1,overflowY:`auto`,overscrollBehavior:`contain`,padding:`10px 16px 20px`,display:`flex`,flexDirection:`column`,background:`transparent`},children:[e.map(e=>{if(e.type===`call_recording`||typeof e.message==`string`&&e.message.includes(`AI chat recording`))return null;let t=e.sender===`system`,n=e.sender===`user`,r=e.sender===`ai`||e.sender===`bot`,l=e.sender===`agent`,u=e.isPending,d=e.type===`file`&&e.metadata?.fileUrl,h=e.agent_name||e.agentName||e.metadata?.agentName||s,g=typeof e.sender_headshot==`string`&&e.sender_headshot.trim()||typeof o==`string`&&o.trim()||null,_=Th(e.replyToContent||e.replyContext?.message||``),b=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,H.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`8px 0`},children:(0,H.jsx)(`div`,{style:{padding:`6px 12px`,borderRadius:`9999px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,fontWeight:500},children:e.message})},e.id):(0,H.jsxs)(`div`,{style:{display:`flex`,justifyContent:n?`flex-end`:`flex-start`,alignItems:`flex-start`,marginBottom:`16px`,gap:`8px`,flexDirection:`row`},children:[!n&&(r||l)&&(0,H.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:l?`#f3f4f6`:c&&r?`transparent`:`var(--flowengage-primary)`,color:l?a:`#fff`,boxShadow:l?`0 2px 8px rgba(0,0,0,0.06)`:c&&r?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`,border:l?`1px solid ${a}22`:`none`,fontSize:`12px`,fontWeight:800,marginTop:!u&&(r||l)?`22px`:`0px`},children:r?c||(0,H.jsx)(yh,{size:16}):(0,H.jsx)(Vh,{src:g||``,name:h,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,H.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`75%`,minWidth:0},children:[!u&&l&&(0,H.jsxs)(`button`,{type:`button`,onClick:()=>i(e),style:{opacity:1,marginBottom:`4px`,display:`flex`,alignItems:`center`,gap:`4px`,fontSize:`11px`,color:`#9ca3af`,background:`transparent`,border:0,cursor:`pointer`,padding:0,marginLeft:`2px`},onMouseEnter:e=>{e.currentTarget.style.color=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:[(0,H.jsx)(gh,{}),`Reply`]}),(0,H.jsxs)(`div`,{style:{padding:`8px 16px`,borderRadius:n?`20px 6px 20px 20px`:`6px 20px 20px 20px`,lineHeight:1.8,letterSpacing:0,boxShadow:`0 2px 8px rgba(0,0,0,0.06)`,background:n?`var(--flowengage-primary)`:`rgba(255,255,255,0.92)`,color:n?`#fff`:`#111827`,fontSize:`14px`,fontWeight:400,opacity:u?.55:1,transition:`opacity 0.3s ease`,wordBreak:`break-word`,width:`fit-content`},children:[_&&(0,H.jsxs)(`div`,{style:{marginBottom:`8px`,borderRadius:`14px`,borderLeft:n?`2px solid rgba(255,255,255,0.8)`:`2px solid var(--flowengage-primary)`,padding:`8px 12px`,fontSize:`12px`,background:n?`rgba(255,255,255,0.15)`:`#f9fafb`,color:n?`rgba(255,255,255,0.9)`:`#6b7280`},children:[(0,H.jsx)(`div`,{style:{marginBottom:`2px`,fontWeight:600},children:b}),(0,H.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:_})]}),d?(()=>{let t=e.metadata.fileType||``,r=e.metadata.fileName||e.message||`File`,i=Rh(e.metadata.fileSize),a=t.startsWith(`image/`),o=`shared file: ${r}`.toLowerCase(),s=(e.message||``).trim(),c=s&&s.toLowerCase()!==o&&!s.toLowerCase().startsWith(`shared file:`),l=t===`application/pdf`?{color:`#ef4444`,label:`PDF`}:t.includes(`word`)||t.includes(`docx`)?{color:`#3b82f6`,label:`DOCX`}:t.includes(`excel`)||t.includes(`sheet`)||t===`text/csv`?{color:`#10b981`,label:`XLSX`}:{color:`#6b7280`,label:`FILE`};return(0,H.jsxs)(`div`,{style:{minWidth:`200px`,maxWidth:`240px`},children:[c&&(0,H.jsx)(`div`,{style:{marginBottom:`6px`,fontSize:`14px`,color:n?`#fff`:`#111827`,whiteSpace:`normal`,wordBreak:`break-word`},children:s}),a?(0,H.jsx)(`button`,{type:`button`,onClick:()=>f({url:e.metadata.fileUrl,name:r}),onMouseEnter:()=>m(e.id),onMouseLeave:()=>m(null),style:{display:`block`,width:`100%`,background:`transparent`,border:0,padding:0,margin:0,textAlign:`left`,cursor:`pointer`},children:(0,H.jsxs)(`div`,{style:{position:`relative`},children:[(0,H.jsx)(`img`,{src:e.metadata.fileUrl,alt:r,style:{width:`100%`,borderRadius:`10px`,display:`block`,maxHeight:`180px`,objectFit:`cover`}}),(0,H.jsx)(`div`,{style:{position:`absolute`,inset:0,borderRadius:`10px`,background:p===e.id?`rgba(17,24,39,0.32)`:`rgba(17,24,39,0)`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#fff`,fontSize:`13px`,fontWeight:700,letterSpacing:`0.02em`,opacity:p===e.id?1:0,transition:`background 0.18s ease, opacity 0.18s ease`,pointerEvents:`none`},children:`Preview`})]})}):(0,H.jsx)(`a`,{href:e.metadata.fileUrl,target:`_blank`,rel:`noopener noreferrer`,style:{textDecoration:`none`,display:`block`},children:(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`10px`,background:n?`rgba(255,255,255,0.15)`:`#f3f4f6`,borderRadius:`12px`,padding:`10px 12px`},children:[(0,H.jsxs)(`div`,{style:{width:`38px`,height:`46px`,borderRadius:`8px`,background:n?`rgba(255,255,255,0.22)`:`#fff`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 1px 4px rgba(0,0,0,0.1)`,gap:`3px`},children:[(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`#fff`:l.color,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`}),(0,H.jsx)(`polyline`,{points:`14 2 14 8 20 8`})]}),(0,H.jsx)(`span`,{style:{fontSize:`7px`,fontWeight:800,letterSpacing:`0.04em`,color:n?`#fff`:l.color,lineHeight:1},children:l.label})]}),(0,H.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,H.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:n?`#fff`:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:r}),i&&(0,H.jsx)(`div`,{style:{fontSize:`11px`,marginTop:`3px`,color:n?`rgba(255,255,255,0.6)`:`#9ca3af`},children:i})]}),(0,H.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`rgba(255,255,255,0.65)`:`#9ca3af`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,H.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,H.jsx)(`polyline`,{points:`7 10 12 15 17 10`}),(0,H.jsx)(`line`,{x1:`12`,y1:`15`,x2:`12`,y2:`3`})]})]})})]})})():r?(0,H.jsx)(`div`,{className:`flowengage-message-content fe-bot-message`,dangerouslySetInnerHTML:{__html:Mh(e.message)},onClick:v}):(0,H.jsx)(`div`,{style:{whiteSpace:`pre-wrap`},children:e.message})]}),(0,H.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,marginTop:`4px`,padding:`0 4px`,alignSelf:n?`flex-end`:`flex-start`},children:u?(0,H.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500,fontStyle:`italic`},children:`sending…`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500},children:y(e.timestamp||e.createdAt)}),(0,H.jsx)(`span`,{style:{fontSize:`10px`,fontWeight:700,color:n?`var(--flowengage-primary)`:`#9ca3af`},children:`✓`})]})})]})]},e.id)}),(t||n)&&(0,H.jsxs)(`div`,{style:{marginBottom:`16px`,display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,H.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:c?`transparent`:`var(--flowengage-primary)`,color:`#fff`,boxShadow:c?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`},children:c||(0,H.jsx)(yh,{size:16})}),(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`2px`,color:`#374151`,fontSize:`13px`,fontWeight:500,fontStyle:`italic`},children:[`Analysing`,[0,1,2].map(e=>(0,H.jsx)(`span`,{style:{animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`},children:`.`},e))]})]}),r&&(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:`8px`,marginBottom:`12px`},children:[(0,H.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,overflow:`hidden`},children:(0,H.jsx)(Vh,{src:o||``,name:s,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,H.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,H.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})]}),(0,H.jsx)(`div`,{ref:u}),d&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>f(null),style:{position:`fixed`,inset:0,zIndex:1e4,border:0,padding:`16px`,margin:0,background:`rgba(2,6,23,0.88)`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`default`},children:(0,H.jsxs)(`div`,{style:{position:`relative`,maxWidth:`min(96vw, 1100px)`,maxHeight:`96vh`,width:`100%`,display:`flex`,flexDirection:`column`,gap:`10px`,alignItems:`center`},children:[(0,H.jsx)(`img`,{src:d.url,alt:d.name,style:{width:`100%`,maxHeight:`calc(96vh - 72px)`,objectFit:`contain`,borderRadius:`16px`,boxShadow:`0 30px 80px rgba(0,0,0,0.42)`}}),(0,H.jsx)(`div`,{style:{maxWidth:`100%`,padding:`8px 14px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.92)`,color:`#0f172a`,fontSize:`12px`,fontWeight:600,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:d.name})]})})]})}var Uh=typeof window<`u`&&(window.matchMedia?.(`(pointer: coarse)`).matches||navigator.maxTouchPoints>0);function Wh({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:u,emailInput:d,setEmailInput:f,emailError:p,showVoiceToggle:m=!1,voiceEnabled:h=!0,onFileSelect:g,selectedFile:_=null,onRemoveSelectedFile:v,attachmentError:y=``,isUploadingAttachment:x=!1,inputPlaceholder:S=`Type your message`}){let C=(0,b.useRef)(null),w=(0,b.useRef)(null),T=e=>{e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)};(0,b.useEffect)(()=>{u||T(w.current)},[e,u]),(0,b.useEffect)(()=>{u||Uh||e||s||w.current?.focus()},[e,u,s]);let E=e=>{e.key===`Enter`&&(Uh||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||(e.preventDefault(),e.currentTarget.form?.requestSubmit()))},ee=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`,D=u?!!d?.trim():!!e?.trim()||!!_,O=s||x||!D,k=!u&&h&&m;return(0,H.jsxs)(`div`,{style:{padding:`0 16px`,background:`transparent`},children:[c&&(0,H.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,H.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,H.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,ee]}),(0,H.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,H.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),u&&(0,H.jsx)(`div`,{style:{marginBottom:`8px`,padding:`0 8px`},children:(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,H.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,H.jsx)(yh,{size:13})}),(0,H.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),_&&!u&&(0,H.jsxs)(`div`,{style:{marginBottom:`10px`,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.06)`,background:`#fff`,padding:`12px 14px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,H.jsxs)(`div`,{style:{minWidth:0,flex:1},children:[(0,H.jsx)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`,marginBottom:`2px`},children:`Attachment ready`}),(0,H.jsx)(`div`,{style:{fontSize:`13px`,color:`#111827`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`},children:zh(_)}),(0,H.jsx)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginTop:`2px`},children:Rh(_.size)})]}),(0,H.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`,flexShrink:0},onClick:v,"aria-label":`Remove attachment`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),(0,H.jsxs)(`form`,{style:{display:`flex`,alignItems:`flex-end`,gap:`8px`,minHeight:`40px`,padding:`4px`,border:`1px solid rgba(0,0,0,0.06)`,borderRadius:`20px`,background:`#fff`,boxShadow:`0 4px 14px rgba(0,0,0,0.04)`,opacity:1},onSubmit:n,children:[k?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`input`,{ref:C,type:`file`,accept:Fh,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];t&&g?.(t),e.target.value=``}}),(0,H.jsx)(`button`,{type:`button`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`#f3f4f8`,color:`var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, opacity 0.2s ease`,border:0,cursor:`pointer`,flexShrink:0},onClick:()=>C.current?.click(),title:`Attach file`,"aria-label":`Attach file`,disabled:x,onMouseEnter:e=>{e.currentTarget.style.opacity=`0.8`},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,H.jsx)(bh,{size:16,color:`currentColor`})})]}):null,u?(0,H.jsx)(`input`,{className:`flowengage-chat-text-input`,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:0,paddingLeft:k?`0`:`8px`,color:`#111827`,background:`transparent`,cursor:`text`,alignSelf:`center`},value:d,onChange:e=>f(e.target.value),placeholder:`Enter your Email`,disabled:s,type:`email`,autoComplete:`email`}):(0,H.jsx)(`textarea`,{ref:w,className:`flowengage-chat-text-input`,rows:1,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,lineHeight:`20px`,outline:`none`,padding:`6px 0`,paddingLeft:k?`0`:`8px`,color:`#111827`,background:`transparent`,cursor:`text`,resize:`none`,maxHeight:`120px`,overflowY:`auto`},value:e,onChange:e=>{t(e.target.value),T(e.target)},onKeyDown:E,placeholder:o===`agent`?`Message the agent…`:S,disabled:s,autoComplete:`off`}),(0,H.jsx)(`button`,{type:`submit`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`var(--flowengage-primary)`,color:`#fff`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`opacity 0.2s ease`,cursor:O?`not-allowed`:`pointer`,opacity:O?.45:1,flexShrink:0},disabled:O,onMouseEnter:e=>{O||(e.currentTarget.style.opacity=`0.85`)},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,H.jsx)(hh,{size:16})})]}),!u&&y&&(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`7px 4px 0`},children:[(0,H.jsxs)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#dc2626`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,H.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,H.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,H.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),(0,H.jsx)(`span`,{style:{fontSize:`11px`,color:`#dc2626`,fontWeight:500},children:y})]}),u&&p&&(0,H.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:p})]})}function Gh({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,isRateLimited:i,rateLimitMessage:a}){return(0,H.jsxs)(H.Fragment,{children:[(e||t)&&(0,H.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,H.jsx)(vh,{className:``}),(0,H.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,H.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),i&&(0,H.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:a})]})}var Kh=[`#135bd8`,`#ef334b`,`#ffbd2e`];function qh(e){return!Array.isArray(e)||e.length===0?Kh:e.length===1?[e[0],e[0],e[0]]:e.length===2?[e[0],e[1],e[0]]:[e[0],e[1],e[2]]}var Jh={idle:3,listening:.75,thinking:1,speaking:1.4,muted:.75,error:.08};function Yh(e){if(!e||typeof e!=`string`)return[0,0,0];let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}function Xh(e,t){if(!e||typeof e!=`string`)return`rgba(0,0,0,${t})`;if(e.startsWith(`rgb`))return e.replace(/[\d.]+\)$/,`${t})`);let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n;return`rgba(${parseInt(r.slice(0,2),16)},${parseInt(r.slice(2,4),16)},${parseInt(r.slice(4,6),16)},${t})`}var Zh=`
|
|
39
|
+
`).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>wh(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 kh(n.map(e=>{let t=e.split(`
|
|
40
|
+
`).map(e=>e.trim()).filter(Boolean),n=t.filter(e=>/^[-*]\s+/.test(e));if(n.length>=2&&n.length===t.length)return`<ul>${n.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`;let i=e.split(/\s+(?=[-*]\s+\*\*?)/).map(e=>e.trim()).filter(Boolean);return i.length>=2&&i.every(e=>/^[-*]\s+/.test(e))?`<ul>${i.map(e=>`<li>${r(e.replace(/^[-*]\s+/,``))}</li>`).join(``)}</ul>`:`<p>${r(e).replace(/\n/g,`<br />`)}</p>`}).join(``))},jh=new Set([`application/pdf`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`]),Mh=new Set([`.pdf`,`.docx`,`.png`,`.jpg`,`.jpeg`]),Nh=`image/png,image/jpeg,.pdf,.docx`;function Ph(e){if(!e)return!1;let t=typeof e.name==`string`?e.name.toLowerCase():``,n=t.includes(`.`)?`.${t.split(`.`).pop()}`:``,r=typeof e.type==`string`?e.type.toLowerCase():``;return r===`image/png`||r===`image/jpeg`||jh.has(r)||Mh.has(n)}function Fh(e){return e?Ph(e)?e.size>2097152?`File must be 2 MB or smaller.`:``:`Only PNG, JPEG, PDF, and DOCX files are allowed.`:`No file selected.`}function Ih(e=0){if(!Number.isFinite(e)||e<=0)return``;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;let i=n>=10||r===0?0:1;return`${n.toFixed(i)} ${t[r]}`}function Lh(e){return e?e.name||`Attachment`:``}function Rh(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function zh({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,b.useState)(null),o=typeof e==`string`?e.trim():``;return(0,b.useEffect)(()=>{if(!o){a(null);return}a(null);let e=!1,t=new window.Image;return t.onload=()=>{e||a(o)},t.onerror=()=>{e||a(null)},t.src=o,()=>{e=!0}},[o]),i?(0,H.jsx)(`img`,{src:i,alt:``,style:n,onError:()=>a(null)}):(0,H.jsx)(`span`,{style:r,children:Rh(t)})}function Bh({chatHistory:e,isAiTyping:t,isLoading:n,isAgentTyping:r,setReplyContext:i,primaryColor:a=`#3B82F6`,agentHeadshot:o=null,agentDisplayName:s=`Agent`,botAvatarNode:c=null}){let{resolvedConfig:l}=wn(),u=(0,b.useRef)(null),[d,f]=(0,b.useState)(null),[p,m]=(0,b.useState)(null),h=(0,b.useRef)(e.length),g=(0,b.useRef)(!0),_=(0,b.useRef)(null),v=(0,b.useCallback)(e=>{let t=e.target.closest(`a[href]`);if(!t)return;let n=t.getAttribute(`href`)||``;if(!(!n||n.startsWith(`mailto:`)||n.startsWith(`tel:`)||n.startsWith(`javascript:`)))try{let t=new URL(n,window.location.href);if(t.origin!==window.location.origin){e.preventDefault(),window.open(t.href,`_blank`,`noopener,noreferrer`);return}e.preventDefault(),hr(t.href,{siteId:l?.siteId,apiBaseUrl:l?.apiBaseUrl}).then(({allowed:e,correctedUrl:n})=>{e&&Er(n||t.href)})}catch{}},[l]),y=e=>{if(!e)return`just now`;let t=new Date,n=new Date(e),r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`just now`;let i=Math.floor(r/60);if(i<60)return`${i} min${i>1?`s`:``} ago`;let a=Math.floor(i/60);if(a<24)return`${a} hr${a>1?`s`:``} ago`;let o=Math.floor(a/24);return`${o} day${o>1?`s`:``} ago`};return(0,b.useEffect)(()=>{if(g.current){g.current=!1,h.current=e.length,_.current&&(_.current.scrollTop=_.current.scrollHeight);return}let n=e.length>h.current;h.current=e.length,(n||t||r)&&u.current?.scrollIntoView({behavior:`smooth`})},[e.length,t,n,r]),(0,H.jsxs)(`div`,{ref:_,style:{flex:1,overflowY:`auto`,overscrollBehavior:`contain`,padding:`10px 16px 20px`,display:`flex`,flexDirection:`column`,background:`transparent`},children:[e.map(e=>{if(e.type===`call_recording`||typeof e.message==`string`&&e.message.includes(`AI chat recording`))return null;let t=e.sender===`system`,n=e.sender===`user`,r=e.sender===`ai`||e.sender===`bot`,l=e.sender===`agent`,u=e.isPending,d=e.type===`file`&&e.metadata?.fileUrl,h=e.agent_name||e.agentName||e.metadata?.agentName||s,g=typeof e.sender_headshot==`string`&&e.sender_headshot.trim()||typeof o==`string`&&o.trim()||null,_=Ch(e.replyToContent||e.replyContext?.message||``),b=e.replyToSender===`user`?`You`:e.replyToSender===`agent`?`Agent`:e.replyToSender===`ai`||e.replyToSender===`bot`?`AI Assistant`:`Message`;return t?(0,H.jsx)(`div`,{style:{display:`flex`,justifyContent:`center`,margin:`8px 0`},children:(0,H.jsx)(`div`,{style:{padding:`6px 12px`,borderRadius:`9999px`,background:`#f3f4f6`,color:`#6b7280`,fontSize:`12px`,fontWeight:500},children:e.message})},e.id):(0,H.jsxs)(`div`,{style:{display:`flex`,justifyContent:n?`flex-end`:`flex-start`,alignItems:`flex-start`,marginBottom:`16px`,gap:`8px`,flexDirection:`row`},children:[!n&&(r||l)&&(0,H.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:l?`#f3f4f6`:c&&r?`transparent`:`var(--flowengage-primary)`,color:l?a:`#fff`,boxShadow:l?`0 2px 8px rgba(0,0,0,0.06)`:c&&r?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`,border:l?`1px solid ${a}22`:`none`,fontSize:`12px`,fontWeight:800,marginTop:!u&&(r||l)?`22px`:`0px`},children:r?c||(0,H.jsx)(_h,{size:16}):(0,H.jsx)(zh,{src:g||``,name:h,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,H.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:n?`flex-end`:`flex-start`,maxWidth:`75%`,minWidth:0},children:[!u&&l&&(0,H.jsxs)(`button`,{type:`button`,onClick:()=>i(e),style:{opacity:1,marginBottom:`4px`,display:`flex`,alignItems:`center`,gap:`4px`,fontSize:`11px`,color:`#9ca3af`,background:`transparent`,border:0,cursor:`pointer`,padding:0,marginLeft:`2px`},onMouseEnter:e=>{e.currentTarget.style.color=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:[(0,H.jsx)(mh,{}),`Reply`]}),(0,H.jsxs)(`div`,{style:{padding:`8px 16px`,borderRadius:n?`20px 6px 20px 20px`:`6px 20px 20px 20px`,lineHeight:1.8,letterSpacing:0,boxShadow:`0 2px 8px rgba(0,0,0,0.06)`,background:n?`var(--flowengage-primary)`:`rgba(255,255,255,0.92)`,color:n?`#fff`:`#111827`,fontSize:`14px`,fontWeight:400,opacity:u?.55:1,transition:`opacity 0.3s ease`,wordBreak:`break-word`,width:`fit-content`},children:[_&&(0,H.jsxs)(`div`,{style:{marginBottom:`8px`,borderRadius:`14px`,borderLeft:n?`2px solid rgba(255,255,255,0.8)`:`2px solid var(--flowengage-primary)`,padding:`8px 12px`,fontSize:`12px`,background:n?`rgba(255,255,255,0.15)`:`#f9fafb`,color:n?`rgba(255,255,255,0.9)`:`#6b7280`},children:[(0,H.jsx)(`div`,{style:{marginBottom:`2px`,fontWeight:600},children:b}),(0,H.jsx)(`div`,{style:{display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,overflow:`hidden`},children:_})]}),d?(()=>{let t=e.metadata.fileType||``,r=e.metadata.fileName||e.message||`File`,i=Ih(e.metadata.fileSize),a=t.startsWith(`image/`),o=`shared file: ${r}`.toLowerCase(),s=(e.message||``).trim(),c=s&&s.toLowerCase()!==o&&!s.toLowerCase().startsWith(`shared file:`),l=t===`application/pdf`?{color:`#ef4444`,label:`PDF`}:t.includes(`word`)||t.includes(`docx`)?{color:`#3b82f6`,label:`DOCX`}:t.includes(`excel`)||t.includes(`sheet`)||t===`text/csv`?{color:`#10b981`,label:`XLSX`}:{color:`#6b7280`,label:`FILE`};return(0,H.jsxs)(`div`,{style:{minWidth:`200px`,maxWidth:`240px`},children:[c&&(0,H.jsx)(`div`,{style:{marginBottom:`6px`,fontSize:`14px`,color:n?`#fff`:`#111827`,whiteSpace:`normal`,wordBreak:`break-word`},children:s}),a?(0,H.jsx)(`button`,{type:`button`,onClick:()=>f({url:e.metadata.fileUrl,name:r}),onMouseEnter:()=>m(e.id),onMouseLeave:()=>m(null),style:{display:`block`,width:`100%`,background:`transparent`,border:0,padding:0,margin:0,textAlign:`left`,cursor:`pointer`},children:(0,H.jsxs)(`div`,{style:{position:`relative`},children:[(0,H.jsx)(`img`,{src:e.metadata.fileUrl,alt:r,style:{width:`100%`,borderRadius:`10px`,display:`block`,maxHeight:`180px`,objectFit:`cover`}}),(0,H.jsx)(`div`,{style:{position:`absolute`,inset:0,borderRadius:`10px`,background:p===e.id?`rgba(17,24,39,0.32)`:`rgba(17,24,39,0)`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#fff`,fontSize:`13px`,fontWeight:700,letterSpacing:`0.02em`,opacity:p===e.id?1:0,transition:`background 0.18s ease, opacity 0.18s ease`,pointerEvents:`none`},children:`Preview`})]})}):(0,H.jsx)(`a`,{href:e.metadata.fileUrl,target:`_blank`,rel:`noopener noreferrer`,style:{textDecoration:`none`,display:`block`},children:(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`10px`,background:n?`rgba(255,255,255,0.15)`:`#f3f4f6`,borderRadius:`12px`,padding:`10px 12px`},children:[(0,H.jsxs)(`div`,{style:{width:`38px`,height:`46px`,borderRadius:`8px`,background:n?`rgba(255,255,255,0.22)`:`#fff`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 1px 4px rgba(0,0,0,0.1)`,gap:`3px`},children:[(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`#fff`:l.color,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`}),(0,H.jsx)(`polyline`,{points:`14 2 14 8 20 8`})]}),(0,H.jsx)(`span`,{style:{fontSize:`7px`,fontWeight:800,letterSpacing:`0.04em`,color:n?`#fff`:l.color,lineHeight:1},children:l.label})]}),(0,H.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,H.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:n?`#fff`:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:r}),i&&(0,H.jsx)(`div`,{style:{fontSize:`11px`,marginTop:`3px`,color:n?`rgba(255,255,255,0.6)`:`#9ca3af`},children:i})]}),(0,H.jsxs)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:n?`rgba(255,255,255,0.65)`:`#9ca3af`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,H.jsx)(`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`}),(0,H.jsx)(`polyline`,{points:`7 10 12 15 17 10`}),(0,H.jsx)(`line`,{x1:`12`,y1:`15`,x2:`12`,y2:`3`})]})]})})]})})():r?(0,H.jsx)(`div`,{className:`flowengage-message-content fe-bot-message`,dangerouslySetInnerHTML:{__html:Ah(e.message)},onClick:v}):(0,H.jsx)(`div`,{style:{whiteSpace:`pre-wrap`},children:e.message})]}),(0,H.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,marginTop:`4px`,padding:`0 4px`,alignSelf:n?`flex-end`:`flex-start`},children:u?(0,H.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500,fontStyle:`italic`},children:`sending…`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`span`,{style:{fontSize:`10px`,color:`#9ca3af`,fontWeight:500},children:y(e.timestamp||e.createdAt)}),(0,H.jsx)(`span`,{style:{fontSize:`10px`,fontWeight:700,color:n?`var(--flowengage-primary)`:`#9ca3af`},children:`✓`})]})})]})]},e.id)}),(t||n)&&(0,H.jsxs)(`div`,{style:{marginBottom:`16px`,display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,H.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,background:c?`transparent`:`var(--flowengage-primary)`,color:`#fff`,boxShadow:c?`none`:`0 8px 20px rgba(59,130,246,0.24)`,overflow:`hidden`},children:c||(0,H.jsx)(_h,{size:16})}),(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`2px`,color:`#374151`,fontSize:`13px`,fontWeight:500,fontStyle:`italic`},children:[`Analysing`,[0,1,2].map(e=>(0,H.jsx)(`span`,{style:{animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`},children:`.`},e))]})]}),r&&(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:`8px`,marginBottom:`12px`},children:[(0,H.jsx)(`div`,{style:{width:`32px`,height:`32px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,overflow:`hidden`},children:(0,H.jsx)(zh,{src:o||``,name:s,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}),(0,H.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,H.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})]}),(0,H.jsx)(`div`,{ref:u}),d&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>f(null),style:{position:`fixed`,inset:0,zIndex:1e4,border:0,padding:`16px`,margin:0,background:`rgba(2,6,23,0.88)`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`default`},children:(0,H.jsxs)(`div`,{style:{position:`relative`,maxWidth:`min(96vw, 1100px)`,maxHeight:`96vh`,width:`100%`,display:`flex`,flexDirection:`column`,gap:`10px`,alignItems:`center`},children:[(0,H.jsx)(`img`,{src:d.url,alt:d.name,style:{width:`100%`,maxHeight:`calc(96vh - 72px)`,objectFit:`contain`,borderRadius:`16px`,boxShadow:`0 30px 80px rgba(0,0,0,0.42)`}}),(0,H.jsx)(`div`,{style:{maxWidth:`100%`,padding:`8px 14px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.92)`,color:`#0f172a`,fontSize:`12px`,fontWeight:600,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:d.name})]})})]})}var Vh=typeof window<`u`&&(window.matchMedia?.(`(pointer: coarse)`).matches||navigator.maxTouchPoints>0);function Hh({input:e,setInput:t,onSubmit:n,isConversationEnded:r,callUiActive:i,handleToggleVoice:a,activeScreen:o,inputDisabled:s,replyContext:c,clearReplyContext:l,requiresEmail:u,emailInput:d,setEmailInput:f,emailError:p,showVoiceToggle:m=!1,voiceEnabled:h=!0,onFileSelect:g,selectedFile:_=null,onRemoveSelectedFile:v,attachmentError:y=``,isUploadingAttachment:x=!1,inputPlaceholder:S=`Type your message`}){let C=(0,b.useRef)(null),w=(0,b.useRef)(null),T=e=>{e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)};(0,b.useEffect)(()=>{u||T(w.current)},[e,u]),(0,b.useEffect)(()=>{u||Vh||e||s||w.current?.focus()},[e,u,s]);let E=e=>{e.key===`Enter`&&(Vh||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||(e.preventDefault(),e.currentTarget.form?.requestSubmit()))},ee=c?.sender===`user`?`You`:c?.sender===`agent`?`Agent`:`AI Assistant`,D=u?!!d?.trim():!!e?.trim()||!!_,O=s||x||!D,k=!u&&h&&m;return(0,H.jsxs)(`div`,{style:{padding:`0 16px`,background:`transparent`},children:[c&&(0,H.jsxs)(`div`,{style:{marginBottom:`8px`,display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.05)`,background:`#fff`,padding:`12px 16px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,H.jsxs)(`div`,{style:{minWidth:0,flex:1,borderLeft:`2px solid var(--flowengage-primary)`,paddingLeft:`12px`},children:[(0,H.jsxs)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`},children:[`Replying to `,ee]}),(0,H.jsx)(`div`,{style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,fontSize:`12px`,color:`#6b7280`},children:c.replyToContent||c.message})]}),(0,H.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`},onClick:l,"aria-label":`Cancel reply`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),u&&(0,H.jsx)(`div`,{style:{marginBottom:`8px`,padding:`0 8px`},children:(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`#111827`,fontSize:`14px`,fontWeight:500,textAlign:`center`},children:[(0,H.jsx)(`span`,{style:{display:`inline-flex`,width:`22px`,height:`22px`,borderRadius:`9999px`,alignItems:`center`,justifyContent:`center`,background:`rgba(59,130,246,0.08)`,color:`var(--flowengage-primary)`},children:(0,H.jsx)(_h,{size:13})}),(0,H.jsx)(`span`,{children:`Please provide your email address so we can help you.`})]})}),_&&!u&&(0,H.jsxs)(`div`,{style:{marginBottom:`10px`,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`12px`,borderRadius:`16px`,border:`1px solid rgba(0,0,0,0.06)`,background:`#fff`,padding:`12px 14px`,boxShadow:`0 8px 24px rgba(0,0,0,0.05)`},children:[(0,H.jsxs)(`div`,{style:{minWidth:0,flex:1},children:[(0,H.jsx)(`div`,{style:{fontSize:`12px`,fontWeight:600,color:`var(--flowengage-primary)`,marginBottom:`2px`},children:`Attachment ready`}),(0,H.jsx)(`div`,{style:{fontSize:`13px`,color:`#111827`,whiteSpace:`nowrap`,overflow:`hidden`,textOverflow:`ellipsis`},children:Lh(_)}),(0,H.jsx)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginTop:`2px`},children:Ih(_.size)})]}),(0,H.jsx)(`button`,{type:`button`,style:{width:`28px`,height:`28px`,borderRadius:`9999px`,border:0,background:`#f3f4f6`,color:`#6b7280`,transition:`color 0.2s ease, background 0.2s ease`,cursor:`pointer`,flexShrink:0},onClick:v,"aria-label":`Remove attachment`,onMouseEnter:e=>{e.currentTarget.style.background=`#e5e7eb`,e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.background=`#f3f4f6`,e.currentTarget.style.color=`#6b7280`},children:`×`})]}),(0,H.jsxs)(`form`,{style:{display:`flex`,alignItems:`flex-end`,gap:`8px`,minHeight:`40px`,padding:`4px`,border:`1px solid rgba(0,0,0,0.06)`,borderRadius:`20px`,background:`#fff`,boxShadow:`0 4px 14px rgba(0,0,0,0.04)`,opacity:1},onSubmit:n,children:[k?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`input`,{ref:C,type:`file`,accept:Nh,style:{display:`none`},onChange:e=>{let t=e.target.files?.[0];t&&g?.(t),e.target.value=``}}),(0,H.jsx)(`button`,{type:`button`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`#f3f4f8`,color:`var(--flowengage-primary)`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`background 0.2s ease, opacity 0.2s ease`,border:0,cursor:`pointer`,flexShrink:0},onClick:()=>C.current?.click(),title:`Attach file`,"aria-label":`Attach file`,disabled:x,onMouseEnter:e=>{e.currentTarget.style.opacity=`0.8`},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,H.jsx)(vh,{size:16,color:`currentColor`})})]}):null,u?(0,H.jsx)(`input`,{className:`flowengage-chat-text-input`,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,outline:`none`,padding:0,paddingLeft:k?`0`:`8px`,color:`#111827`,background:`transparent`,cursor:`text`,alignSelf:`center`},value:d,onChange:e=>f(e.target.value),placeholder:`Enter your Email`,disabled:s,type:`email`,autoComplete:`email`}):(0,H.jsx)(`textarea`,{ref:w,className:`flowengage-chat-text-input`,rows:1,style:{flex:1,minWidth:0,border:`none`,fontFamily:`inherit`,fontSize:`14px`,lineHeight:`20px`,outline:`none`,padding:`6px 0`,paddingLeft:k?`0`:`8px`,color:`#111827`,background:`transparent`,cursor:`text`,resize:`none`,maxHeight:`120px`,overflowY:`auto`},value:e,onChange:e=>{t(e.target.value),T(e.target)},onKeyDown:E,placeholder:o===`agent`?`Message the agent…`:S,disabled:s,autoComplete:`off`}),(0,H.jsx)(`button`,{type:`submit`,style:{width:`32px`,height:`32px`,borderRadius:`9999px`,background:`var(--flowengage-primary)`,color:`#fff`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`opacity 0.2s ease`,cursor:O?`not-allowed`:`pointer`,opacity:O?.45:1,flexShrink:0},disabled:O,onMouseEnter:e=>{O||(e.currentTarget.style.opacity=`0.85`)},onMouseLeave:e=>{e.currentTarget.style.opacity=`1`},children:(0,H.jsx)(ph,{size:16})})]}),!u&&y&&(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`7px 4px 0`},children:[(0,H.jsxs)(`svg`,{width:`13`,height:`13`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#dc2626`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:[(0,H.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,H.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,H.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),(0,H.jsx)(`span`,{style:{fontSize:`11px`,color:`#dc2626`,fontWeight:500},children:y})]}),u&&p&&(0,H.jsx)(`div`,{style:{padding:`8px 16px 0`,fontSize:`12px`,fontWeight:500,color:`#f43f5e`},children:p})]})}function Uh({webRTCError:e,micError:t,setMicError:n,dismissCallError:r,isRateLimited:i,rateLimitMessage:a}){return(0,H.jsxs)(H.Fragment,{children:[(e||t)&&(0,H.jsxs)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,borderRadius:`12px`,background:`#fef2f2`,border:`1px solid #fee2e2`,display:`flex`,alignItems:`flex-start`,gap:`10px`},children:[(0,H.jsx)(gh,{className:``}),(0,H.jsx)(`span`,{style:{fontSize:`12px`,color:`#b91c1c`,lineHeight:1.5,flex:1},children:e||t}),(0,H.jsx)(`button`,{style:{flexShrink:0,background:`transparent`,border:0,color:`#f87171`,cursor:`pointer`,fontSize:`18px`,lineHeight:1},onClick:()=>{n(null),r()},onMouseEnter:e=>{e.currentTarget.style.color=`#dc2626`},onMouseLeave:e=>{e.currentTarget.style.color=`#f87171`},children:`×`})]}),i&&(0,H.jsx)(`div`,{style:{margin:`0 20px 10px`,padding:`12px 16px`,fontSize:`13px`,borderRadius:`12px`,background:`#fee2e2`,color:`#991b1b`},children:a})]})}var Wh=[`#135bd8`,`#ef334b`,`#ffbd2e`];function Gh(e){return!Array.isArray(e)||e.length===0?Wh:e.length===1?[e[0],e[0],e[0]]:e.length===2?[e[0],e[1],e[0]]:[e[0],e[1],e[2]]}var Kh={idle:3,listening:.75,thinking:1,speaking:1.4,muted:.75,error:.08};function qh(e){if(!e||typeof e!=`string`)return[0,0,0];let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}function Jh(e,t){if(!e||typeof e!=`string`)return`rgba(0,0,0,${t})`;if(e.startsWith(`rgb`))return e.replace(/[\d.]+\)$/,`${t})`);let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n;return`rgba(${parseInt(r.slice(0,2),16)},${parseInt(r.slice(2,4),16)},${parseInt(r.slice(4,6),16)},${t})`}var Yh=`
|
|
41
41
|
attribute vec2 a_pos;
|
|
42
42
|
varying vec2 v_uv;
|
|
43
43
|
void main() {
|
|
44
44
|
v_uv = a_pos * 0.5 + 0.5;
|
|
45
45
|
gl_Position = vec4(a_pos, 0.0, 1.0);
|
|
46
46
|
}
|
|
47
|
-
`,
|
|
47
|
+
`,Xh=`
|
|
48
48
|
precision highp float;
|
|
49
49
|
|
|
50
50
|
varying vec2 v_uv;
|
|
@@ -159,7 +159,7 @@ Error generating stack: `+e.message+`
|
|
|
159
159
|
|
|
160
160
|
gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
|
|
161
161
|
}
|
|
162
|
-
`;function
|
|
162
|
+
`;function Zh(e,t,n){let r=(t,n)=>{let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS)?r:(console.error(`[AnimatedOrb shader]`,e.getShaderInfoLog(r)),null)},i=r(e.VERTEX_SHADER,t),a=r(e.FRAGMENT_SHADER,n);if(!i||!a)return null;let o=e.createProgram();return e.attachShader(o,i),e.attachShader(o,a),e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)?o:(console.error(`[AnimatedOrb link]`,e.getProgramInfoLog(o)),null)}function Qh({size:e=94,voiceState:t=`idle`,isMuted:n=!1,colors:r,onClick:i,style:a,className:o}){let[s,c,l]=Gh(r),u=t===`speaking`,d=e<=50,f=(0,b.useRef)(null),p=(0,b.useRef)(Kh[t]??.35);(0,b.useEffect)(()=>{p.current=Kh[t]??.35},[t]),(0,b.useEffect)(()=>{let t=f.current;if(!t)return;let n=Math.min(window.devicePixelRatio||1,2);t.width=e*n,t.height=e*n;let r=t.getContext(`webgl`,{alpha:!0,antialias:!0})||t.getContext(`experimental-webgl`,{alpha:!0,antialias:!0});if(!r){console.warn(`[AnimatedOrb] WebGL unavailable.`);return}let i=Zh(r,Yh,Xh);if(!i){console.error(`[AnimatedOrb] WebGL program failed to compile/link`);return}r.useProgram(i);let a=r.createBuffer();r.bindBuffer(r.ARRAY_BUFFER,a),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),r.STATIC_DRAW);let o=r.getAttribLocation(i,`a_pos`);r.enableVertexAttribArray(o),r.vertexAttribPointer(o,2,r.FLOAT,!1,0,0);let u={time:r.getUniformLocation(i,`u_time`),speed:r.getUniformLocation(i,`u_speed`),c1:r.getUniformLocation(i,`u_c1`),c2:r.getUniformLocation(i,`u_c2`),c3:r.getUniformLocation(i,`u_c3`)};r.uniform3fv(u.c1,qh(s)),r.uniform3fv(u.c2,qh(c)),r.uniform3fv(u.c3,qh(l)),r.viewport(0,0,t.width,t.height);let d=performance.now(),m,h=e=>{r.uniform1f(u.time,(e-d)/1e3),r.uniform1f(u.speed,p.current),r.drawArrays(r.TRIANGLES,0,6),m=requestAnimationFrame(h)};return m=requestAnimationFrame(h),()=>{cancelAnimationFrame(m),r.deleteProgram(i),r.deleteBuffer(a)}},[s,c,l,e]);let m=n?`saturate(0.3) brightness(1.1)`:t===`error`?`saturate(0.4) hue-rotate(28deg)`:`none`;return(0,H.jsxs)(`div`,{style:{position:`relative`,width:e,height:e,flexShrink:0,cursor:i?`pointer`:`default`,...a},className:o,onClick:i,children:[u&&!d&&(0,H.jsx)(Km.div,{style:{position:`absolute`,inset:-10,borderRadius:`50%`,background:`radial-gradient(circle, ${Jh(s,.18)} 0%, transparent 70%)`,pointerEvents:`none`},animate:{opacity:[.3,.75]},transition:{duration:1,repeat:1/0,repeatType:`mirror`,ease:`easeInOut`}}),(0,H.jsx)(`div`,{style:{width:e,height:e,borderRadius:`50%`,overflow:`hidden`,WebkitMaskImage:`-webkit-radial-gradient(white, black)`,filter:m,transition:`filter 1.2s ease`},children:(0,H.jsx)(`canvas`,{ref:f,style:{width:`100%`,height:`100%`,display:`block`}})}),u&&(0,H.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,pointerEvents:`none`,zIndex:1},children:(0,H.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`3px`},children:[4,8,12,8,4].map((e,t)=>(0,H.jsx)(Km.div,{style:{width:`3px`,borderRadius:`3px`,background:`rgba(255,255,255,0.85)`},animate:{height:[4,e+8,4]},transition:{duration:.48,delay:t*.08,repeat:1/0,ease:`easeInOut`}},t))})})]})}var $h=`
|
|
163
163
|
@keyframes fe-call-ring-pulse {
|
|
164
164
|
0% { transform: scale(1); opacity: 0.55; }
|
|
165
165
|
70% { transform: scale(1.85); opacity: 0; }
|
|
@@ -188,9 +188,9 @@ Error generating stack: `+e.message+`
|
|
|
188
188
|
0%, 100% { opacity: 0.5; transform: scale(1); }
|
|
189
189
|
50% { opacity: 0.9; transform: scale(1.12); }
|
|
190
190
|
}
|
|
191
|
-
`;function ng(e){let t=(e||``).replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return`${parseInt(n.slice(0,2),16)},${parseInt(n.slice(2,4),16)},${parseInt(n.slice(4,6),16)}`}function rg(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 ig(e,t){let n=Array.isArray(e)&&e.length>0?e:[t||`#3B82F6`],[r,i,a]=n;return n.length===1?[`radial-gradient(ellipse 110% 65% at 50% -5%, ${r}28 0%, transparent 68%)`,`radial-gradient(ellipse 90% 55% at 50% 108%, ${r}1a 0%, transparent 65%)`,`#f7f8fa`].join(`, `):n.length===2?[`radial-gradient(ellipse 80% 100% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${i}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 70% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${i}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${a}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function ag({headshot:e,name:t,size:n=80,primaryColor:r=`#3B82F6`}){let i=(t||`A`)[0].toUpperCase(),a=rg(r),o=n>48?{boxShadow:`0 0 0 3px ${r}44`,border:`3px solid rgba(255,255,255,0.15)`}:{border:`1.5px solid ${r}55`};return e?(0,H.jsx)(`img`,{src:e,alt:t||`Agent`,style:{width:n,height:n,borderRadius:`50%`,objectFit:`cover`,position:`relative`,zIndex:1,flexShrink:0,...o}}):(0,H.jsx)(`div`,{style:{width:n,height:n,borderRadius:`50%`,background:`linear-gradient(135deg, ${r}, ${r}99)`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:Math.round(n*.36)+`px`,fontWeight:700,color:a,position:`relative`,zIndex:1,flexShrink:0,...o},children:i})}function og(e){let t=(0,b.useRef)(null),n=(0,b.useCallback)(()=>{if(!t.current)return;let{audioContext:e,oscillator:n,interval:r,toneTimeout:i}=t.current;window.clearInterval(r),window.clearTimeout(i);try{n.stop()}catch{}try{e.close()}catch{}t.current=null},[]),r=(0,b.useCallback)(()=>{if(t.current||typeof window>`u`)return;let e=window.AudioContext||window.webkitAudioContext||null;if(e)try{let n=new e,r=n.createOscillator(),i=n.createGain();r.connect(i),i.connect(n.destination),r.frequency.value=0,r.type=`sine`,i.gain.value=.3;let a=()=>{t.current&&(window.clearTimeout(t.current.toneTimeout),r.frequency.value=440,t.current.toneTimeout=window.setTimeout(()=>{r.frequency.value=0},400))};n.state===`suspended`&&n.resume().catch(e=>{console.warn(`[FlowEngage] ringtone autoplay blocked`,e)}),r.start(),t.current={audioContext:n,oscillator:r,interval:null,toneTimeout:null},a(),t.current.interval=window.setInterval(a,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);return(0,b.useEffect)(()=>{if(e){r();return}n()},[e,r,n]),(0,b.useEffect)(()=>()=>n(),[n]),n}function sg({incomingCall:e,activeCallId:t,callConnectionState:n,callDurationSeconds:r,isCallMuted:i,agentName:a,agentHeadshot:o,fallbackAgentName:s,acceptCall:c,rejectCall:l,endWebRTCCall:u,toggleCallMute:d,formatCallDuration:f,onMinimize:p,primaryColor:m=`#3B82F6`,orbColors:h,chatHistory:g=[]}){let _=a||s||`Agent`,v=e?`incoming`:n===`connecting`?`connecting`:`ongoing`,y=og(!!e),b=async()=>{y(),await c()},x=async()=>{y(),await l()},S=i?`muted`:n===`connecting`?`idle`:`listening`,C=v===`ongoing`,w={position:`absolute`,inset:0,zIndex:10,display:`flex`,flexDirection:`column`,borderRadius:`inherit`,overflow:`hidden`,background:ig(h,m),animation:C?`fe-call-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`:`fe-call-fade-in 0.32s ease`};if(v===`incoming`){let e=Array.isArray(h)&&h.length>0?h:[m];return(0,H.jsxs)(`div`,{style:w,children:[(0,H.jsx)(`style`,{children:tg}),(0,H.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,padding:`60px 32px 56px`},children:[(0,H.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`22px`},children:[(0,H.jsxs)(`div`,{style:{position:`relative`,width:`96px`,height:`96px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,H.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,background:`radial-gradient(circle, rgba(${ng(e[0])},0.2) 0%, transparent 70%)`,filter:`blur(10px)`,zIndex:0}}),[0,.5,1].map((t,n)=>(0,H.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,border:`1.5px solid ${e[n%e.length]}`,animation:`fe-call-ring-pulse 2.6s cubic-bezier(0.215,0.61,0.355,1) ${t}s infinite`,zIndex:1}},n)),(0,H.jsx)(ag,{headshot:o,name:_,size:82,primaryColor:m})]}),(0,H.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,H.jsx)(`div`,{style:{fontSize:`22px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.015em`,lineHeight:1.2},children:_}),(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`6px`,marginTop:`8px`},children:[(0,H.jsx)(`div`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:e[0],boxShadow:`0 0 5px ${e[0]}88`,animation:`fe-call-dot-blink 1.4s ease-in-out infinite`}}),(0,H.jsx)(`span`,{style:{fontSize:`13px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Incoming call`})]})]})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`56px`,alignItems:`flex-end`},children:[(0,H.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,H.jsx)(`button`,{type:`button`,onClick:x,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(239,68,68,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(239,68,68,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(239,68,68,0.5)`},"aria-label":`Decline call`,children:(0,H.jsx)(mh,{size:26})}),(0,H.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Decline`})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,H.jsx)(`button`,{type:`button`,onClick:b,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#22c55e`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(34,197,94,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(34,197,94,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(34,197,94,0.5)`},"aria-label":`Accept call`,children:(0,H.jsx)(_h,{})}),(0,H.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Accept`})]})]})]})]})}return v===`connecting`?(0,H.jsxs)(`div`,{style:w,children:[(0,H.jsx)(`style`,{children:tg}),(0,H.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`24px`},children:[(0,H.jsx)(ag,{headshot:o,name:_,size:64,primaryColor:m}),(0,H.jsx)(`div`,{style:{width:`48px`,height:`48px`,borderRadius:`50%`,border:`3px solid rgba(255,255,255,0.12)`,borderTopColor:Array.isArray(h)&&h[0]||m,animation:`fe-call-spin 0.9s linear infinite`}}),(0,H.jsx)(`span`,{style:{fontSize:`15px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Connecting…`})]})]}):(0,H.jsxs)(`div`,{style:w,children:[(0,H.jsx)(`style`,{children:tg}),(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px 16px 10px`,gap:`10px`,flexShrink:0},children:[(0,H.jsx)(`button`,{type:`button`,onClick:p,style:{width:`40px`,height:`40px`,borderRadius:`50%`,background:`rgba(0,0,0,0.06)`,border:`1px solid rgba(0,0,0,0.1)`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#374151`,transition:`background 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.11)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.06)`},"aria-label":`Minimize call`,children:(0,H.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`polyline`,{points:`15 18 9 12 15 6`})})}),(0,H.jsx)(eg,{colors:h,size:36,voiceState:S}),(0,H.jsx)(`div`,{style:{flex:1,minWidth:0,fontSize:`15px`,fontWeight:600,color:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:_}),(0,H.jsx)(`div`,{style:{flexShrink:0,padding:`3px 10px`,borderRadius:`999px`,background:`${m}18`,border:`1px solid ${m}44`,display:`flex`,alignItems:`center`},children:(0,H.jsx)(`span`,{style:{fontSize:`11px`,fontWeight:600,color:m,letterSpacing:`0.02em`,lineHeight:1},children:`On Call`})})]}),(0,H.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`,padding:`0 24px 16px`},children:[(0,H.jsx)(ag,{headshot:o,name:_,size:116,primaryColor:m}),(0,H.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,H.jsx)(`div`,{style:{fontSize:`20px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.01em`},children:_}),(0,H.jsx)(`div`,{style:{marginTop:`8px`,fontSize:`24px`,fontWeight:300,color:`#9ca3af`,letterSpacing:`0.06em`,fontVariantNumeric:`tabular-nums`},children:f(r)})]})]}),(0,H.jsxs)(`div`,{style:{flexShrink:0,display:`flex`,gap:`12px`,padding:`16px 24px 40px`},children:[(0,H.jsxs)(`button`,{type:`button`,onClick:d,style:{flex:1,height:`54px`,borderRadius:`14px`,background:i?`rgba(239,68,68,0.1)`:`rgba(0,0,0,0.06)`,border:i?`1.5px solid rgba(239,68,68,0.4)`:`1.5px solid rgba(0,0,0,0.1)`,cursor:`pointer`,color:i?`#ef4444`:`#374151`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,fontSize:`14px`,fontWeight:600,transition:`all 0.2s ease`},"aria-label":i?`Unmute`:`Mute`,children:[i?(0,H.jsx)(wh,{size:18}):(0,H.jsx)(ph,{size:18}),i?`Unmute`:`Mute`]}),(0,H.jsxs)(`button`,{type:`button`,onClick:u,style:{flex:1,height:`54px`,borderRadius:`14px`,background:`rgba(239,68,68,0.9)`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`white`,fontSize:`14px`,fontWeight:600,boxShadow:`0 4px 20px rgba(239,68,68,0.38)`,transition:`transform 0.15s ease, background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#ef4444`,e.currentTarget.style.transform=`scale(1.02)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(239,68,68,0.9)`,e.currentTarget.style.transform=`scale(1)`},"aria-label":`End call`,children:[(0,H.jsx)(mh,{size:18}),`End Call`]})]})]})}function cg({agentName:e,agentHeadshot:t,fallbackAgentName:n,callDurationSeconds:r,isCallMuted:i,formatCallDuration:a,toggleCallMute:o,endWebRTCCall:s,onExpand:c,primaryColor:l=`#3B82F6`}){let u=e||n||`Agent`;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`style`,{children:tg}),(0,H.jsxs)(`div`,{role:`button`,tabIndex:0,onClick:c,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&c?.()},onMouseEnter:e=>{e.currentTarget.style.boxShadow=`0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08), inset 0 1px 0 rgba(255,255,255,0.95)`,e.currentTarget.style.transform=`translateY(-2px)`},onMouseLeave:e=>{e.currentTarget.style.boxShadow=`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,e.currentTarget.style.transform=`translateY(0)`},style:{display:`flex`,alignItems:`center`,gap:`12px`,padding:`10px 12px 10px 10px`,margin:`0 12px 8px`,borderRadius:`18px`,background:`rgba(255,255,255,0.88)`,backdropFilter:`blur(20px)`,WebkitBackdropFilter:`blur(20px)`,border:`1px solid rgba(255,255,255,0.65)`,boxShadow:`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,cursor:`pointer`,animation:`fe-call-bar-slide-in 0.3s cubic-bezier(0.16,1,0.3,1)`,flexShrink:0,userSelect:`none`,outline:`none`,transition:`box-shadow 0.22s ease, transform 0.18s ease`},children:[(0,H.jsxs)(`div`,{style:{position:`relative`,flexShrink:0,width:`42px`,height:`42px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,H.jsx)(`div`,{style:{position:`absolute`,inset:`-4px`,borderRadius:`50%`,background:`${l}28`,animation:`fe-call-avatar-breathe 2.8s ease-in-out infinite`}}),(0,H.jsx)(`div`,{style:{position:`absolute`,inset:`-2px`,borderRadius:`50%`,border:`1.5px solid ${l}55`}}),(0,H.jsx)(ag,{headshot:t,name:u,size:38,primaryColor:l})]}),(0,H.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,H.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:`#111827`,lineHeight:1.3,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:u}),(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,marginTop:`3px`},children:[(0,H.jsx)(`div`,{style:{width:`6px`,height:`6px`,borderRadius:`50%`,background:`#22c55e`,flexShrink:0,boxShadow:`0 0 4px rgba(34,197,94,0.6)`,animation:`fe-call-dot-blink 1.6s ease-in-out infinite`}}),(0,H.jsxs)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontVariantNumeric:`tabular-nums`,letterSpacing:`0.01em`},children:[`On Call\xA0•\xA0`,a(r)]})]})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`,flexShrink:0},children:[(0,H.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:i?`${l}18`:`rgba(0,0,0,0.05)`,border:i?`1.5px solid ${l}55`:`1.5px solid rgba(0,0,0,0.08)`,cursor:`pointer`,color:i?l:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,transition:`all 0.18s ease`,boxShadow:i?`0 0 0 3px ${l}12`:`none`},"aria-label":i?`Unmute`:`Mute`,children:i?(0,H.jsx)(wh,{size:15}):(0,H.jsx)(ph,{size:15})}),(0,H.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),s()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`,e.currentTarget.style.boxShadow=`0 4px 16px rgba(239,68,68,0.55)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 2px 10px rgba(239,68,68,0.35)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,color:`white`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 2px 10px rgba(239,68,68,0.35)`,transition:`all 0.18s ease`},"aria-label":`End call`,children:(0,H.jsx)(mh,{size:16})})]})]})]})}function lg(e,t={}){let n=t.maxChars??4500;if(!Array.isArray(e)||e.length===0)return``;let r=[];for(let t of e){if(!t||t.isPending)continue;let e=String(t.sender||``).toLowerCase(),n=null;if(e===`user`?n=`Visitor`:(e===`bot`||e===`ai`||e===`agent`)&&(n=`Assistant`),!n)continue;let i=String(t.message||``).replace(/<[^>]+>/g,` `).replace(/\s+/g,` `).trim().slice(0,1200);i&&r.push(`${n}: ${i}`)}if(r.length===0)return``;let i=r.join(`
|
|
191
|
+
`;function eg(e){let t=(e||``).replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t;return`${parseInt(n.slice(0,2),16)},${parseInt(n.slice(2,4),16)},${parseInt(n.slice(4,6),16)}`}function tg(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 ng(e,t){let n=Array.isArray(e)&&e.length>0?e:[t||`#3B82F6`],[r,i,a]=n;return n.length===1?[`radial-gradient(ellipse 110% 65% at 50% -5%, ${r}28 0%, transparent 68%)`,`radial-gradient(ellipse 90% 55% at 50% 108%, ${r}1a 0%, transparent 65%)`,`#f7f8fa`].join(`, `):n.length===2?[`radial-gradient(ellipse 80% 100% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${i}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 70% at -10% 50%, ${r}22 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${i}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${a}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function rg({headshot:e,name:t,size:n=80,primaryColor:r=`#3B82F6`}){let i=(t||`A`)[0].toUpperCase(),a=tg(r),o=n>48?{boxShadow:`0 0 0 3px ${r}44`,border:`3px solid rgba(255,255,255,0.15)`}:{border:`1.5px solid ${r}55`};return e?(0,H.jsx)(`img`,{src:e,alt:t||`Agent`,style:{width:n,height:n,borderRadius:`50%`,objectFit:`cover`,position:`relative`,zIndex:1,flexShrink:0,...o}}):(0,H.jsx)(`div`,{style:{width:n,height:n,borderRadius:`50%`,background:`linear-gradient(135deg, ${r}, ${r}99)`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:Math.round(n*.36)+`px`,fontWeight:700,color:a,position:`relative`,zIndex:1,flexShrink:0,...o},children:i})}function ig(e){let t=(0,b.useRef)(null),n=(0,b.useCallback)(()=>{if(!t.current)return;let{audioContext:e,oscillator:n,interval:r,toneTimeout:i}=t.current;window.clearInterval(r),window.clearTimeout(i);try{n.stop()}catch{}try{e.close()}catch{}t.current=null},[]),r=(0,b.useCallback)(()=>{if(t.current||typeof window>`u`)return;let e=window.AudioContext||window.webkitAudioContext||null;if(e)try{let n=new e,r=n.createOscillator(),i=n.createGain();r.connect(i),i.connect(n.destination),r.frequency.value=0,r.type=`sine`,i.gain.value=.3;let a=()=>{t.current&&(window.clearTimeout(t.current.toneTimeout),r.frequency.value=440,t.current.toneTimeout=window.setTimeout(()=>{r.frequency.value=0},400))};n.state===`suspended`&&n.resume().catch(e=>{console.warn(`[FlowEngage] ringtone autoplay blocked`,e)}),r.start(),t.current={audioContext:n,oscillator:r,interval:null,toneTimeout:null},a(),t.current.interval=window.setInterval(a,1e3)}catch(e){console.warn(`[FlowEngage] failed to start ringtone`,e)}},[]);return(0,b.useEffect)(()=>{if(e){r();return}n()},[e,r,n]),(0,b.useEffect)(()=>()=>n(),[n]),n}function ag({incomingCall:e,activeCallId:t,callConnectionState:n,callDurationSeconds:r,isCallMuted:i,agentName:a,agentHeadshot:o,fallbackAgentName:s,acceptCall:c,rejectCall:l,endWebRTCCall:u,toggleCallMute:d,formatCallDuration:f,onMinimize:p,primaryColor:m=`#3B82F6`,orbColors:h,chatHistory:g=[]}){let _=a||s||`Agent`,v=e?`incoming`:n===`connecting`?`connecting`:`ongoing`,y=ig(!!e),b=async()=>{y(),await c()},x=async()=>{y(),await l()},S=i?`muted`:n===`connecting`?`idle`:`listening`,C=v===`ongoing`,w={position:`absolute`,inset:0,zIndex:10,display:`flex`,flexDirection:`column`,borderRadius:`inherit`,overflow:`hidden`,background:ng(h,m),animation:C?`fe-call-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`:`fe-call-fade-in 0.32s ease`};if(v===`incoming`){let e=Array.isArray(h)&&h.length>0?h:[m];return(0,H.jsxs)(`div`,{style:w,children:[(0,H.jsx)(`style`,{children:$h}),(0,H.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,padding:`60px 32px 56px`},children:[(0,H.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`22px`},children:[(0,H.jsxs)(`div`,{style:{position:`relative`,width:`96px`,height:`96px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,H.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,background:`radial-gradient(circle, rgba(${eg(e[0])},0.2) 0%, transparent 70%)`,filter:`blur(10px)`,zIndex:0}}),[0,.5,1].map((t,n)=>(0,H.jsx)(`div`,{style:{position:`absolute`,width:`96px`,height:`96px`,borderRadius:`50%`,border:`1.5px solid ${e[n%e.length]}`,animation:`fe-call-ring-pulse 2.6s cubic-bezier(0.215,0.61,0.355,1) ${t}s infinite`,zIndex:1}},n)),(0,H.jsx)(rg,{headshot:o,name:_,size:82,primaryColor:m})]}),(0,H.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,H.jsx)(`div`,{style:{fontSize:`22px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.015em`,lineHeight:1.2},children:_}),(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`6px`,marginTop:`8px`},children:[(0,H.jsx)(`div`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:e[0],boxShadow:`0 0 5px ${e[0]}88`,animation:`fe-call-dot-blink 1.4s ease-in-out infinite`}}),(0,H.jsx)(`span`,{style:{fontSize:`13px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Incoming call`})]})]})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`56px`,alignItems:`flex-end`},children:[(0,H.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,H.jsx)(`button`,{type:`button`,onClick:x,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(239,68,68,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(239,68,68,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(239,68,68,0.5)`},"aria-label":`Decline call`,children:(0,H.jsx)(fh,{size:26})}),(0,H.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Decline`})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`10px`},children:[(0,H.jsx)(`button`,{type:`button`,onClick:b,style:{width:`68px`,height:`68px`,borderRadius:`50%`,background:`#22c55e`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`white`,boxShadow:`0 6px 24px rgba(34,197,94,0.5)`,transition:`transform 0.15s ease, box-shadow 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.08)`,e.currentTarget.style.boxShadow=`0 8px 28px rgba(34,197,94,0.65)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 6px 24px rgba(34,197,94,0.5)`},"aria-label":`Accept call`,children:(0,H.jsx)(hh,{})}),(0,H.jsx)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontWeight:500,letterSpacing:`0.01em`},children:`Accept`})]})]})]})]})}return v===`connecting`?(0,H.jsxs)(`div`,{style:w,children:[(0,H.jsx)(`style`,{children:$h}),(0,H.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`24px`},children:[(0,H.jsx)(rg,{headshot:o,name:_,size:64,primaryColor:m}),(0,H.jsx)(`div`,{style:{width:`48px`,height:`48px`,borderRadius:`50%`,border:`3px solid rgba(255,255,255,0.12)`,borderTopColor:Array.isArray(h)&&h[0]||m,animation:`fe-call-spin 0.9s linear infinite`}}),(0,H.jsx)(`span`,{style:{fontSize:`15px`,color:`#6b7280`,letterSpacing:`0.01em`},children:`Connecting…`})]})]}):(0,H.jsxs)(`div`,{style:w,children:[(0,H.jsx)(`style`,{children:$h}),(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px 16px 10px`,gap:`10px`,flexShrink:0},children:[(0,H.jsx)(`button`,{type:`button`,onClick:p,style:{width:`40px`,height:`40px`,borderRadius:`50%`,background:`rgba(0,0,0,0.06)`,border:`1px solid rgba(0,0,0,0.1)`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,color:`#374151`,transition:`background 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.11)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(0,0,0,0.06)`},"aria-label":`Minimize call`,children:(0,H.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`polyline`,{points:`15 18 9 12 15 6`})})}),(0,H.jsx)(Qh,{colors:h,size:36,voiceState:S}),(0,H.jsx)(`div`,{style:{flex:1,minWidth:0,fontSize:`15px`,fontWeight:600,color:`#111827`,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:_}),(0,H.jsx)(`div`,{style:{flexShrink:0,padding:`3px 10px`,borderRadius:`999px`,background:`${m}18`,border:`1px solid ${m}44`,display:`flex`,alignItems:`center`},children:(0,H.jsx)(`span`,{style:{fontSize:`11px`,fontWeight:600,color:m,letterSpacing:`0.02em`,lineHeight:1},children:`On Call`})})]}),(0,H.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`,padding:`0 24px 16px`},children:[(0,H.jsx)(rg,{headshot:o,name:_,size:116,primaryColor:m}),(0,H.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,H.jsx)(`div`,{style:{fontSize:`20px`,fontWeight:700,color:`#111827`,letterSpacing:`-0.01em`},children:_}),(0,H.jsx)(`div`,{style:{marginTop:`8px`,fontSize:`24px`,fontWeight:300,color:`#9ca3af`,letterSpacing:`0.06em`,fontVariantNumeric:`tabular-nums`},children:f(r)})]})]}),(0,H.jsxs)(`div`,{style:{flexShrink:0,display:`flex`,gap:`12px`,padding:`16px 24px 40px`},children:[(0,H.jsxs)(`button`,{type:`button`,onClick:d,style:{flex:1,height:`54px`,borderRadius:`14px`,background:i?`rgba(239,68,68,0.1)`:`rgba(0,0,0,0.06)`,border:i?`1.5px solid rgba(239,68,68,0.4)`:`1.5px solid rgba(0,0,0,0.1)`,cursor:`pointer`,color:i?`#ef4444`:`#374151`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,fontSize:`14px`,fontWeight:600,transition:`all 0.2s ease`},"aria-label":i?`Unmute`:`Mute`,children:[i?(0,H.jsx)(Sh,{size:18}):(0,H.jsx)(dh,{size:18}),i?`Unmute`:`Mute`]}),(0,H.jsxs)(`button`,{type:`button`,onClick:u,style:{flex:1,height:`54px`,borderRadius:`14px`,background:`rgba(239,68,68,0.9)`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`8px`,color:`white`,fontSize:`14px`,fontWeight:600,boxShadow:`0 4px 20px rgba(239,68,68,0.38)`,transition:`transform 0.15s ease, background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#ef4444`,e.currentTarget.style.transform=`scale(1.02)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(239,68,68,0.9)`,e.currentTarget.style.transform=`scale(1)`},"aria-label":`End call`,children:[(0,H.jsx)(fh,{size:18}),`End Call`]})]})]})}function og({agentName:e,agentHeadshot:t,fallbackAgentName:n,callDurationSeconds:r,isCallMuted:i,formatCallDuration:a,toggleCallMute:o,endWebRTCCall:s,onExpand:c,primaryColor:l=`#3B82F6`}){let u=e||n||`Agent`;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`style`,{children:$h}),(0,H.jsxs)(`div`,{role:`button`,tabIndex:0,onClick:c,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&c?.()},onMouseEnter:e=>{e.currentTarget.style.boxShadow=`0 8px 32px rgba(0,0,0,0.14), 0 2px 8px rgba(0,0,0,0.08), inset 0 1px 0 rgba(255,255,255,0.95)`,e.currentTarget.style.transform=`translateY(-2px)`},onMouseLeave:e=>{e.currentTarget.style.boxShadow=`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,e.currentTarget.style.transform=`translateY(0)`},style:{display:`flex`,alignItems:`center`,gap:`12px`,padding:`10px 12px 10px 10px`,margin:`0 12px 8px`,borderRadius:`18px`,background:`rgba(255,255,255,0.88)`,backdropFilter:`blur(20px)`,WebkitBackdropFilter:`blur(20px)`,border:`1px solid rgba(255,255,255,0.65)`,boxShadow:`0 4px 20px rgba(0,0,0,0.09), 0 1px 6px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.9)`,cursor:`pointer`,animation:`fe-call-bar-slide-in 0.3s cubic-bezier(0.16,1,0.3,1)`,flexShrink:0,userSelect:`none`,outline:`none`,transition:`box-shadow 0.22s ease, transform 0.18s ease`},children:[(0,H.jsxs)(`div`,{style:{position:`relative`,flexShrink:0,width:`42px`,height:`42px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[(0,H.jsx)(`div`,{style:{position:`absolute`,inset:`-4px`,borderRadius:`50%`,background:`${l}28`,animation:`fe-call-avatar-breathe 2.8s ease-in-out infinite`}}),(0,H.jsx)(`div`,{style:{position:`absolute`,inset:`-2px`,borderRadius:`50%`,border:`1.5px solid ${l}55`}}),(0,H.jsx)(rg,{headshot:t,name:u,size:38,primaryColor:l})]}),(0,H.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,H.jsx)(`div`,{style:{fontSize:`13px`,fontWeight:600,color:`#111827`,lineHeight:1.3,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:u}),(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,marginTop:`3px`},children:[(0,H.jsx)(`div`,{style:{width:`6px`,height:`6px`,borderRadius:`50%`,background:`#22c55e`,flexShrink:0,boxShadow:`0 0 4px rgba(34,197,94,0.6)`,animation:`fe-call-dot-blink 1.6s ease-in-out infinite`}}),(0,H.jsxs)(`span`,{style:{fontSize:`12px`,color:`#6b7280`,fontVariantNumeric:`tabular-nums`,letterSpacing:`0.01em`},children:[`On Call\xA0•\xA0`,a(r)]})]})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`,flexShrink:0},children:[(0,H.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:i?`${l}18`:`rgba(0,0,0,0.05)`,border:i?`1.5px solid ${l}55`:`1.5px solid rgba(0,0,0,0.08)`,cursor:`pointer`,color:i?l:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,transition:`all 0.18s ease`,boxShadow:i?`0 0 0 3px ${l}12`:`none`},"aria-label":i?`Unmute`:`Mute`,children:i?(0,H.jsx)(Sh,{size:15}):(0,H.jsx)(dh,{size:15})}),(0,H.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),s()},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.12)`,e.currentTarget.style.boxShadow=`0 4px 16px rgba(239,68,68,0.55)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`,e.currentTarget.style.boxShadow=`0 2px 10px rgba(239,68,68,0.35)`},style:{width:`36px`,height:`36px`,borderRadius:`50%`,background:`#ef4444`,border:`none`,cursor:`pointer`,color:`white`,display:`flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0,boxShadow:`0 2px 10px rgba(239,68,68,0.35)`,transition:`all 0.18s ease`},"aria-label":`End call`,children:(0,H.jsx)(fh,{size:16})})]})]})]})}function sg(e,t={}){let n=t.maxChars??4500;if(!Array.isArray(e)||e.length===0)return``;let r=[];for(let t of e){if(!t||t.isPending)continue;let e=String(t.sender||``).toLowerCase(),n=null;if(e===`user`?n=`Visitor`:(e===`bot`||e===`ai`||e===`agent`)&&(n=`Assistant`),!n)continue;let i=String(t.message||``).replace(/<[^>]+>/g,` `).replace(/\s+/g,` `).trim().slice(0,1200);i&&r.push(`${n}: ${i}`)}if(r.length===0)return``;let i=r.join(`
|
|
192
192
|
`);return i.length>n&&(i=`…(earlier messages omitted)
|
|
193
|
-
`+i.slice(-n)),i}var Q=`fe-vv`;function
|
|
193
|
+
`+i.slice(-n)),i}var Q=`fe-vv`;function cg(){if(typeof document>`u`||document.getElementById(`${Q}-styles`))return;let e=`
|
|
194
194
|
/* ── Action toast ───────────────────────────────────────────────────────────── */
|
|
195
195
|
#${Q}-toast {
|
|
196
196
|
position: fixed;
|
|
@@ -330,27 +330,27 @@ Error generating stack: `+e.message+`
|
|
|
330
330
|
50% { transform: translate(-4px,-4px) scale(0.82); }
|
|
331
331
|
100% { transform: translate(-4px,-4px) scale(1); }
|
|
332
332
|
}
|
|
333
|
-
`,t=document.createElement(`style`);t.id=`${Q}-styles`,t.textContent=e,(document.head||document.documentElement).appendChild(t)}var
|
|
333
|
+
`,t=document.createElement(`style`);t.id=`${Q}-styles`,t.textContent=e,(document.head||document.documentElement).appendChild(t)}var lg=null,ug=null;function dg(){return(!lg||!lg.isConnected)&&(lg=document.createElement(`div`),lg.id=`${Q}-toast`,document.body.appendChild(lg)),lg}function fg(e,{spinner:t=!0,icon:n=null,duration:r=0}={}){if(typeof document>`u`)return;cg(),ug&&=(clearTimeout(ug),null);let i=dg();if(i.innerHTML=``,n){let e=document.createElement(`span`);e.className=`${Q}-icon`,e.textContent=n,i.appendChild(e)}else if(t){let e=document.createElement(`span`);e.className=`${Q}-spin`,i.appendChild(e)}let a=document.createElement(`span`);a.textContent=e,i.appendChild(a),i.classList.remove(`${Q}-show`),i.offsetHeight,i.classList.add(`${Q}-show`),r>0&&(ug=setTimeout(()=>pg(),r))}function pg(e=0){lg&&(e>0?ug=setTimeout(()=>{lg&&lg.classList.remove(`${Q}-show`)},e):lg&&lg.classList.remove(`${Q}-show`))}var mg=null,hg=[];function gg(){return(!mg||!mg.isConnected)&&(mg=document.createElement(`div`),mg.id=`${Q}-bar`,document.body.appendChild(mg)),mg}function _g(){if(typeof document>`u`)return;cg(),hg.forEach(clearTimeout),hg=[];let e=gg();e.style.transition=`none`,e.style.width=`0%`,e.classList.add(`${Q}-bar-active`),e.offsetHeight,e.style.transition=`width 0.35s ease, opacity 0.25s ease`;let t=[[80,`width 0.6s ease`],[92,`width 1.2s ease`]],n=50;for(let[e,r]of t){let t=n,i=e,a=r;hg.push(setTimeout(()=>{mg&&(mg.style.transition=a,mg.style.width=`${i}%`)},t)),n+=800}}function vg(){mg&&(hg.forEach(clearTimeout),hg=[],mg.style.transition=`width 0.2s ease`,mg.style.width=`100%`,hg.push(setTimeout(()=>{mg&&(mg.style.transition=`opacity 0.35s ease`,mg.style.opacity=`0`,hg.push(setTimeout(()=>{mg&&(mg.style.width=`0%`,mg.classList.remove(`${Q}-bar-active`))},380)))},220)))}var yg=`<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 22 22" fill="none">
|
|
334
334
|
<filter id="${Q}-csh">
|
|
335
335
|
<feDropShadow dx="1" dy="2" stdDeviation="1.5" flood-color="#00000060"/>
|
|
336
336
|
</filter>
|
|
337
337
|
<path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
|
|
338
338
|
fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
|
|
339
339
|
filter="url(#${Q}-csh)"/>
|
|
340
|
-
</svg>`,
|
|
340
|
+
</svg>`,bg=null,xg=!1;function Sg(){return(!bg||!bg.isConnected)&&(bg=document.createElement(`div`),bg.id=`${Q}-cursor`,bg.innerHTML=yg,document.body.appendChild(bg),xg=!1),bg}async function Cg(e){if(typeof document>`u`||!e)return;cg();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=Sg();xg||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await Dg(360)}function wg(e=!1){bg&&(e?(bg.classList.remove(`${Q}-cursor-visible`),xg=!1):(bg.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{xg=!1},250)))}async function Tg(e){bg&&(bg.classList.add(`${Q}-cursor-click`),await Dg(280),bg.classList.remove(`${Q}-cursor-click`))}function Eg(e){if(!e||typeof document>`u`)return;cg();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function Dg(e){return new Promise(t=>setTimeout(t,e))}var Og=/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i;function kg(e){return String(e||``).replace(Og,``).replace(/\/+$/,``).toLowerCase()||`/`}function Ag(e,t){return kg(e)===kg(t)}function $(...e){Tn()&&console.log(`[FlowEngage:voice-tools]`,...e)}function jg(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Mg(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!jn(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function Ng(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function Pg(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return Ng(r.join(` `))}if(e.labels&&e.labels.length)return Ng(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return Ng(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return Ng(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return Ng(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=Ng(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return Ng(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return Ng(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?Ng(o):null}function Fg(){let e=[];return Mg(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(jn(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=jg(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function Ig(){return Fg().map((e,t)=>{let n={formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:Pg(e),placeholder:e.placeholder||null};return e.tagName===`SELECT`&&(n.options=Array.from(e.options).filter(e=>e.value!==``&&!e.disabled).map(e=>({value:e.value,text:e.text.trim()})),n.currentValue=e.value||null),n})}function Lg(){let e=[];return Mg(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(jn(e)||e.disabled)return!1;try{let t=jg(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function Rg(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function zg(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=(e.innerText||e.textContent||``).replace(/\s+/g,` `).trim(),i=[r,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-text`),e.getAttribute(`data-label`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(i.includes(n)||r.toLowerCase()===n)return 100;let a=n.split(/\s+/).filter(e=>e.length>1);if(!a.length)return 0;let o=0;for(let e of a)i.includes(e)&&(o+=1);return o/a.length*92}function Bg(e,t,n=6){let r=String(t||``).toLowerCase().trim();if(!r)return!1;let i=e;for(let e=0;e<n&&i&&(i=i.parentElement,i);e++)if((i.innerText||i.textContent||``).toLowerCase().includes(r))return!0;return!1}function Vg(e,t,n){let r=[];Mg(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));r.push(...t.filter(e=>{if(jn(e)||e.disabled)return!1;try{let t=jg(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1}catch{}return!0}))});let i=0,a=r.map(t=>({el:t,s:zg(t,e)}));for(let{s:e}of a)e>i&&(i=e);if(i<28)return null;let o=a.filter(({s:e})=>e===i).map(({el:e})=>e);if(o.length===1)return o[0];if(n){let e=o.filter(e=>Bg(e,n));if(e.length===1)return e[0];e.length>1&&(o=e)}let s=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(s.length){let e=o[0],t=1/0;for(let n of o)for(let r of s){let i=Rg(n,r);i<t&&(t=i,e=n)}return e}return o[0]}function Hg(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function Ug(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function Wg(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function Gg(){let e=e=>{let t=Array.from(e).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)&&!e.closest(`nav, footer, header, aside, .nav, .footer, .header, .sidebar`)),n=[],r=0;for(;r<t.length;){let e=t[r],i=Mn(e);if(!i||i.length<2){r++;continue}let a=i;if(i.length<40&&!/[.!?:;]$/.test(i)&&r+1<t.length){let n=t[r+1],o=Mn(n);o&&n.tagName===e.tagName&&o.length<60&&(e.nextElementSibling===n||e.parentElement===n.parentElement)&&(a=`${i} ${o}`,r++)}a.length>2&&a.length<200&&n.push({text:a,level:Number(e.tagName.slice(1))||6}),r++}return n},t=document.querySelector(`main, [role='main']`)||document.body,n=e(t.querySelectorAll(`h1, h2, h3, h4, h5`));n.length||(n=e(document.body.querySelectorAll(`h1, h2, h3, h4, h5`)));let r=new Set,i=[];for(let e of n)if(!(!e||r.has(e.text))&&(r.add(e.text),i.push(e),i.length>=30))break;let a=i.map(e=>e.text),o=[];for(let e=0;e<i.length;e++){let t=0;for(let n=e+1;n<i.length&&!(i[n].level<=i[e].level);n++)t+=1;t>=3&&o.push(i[e].text)}let s=Array.from(t.querySelectorAll(`h1`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)&&!e.closest(`nav, footer, header, aside, .nav, .footer, .header, .sidebar`)),c=null;if(s.length===1){let e=Mn(s[0]);e&&a[0]&&a[0].toLowerCase().trim()===e.toLowerCase().trim()&&(c=a[0])}let l=``;try{let e=t.querySelector(`h1, h2, h3, h4, h5`);if(e){let n=document.createRange();n.setStart(t,0),n.setEndBefore(e);let r=n.cloneContents(),i=[];r.querySelectorAll(`p, li`).forEach(e=>{let t=e.textContent.replace(/\s+/g,` `).trim();t.length>20&&i.push(t)}),l=i.join(` `).slice(0,600)}}catch{}return{headings:a,pageTitleHeading:c,introText:l,containerHeadings:o}}function Kg(e){if(!e||typeof document>`u`)return``;let t=new Set([`script`,`style`,`noscript`,`svg`,`iframe`,`nav`,`footer`,`header`,`aside`]),n=parseInt(e.tagName[1],10),r=Array.from({length:n},(e,t)=>`h${t+1}`).join(`, `),i=Array.from(document.querySelectorAll(r)).filter(e=>!e.closest(An)),a=i.indexOf(e),o=a===-1?null:i[a+1],s=document.createRange();try{if(s.setStartAfter(e),o)s.setEndBefore(o);else{let e=document.querySelector(`main, [role='main'], article`)||document.body;s.setEnd(e,e.childNodes.length)}}catch{return e.textContent.replace(/\s+/g,` `).trim()}let c;try{c=s.cloneContents()}catch{return e.textContent.replace(/\s+/g,` `).trim()}let l=[];function u(e){if(e.nodeType===Node.TEXT_NODE){let t=e.textContent.replace(/\s+/g,` `).trim();t&&l.push(t);return}if(e.nodeType!==Node.ELEMENT_NODE)return;let n=e.tagName.toLowerCase();if(!t.has(n)){if(n===`ul`||n===`ol`){let t=Array.from(e.querySelectorAll(`:scope > li`)).map(e=>{let t=e.textContent.replace(/\s+/g,` `).trim();return t?`• ${t}`:null}).filter(Boolean);t.length&&l.push(t.join(`
|
|
341
341
|
`));return}if(n===`table`){let t=Array.from(e.querySelectorAll(`tr`)).map(e=>Array.from(e.querySelectorAll(`td, th`)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(Boolean).join(` | `)).filter(Boolean);t.length&&l.push(t.join(`
|
|
342
342
|
`));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(`
|
|
343
343
|
`).replace(/\n{3,}/g,`
|
|
344
344
|
|
|
345
|
-
`).trim()}function Yg(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=Wg(n),a=Gg(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 hr(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{mg(`Navigating to ${a}...`,{spinner:!0}),yg(),kn();try{let e=r?r():``;if(e&&t){let n=lg([{sender:`user`,message:e}]);n&&_e(t,n)}}catch{}xe();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`&&Oe(t,window.location.href,e,n),vr(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&&!!Yn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),i&&Bn(12e3),Er(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}=qg(),!(o.length>=1)););Kg(),$(`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=ur(null,n);if(e){let r=Jg(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(xr())return yr(),$(`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&&!Mg(h,e)&&Mg(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=Mg(h,e),y=!Mg(h,t),b=v||y;return $(`fwh-navigate-mvp settled:`,h,`target:`,e,`match:`,b),b?(yr(),`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.`):(yr(),`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),mg(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{bg(),hg(900)}},"fwh-highlight-mvp":async e=>{$(`fwh-highlight-mvp ▶`,e);let t=Wg(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(Bn(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.`}Kg();let i=(e=>e&&e.replace(/^\d+\.\s*/,``).replace(/^["']|["']$/g,``).trim())(r),a=ur(n||null,i||null);if(!a&&i){let e=Date.now()+600;for(;!a&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),Kg(),a=ur(null,i)}if(!a){$(`fwh-highlight-mvp ✖ no element for:`,i||n);let{headings:e}=qg(),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 On(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=Wg(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=ur(null,n);if(!t)return`Could not find section "${n}" on the page.`;e=Jg(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=Wg(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=Wg(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(`
|
|
346
|
-
`);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(
|
|
347
|
-
`);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(xr())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}=qg();$(`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=Rg(),t=zg();$(`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=Wg(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=Ug(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{mg(`Clicking ${n}...`,{spinner:!0});try{a.scrollIntoView({block:`center`,inline:`nearest`})}catch{a.scrollIntoView(!0)}await Tg(a),a.focus?.(),await Dg(a),Og(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),mg(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`fwh-click-button-mvp ✖`,t),mg(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{Eg(),hg(700)}},"fwh-cart-get-mvp":async()=>{$(`fwh-cart-get-mvp ▶`);try{let e=await zr();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 Kr(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 Br(n,r);await Vr(e.id,i);let a=await Ir(),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 ${Rr(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 Ir(),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 Hr(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 ${Rr(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 Ir(),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 Hr(t,0),i=await o(r),a=`REMOVED ${n.product_title||n.title}. Cart now has ${r.item_count} item(s), subtotal ${Rr(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(Ur(),`Cart`)),"fwh-checkout-mvp":async()=>{$(`fwh-checkout-mvp ▶`);try{if(!(await Ir()).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(Wr(),`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(Gr(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 ei(e);if(!t&&qr())return` NOTE: the cart list on this page could not be re-rendered — briefly tell the visitor the page may need a quick refresh to show the change.`}catch{}return``}function 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&&Oe(t,window.location.href,r,n),vr(r),Tr().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 Xg=/^(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 Zg(){try{let{headings:e,pageTitleHeading:t,containerHeadings:n}=qg(),r=new Set((n||[]).map(e=>e.trim())),i=(e||[]).map(e=>typeof e==`string`?e:e?.text||``).filter(Boolean).filter(e=>!t||e.trim()!==t.trim()).filter(e=>!Xg.test(e.trim())),a=i.filter(e=>!r.has(e.trim()));return a.length?a:i}catch{return[]}}function Qg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Tn();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 $g=`[PAGE_CONTEXT]`;function e_(e,t,n){return`${$g} SESSION_CONTEXT (NOT a tool result — do NOT treat as CURRENT_PAGE): Visitor is on: ${e} | Approx headings for awareness only: ${t||``}. ${n?`Forms: ${n}. `:``}The visitor is ALREADY on this page — do NOT offer to navigate there.`}var t_={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function n_(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 r_(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 i_(e){let[t,n]=b.useState(null),r=typeof e==`string`?e.trim():``;return b.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 a_({logo:e,style:t}){let n=i_(typeof e==`string`?e:null);if(!e)return null;if(typeof e==`string`)return n?(0,H.jsx)(`img`,{src:n,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}}):null;let r=typeof e==`function`?b.createElement(e):b.isValidElement(e)?e:null;return r?(0,H.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:r}):null}function o_({title:e}){return(0,H.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 s_(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 c_({orbColors:e,...t}){return(0,H.jsx)(eg,{colors:e,...t})}function l_({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||t_.green,c=r_(s),l=a?72:94,u=(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,H.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,H.jsx)(Km.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,H.jsxs)(Km.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,H.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,H.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,H.jsx)(Km.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,H.jsx)(c_,{size:l,orbColors:t})})]});return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Km.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,H.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,H.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function u_({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||t_.green,l=r_(c);return(0,H.jsxs)(Km.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,H.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,H.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,H.jsx)(c_,{size:72,orbColors:t}),(0,H.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,H.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,lineHeight:1.4},children:e.connectionTitle}),e.connectionSubtitle&&(0,H.jsx)(`p`,{style:{margin:`6px 0 0`,fontSize:`13px`,fontWeight:400,color:`#6b7280`,lineHeight:1.4},children:e.connectionSubtitle})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,H.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,H.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 d_({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l,websiteName:u,voiceFirstMessage:d,captureVisitorEmail:f,emailRequired:p,emailCaptureEnabled:m=!0,listeningLabel:h=`Listening...`,thinkingLabel:g=`Thinking...`,enterChatModeLabel:_=`Enter Chat Mode`,endConversationLabel:v=`End Conversation`}){(0,b.useEffect)(()=>(console.log(`[FlowEngage:VoiceDebug] 🔵 VoiceMode MOUNTED`),()=>console.log(`[FlowEngage:VoiceDebug] 🔴 VoiceMode UNMOUNTED`)),[]);let[y,x]=(0,b.useState)(`idle`),[S,C]=(0,b.useState)(!1),[w,T]=(0,b.useState)(!1),[E,ee]=(0,b.useState)(!1),[D,O]=(0,b.useState)(``),[k,A]=(0,b.useState)(``),te=(0,b.useRef)(!1),ne=(0,b.useRef)(!1),re=(0,b.useRef)(null),ie=(0,b.useRef)(0),j=(0,b.useRef)(``),M=(0,b.useRef)(!1),ae=(0,b.useRef)(0),oe=(0,b.useRef)(!1),se=(0,b.useRef)(!1),ce=(0,b.useRef)(!1),N=(0,b.useRef)([]),P=(0,b.useRef)(null),le=(0,b.useRef)(null),ue=e=>{oe.current=e,e||(se.current=!1),F.current?.setWalkthroughActive?.(e)};le.current=async()=>{if(se.current)return;let e=typeof window<`u`?window.location.pathname:null;if(e&&P.current&&e!==P.current){console.log(`[FlowEngage] walkthrough ended — visitor left `+P.current),P.current=null,N.current=[],ue(!1);return}let t=N.current;de.current+=1;let n=de.current,r=t[n];if(!r){if(ue(!1),t.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(n===0){let e=``;try{let t=await fe.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 fe.current?.highlightOnPage?.({section_text:r})}catch(e){console.warn(`[FlowEngage] walkthrough highlight failed:`,e?.message||e)}console.debug(`[FlowEngage] walkthrough step ${n+1}/${t.length}: ${r}`);let i=``;try{let e=await fe.current?.[`fwh-read-content-mvp`]?.({section_text:r});typeof e==`string`&&e&&!/^Could not/i.test(e)&&(i=e.slice(0,2500))}catch{}let a=i?`Here is this section's full content — describe it from THIS text only, and do not call any tool:\n"""${i}"""\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 "${r}" in 3-4 sentences, starting with ${n===0?`Starting with`:`Next —`} ${r}. 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; `+a+`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 de=(0,b.useRef)(0),F=(0,b.useRef)(null),fe=(0,b.useRef)(null),pe=(0,b.useRef)(``),me=(0,b.useRef)(async()=>{}),I=(0,b.useRef)(!1),he=(0,b.useRef)(!1),ge=(0,b.useRef)(!1),be=(0,b.useRef)(!1),Se=(0,b.useRef)(`minimized`),Ce=(0,b.useRef)(null),we=(0,b.useRef)(null),Te=(0,b.useRef)(null),De=(0,b.useRef)(0),Oe=(0,b.useRef)(!1),Ae=(0,b.useRef)(`idle`),L=(0,b.useRef)(null),je=(0,b.useRef)(!1),Me=(0,b.useRef)(null),Ne=(0,b.useCallback)((e=`minimized`)=>{console.warn(`[FlowEngage:VoiceDebug] 🛑 requestSessionShutdown called`,{destination:e,stack:Error().stack?.split(`
|
|
348
|
-
`).slice(1,4).join(` | `)}),Se.current=e,be.current=!0,queueMicrotask(()=>{I.current||(I.current=!0,me.current?.())})},[s]),R=(0,b.useCallback)(()=>{re.current&&=(clearTimeout(re.current),null)},[]);(0,b.useEffect)(()=>{if(p){te.current=!1;return}if(te.current=!0,ne.current=!1,ee(!1),R(),M.current){M.current=!1,F.current?.setMicMuted?.(!1);let e=j.current;j.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.`)},[p,R]);let Pe=/(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,Fe=/(that covers everything|that was all|covered everything|that(?:'|’)?s everything)/i,Ie=/^((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,Le=/^((uh+|um+|oh|ah|so|well)[,.\s]+)*(cool|nice|great|awesome|wow|lovely|perfect|got it|gotcha|i see|understood|makes sense|interesting|right|alright|sounds good|mm+-?hmm+|hmm+|k)[\s.!,]*$/i,Re=e=>String(e||``).replace(/[\s.,!?]*((uh+|um+|er+|hmm+|mm+)[\s.,!?]*)+$/i,``).trim(),ze=(0,b.useCallback)(()=>{R(),re.current=setTimeout(()=>{if(!(!ne.current||te.current))if(ie.current<3){ie.current+=1;try{F.current?.injectAgentSpeech?.(`I still need your email in the box below to continue — could you enter it, please?`,`queue`)}catch{}ze()}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{}ne.current=!1,ee(!1),R(),Oe.current=!0}},1e4)},[R]),Be=(0,b.useCallback)(async e=>{be.current=!0;try{kn()}catch{}if(i)try{ke(i)}catch{}try{await F.current?.endSession?.()}catch{}let t=Ce.current,n=we.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(Ce.current=null,we.current=null,F.current=null,x(`idle`),C(!1),I.current=!1,Ar(),i)try{ye(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);me.current=()=>Be(Se.current===`chat`?t:n),(0,b.useEffect)(()=>{he.current=S},[S]),(0,b.useEffect)(()=>{l&&Ne(`chat`)},[l]),(0,b.useEffect)(()=>{let e=!1,l=null,f=null,h=null;return(async()=>{if(!i){x(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],pe.current=``,I.current=!1,ge.current=!1,be.current=!1,Se.current=`minimized`,kr({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=lg(s.current);e&&_e(i,e)}catch{}if(!Yn()){let e=Ce.current,t=we.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(()=>{}),Ce.current=null,we.current=null}catch{}}xe()}});let t=Qg(Yg({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>pe.current,isWalkthroughActive:()=>oe.current&&!se.current,requestEndSession:()=>{Oe.current=!0},requestEmailCollection:()=>{m&&(te.current||ne.current||(ne.current=!0,ie.current=0,ee(!0),ze()))}})),n=i?ve(i):null,r=!!n?.transcript,c=i?ke(i):null,g=!!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===``,S={apiBaseUrl:a,siteId:i,chatId:o,clientTools:t};fe.current=t;let w=(_.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||w||``,D=E?`the ${E} page`:`this page`,O=(()=>{if(!c?.targetUrl)return!0;try{return new URL(c.targetUrl,window.location.href).pathname.replace(/\/$/,``)===window.location.pathname.replace(/\/$/,``)}catch{return!0}})(),k=(()=>{if(!c?.targetUrl)return null;try{return new URL(c.targetUrl,window.location.href).pathname}catch{return null}})();if(g&&!O)S.greeting=`You're on ${D}. What would you like to know?`,console.warn(`[FlowEngage] nav target "${c?.pageName}" not reached — on "${E}" instead; not claiming navigation`);else if(g){let e=c?.pageName?`the ${c.pageName} page`:D;S.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)S.greeting=`Welcome back! I see you're now on ${D}. 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||``;S.greeting=d||(b?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to ${D}! How may I help you?`),b||console.log(`[FlowEngage] 🏠 Page-context greeting: "${E}" for ${_}`)}let A=!1,re=g?`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,me=!1,ye=!g&&!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,Te=r&&!g,Be=!1,Ve=Te?`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,He=!1,Ue=!1,We=m&&!!p&&!ce.current,Ge=await fh.startSession({...S,onConnect:({conversationId:e})=>{Ce.current=e,we.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onSessionInfo:({emailOnFile:e})=>{ce.current=!!e,e&&(te.current=!0,ne.current=!1,ee(!1),R(),console.log(`[FlowEngage] email already on file per server — gate disabled`))},onAgentTurnEnd:()=>{e||oe.current&&(se.current||M.current||setTimeout(()=>le.current?.(),250))},onSessionEnding:()=>{e||Ne(`minimized`)},onModeChange:({mode:t,tentative:n})=>{if(!e){if(t===`speaking`){L.current&&=(clearTimeout(L.current),null),Me.current&&=(clearTimeout(Me.current),null),x(`speaking`),Ae.current=`speaking`,je.current=!1;return}if(t===`user-speaking`){if(ne.current&&!te.current&&ze(),Me.current&&=(clearTimeout(Me.current),null),Ae.current===`speaking`)return;try{kn()}catch{}L.current&&=(clearTimeout(L.current),null),Ae.current!==`listening`&&(x(`listening`),Ae.current=`listening`);return}if(t===`thinking`){if(L.current&&=(clearTimeout(L.current),null),Me.current&&=(clearTimeout(Me.current),null),Ae.current===`speaking`)return;x(`thinking`),Ae.current=`thinking`,n&&(Me.current=setTimeout(()=>{Me.current=null,!(e||Ae.current!==`thinking`)&&(Ae.current=`listening`,x(`listening`))},4e3));return}if(Ae.current=`listening`,Oe.current){Oe.current=!1,Ne();return}if(We&&!Ue&&!te.current&&!ce.current){Ue=!0,A=!0,me=!0;try{F.current?.sendContextualUpdate?.(`CRITICAL — EMAIL REQUIRED BEFORE ANYTHING ELSE. The visitor has not provided their email. The app itself speaks the email request out loud — you must NOT say it, and you must NOT answer. Stay completely silent from now until you receive an EMAIL_SAVED message: produce no speech and call no tools, no matter what the visitor says. Remember their question. On EMAIL_SAVED, thank them briefly and answer that remembered question in full.`)}catch{}}if(re&&!A){A=!0;try{F.current?.sendContextualUpdate?.(re)}catch{}}if(Ve&&!Be){Be=!0;try{F.current?.sendContextualUpdate?.(Ve)}catch{}}if(ye&&!me){me=!0;try{F.current?.sendContextualUpdate?.(ye)}catch{}}L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{e||Ae.current!==`speaking`&&(je.current||(L.current=null,Ae.current=`listening`,x(`listening`)))},1200)}},onMessage:t=>{if(e||M.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`&&Pe.test(String(t.message||``)))typeof window<`u`&&(window.__fe_user_nav_during_speech=null),ue(!0),se.current=!1,ae.current=0,de.current=-1,N.current=Zg(),P.current=typeof window<`u`?window.location.pathname:null,setTimeout(()=>le.current?.(),400),console.log(`[FlowEngage] walkthrough armed — ${N.current.length} sections on this page`);else if(!n&&t.role===`user`&&oe.current){let e=String(t.message||``).trim(),n=Re(e),r=e=>!!e&&(Ie.test(e)||Le.test(e));!n||r(e)||r(n)?se.current&&(se.current=!1,console.debug(`[FlowEngage] walkthrough resumed by visitor`),setTimeout(()=>le.current?.(),300)):(console.log(`[FlowEngage] walkthrough ended — visitor moved to a new topic`),P.current=null,N.current=[],ue(!1))}if(t.role!==`user`&&Fe.test(String(t.message||``))){let e=N.current.length;!e||de.current>=e-1?ue(!1):console.debug(`[FlowEngage] agent claimed completion at step ${de.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`&&(pe.current=o,typeof window<`u`&&(window.__fe_user_nav_during_speech=null),je.current=!0,L.current&&=(clearTimeout(L.current),null),Ae.current!==`speaking`&&(x(`thinking`),Ae.current=`thinking`),We&&!He&&!te.current&&!ce.current&&(He=!0,j.current=o,M.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),ne.current||(ne.current=!0,ie.current=0,ee(!0),ze()))),s.current=[...s.current,{sender:a,message:o,timestamp:new Date().toISOString(),debug:t.debug}],i)try{let e=lg(s.current);e&&_e(i,e)}catch{}if(s_(a,o)){Oe.current=!0;return}if(he.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&&Ne(`minimized`)}},onError:t=>{if(!e&&!be.current&&!ge.current&&!Ee()){ge.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{F.current?.setMicMuted?.(!0)}catch{}C(!0),x(`error`),Ne(`chat`)}},onDisconnect:t=>{if(e||be.current||ge.current||Ee())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:pe.current||``,wasMuted:he.current}),ge.current=!0;try{F.current?.setMicMuted?.(!0)}catch{}C(!0),Ne(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),Ge.endSession().catch(()=>{});return}l=Ge,F.current=Ge,x(`listening`);try{sessionStorage.setItem(`el_conv_${i}`,Ge.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&&!g?`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`:``;Ge.sendContextualUpdate(`${s}SiteId: ${i||`unknown`}. ${p?``:`Visitor's email is already on file from a prior session — do NOT ask for it again. `}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. Do NOT skip fwh-get-current-page-mvp. Voice: call end_voice_session or say you are ending the session to stop.`),Ge.sendContextualUpdate(e_(e,o,a))}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=k&&r(i)===r(k)||Vn()||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{kn()}catch{}let d=u.map(e=>e.text).join(` | `),f=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,p=f(s),m=f(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 "${m}" page (${c}) at their request — this was YOUR action, not theirs. Page title: "${l}". Sections: ${JSON.stringify(u)}. Say: "Here we are on the ${m} 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{}try{F.current?.sendContextualUpdate?.(e_(c,d))}catch{}return}typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:s,toPath:i,fromPageName:p,toPageName:m,ts:Date.now()}),console.log(`[FlowEngage] visitor navigation detected: "${s}" → "${i}" (agent target: ${k||`none`})`);try{F.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${m}" 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 ${m} 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 "${m}" only.]`)}catch{}try{F.current?.sendContextualUpdate?.(e_(c,d))}catch{}};f=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{f(...e),setTimeout(i,50)},h=()=>setTimeout(i,50),window.addEventListener(`popstate`,h)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(x(`error`),Se.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,be.current=!0;try{kn()}catch{}if(i)try{ke(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Ar(),L.current&&=(clearTimeout(L.current),null),Me.current&&=(clearTimeout(Me.current),null),re.current&&=(clearTimeout(re.current),null),je.current=!1,Ae.current=`idle`,f&&typeof window<`u`&&(window.history.pushState=f),h&&typeof window<`u`&&window.removeEventListener(`popstate`,h);let t=l||F.current,n=Ce.current,u=we.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(()=>{}),Ce.current=null,we.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Ne]),(0,b.useEffect)(()=>{if(!w)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Te.current&&!Te.current.contains(t)&&T(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[w]);let Ve=async()=>{if(F.current)try{if(S){De.current=0,await F.current.setMicMuted?.(!1),C(!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),C(!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{}},He=(0,b.useCallback)(async e=>{e?.preventDefault?.();let t=D.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){A(`Please enter a valid email address.`);return}A(``),te.current=!0,ne.current=!1,R(),ee(!1),O(``),M.current=!1;try{typeof f==`function`&&await f(t)}catch{}F.current?.setMicMuted?.(!1);let n=j.current;j.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,f,R]),Ue=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,H.jsxs)(`div`,{ref:Te,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:[E&&(0,H.jsxs)(`form`,{onSubmit:He,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,H.jsx)(`span`,{style:{color:`white`,fontSize:`13px`,fontWeight:600,lineHeight:1.4},children:`Please enter your email to continue`}),(0,H.jsx)(`input`,{type:`email`,inputMode:`email`,autoComplete:`email`,autoFocus:!0,value:D,onChange:e=>{O(e.target.value),k&&A(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:k?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),k&&(0,H.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:k}),(0,H.jsx)(`button`,{type:`submit`,disabled:!D.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:D.trim()?Ue:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:D.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,H.jsxs)(`div`,{style:{position:`relative`},children:[(y===`listening`||y===`thinking`)&&!S&&(0,H.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:y===`thinking`?g:h}),S&&(0,H.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,H.jsx)(c_,{size:72,voiceState:y,isMuted:S,orbColors:e})]}),y===`error`&&(0,H.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,H.jsx)(`button`,{onClick:Ve,title:S?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:S?`#7f1d1d`:`#1f2937`,border:S?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:S?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:S?(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,H.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,H.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,H.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,H.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,H.jsx)(ph,{size:16,color:`currentColor`})}),(0,H.jsx)(`button`,{onClick:()=>T(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,H.jsx)(xh,{size:16,color:`currentColor`})})]}),w&&(0,H.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,H.jsxs)(`button`,{onClick:()=>{T(!1),Se.current=`chat`,Be(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,H.jsx)(Sh,{}),_]}),(0,H.jsxs)(`button`,{onClick:()=>{T(!1),Se.current=`minimized`,Be(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,H.jsx)(Ch,{}),v]}),(0,H.jsx)(`button`,{onClick:()=>T(!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,H.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,H.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function f_({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,H.jsx)(`div`,{style:{width:`32px`,height:`32px`,borderRadius:`50%`,flexShrink:0,background:`
|
|
345
|
+
`).trim()}function qg(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=Hg(n),a=Ug(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 hr(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{fg(`Navigating to ${a}...`,{spinner:!0}),_g(),kn();try{let e=r?r():``;if(e&&t){let n=sg([{sender:`user`,message:e}]);n&&_e(t,n)}}catch{}xe();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`&&Oe(t,window.location.href,e,n),vr(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&&!!Yn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),i&&Bn(12e3),Er(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}=Gg(),!(o.length>=1)););Wg(),$(`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=ur(null,n);if(e){let r=Kg(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(xr())return yr(),$(`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&&!Ag(h,e)&&Ag(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=Ag(h,e),y=!Ag(h,t),b=v||y;return $(`fwh-navigate-mvp settled:`,h,`target:`,e,`match:`,b),b?(yr(),`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.`):(yr(),`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),fg(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{vg(),pg(900)}},"fwh-highlight-mvp":async e=>{$(`fwh-highlight-mvp ▶`,e);let t=Hg(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(Bn(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.`}Wg();let i=(e=>e&&e.replace(/^\d+\.\s*/,``).replace(/^["']|["']$/g,``).trim())(r),a=ur(n||null,i||null);if(!a&&i){let e=Date.now()+600;for(;!a&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),Wg(),a=ur(null,i)}if(!a){$(`fwh-highlight-mvp ✖ no element for:`,i||n);let{headings:e}=Gg(),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 On(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=Hg(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=ur(null,n);if(!t)return`Could not find section "${n}" on the page.`;e=Kg(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=Hg(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=Hg(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(`
|
|
346
|
+
`);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(Mg(t=>{for(let r of n)try{t.querySelectorAll(r).forEach(t=>{if(jn(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&&jg(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(jn(t))return;let n=Pg(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(`
|
|
347
|
+
`);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(xr())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}=Gg();$(`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=Ig(),t=Lg();$(`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=Hg(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=Vg(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{fg(`Clicking ${n}...`,{spinner:!0});try{a.scrollIntoView({block:`center`,inline:`nearest`})}catch{a.scrollIntoView(!0)}await Cg(a),a.focus?.(),await Tg(a),Eg(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),fg(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`fwh-click-button-mvp ✖`,t),fg(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{wg(),pg(700)}},"fwh-cart-get-mvp":async()=>{$(`fwh-cart-get-mvp ▶`);try{let e=await zr();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 Kr(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 Br(n,r);await Vr(e.id,i);let a=await Ir(),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 ${Rr(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 Ir(),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 Hr(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 ${Rr(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 Ir(),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 Hr(t,0),i=await o(r),a=`REMOVED ${n.product_title||n.title}. Cart now has ${r.item_count} item(s), subtotal ${Rr(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(Ur(),`Cart`)),"fwh-checkout-mvp":async()=>{$(`fwh-checkout-mvp ▶`);try{if(!(await Ir()).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(Wr(),`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(Gr(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 ei(e);if(!t&&qr())return` NOTE: the cart list on this page could not be re-rendered — briefly tell the visitor the page may need a quick refresh to show the change.`}catch{}return``}function 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&&Oe(t,window.location.href,r,n),vr(r),Tr().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 Jg=/^(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 Yg(){try{let{headings:e,pageTitleHeading:t,containerHeadings:n}=Gg(),r=new Set((n||[]).map(e=>e.trim())),i=(e||[]).map(e=>typeof e==`string`?e:e?.text||``).filter(Boolean).filter(e=>!t||e.trim()!==t.trim()).filter(e=>!Jg.test(e.trim())),a=i.filter(e=>!r.has(e.trim()));return a.length?a:i}catch{return[]}}function Xg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Tn();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 Zg=`[PAGE_CONTEXT]`;function Qg(e,t,n){return`${Zg} SESSION_CONTEXT (NOT a tool result — do NOT treat as CURRENT_PAGE): Visitor is on: ${e} | Approx headings for awareness only: ${t||``}. ${n?`Forms: ${n}. `:``}The visitor is ALREADY on this page — do NOT offer to navigate there.`}var $g={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function e_(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 t_(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 n_(e){let[t,n]=b.useState(null),r=typeof e==`string`?e.trim():``;return b.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 r_({logo:e,style:t}){let n=n_(typeof e==`string`?e:null);if(!e)return null;if(typeof e==`string`)return n?(0,H.jsx)(`img`,{src:n,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}}):null;let r=typeof e==`function`?b.createElement(e):b.isValidElement(e)?e:null;return r?(0,H.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:r}):null}function i_({title:e}){return(0,H.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 a_(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 o_({orbColors:e,...t}){return(0,H.jsx)(Qh,{colors:e,...t})}function s_({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||$g.green,c=t_(s),l=a?72:94,u=(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,H.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,H.jsx)(Km.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,H.jsxs)(Km.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,H.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,H.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,H.jsx)(Km.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,H.jsx)(o_,{size:l,orbColors:t})})]});return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Km.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,H.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,H.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function c_({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||$g.green,l=t_(c);return(0,H.jsxs)(Km.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,H.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,H.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,H.jsx)(o_,{size:72,orbColors:t}),(0,H.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,H.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,lineHeight:1.4},children:e.connectionTitle}),e.connectionSubtitle&&(0,H.jsx)(`p`,{style:{margin:`6px 0 0`,fontSize:`13px`,fontWeight:400,color:`#6b7280`,lineHeight:1.4},children:e.connectionSubtitle})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,H.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,H.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 l_({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l,websiteName:u,voiceFirstMessage:d,captureVisitorEmail:f,emailRequired:p,emailCaptureEnabled:m=!0,listeningLabel:h=`Listening...`,thinkingLabel:g=`Thinking...`,enterChatModeLabel:_=`Enter Chat Mode`,endConversationLabel:v=`End Conversation`}){(0,b.useEffect)(()=>(console.log(`[FlowEngage:VoiceDebug] 🔵 VoiceMode MOUNTED`),()=>console.log(`[FlowEngage:VoiceDebug] 🔴 VoiceMode UNMOUNTED`)),[]);let[y,x]=(0,b.useState)(`idle`),[S,C]=(0,b.useState)(!1),[w,T]=(0,b.useState)(!1),[E,ee]=(0,b.useState)(!1),[D,O]=(0,b.useState)(``),[k,A]=(0,b.useState)(``),te=(0,b.useRef)(!1),ne=(0,b.useRef)(!1),re=(0,b.useRef)(null),ie=(0,b.useRef)(0),j=(0,b.useRef)(``),M=(0,b.useRef)(!1),ae=(0,b.useRef)(0),oe=(0,b.useRef)(!1),se=(0,b.useRef)(!1),ce=(0,b.useRef)(!1),N=(0,b.useRef)([]),P=(0,b.useRef)(null),le=(0,b.useRef)(null),ue=e=>{oe.current=e,e||(se.current=!1),F.current?.setWalkthroughActive?.(e)};le.current=async()=>{if(se.current)return;let e=typeof window<`u`?window.location.pathname:null;if(e&&P.current&&e!==P.current){console.log(`[FlowEngage] walkthrough ended — visitor left `+P.current),P.current=null,N.current=[],ue(!1);return}let t=N.current;de.current+=1;let n=de.current,r=t[n];if(!r){if(ue(!1),t.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(n===0){let e=``;try{let t=await fe.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 fe.current?.highlightOnPage?.({section_text:r})}catch(e){console.warn(`[FlowEngage] walkthrough highlight failed:`,e?.message||e)}console.debug(`[FlowEngage] walkthrough step ${n+1}/${t.length}: ${r}`);let i=``;try{let e=await fe.current?.[`fwh-read-content-mvp`]?.({section_text:r});typeof e==`string`&&e&&!/^Could not/i.test(e)&&(i=e.slice(0,2500))}catch{}let a=i?`Here is this section's full content — describe it from THIS text only, and do not call any tool:\n"""${i}"""\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 "${r}" in 3-4 sentences, starting with ${n===0?`Starting with`:`Next —`} ${r}. 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; `+a+`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 de=(0,b.useRef)(0),F=(0,b.useRef)(null),fe=(0,b.useRef)(null),pe=(0,b.useRef)(``),me=(0,b.useRef)(async()=>{}),I=(0,b.useRef)(!1),he=(0,b.useRef)(!1),ge=(0,b.useRef)(!1),be=(0,b.useRef)(!1),Se=(0,b.useRef)(`minimized`),Ce=(0,b.useRef)(null),we=(0,b.useRef)(null),Te=(0,b.useRef)(null),De=(0,b.useRef)(0),Oe=(0,b.useRef)(!1),Ae=(0,b.useRef)(`idle`),L=(0,b.useRef)(null),je=(0,b.useRef)(!1),Me=(0,b.useRef)(null),Ne=(0,b.useCallback)((e=`minimized`)=>{console.warn(`[FlowEngage:VoiceDebug] 🛑 requestSessionShutdown called`,{destination:e,stack:Error().stack?.split(`
|
|
348
|
+
`).slice(1,4).join(` | `)}),Se.current=e,be.current=!0,queueMicrotask(()=>{I.current||(I.current=!0,me.current?.())})},[s]),R=(0,b.useCallback)(()=>{re.current&&=(clearTimeout(re.current),null)},[]);(0,b.useEffect)(()=>{if(p){te.current=!1;return}if(te.current=!0,ne.current=!1,ee(!1),R(),M.current){M.current=!1,F.current?.setMicMuted?.(!1);let e=j.current;j.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.`)},[p,R]);let Pe=/(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,Fe=/(that covers everything|that was all|covered everything|that(?:'|’)?s everything)/i,Ie=/^((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,Le=/^((uh+|um+|oh|ah|so|well)[,.\s]+)*(cool|nice|great|awesome|wow|lovely|perfect|got it|gotcha|i see|understood|makes sense|interesting|right|alright|sounds good|mm+-?hmm+|hmm+|k)[\s.!,]*$/i,Re=e=>String(e||``).replace(/[\s.,!?]*((uh+|um+|er+|hmm+|mm+)[\s.,!?]*)+$/i,``).trim(),ze=(0,b.useCallback)(()=>{R(),re.current=setTimeout(()=>{if(!(!ne.current||te.current))if(ie.current<3){ie.current+=1;try{F.current?.injectAgentSpeech?.(`I still need your email in the box below to continue — could you enter it, please?`,`queue`)}catch{}ze()}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{}ne.current=!1,ee(!1),R(),Oe.current=!0}},1e4)},[R]),Be=(0,b.useCallback)(async e=>{be.current=!0;try{kn()}catch{}if(i)try{ke(i)}catch{}try{await F.current?.endSession?.()}catch{}let t=Ce.current,n=we.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(Ce.current=null,we.current=null,F.current=null,x(`idle`),C(!1),I.current=!1,Ar(),i)try{ye(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);me.current=()=>Be(Se.current===`chat`?t:n),(0,b.useEffect)(()=>{he.current=S},[S]),(0,b.useEffect)(()=>{l&&Ne(`chat`)},[l]),(0,b.useEffect)(()=>{let e=!1,l=null,f=null,h=null;return(async()=>{if(!i){x(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],pe.current=``,I.current=!1,ge.current=!1,be.current=!1,Se.current=`minimized`,kr({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=sg(s.current);e&&_e(i,e)}catch{}if(!Yn()){let e=Ce.current,t=we.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(()=>{}),Ce.current=null,we.current=null}catch{}}xe()}});let t=Xg(qg({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>pe.current,isWalkthroughActive:()=>oe.current&&!se.current,requestEndSession:()=>{Oe.current=!0},requestEmailCollection:()=>{m&&(te.current||ne.current||(ne.current=!0,ie.current=0,ee(!0),ze()))}})),n=i?ve(i):null,r=!!n?.transcript,c=i?ke(i):null,g=!!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===``,S={apiBaseUrl:a,siteId:i,chatId:o,clientTools:t};fe.current=t;let w=(_.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||w||``,D=E?`the ${E} page`:`this page`,O=(()=>{if(!c?.targetUrl)return!0;try{return new URL(c.targetUrl,window.location.href).pathname.replace(/\/$/,``)===window.location.pathname.replace(/\/$/,``)}catch{return!0}})(),k=(()=>{if(!c?.targetUrl)return null;try{return new URL(c.targetUrl,window.location.href).pathname}catch{return null}})();if(g&&!O)S.greeting=`You're on ${D}. What would you like to know?`,console.warn(`[FlowEngage] nav target "${c?.pageName}" not reached — on "${E}" instead; not claiming navigation`);else if(g){let e=c?.pageName?`the ${c.pageName} page`:D;S.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)S.greeting=`Welcome back! I see you're now on ${D}. 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||``;S.greeting=d||(b?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to ${D}! How may I help you?`),b||console.log(`[FlowEngage] 🏠 Page-context greeting: "${E}" for ${_}`)}let A=!1,re=g?`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,me=!1,ye=!g&&!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,Te=r&&!g,Be=!1,Ve=Te?`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,He=!1,Ue=!1,We=m&&!!p&&!ce.current,Ge=await uh.startSession({...S,onConnect:({conversationId:e})=>{Ce.current=e,we.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onSessionInfo:({emailOnFile:e})=>{ce.current=!!e,e&&(te.current=!0,ne.current=!1,ee(!1),R(),console.log(`[FlowEngage] email already on file per server — gate disabled`))},onAgentTurnEnd:()=>{e||oe.current&&(se.current||M.current||setTimeout(()=>le.current?.(),250))},onSessionEnding:()=>{e||Ne(`minimized`)},onModeChange:({mode:t,tentative:n})=>{if(!e){if(t===`speaking`){L.current&&=(clearTimeout(L.current),null),Me.current&&=(clearTimeout(Me.current),null),x(`speaking`),Ae.current=`speaking`,je.current=!1;return}if(t===`user-speaking`){if(ne.current&&!te.current&&ze(),Me.current&&=(clearTimeout(Me.current),null),Ae.current===`speaking`)return;try{kn()}catch{}L.current&&=(clearTimeout(L.current),null),Ae.current!==`listening`&&(x(`listening`),Ae.current=`listening`);return}if(t===`thinking`){if(L.current&&=(clearTimeout(L.current),null),Me.current&&=(clearTimeout(Me.current),null),Ae.current===`speaking`)return;x(`thinking`),Ae.current=`thinking`,n&&(Me.current=setTimeout(()=>{Me.current=null,!(e||Ae.current!==`thinking`)&&(Ae.current=`listening`,x(`listening`))},4e3));return}if(Ae.current=`listening`,Oe.current){Oe.current=!1,Ne();return}if(We&&!Ue&&!te.current&&!ce.current){Ue=!0,A=!0,me=!0;try{F.current?.sendContextualUpdate?.(`CRITICAL — EMAIL REQUIRED BEFORE ANYTHING ELSE. The visitor has not provided their email. The app itself speaks the email request out loud — you must NOT say it, and you must NOT answer. Stay completely silent from now until you receive an EMAIL_SAVED message: produce no speech and call no tools, no matter what the visitor says. Remember their question. On EMAIL_SAVED, thank them briefly and answer that remembered question in full.`)}catch{}}if(re&&!A){A=!0;try{F.current?.sendContextualUpdate?.(re)}catch{}}if(Ve&&!Be){Be=!0;try{F.current?.sendContextualUpdate?.(Ve)}catch{}}if(ye&&!me){me=!0;try{F.current?.sendContextualUpdate?.(ye)}catch{}}L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{e||Ae.current!==`speaking`&&(je.current||(L.current=null,Ae.current=`listening`,x(`listening`)))},1200)}},onMessage:t=>{if(e||M.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`&&Pe.test(String(t.message||``)))typeof window<`u`&&(window.__fe_user_nav_during_speech=null),ue(!0),se.current=!1,ae.current=0,de.current=-1,N.current=Yg(),P.current=typeof window<`u`?window.location.pathname:null,setTimeout(()=>le.current?.(),400),console.log(`[FlowEngage] walkthrough armed — ${N.current.length} sections on this page`);else if(!n&&t.role===`user`&&oe.current){let e=String(t.message||``).trim(),n=Re(e),r=e=>!!e&&(Ie.test(e)||Le.test(e));!n||r(e)||r(n)?se.current&&(se.current=!1,console.debug(`[FlowEngage] walkthrough resumed by visitor`),setTimeout(()=>le.current?.(),300)):(console.log(`[FlowEngage] walkthrough ended — visitor moved to a new topic`),P.current=null,N.current=[],ue(!1))}if(t.role!==`user`&&Fe.test(String(t.message||``))){let e=N.current.length;!e||de.current>=e-1?ue(!1):console.debug(`[FlowEngage] agent claimed completion at step ${de.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`&&(pe.current=o,typeof window<`u`&&(window.__fe_user_nav_during_speech=null),je.current=!0,L.current&&=(clearTimeout(L.current),null),Ae.current!==`speaking`&&(x(`thinking`),Ae.current=`thinking`),We&&!He&&!te.current&&!ce.current&&(He=!0,j.current=o,M.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),ne.current||(ne.current=!0,ie.current=0,ee(!0),ze()))),s.current=[...s.current,{sender:a,message:o,timestamp:new Date().toISOString(),debug:t.debug}],i)try{let e=sg(s.current);e&&_e(i,e)}catch{}if(a_(a,o)){Oe.current=!0;return}if(he.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&&Ne(`minimized`)}},onError:t=>{if(!e&&!be.current&&!ge.current&&!Ee()){ge.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{F.current?.setMicMuted?.(!0)}catch{}C(!0),x(`error`),Ne(`chat`)}},onDisconnect:t=>{if(e||be.current||ge.current||Ee())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:pe.current||``,wasMuted:he.current}),ge.current=!0;try{F.current?.setMicMuted?.(!0)}catch{}C(!0),Ne(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),Ge.endSession().catch(()=>{});return}l=Ge,F.current=Ge,x(`listening`);try{sessionStorage.setItem(`el_conv_${i}`,Ge.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&&!g?`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`:``;Ge.sendContextualUpdate(`${s}SiteId: ${i||`unknown`}. ${p?``:`Visitor's email is already on file from a prior session — do NOT ask for it again. `}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. Do NOT skip fwh-get-current-page-mvp. Voice: call end_voice_session or say you are ending the session to stop.`),Ge.sendContextualUpdate(Qg(e,o,a))}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=k&&r(i)===r(k)||Vn()||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{kn()}catch{}let d=u.map(e=>e.text).join(` | `),f=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,p=f(s),m=f(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 "${m}" page (${c}) at their request — this was YOUR action, not theirs. Page title: "${l}". Sections: ${JSON.stringify(u)}. Say: "Here we are on the ${m} 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{}try{F.current?.sendContextualUpdate?.(Qg(c,d))}catch{}return}typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:s,toPath:i,fromPageName:p,toPageName:m,ts:Date.now()}),console.log(`[FlowEngage] visitor navigation detected: "${s}" → "${i}" (agent target: ${k||`none`})`);try{F.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${m}" 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 ${m} 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 "${m}" only.]`)}catch{}try{F.current?.sendContextualUpdate?.(Qg(c,d))}catch{}};f=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{f(...e),setTimeout(i,50)},h=()=>setTimeout(i,50),window.addEventListener(`popstate`,h)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(x(`error`),Se.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,be.current=!0;try{kn()}catch{}if(i)try{ke(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Ar(),L.current&&=(clearTimeout(L.current),null),Me.current&&=(clearTimeout(Me.current),null),re.current&&=(clearTimeout(re.current),null),je.current=!1,Ae.current=`idle`,f&&typeof window<`u`&&(window.history.pushState=f),h&&typeof window<`u`&&window.removeEventListener(`popstate`,h);let t=l||F.current,n=Ce.current,u=we.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(()=>{}),Ce.current=null,we.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Ne]),(0,b.useEffect)(()=>{if(!w)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Te.current&&!Te.current.contains(t)&&T(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[w]);let Ve=async()=>{if(F.current)try{if(S){De.current=0,await F.current.setMicMuted?.(!1),C(!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),C(!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{}},He=(0,b.useCallback)(async e=>{e?.preventDefault?.();let t=D.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){A(`Please enter a valid email address.`);return}A(``),te.current=!0,ne.current=!1,R(),ee(!1),O(``),M.current=!1;try{typeof f==`function`&&await f(t)}catch{}F.current?.setMicMuted?.(!1);let n=j.current;j.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,f,R]),Ue=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,H.jsxs)(`div`,{ref:Te,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:[E&&(0,H.jsxs)(`form`,{onSubmit:He,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,H.jsx)(`span`,{style:{color:`white`,fontSize:`13px`,fontWeight:600,lineHeight:1.4},children:`Please enter your email to continue`}),(0,H.jsx)(`input`,{type:`email`,inputMode:`email`,autoComplete:`email`,autoFocus:!0,value:D,onChange:e=>{O(e.target.value),k&&A(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:k?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),k&&(0,H.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:k}),(0,H.jsx)(`button`,{type:`submit`,disabled:!D.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:D.trim()?Ue:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:D.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,H.jsxs)(`div`,{style:{position:`relative`},children:[(y===`listening`||y===`thinking`)&&!S&&(0,H.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:y===`thinking`?g:h}),S&&(0,H.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,H.jsx)(o_,{size:72,voiceState:y,isMuted:S,orbColors:e})]}),y===`error`&&(0,H.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,H.jsx)(`button`,{onClick:Ve,title:S?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:S?`#7f1d1d`:`#1f2937`,border:S?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:S?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:S?(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,H.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,H.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,H.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,H.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,H.jsx)(dh,{size:16,color:`currentColor`})}),(0,H.jsx)(`button`,{onClick:()=>T(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,H.jsx)(yh,{size:16,color:`currentColor`})})]}),w&&(0,H.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,H.jsxs)(`button`,{onClick:()=>{T(!1),Se.current=`chat`,Be(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,H.jsx)(bh,{}),_]}),(0,H.jsxs)(`button`,{onClick:()=>{T(!1),Se.current=`minimized`,Be(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,H.jsx)(xh,{}),v]}),(0,H.jsx)(`button`,{onClick:()=>T(!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,H.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,H.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function u_({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,H.jsx)(`div`,{style:{width:`32px`,height:`32px`,borderRadius:`50%`,flexShrink:0,background:`
|
|
349
349
|
radial-gradient(circle at 18% 50%, ${n} 0%, ${n}99 35%, transparent 65%),
|
|
350
350
|
radial-gradient(circle at 82% 50%, ${r} 0%, ${r}99 35%, transparent 65%),
|
|
351
351
|
radial-gradient(circle at 50% 82%, ${i} 0%, ${i}99 30%, transparent 58%),
|
|
352
352
|
white
|
|
353
|
-
`.replace(/\s+/g,` `).trim()}})}var p_=()=>(0,H.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,H.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,H.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function m_({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:d,agentName:f,agentHeadshot:p,fallbackAgentName:m,input:h,setInput:g,onSubmit:_,isConversationEnded:v,isLoading:y,isRateLimited:x,rateLimitMessage:S,selectedFile:C,onFileSelect:w,onRemoveSelectedFile:T,attachmentError:E,isUploadingAttachment:ee,requiresEmail:D,emailInput:O,setEmailInput:k,emailError:A,emailCaptureSuccess:te,replyContext:ne,setReplyContext:re,webRTCError:ie,micError:j,setMicError:M,dismissCallError:ae,activeCallId:oe,isCallMuted:se,toggleCallMute:ce,endWebRTCCall:N,formatCallDuration:P,callDurationSeconds:le,isCallMinimized:ue,onExpand:de,onCollapse:F,onStartVoice:fe,voiceEnabled:pe,headerBgColor:me,onNewChat:I,showPoweredBy:he,privacyPolicyUrl:ge,getVisitorChatHistory:_e,resumeChat:ve,isSessionRestoring:ye,isClosing:be}){let xe=c.length>0,Se=y||x||v,Ce=!!oe,[we,Te]=(0,b.useState)(!1),[Ee,De]=(0,b.useState)(!1),[Oe,ke]=(0,b.useState)([]),[Ae,L]=(0,b.useState)(!1),je=(0,b.useRef)(null),[Me,Ne]=(0,b.useState)(()=>typeof window<`u`?window.visualViewport?.height??window.innerHeight:600),[R,Pe]=(0,b.useState)(0);(0,b.useEffect)(()=>{if(!s)return;let e=window.visualViewport;if(!e)return;let t=()=>{Ne(e.height),Pe(Math.max(0,window.innerHeight-e.offsetTop-e.height))};return e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}},[s]);let Fe=s&&window.innerHeight-Me>150,Ie=async()=>{Te(!1),De(!0),L(!0);try{let e=await _e();e?.data&&ke(e.data)}catch(e){console.error(e)}finally{L(!1)}},Le=async e=>{De(!1),ve?.(e.chatId)};return(0,b.useEffect)(()=>{if(!we)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;je.current&&!je.current.contains(t)&&Te(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[we]),(0,H.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`0`,right:`0`,bottom:`${R}px`,height:Me>0?`${Math.round(Me*(Fe?1:.92))}px`:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:be?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:be?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,H.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:me||`transparent`,flexShrink:0,position:`relative`,zIndex:30},children:[(0,H.jsx)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,H.jsx)(`button`,{onClick:F,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,H.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})})}),(()=>{let t=!!i,n=!!e.hasCustomTitle,r=t||n,a=t||!r,o=n||!r,c=a&&o;return(0,H.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:c?`minmax(72px, 40%) minmax(0, 60%)`:`1fr`,columnGap:c?`12px`:0,alignItems:`center`,justifyItems:c?`stretch`:`center`},children:[a&&(0,H.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,H.jsx)(a_,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,H.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,H.jsx)(o_,{title:e.chatTitle})})}),o&&(0,H.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:c?`flex-start`:`center`},children:(0,H.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]})})(),(0,H.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:je,children:[(0,H.jsx)(`button`,{type:`button`,onClick:()=>Te(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,H.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,H.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,H.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,H.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),we&&(0,H.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[pe&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{Te(!1),fe?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,H.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,H.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}})]}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{Te(!1),I?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`path`,{d:`M12 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,H.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new chat`]}),_e&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,H.jsxs)(`button`,{type:`button`,onClick:Ie,style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,H.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`path`,{d:`M12 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,H.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{Te(!1),F?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,H.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,H.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,H.jsx)(Gh,{webRTCError:ie,micError:j,setMicError:M,dismissCallError:ae,isRateLimited:x,rateLimitMessage:S}),ue&&(0,H.jsx)(cg,{agentName:f,agentHeadshot:p,fallbackAgentName:m,callDurationSeconds:le,isCallMuted:se,formatCallDuration:P,toggleCallMute:ce,endWebRTCCall:N,onExpand:de,primaryColor:n}),(0,H.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Ee?(0,H.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,H.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:(0,H.jsxs)(`button`,{onClick:()=>De(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,H.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,H.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,H.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Ae?(0,H.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):Oe.length>0?(0,H.jsx)(`div`,{children:Oe.map(e=>(0,H.jsxs)(`div`,{onClick:()=>Le(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,H.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,H.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,H.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,xe?(0,H.jsx)(Hh,{chatHistory:c,isAiTyping:l,isLoading:y,isAgentTyping:u,setReplyContext:re,TypingDots:p_,primaryColor:n,agentHeadshot:p,agentDisplayName:f||m,botAvatarNode:(0,H.jsx)(f_,{orbColors:t})}):ye?(0,H.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,H.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,H.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,H.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(0,H.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,H.jsx)(c_,{size:94,orbColors:t}),(0,H.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,H.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,H.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})]}),te&&(0,H.jsxs)(`div`,{style:{margin:`0 16px 8px`,padding:`9px 14px`,borderRadius:`12px`,background:`#ecfdf5`,border:`1px solid #6ee7b7`,display:`flex`,alignItems:`center`,gap:`8px`,animation:`fe-orb-fade-in 0.2s ease`,flexShrink:0},children:[(0,H.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#10b981`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,H.jsx)(`polyline`,{points:`20 6 9 17 4 12`})}),(0,H.jsx)(`span`,{style:{fontSize:`13px`,fontWeight:500,color:`#065f46`},children:`Email saved — we'll be in touch!`})]}),(0,H.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:D?`6px 0 0`:`12px 0 0`},children:(0,H.jsx)(Wh,{input:h,setInput:g,onSubmit:_,isConversationEnded:v,callUiActive:Ce,handleToggleVoice:fe,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Se,replyContext:ne,clearReplyContext:()=>re(null),onFileSelect:w,selectedFile:C,onRemoveSelectedFile:T,attachmentError:E,isUploadingAttachment:ee,requiresEmail:D,emailInput:O,setEmailInput:k,emailError:A,inputPlaceholder:e.inputPlaceholder})}),!Fe&&(0,H.jsxs)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`8px 20px`,paddingBottom:`max(12px, env(safe-area-inset-bottom, 12px))`,pointerEvents:`none`},children:[ge&&(0,H.jsxs)(`p`,{style:{margin:`0 0 4px`,fontSize:`10px`,color:`#9ca3af`,lineHeight:1.4,userSelect:`none`,pointerEvents:`auto`},children:[`This conversation is recorded for quality assurance purposes.`,` `,(0,H.jsx)(`a`,{href:ge,target:`_blank`,rel:`noopener noreferrer`,style:{color:`#6b7280`,textDecoration:`underline`},children:`See our privacy policy`})]}),he&&(0,H.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,H.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})]})]})}function h_(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:d,isLoading:f,isRateLimited:p,rateLimitMessage:m,isConversationEnded:h,incomingCall:g,activeCallId:_,callConnectionState:v,callConnectedAt:y,isCallMuted:x,webRTCError:S,language:C,chatId:w,historyRef:T,onMessageSync:E,sendMessage:ee,uploadChatFile:D,openWidget:O,captureVisitorEmail:k,setVoiceMode:A,endConversation:te,startNewChat:ne,acceptCall:re,rejectCall:ie,endWebRTCCall:ae,toggleCallMute:oe,dismissCallError:se,startTyping:ce,stopTyping:N,updateTypingDraft:P,getVisitorChatHistory:le,resumeChat:ue,isSessionRestoring:de,openToChatCounter:F,voiceEndCounter:fe}=wn();(0,b.useEffect)(()=>{try{cr()}catch{}},[]),(0,b.useEffect)(()=>{F&&Xe!==`voice_mode`&&Xe!==`text_chat`&&Xe!==`call_screen`&&(A?.(!1),Ze(`text_chat`))},[F]);let pe=t?.widgetSettings||{},me=n?.widgetSettings||{},I={...pe.branding||{},...me.branding||{}},he={...pe.theme||{},...me.theme||{}},ge={...pe.features||{},...me.features||{}},_e=ge.voice!==!1,be=Array.isArray(he.orbColors)&&he.orbColors.length>0?he.orbColors:null,xe=he.buttonColor||he.primaryColor||be?.[0]||`#3B82F6`,Ce={small:50,medium:64,large:80},we=Ce[he.orbSize]||Ce.small,Ee=he.position||`bottom-right`,De=I.fallbackAgentName||`Agent`,Oe=n_(be??he.chatBgColors),ke=I.logo||I.logoUrl||null,Ae=C||`en`,L=pe.recommendations?.[Ae]||[],je=(me.recommendations?.[Ae]??L).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Me=Array.isArray(I.quickChatOptions)&&I.quickChatOptions.length>0?I.quickChatOptions:je,Ne=I.hideWatermark===!0?!1:I.showPoweredBy!==!1,R=I.headerBgColor||null,Pe=he.bottomPosition==null?`1.5rem`:`${he.bottomPosition}px`,Fe=I.privacyPolicyUrl||null,Ie=I.chatbotEnabled!==!1&&he.chatbotEnabled!==!1,[Le,Re]=(0,b.useState)(()=>typeof window<`u`?window.location.pathname:`/`);(0,b.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>Re(window.location.pathname),t=window.history.pushState.bind(window.history);return window.history.pushState=(...n)=>{t(...n),setTimeout(e,50)},window.addEventListener(`popstate`,e),()=>{window.history.pushState=t,window.removeEventListener(`popstate`,e)}},[]);let ze=(()=>{let e={...pe.pageVisibility||{},...me.pageVisibility||{}};return Array.isArray(e.allowedPaths)?e.allowedPaths.filter(Boolean):[]})(),Be=ze.length===0||ze.some(e=>e===`*`||e===`/*`?!0:e.endsWith(`/*`)?Le.startsWith(e.slice(0,-1)):Le.replace(/\/$/,``)===e.replace(/\/$/,``)),Ve=pe.greetings?.[C]||me.greetings?.[C]||I.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,He={entryPrompt:I.entryPrompt||`Do you want to explore in a new way?`,yesLabel:I.yesLabel||`Yes`,laterLabel:I.laterLabel||`Later`,connectionTitle:I.connectionTitle||`How would you like to connect?`,connectionSubtitle:I.connectionSubtitle||``,voiceLabel:I.voiceLabel||`Voice`,textLabel:I.textLabel||`Text`,chatTitle:I.headerName||`Chat with FlowEngage`,hasCustomTitle:!!(I.headerName&&String(I.headerName).trim()),introGreeting:Ve,inputPlaceholder:I.inputPlaceholder||`Type your message`,analysingLabel:I.analysingLabel||`analysing...`},Ue=me.elevenLabsAgentId||t?.elevenLabsAgentId||null,We=t?.siteId||n?.siteId||null,Ge=t?.apiBaseUrl||``;(0,b.useEffect)(()=>{Jn(t?.siteType||null)},[t?.siteType]);let Ke=(0,b.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),qe=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,z=r.some(e=>e.sender===`user`),Je=(0,b.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),Ye=!!(me._dashboardLivePreview||pe._dashboardLivePreview),[Xe,Ze]=(0,b.useState)(()=>Ye?`text_chat`:`entry_prompt`),[Qe,$e]=(0,b.useState)(``),[et,tt]=(0,b.useState)(null),[nt,rt]=(0,b.useState)(l||``),[it,at]=(0,b.useState)(``),[ot,B]=(0,b.useState)(!1),[st,ct]=(0,b.useState)(0),[lt,ut]=(0,b.useState)(null),[dt,ft]=(0,b.useState)(null),[pt,mt]=(0,b.useState)(``),[ht,gt]=(0,b.useState)(!1),[_t,vt]=(0,b.useState)(!1),[yt,bt]=(0,b.useState)(!1),xt=(0,b.useRef)(null),St=(0,b.useRef)(!1),Ct=!l&&z&&Je&&Xe!==`voice_mode`;(0,b.useLayoutEffect)(()=>{if(e!==`ready`||St.current)return;if(St.current=!0,!_e){Ze(`minimized_orb`);return}let t=!1;try{t=br().shouldResumeVoice}catch{}let n=Se(),r=We?ve(We):null,i=n||!!r?.transcript;if(t){O?.({notifyChatInitiated:!0}),A?.(!0),Ze(`voice_mode`);return}if(Te()){O?.({notifyChatInitiated:!1}),Ze(`text_chat`);return}if(i){if((typeof performance<`u`?performance.getEntriesByType?.(`navigation`)?.[0]?.type??`navigate`:`navigate`)===`reload`){Ze(`minimized_orb`);return}O?.({notifyChatInitiated:!0}),A?.(!0),Ze(`voice_mode`);return}if(We)try{ye(We)}catch{}if(j(We)){Ze(`minimized_orb`);return}},[e,r]);let[wt,Tt]=(0,b.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,b.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>Tt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,b.useEffect)(()=>{rt(l||``),l&&at(``)},[l]);let Et=(0,b.useCallback)(()=>{ft(null),mt(``)},[]),Dt=(0,b.useCallback)(e=>{let t=Lh(e);if(t){ft(null),mt(t);return}ft(e),mt(``)},[]);(0,b.useEffect)(()=>{if(!y||v!==`connected`){ct(0);return}let e=()=>{let e=new Date(y).getTime();isNaN(e)||ct(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[y,v]);let Ot=(0,b.useCallback)(()=>{Ze(`call_screen`),vt(!1)},[]),kt=(0,b.useCallback)(()=>{Ze(`text_chat`),vt(!0)},[]);(0,b.useEffect)(()=>{let e=g?.callId||_||null;if(!e){xt.current=null;return}if(g?.callId||v===`connecting`||v===`connected`){if(Xe===`minimized_orb`&&_t&&_&&!g?.callId){xt.current=e;return}!(!i||Xe===`minimized_orb`||Xe===`voice_mode`)&&xt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:Xe,hasIncomingCall:!!g?.callId,activeCallId:_,callConnectionState:v}),xt.current=e,Xe===`voice_mode`&&A?.(!1),O?.(),Ot())}},[_,v,Ot,g?.callId,i,O,A,Xe]),(0,b.useEffect)(()=>{!g&&!_&&Xe===`call_screen`&&Ze(`text_chat`)},[g,_,Xe]),(0,b.useEffect)(()=>{!_&&_t&&vt(!1)},[_,_t]),(0,b.useEffect)(()=>{if(!o||h){P?.(``),N?.();return}if(!Qe.trim()||dt){P?.(``);let e=window.setTimeout(()=>N?.(),100);return()=>window.clearTimeout(e)}ce?.();let e=window.setTimeout(()=>P?.(Qe),120),t=window.setTimeout(()=>N?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[Qe,dt,o,h,ce,N,P]);let At=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,jt=async e=>{if(e.preventDefault(),h)return;if(Ct){let e=nt.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){at(`Please enter a valid email so we can continue helping you.`);return}await k(e),at(``),B(!0),setTimeout(()=>B(!1),3e3);return}let t=At(et);if(!Qe.trim()&&!dt)return;if(dt){try{gt(!0),mt(``);let e=await D(dt),n=e?.data||e,r=Qe.trim()||`Shared file: ${zh(dt)}`;$e(``),tt(null),Et(),await ee(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||dt.name,fileType:n?.fileType||dt.type,fileSize:n?.fileSize||dt.size}})}catch(e){mt(e?.message||`Failed to upload the selected file.`)}finally{gt(!1)}return}let n=Qe.trim();$e(``),tt(null),await ee(n,``,t)},Mt=(0,b.useCallback)(()=>{r.length!==0&&ne?.()},[r.length,ne]),Nt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},Pt=(0,b.useCallback)(async e=>{if(h||f)return;let t=e.message||e.label||e.text||``;t.trim()&&await ee(t.trim(),``)},[h,f,ee]),Ft=wt&&Xe===`entry_prompt`?{inset:0}:wt&&Xe===`text_chat`?{left:0,right:0,bottom:0}:wt&&Xe===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:wt&&Xe===`connection_modal`?{left:`12px`,right:`12px`,bottom:`12px`}:Xe===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Ee===`bottom-left`?{left:`1.5rem`,bottom:Pe}:{right:`1.5rem`,bottom:Pe}}:Ee===`bottom-left`?{left:`1.5rem`,bottom:Pe}:{right:`1.5rem`,bottom:Pe},It=(0,b.useCallback)(()=>{Xe!==`minimized_orb`&&(bt(!0),setTimeout(()=>{Ze(`minimized_orb`),bt(!1),_&&vt(!0)},280))},[_,Xe]),Lt=()=>Ze(`connection_modal`),Rt=()=>{try{let e=window.AudioContext||window.webkitAudioContext;if(e){let t=new e;t.resume().catch(()=>{}),setTimeout(()=>t.close().catch(()=>{}),3e3)}}catch{}O({notifyChatInitiated:!0}),A?.(!0),Ze(`voice_mode`)},zt=()=>{O({notifyChatInitiated:!0}),A?.(!1),Ze(`text_chat`)},Bt=()=>{A?.(!1),It()};return e!==`ready`||!Ie||ge.chat===!1||!Be?null:(0,H.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Ft},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[Xe===`entry_prompt`&&(0,H.jsx)(l_,{copy:He,orbColors:be,primaryColor:xe,onYes:()=>{M(We),Rt()},onLater:()=>{M(We),It()},isMobile:wt,isClosing:yt}),Xe===`minimized_orb`&&(0,H.jsxs)(Km.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Ee===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[_&&(0,H.jsxs)(`button`,{type:`button`,onClick:Ot,style:{maxWidth:wt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,H.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,H.jsxs)(`span`,{style:{minWidth:0},children:[(0,H.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:v===`connected`?`Call in progress`:`Call is active`}),(0,H.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:v===`connected`?`${Nt(st)} with ${Ke}`:`Tap to return to ${Ke}`})]})]}),(0,H.jsx)(c_,{size:we,orbColors:be,onClick:_?Ot:_e?Lt:zt})]}),Xe===`connection_modal`&&(0,H.jsx)(u_,{copy:He,orbColors:be,primaryColor:xe,onVoice:Rt,onText:zt,onClose:It,isMobile:wt,isClosing:yt}),Xe===`voice_mode`&&(0,H.jsx)(d_,{orbColors:be,onEnterChat:zt,onEndChat:Bt,agentId:Ue,siteId:We,apiBaseUrl:Ge,chatId:w,historyRef:T,onMessageSync:E,voiceEndCounter:fe,websiteName:t?.websiteName,voiceFirstMessage:pe.voiceFirstMessage||null,captureVisitorEmail:k,emailRequired:!l,emailCaptureEnabled:ge.emailCapture!==!1&&I.disableEmailCapture!==!0,listeningLabel:I.voiceListeningLabel||`Listening...`,thinkingLabel:I.voiceThinkingLabel||`Thinking...`,enterChatModeLabel:I.voiceEnterChatLabel||`Enter Chat Mode`,endConversationLabel:I.voiceEndConversationLabel||`End Conversation`},`voice`),Xe===`call_screen`&&(0,H.jsx)(sg,{incomingCall:g,activeCallId:_,callConnectionState:v,callDurationSeconds:st,isCallMuted:x,agentName:Ke,agentHeadshot:qe,fallbackAgentName:De,acceptCall:re,rejectCall:ie,endWebRTCCall:ae,toggleCallMute:oe,formatCallDuration:Nt,onMinimize:kt,primaryColor:xe,orbColors:be,chatHistory:r}),Xe===`text_chat`&&(0,H.jsx)(m_,{isClosing:yt,copy:He,orbColors:be,primaryColor:xe,chatBgGradient:Oe,logo:ke,quickChatOptions:Me,onQuickChatSelect:Pt,isMobile:wt,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Ke,agentHeadshot:qe,fallbackAgentName:De,input:Qe,setInput:$e,onSubmit:jt,isConversationEnded:h,isLoading:f,isRateLimited:p,rateLimitMessage:m,selectedFile:dt,onFileSelect:Dt,onRemoveSelectedFile:Et,attachmentError:pt,isUploadingAttachment:ht,requiresEmail:Ct,emailInput:nt,setEmailInput:rt,emailError:it,emailCaptureSuccess:ot,replyContext:et,setReplyContext:tt,webRTCError:S,micError:lt,setMicError:ut,dismissCallError:se,activeCallId:_,isCallMuted:x,toggleCallMute:oe,endWebRTCCall:ae,formatCallDuration:Nt,callDurationSeconds:st,onCollapse:It,onStartVoice:Rt,voiceEnabled:_e,onNewChat:Mt,onMinimize:kt,onExpand:Ot,isCallMinimized:!!_,showPoweredBy:Ne,privacyPolicyUrl:Fe,headerBgColor:R,getVisitorChatHistory:le,resumeChat:ue,isSessionRestoring:de}),(0,H.jsx)(`style`,{children:`
|
|
353
|
+
`.replace(/\s+/g,` `).trim()}})}var d_=()=>(0,H.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,H.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,H.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function f_({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:d,agentName:f,agentHeadshot:p,fallbackAgentName:m,input:h,setInput:g,onSubmit:_,isConversationEnded:v,isLoading:y,isRateLimited:x,rateLimitMessage:S,selectedFile:C,onFileSelect:w,onRemoveSelectedFile:T,attachmentError:E,isUploadingAttachment:ee,requiresEmail:D,emailInput:O,setEmailInput:k,emailError:A,emailCaptureSuccess:te,replyContext:ne,setReplyContext:re,webRTCError:ie,micError:j,setMicError:M,dismissCallError:ae,activeCallId:oe,isCallMuted:se,toggleCallMute:ce,endWebRTCCall:N,formatCallDuration:P,callDurationSeconds:le,isCallMinimized:ue,onExpand:de,onCollapse:F,onStartVoice:fe,voiceEnabled:pe,headerBgColor:me,onNewChat:I,showPoweredBy:he,privacyPolicyUrl:ge,getVisitorChatHistory:_e,resumeChat:ve,isSessionRestoring:ye,isClosing:be}){let xe=c.length>0,Se=y||x||v,Ce=!!oe,[we,Te]=(0,b.useState)(!1),[Ee,De]=(0,b.useState)(!1),[Oe,ke]=(0,b.useState)([]),[Ae,L]=(0,b.useState)(!1),je=(0,b.useRef)(null),[Me,Ne]=(0,b.useState)(()=>typeof window<`u`?window.visualViewport?.height??window.innerHeight:600),[R,Pe]=(0,b.useState)(0);(0,b.useEffect)(()=>{if(!s)return;let e=window.visualViewport;if(!e)return;let t=()=>{Ne(e.height),Pe(Math.max(0,window.innerHeight-e.offsetTop-e.height))};return e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}},[s]);let Fe=s&&window.innerHeight-Me>150,Ie=async()=>{Te(!1),De(!0),L(!0);try{let e=await _e();e?.data&&ke(e.data)}catch(e){console.error(e)}finally{L(!1)}},Le=async e=>{De(!1),ve?.(e.chatId)};return(0,b.useEffect)(()=>{if(!we)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;je.current&&!je.current.contains(t)&&Te(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[we]),(0,H.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`0`,right:`0`,bottom:`${R}px`,height:Me>0?`${Math.round(Me*(Fe?1:.92))}px`:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:be?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:be?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,H.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:me||`transparent`,flexShrink:0,position:`relative`,zIndex:30},children:[(0,H.jsx)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,H.jsx)(`button`,{onClick:F,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,H.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})})}),(()=>{let t=!!i,n=!!e.hasCustomTitle,r=t||n,a=t||!r,o=n||!r,c=a&&o;return(0,H.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:c?`minmax(72px, 40%) minmax(0, 60%)`:`1fr`,columnGap:c?`12px`:0,alignItems:`center`,justifyItems:c?`stretch`:`center`},children:[a&&(0,H.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,H.jsx)(r_,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,H.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,H.jsx)(i_,{title:e.chatTitle})})}),o&&(0,H.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:c?`flex-start`:`center`},children:(0,H.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]})})(),(0,H.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:je,children:[(0,H.jsx)(`button`,{type:`button`,onClick:()=>Te(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,H.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,H.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,H.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,H.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),we&&(0,H.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[pe&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{Te(!1),fe?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,H.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,H.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}})]}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{Te(!1),I?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`path`,{d:`M12 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,H.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new chat`]}),_e&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,H.jsxs)(`button`,{type:`button`,onClick:Ie,style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,H.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`path`,{d:`M12 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,H.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,H.jsxs)(`button`,{type:`button`,onClick:()=>{Te(!1),F?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,H.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,H.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,H.jsx)(Uh,{webRTCError:ie,micError:j,setMicError:M,dismissCallError:ae,isRateLimited:x,rateLimitMessage:S}),ue&&(0,H.jsx)(og,{agentName:f,agentHeadshot:p,fallbackAgentName:m,callDurationSeconds:le,isCallMuted:se,formatCallDuration:P,toggleCallMute:ce,endWebRTCCall:N,onExpand:de,primaryColor:n}),(0,H.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Ee?(0,H.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,H.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:(0,H.jsxs)(`button`,{onClick:()=>De(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,H.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,H.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,H.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Ae?(0,H.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):Oe.length>0?(0,H.jsx)(`div`,{children:Oe.map(e=>(0,H.jsxs)(`div`,{onClick:()=>Le(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,H.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,H.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,H.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,xe?(0,H.jsx)(Bh,{chatHistory:c,isAiTyping:l,isLoading:y,isAgentTyping:u,setReplyContext:re,TypingDots:d_,primaryColor:n,agentHeadshot:p,agentDisplayName:f||m,botAvatarNode:(0,H.jsx)(u_,{orbColors:t})}):ye?(0,H.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,H.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,H.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,H.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(0,H.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,H.jsx)(o_,{size:94,orbColors:t}),(0,H.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,H.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,H.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})]}),te&&(0,H.jsxs)(`div`,{style:{margin:`0 16px 8px`,padding:`9px 14px`,borderRadius:`12px`,background:`#ecfdf5`,border:`1px solid #6ee7b7`,display:`flex`,alignItems:`center`,gap:`8px`,animation:`fe-orb-fade-in 0.2s ease`,flexShrink:0},children:[(0,H.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#10b981`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,H.jsx)(`polyline`,{points:`20 6 9 17 4 12`})}),(0,H.jsx)(`span`,{style:{fontSize:`13px`,fontWeight:500,color:`#065f46`},children:`Email saved — we'll be in touch!`})]}),(0,H.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:D?`6px 0 0`:`12px 0 0`},children:(0,H.jsx)(Hh,{input:h,setInput:g,onSubmit:_,isConversationEnded:v,callUiActive:Ce,handleToggleVoice:fe,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Se,replyContext:ne,clearReplyContext:()=>re(null),onFileSelect:w,selectedFile:C,onRemoveSelectedFile:T,attachmentError:E,isUploadingAttachment:ee,requiresEmail:D,emailInput:O,setEmailInput:k,emailError:A,inputPlaceholder:e.inputPlaceholder})}),!Fe&&(0,H.jsxs)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`8px 20px`,paddingBottom:`max(12px, env(safe-area-inset-bottom, 12px))`,pointerEvents:`none`},children:[ge&&(0,H.jsxs)(`p`,{style:{margin:`0 0 4px`,fontSize:`10px`,color:`#9ca3af`,lineHeight:1.4,userSelect:`none`,pointerEvents:`auto`},children:[`This conversation is recorded for quality assurance purposes.`,` `,(0,H.jsx)(`a`,{href:ge,target:`_blank`,rel:`noopener noreferrer`,style:{color:`#6b7280`,textDecoration:`underline`},children:`See our privacy policy`})]}),he&&(0,H.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,H.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})]})]})}function p_(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:d,isLoading:f,isRateLimited:p,rateLimitMessage:m,isConversationEnded:h,incomingCall:g,activeCallId:_,callConnectionState:v,callConnectedAt:y,isCallMuted:x,webRTCError:S,language:C,chatId:w,historyRef:T,onMessageSync:E,sendMessage:ee,uploadChatFile:D,openWidget:O,captureVisitorEmail:k,setVoiceMode:A,endConversation:te,startNewChat:ne,acceptCall:re,rejectCall:ie,endWebRTCCall:ae,toggleCallMute:oe,dismissCallError:se,startTyping:ce,stopTyping:N,updateTypingDraft:P,getVisitorChatHistory:le,resumeChat:ue,isSessionRestoring:de,openToChatCounter:F,voiceEndCounter:fe}=wn();(0,b.useEffect)(()=>{try{cr()}catch{}},[]),(0,b.useEffect)(()=>{F&&Xe!==`voice_mode`&&Xe!==`text_chat`&&Xe!==`call_screen`&&(A?.(!1),Ze(`text_chat`))},[F]);let pe=t?.widgetSettings||{},me=n?.widgetSettings||{},I={...pe.branding||{},...me.branding||{}},he={...pe.theme||{},...me.theme||{}},ge={...pe.features||{},...me.features||{}},_e=ge.voice!==!1,be=Array.isArray(he.orbColors)&&he.orbColors.length>0?he.orbColors:null,xe=he.buttonColor||he.primaryColor||be?.[0]||`#3B82F6`,Ce={small:50,medium:64,large:80},we=Ce[he.orbSize]||Ce.small,Ee=he.position||`bottom-right`,De=I.fallbackAgentName||`Agent`,Oe=e_(be??he.chatBgColors),ke=I.logo||I.logoUrl||null,Ae=C||`en`,L=pe.recommendations?.[Ae]||[],je=(me.recommendations?.[Ae]??L).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Me=Array.isArray(I.quickChatOptions)&&I.quickChatOptions.length>0?I.quickChatOptions:je,Ne=I.hideWatermark===!0?!1:I.showPoweredBy!==!1,R=I.headerBgColor||null,Pe=he.bottomPosition==null?`1.5rem`:`${he.bottomPosition}px`,Fe=I.privacyPolicyUrl||null,Ie=I.chatbotEnabled!==!1&&he.chatbotEnabled!==!1,[Le,Re]=(0,b.useState)(()=>typeof window<`u`?window.location.pathname:`/`);(0,b.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>Re(window.location.pathname),t=window.history.pushState.bind(window.history);return window.history.pushState=(...n)=>{t(...n),setTimeout(e,50)},window.addEventListener(`popstate`,e),()=>{window.history.pushState=t,window.removeEventListener(`popstate`,e)}},[]);let ze=(()=>{let e={...pe.pageVisibility||{},...me.pageVisibility||{}};return Array.isArray(e.allowedPaths)?e.allowedPaths.filter(Boolean):[]})(),Be=ze.length===0||ze.some(e=>e===`*`||e===`/*`?!0:e.endsWith(`/*`)?Le.startsWith(e.slice(0,-1)):Le.replace(/\/$/,``)===e.replace(/\/$/,``)),Ve=pe.greetings?.[C]||me.greetings?.[C]||I.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,He={entryPrompt:I.entryPrompt||`Do you want to explore in a new way?`,yesLabel:I.yesLabel||`Yes`,laterLabel:I.laterLabel||`Later`,connectionTitle:I.connectionTitle||`How would you like to connect?`,connectionSubtitle:I.connectionSubtitle||``,voiceLabel:I.voiceLabel||`Voice`,textLabel:I.textLabel||`Text`,chatTitle:I.headerName||`Chat with FlowEngage`,hasCustomTitle:!!(I.headerName&&String(I.headerName).trim()),introGreeting:Ve,inputPlaceholder:I.inputPlaceholder||`Type your message`,analysingLabel:I.analysingLabel||`analysing...`},Ue=me.elevenLabsAgentId||t?.elevenLabsAgentId||null,We=t?.siteId||n?.siteId||null,Ge=t?.apiBaseUrl||``;(0,b.useEffect)(()=>{Jn(t?.siteType||null)},[t?.siteType]);let Ke=(0,b.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),qe=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,z=r.some(e=>e.sender===`user`),Je=(0,b.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),Ye=!!(me._dashboardLivePreview||pe._dashboardLivePreview),[Xe,Ze]=(0,b.useState)(()=>Ye?`text_chat`:`entry_prompt`),[Qe,$e]=(0,b.useState)(``),[et,tt]=(0,b.useState)(null),[nt,rt]=(0,b.useState)(l||``),[it,at]=(0,b.useState)(``),[ot,B]=(0,b.useState)(!1),[st,ct]=(0,b.useState)(0),[lt,ut]=(0,b.useState)(null),[dt,ft]=(0,b.useState)(null),[pt,mt]=(0,b.useState)(``),[ht,gt]=(0,b.useState)(!1),[_t,vt]=(0,b.useState)(!1),[yt,bt]=(0,b.useState)(!1),xt=(0,b.useRef)(null),St=(0,b.useRef)(!1),Ct=!l&&z&&Je&&Xe!==`voice_mode`;(0,b.useLayoutEffect)(()=>{if(e!==`ready`||St.current)return;if(St.current=!0,!_e){Ze(`minimized_orb`);return}let t=!1;try{t=br().shouldResumeVoice}catch{}let n=Se(),r=We?ve(We):null,i=n||!!r?.transcript;if(t){O?.({notifyChatInitiated:!0}),A?.(!0),Ze(`voice_mode`);return}if(Te()){O?.({notifyChatInitiated:!1}),Ze(`text_chat`);return}if(i){if((typeof performance<`u`?performance.getEntriesByType?.(`navigation`)?.[0]?.type??`navigate`:`navigate`)===`reload`){Ze(`minimized_orb`);return}O?.({notifyChatInitiated:!0}),A?.(!0),Ze(`voice_mode`);return}if(We)try{ye(We)}catch{}if(j(We)){Ze(`minimized_orb`);return}},[e,r]);let[wt,Tt]=(0,b.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,b.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>Tt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,b.useEffect)(()=>{rt(l||``),l&&at(``)},[l]);let Et=(0,b.useCallback)(()=>{ft(null),mt(``)},[]),Dt=(0,b.useCallback)(e=>{let t=Fh(e);if(t){ft(null),mt(t);return}ft(e),mt(``)},[]);(0,b.useEffect)(()=>{if(!y||v!==`connected`){ct(0);return}let e=()=>{let e=new Date(y).getTime();isNaN(e)||ct(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[y,v]);let Ot=(0,b.useCallback)(()=>{Ze(`call_screen`),vt(!1)},[]),kt=(0,b.useCallback)(()=>{Ze(`text_chat`),vt(!0)},[]);(0,b.useEffect)(()=>{let e=g?.callId||_||null;if(!e){xt.current=null;return}if(g?.callId||v===`connecting`||v===`connected`){if(Xe===`minimized_orb`&&_t&&_&&!g?.callId){xt.current=e;return}!(!i||Xe===`minimized_orb`||Xe===`voice_mode`)&&xt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:Xe,hasIncomingCall:!!g?.callId,activeCallId:_,callConnectionState:v}),xt.current=e,Xe===`voice_mode`&&A?.(!1),O?.(),Ot())}},[_,v,Ot,g?.callId,i,O,A,Xe]),(0,b.useEffect)(()=>{!g&&!_&&Xe===`call_screen`&&Ze(`text_chat`)},[g,_,Xe]),(0,b.useEffect)(()=>{!_&&_t&&vt(!1)},[_,_t]),(0,b.useEffect)(()=>{if(!o||h){P?.(``),N?.();return}if(!Qe.trim()||dt){P?.(``);let e=window.setTimeout(()=>N?.(),100);return()=>window.clearTimeout(e)}ce?.();let e=window.setTimeout(()=>P?.(Qe),120),t=window.setTimeout(()=>N?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[Qe,dt,o,h,ce,N,P]);let At=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,jt=async e=>{if(e.preventDefault(),h)return;if(Ct){let e=nt.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){at(`Please enter a valid email so we can continue helping you.`);return}await k(e),at(``),B(!0),setTimeout(()=>B(!1),3e3);return}let t=At(et);if(!Qe.trim()&&!dt)return;if(dt){try{gt(!0),mt(``);let e=await D(dt),n=e?.data||e,r=Qe.trim()||`Shared file: ${Lh(dt)}`;$e(``),tt(null),Et(),await ee(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||dt.name,fileType:n?.fileType||dt.type,fileSize:n?.fileSize||dt.size}})}catch(e){mt(e?.message||`Failed to upload the selected file.`)}finally{gt(!1)}return}let n=Qe.trim();$e(``),tt(null),await ee(n,``,t)},Mt=(0,b.useCallback)(()=>{r.length!==0&&ne?.()},[r.length,ne]),Nt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},Pt=(0,b.useCallback)(async e=>{if(h||f)return;let t=e.message||e.label||e.text||``;t.trim()&&await ee(t.trim(),``)},[h,f,ee]),Ft=wt&&Xe===`entry_prompt`?{inset:0}:wt&&Xe===`text_chat`?{left:0,right:0,bottom:0}:wt&&Xe===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:wt&&Xe===`connection_modal`?{left:`12px`,right:`12px`,bottom:`12px`}:Xe===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Ee===`bottom-left`?{left:`1.5rem`,bottom:Pe}:{right:`1.5rem`,bottom:Pe}}:Ee===`bottom-left`?{left:`1.5rem`,bottom:Pe}:{right:`1.5rem`,bottom:Pe},It=(0,b.useCallback)(()=>{Xe!==`minimized_orb`&&(bt(!0),setTimeout(()=>{Ze(`minimized_orb`),bt(!1),_&&vt(!0)},280))},[_,Xe]),Lt=()=>Ze(`connection_modal`),Rt=()=>{try{let e=window.AudioContext||window.webkitAudioContext;if(e){let t=new e;t.resume().catch(()=>{}),setTimeout(()=>t.close().catch(()=>{}),3e3)}}catch{}O({notifyChatInitiated:!0}),A?.(!0),Ze(`voice_mode`)},zt=()=>{O({notifyChatInitiated:!0}),A?.(!1),Ze(`text_chat`)},Bt=()=>{A?.(!1),It()};return e!==`ready`||!Ie||ge.chat===!1||!Be?null:(0,H.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Ft},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[Xe===`entry_prompt`&&(0,H.jsx)(s_,{copy:He,orbColors:be,primaryColor:xe,onYes:()=>{M(We),Rt()},onLater:()=>{M(We),It()},isMobile:wt,isClosing:yt}),Xe===`minimized_orb`&&(0,H.jsxs)(Km.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Ee===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[_&&(0,H.jsxs)(`button`,{type:`button`,onClick:Ot,style:{maxWidth:wt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,H.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,H.jsxs)(`span`,{style:{minWidth:0},children:[(0,H.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:v===`connected`?`Call in progress`:`Call is active`}),(0,H.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:v===`connected`?`${Nt(st)} with ${Ke}`:`Tap to return to ${Ke}`})]})]}),(0,H.jsx)(o_,{size:we,orbColors:be,onClick:_?Ot:_e?Lt:zt})]}),Xe===`connection_modal`&&(0,H.jsx)(c_,{copy:He,orbColors:be,primaryColor:xe,onVoice:Rt,onText:zt,onClose:It,isMobile:wt,isClosing:yt}),Xe===`voice_mode`&&(0,H.jsx)(l_,{orbColors:be,onEnterChat:zt,onEndChat:Bt,agentId:Ue,siteId:We,apiBaseUrl:Ge,chatId:w,historyRef:T,onMessageSync:E,voiceEndCounter:fe,websiteName:t?.websiteName,voiceFirstMessage:pe.voiceFirstMessage||null,captureVisitorEmail:k,emailRequired:!l,emailCaptureEnabled:ge.emailCapture!==!1&&I.disableEmailCapture!==!0,listeningLabel:I.voiceListeningLabel||`Listening...`,thinkingLabel:I.voiceThinkingLabel||`Thinking...`,enterChatModeLabel:I.voiceEnterChatLabel||`Enter Chat Mode`,endConversationLabel:I.voiceEndConversationLabel||`End Conversation`},`voice`),Xe===`call_screen`&&(0,H.jsx)(ag,{incomingCall:g,activeCallId:_,callConnectionState:v,callDurationSeconds:st,isCallMuted:x,agentName:Ke,agentHeadshot:qe,fallbackAgentName:De,acceptCall:re,rejectCall:ie,endWebRTCCall:ae,toggleCallMute:oe,formatCallDuration:Nt,onMinimize:kt,primaryColor:xe,orbColors:be,chatHistory:r}),Xe===`text_chat`&&(0,H.jsx)(f_,{isClosing:yt,copy:He,orbColors:be,primaryColor:xe,chatBgGradient:Oe,logo:ke,quickChatOptions:Me,onQuickChatSelect:Pt,isMobile:wt,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Ke,agentHeadshot:qe,fallbackAgentName:De,input:Qe,setInput:$e,onSubmit:jt,isConversationEnded:h,isLoading:f,isRateLimited:p,rateLimitMessage:m,selectedFile:dt,onFileSelect:Dt,onRemoveSelectedFile:Et,attachmentError:pt,isUploadingAttachment:ht,requiresEmail:Ct,emailInput:nt,setEmailInput:rt,emailError:it,emailCaptureSuccess:ot,replyContext:et,setReplyContext:tt,webRTCError:S,micError:lt,setMicError:ut,dismissCallError:se,activeCallId:_,isCallMuted:x,toggleCallMute:oe,endWebRTCCall:ae,formatCallDuration:Nt,callDurationSeconds:st,onCollapse:It,onStartVoice:Rt,voiceEnabled:_e,onNewChat:Mt,onMinimize:kt,onExpand:Ot,isCallMinimized:!!_,showPoweredBy:Ne,privacyPolicyUrl:Fe,headerBgColor:R,getVisitorChatHistory:le,resumeChat:ue,isSessionRestoring:de}),(0,H.jsx)(`style`,{children:`
|
|
354
354
|
/* Force any SVG (or img) inside LogoSlot to fill the container height
|
|
355
355
|
regardless of whether the component forwards its style prop. */
|
|
356
356
|
.fe-logo-slot svg,
|
|
@@ -369,4 +369,4 @@ Error generating stack: `+e.message+`
|
|
|
369
369
|
@keyframes fe-orb-bar-3 { from{height:8px} to{height:20px} }
|
|
370
370
|
@keyframes fe-orb-bar-4 { from{height:6px} to{height:16px} }
|
|
371
371
|
@keyframes fe-dot-bounce { 0%,80%,100%{transform:translateY(0);opacity:.5} 40%{transform:translateY(-5px);opacity:1} }
|
|
372
|
-
`})]})}var g_=class extends b.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`[FlowEngage] Widget crashed:`,e,t.componentStack)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}},__=`@import "https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap";:host{all:initial;box-sizing:border-box!important;color:#111827!important;-webkit-font-smoothing:antialiased!important;z-index:2147483647!important;background:0 0!important;border:none!important;margin:0!important;padding:0!important;font-family:Poppins,system-ui,-apple-system,sans-serif!important;font-size:16px!important;line-height:1.5!important;display:block!important;position:relative!important}:host *,:host :before,:host :after{box-sizing:border-box}.flowengage-widget-root{-moz-osx-font-smoothing:grayscale;text-rendering:optimizelegibility;color:#111827!important;-webkit-font-smoothing:antialiased!important;font-family:Poppins,system-ui,-apple-system,sans-serif!important;font-size:16px!important;line-height:1.5!important}.flowengage-widget-root *,.flowengage-widget-root :before,.flowengage-widget-root :after{font-family:inherit!important}.flowengage-widget-root input,.flowengage-widget-root textarea,.flowengage-widget-root button,.flowengage-widget-root select,.flowengage-widget-root optgroup,.flowengage-widget-root option{font-size:inherit;line-height:inherit;font-family:inherit!important}.flowengage-shell,.flowengage-shell *{font-family:inherit!important}.flowengage-chat-panel{border:none;border-radius:0;outline:none;flex-direction:column;width:100%;height:100%;display:flex;position:relative;overflow:hidden;box-shadow:0 20px 50px #00000026}.flowengage-chat-text-input{margin:0!important}.flowengage-chat-text-input:focus{box-shadow:none!important;border:none!important;outline:none!important}@media (width>=768px){.flowengage-chat-panel{border-radius:24px;width:min(350px,100vw - 40px);height:min(700px,100vh - 120px)}}.flowengage-shell[data-open=true]{inset:0}@media (width>=768px){.flowengage-shell[data-open=true]{inset:auto 1.5rem 1.5rem auto}}.flowengage-logo-fallback{background:conic-gradient(from 180deg, var(--flowengage-primary) 0%, var(--flowengage-accent) 45%, var(--flowengage-primary) 100%)}.fe-bot-message p{margin:0 0 .5em}.fe-bot-message p:last-child{margin-bottom:0}.fe-bot-message ul,.fe-bot-message ol{margin:.4em 0 .4em 1.2em;padding:0}.fe-bot-message li{margin-bottom:.25em}.fe-bot-message strong{font-weight:600}.fe-bot-message a{color:var(--flowengage-primary);text-decoration:underline}.fe-bot-message a:hover{opacity:.8}.incoming-call-overlay{z-index:1000;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#1a1a2ef2;justify-content:center;align-items:center;transition:all .3s ease-in-out;display:flex;position:absolute;left:0;right:0}.incoming-call-overlay.bottom-mode{border-top:2px solid #ffffff1a;min-height:120px;animation:.4s cubic-bezier(.16,1,.3,1) slideUpBanner;top:auto;bottom:0;box-shadow:0 -10px 30px #00000080}.incoming-call-overlay.header-mode{border-bottom:2px solid #ffffff1a;min-height:80px;animation:.4s cubic-bezier(.16,1,.3,1) slideDownBanner;top:0;bottom:auto;box-shadow:0 10px 30px #00000080}.incoming-call-container{justify-content:space-between;align-items:center;gap:14px;width:100%;padding:14px 16px;display:flex}.incoming-call-container.connected-layout{flex-direction:column;justify-content:center;align-items:stretch;gap:14px}.call-connected-top{justify-content:space-between;align-items:center;gap:16px;width:100%;display:flex}.call-connected-identity{flex:1;align-items:center;gap:14px;min-width:0;display:flex}.call-icon-wrapper{color:#fff;z-index:1;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;width:54px;height:54px;margin-right:4px;display:flex;position:relative}.call-icon-wrapper.incoming{background:linear-gradient(135deg,#4caf50,#45a049);animation:1s ease-in-out infinite bounce}.call-icon-wrapper.connecting{background:linear-gradient(135deg,#2196f3,#1976d2)}.call-icon-wrapper.connected{background:linear-gradient(135deg,#4caf50,#45a049)}.call-pulse-animation{z-index:-1;background:#4caf504d;border-radius:50%;width:120px;height:120px;animation:1.5s ease-out infinite pulse;position:absolute}.call-connecting-animation{z-index:-1;border:3px solid #0000;border-top-color:#2196f3;border-radius:50%;width:100px;height:100px;animation:1s linear infinite spin;position:absolute}.call-info-group{flex-direction:column;flex:1;min-width:0;margin-right:8px;display:flex}.call-title{color:#fff;white-space:normal;text-overflow:clip;margin:0;font-size:16px;font-weight:700;line-height:1.2;overflow:visible}.call-subtitle{color:#ffffffb3;white-space:normal;text-overflow:clip;margin:4px 0 0;font-size:12px;line-height:1.35;overflow:visible}.call-timer{text-align:center;color:#fff;flex-shrink:0;min-width:54px;font-size:13px;font-weight:700}.call-actions{flex-shrink:0;align-items:center;gap:8px;display:flex}.call-actions.connected{justify-content:center;width:100%}.flowengage-call-btn{cursor:pointer;color:#fff;border:none;border-radius:8px;justify-content:center;align-items:center;gap:6px;min-width:92px;padding:8px 12px;font-size:12px;font-weight:600;line-height:1;transition:transform .2s,box-shadow .2s,background .2s;display:flex}.flowengage-call-btn svg{flex-shrink:0;display:block}.flowengage-call-btn span{justify-content:center;align-items:center;line-height:1;display:flex}.flowengage-call-btn.icon-only{border-radius:9999px;width:46px;min-width:46px;height:46px;padding:0}.flowengage-call-btn-accept{background:linear-gradient(135deg,#4caf50,#45a049);box-shadow:0 8px 24px #4caf5066}.flowengage-call-btn-reject,.flowengage-call-btn-end{background:linear-gradient(135deg,#f44336,#d32f2f);box-shadow:0 4px 12px #f4433666}.flowengage-call-btn-mute{background:#ffffff1a;border:2px solid #fff3}.flowengage-call-btn-mute.active{background:#f443364d;border-color:#f44336}.flowengage-call-btn:hover:not(:disabled){transform:scale(1.05)}.incoming-call-overlay.header-mode .flowengage-call-btn{border-radius:9999px!important;width:36px!important;min-width:36px!important;height:36px!important;padding:0!important}.incoming-call-overlay.header-mode .flowengage-call-btn span{display:none!important}.incoming-call-overlay.header-mode .call-icon-wrapper{width:40px;height:40px;margin-right:0}.incoming-call-overlay.header-mode .call-info-group{min-width:0}.incoming-call-overlay.header-mode .call-title,.incoming-call-overlay.header-mode .call-subtitle{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}@media (width<=640px){.incoming-call-container{align-items:flex-start;gap:10px;padding:12px 14px}.incoming-call-container.connected-layout{align-items:stretch}.call-connected-top{flex-direction:column;align-items:flex-start;gap:10px}.call-connected-identity{width:100%}.call-info-group{margin-right:0}.call-actions{flex-wrap:wrap;align-self:stretch;gap:6px}.call-actions.connected{justify-content:stretch}.call-actions.connected .flowengage-call-btn{flex:1}.flowengage-call-btn{min-width:78px;padding:8px 10px}}@keyframes slideUpBanner{0%{transform:translateY(100%)}to{transform:translateY(0)}}@keyframes slideDownBanner{0%{transform:translateY(-100%)}to{transform:translateY(0)}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-10px)}}@keyframes pulse{0%{opacity:1;transform:scale(.8)}to{opacity:0;transform:scale(2)}}@keyframes spin{to{transform:rotate(360deg)}}.fe-screen-fade-in{animation:.4s cubic-bezier(.16,1,.3,1) forwards feFadeIn}@keyframes feFadeIn{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.flowengage-initial-bg{background-color:#fff;position:relative;overflow:hidden}.flowengage-initial-bg:before{content:"";background:linear-gradient(to bottom, var(--flowengage-primary) 0%, var(--flowengage-accent) 55%, white 82%);opacity:0;pointer-events:none;z-index:0;transition:opacity .6s cubic-bezier(.4,0,.2,1);position:absolute;inset:0}.flowengage-initial-bg.is-initial:before{opacity:1}.flowengage-content-wrapper{z-index:1;flex-direction:column;flex:1;min-height:0;display:flex;position:relative}`,v_=null,y_=!1;function b_(){let e=document.createElement(`div`);e.id=`flowengage-root`;let t=e.attachShadow({mode:`open`}),n=document.createElement(`style`);n.textContent=__,t.appendChild(n);let r=document.createElement(`div`);return r.setAttribute(`data-flowengage-mount`,`true`),r.className=`flowengage-widget-root`,t.appendChild(r),{host:e,mount:r}}function x_(e){if(document.body){e();return}let t=new MutationObserver(()=>{document.body&&(t.disconnect(),e())});t.observe(document.documentElement,{childList:!0})}function S_({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}){if(y_){console.warn(`[FlowEngage] Already initialized. Call FlowEngage.destroy() first to re-initialize.`);return}if(!e){console.error(`[FlowEngage] siteId is required. Pass it via data-site-id attribute or FlowEngage.init({ siteId: 'YOUR_SITE_ID' }).`);return}if(!document.body){console.error(`[FlowEngage] document.body is not available yet. The widget will auto-retry once the DOM is ready.`),x_(()=>S_({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}));return}if(document.getElementById(`flowengage-root`)){console.warn(`[FlowEngage] #flowengage-root already exists. Skipping duplicate mount.`);return}let{host:i,mount:a}=b_();document.body.appendChild(i),v_=(0,x.createRoot)(a);let o={widgetSettings:n,...r&&{apiBaseUrl:r}};v_.render(b.createElement(g_,null,b.createElement(gi,{siteId:e,language:t,config:o},b.createElement(h_)))),y_=!0}var C_={init({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}={}){document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>x_(()=>S_({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))):x_(()=>S_({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))},destroy(){v_&&=(v_.unmount(),null);let e=document.getElementById(`flowengage-root`);e&&e.remove();let t=document.getElementById(`flowengage-styles`);t&&t.remove(),y_=!1}},w_=()=>{let e=document.currentScript;(!e||!e.getAttribute(`data-site-id`)&&!e.getAttribute(`data-shop-domain`))&&(e=document.querySelector(`script[data-site-id], script[data-shop-domain]`));let t=e?.getAttribute(`data-site-id`),n=e?.getAttribute(`data-shop-domain`);if(!t&&!n)return;let r=e?.getAttribute(`data-language`)||`en`,i=e?.getAttribute(`data-api-url`)||void 0,a={};try{let t=e?.getAttribute(`data-widget-settings`);t&&(a=JSON.parse(t))}catch{}if(t){x_(()=>S_({siteId:t,language:r,widgetSettings:a,apiBaseUrl:i}));return}let o=(i||`https://be-flowengage-dev.oslabs.app`).replace(/\/+$/,``);fetch(`${o}/api/widget/resolve-shopify-tenant?shopDomain=${encodeURIComponent(n)}`).then(e=>e.json()).then(e=>{if(!e?.success||!e.siteId){console.error(`[FlowEngage] Could not resolve a FlowEngage account for shop:`,n,e?.message);return}x_(()=>S_({siteId:e.siteId,language:r,widgetSettings:a,apiBaseUrl:i}))}).catch(e=>console.error(`[FlowEngage] Failed to resolve shop tenant:`,e))};return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,w_):w_(),typeof window<`u`&&(window.FlowEngage=C_),C_})();
|
|
372
|
+
`})]})}var m_=class extends b.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`[FlowEngage] Widget crashed:`,e,t.componentStack)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}},h_=`@import "https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap";:host{all:initial;box-sizing:border-box!important;color:#111827!important;-webkit-font-smoothing:antialiased!important;z-index:2147483647!important;background:0 0!important;border:none!important;margin:0!important;padding:0!important;font-family:Poppins,system-ui,-apple-system,sans-serif!important;font-size:16px!important;line-height:1.5!important;display:block!important;position:relative!important}:host *,:host :before,:host :after{box-sizing:border-box}.flowengage-widget-root{-moz-osx-font-smoothing:grayscale;text-rendering:optimizelegibility;color:#111827!important;-webkit-font-smoothing:antialiased!important;font-family:Poppins,system-ui,-apple-system,sans-serif!important;font-size:16px!important;line-height:1.5!important}.flowengage-widget-root *,.flowengage-widget-root :before,.flowengage-widget-root :after{font-family:inherit!important}.flowengage-widget-root input,.flowengage-widget-root textarea,.flowengage-widget-root button,.flowengage-widget-root select,.flowengage-widget-root optgroup,.flowengage-widget-root option{font-size:inherit;line-height:inherit;font-family:inherit!important}.flowengage-shell,.flowengage-shell *{font-family:inherit!important}.flowengage-chat-panel{border:none;border-radius:0;outline:none;flex-direction:column;width:100%;height:100%;display:flex;position:relative;overflow:hidden;box-shadow:0 20px 50px #00000026}.flowengage-chat-text-input{margin:0!important}.flowengage-chat-text-input:focus{box-shadow:none!important;border:none!important;outline:none!important}@media (width>=768px){.flowengage-chat-panel{border-radius:24px;width:min(350px,100vw - 40px);height:min(700px,100vh - 120px)}}.flowengage-shell[data-open=true]{inset:0}@media (width>=768px){.flowengage-shell[data-open=true]{inset:auto 1.5rem 1.5rem auto}}.flowengage-logo-fallback{background:conic-gradient(from 180deg, var(--flowengage-primary) 0%, var(--flowengage-accent) 45%, var(--flowengage-primary) 100%)}.fe-bot-message p{margin:0 0 .5em}.fe-bot-message p:last-child{margin-bottom:0}.fe-bot-message ul,.fe-bot-message ol{margin:.4em 0 .4em 1.2em;padding:0}.fe-bot-message li{margin-bottom:.25em}.fe-bot-message strong{font-weight:600}.fe-bot-message a{color:var(--flowengage-primary);text-decoration:underline}.fe-bot-message a:hover{opacity:.8}.incoming-call-overlay{z-index:1000;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#1a1a2ef2;justify-content:center;align-items:center;transition:all .3s ease-in-out;display:flex;position:absolute;left:0;right:0}.incoming-call-overlay.bottom-mode{border-top:2px solid #ffffff1a;min-height:120px;animation:.4s cubic-bezier(.16,1,.3,1) slideUpBanner;top:auto;bottom:0;box-shadow:0 -10px 30px #00000080}.incoming-call-overlay.header-mode{border-bottom:2px solid #ffffff1a;min-height:80px;animation:.4s cubic-bezier(.16,1,.3,1) slideDownBanner;top:0;bottom:auto;box-shadow:0 10px 30px #00000080}.incoming-call-container{justify-content:space-between;align-items:center;gap:14px;width:100%;padding:14px 16px;display:flex}.incoming-call-container.connected-layout{flex-direction:column;justify-content:center;align-items:stretch;gap:14px}.call-connected-top{justify-content:space-between;align-items:center;gap:16px;width:100%;display:flex}.call-connected-identity{flex:1;align-items:center;gap:14px;min-width:0;display:flex}.call-icon-wrapper{color:#fff;z-index:1;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;width:54px;height:54px;margin-right:4px;display:flex;position:relative}.call-icon-wrapper.incoming{background:linear-gradient(135deg,#4caf50,#45a049);animation:1s ease-in-out infinite bounce}.call-icon-wrapper.connecting{background:linear-gradient(135deg,#2196f3,#1976d2)}.call-icon-wrapper.connected{background:linear-gradient(135deg,#4caf50,#45a049)}.call-pulse-animation{z-index:-1;background:#4caf504d;border-radius:50%;width:120px;height:120px;animation:1.5s ease-out infinite pulse;position:absolute}.call-connecting-animation{z-index:-1;border:3px solid #0000;border-top-color:#2196f3;border-radius:50%;width:100px;height:100px;animation:1s linear infinite spin;position:absolute}.call-info-group{flex-direction:column;flex:1;min-width:0;margin-right:8px;display:flex}.call-title{color:#fff;white-space:normal;text-overflow:clip;margin:0;font-size:16px;font-weight:700;line-height:1.2;overflow:visible}.call-subtitle{color:#ffffffb3;white-space:normal;text-overflow:clip;margin:4px 0 0;font-size:12px;line-height:1.35;overflow:visible}.call-timer{text-align:center;color:#fff;flex-shrink:0;min-width:54px;font-size:13px;font-weight:700}.call-actions{flex-shrink:0;align-items:center;gap:8px;display:flex}.call-actions.connected{justify-content:center;width:100%}.flowengage-call-btn{cursor:pointer;color:#fff;border:none;border-radius:8px;justify-content:center;align-items:center;gap:6px;min-width:92px;padding:8px 12px;font-size:12px;font-weight:600;line-height:1;transition:transform .2s,box-shadow .2s,background .2s;display:flex}.flowengage-call-btn svg{flex-shrink:0;display:block}.flowengage-call-btn span{justify-content:center;align-items:center;line-height:1;display:flex}.flowengage-call-btn.icon-only{border-radius:9999px;width:46px;min-width:46px;height:46px;padding:0}.flowengage-call-btn-accept{background:linear-gradient(135deg,#4caf50,#45a049);box-shadow:0 8px 24px #4caf5066}.flowengage-call-btn-reject,.flowengage-call-btn-end{background:linear-gradient(135deg,#f44336,#d32f2f);box-shadow:0 4px 12px #f4433666}.flowengage-call-btn-mute{background:#ffffff1a;border:2px solid #fff3}.flowengage-call-btn-mute.active{background:#f443364d;border-color:#f44336}.flowengage-call-btn:hover:not(:disabled){transform:scale(1.05)}.incoming-call-overlay.header-mode .flowengage-call-btn{border-radius:9999px!important;width:36px!important;min-width:36px!important;height:36px!important;padding:0!important}.incoming-call-overlay.header-mode .flowengage-call-btn span{display:none!important}.incoming-call-overlay.header-mode .call-icon-wrapper{width:40px;height:40px;margin-right:0}.incoming-call-overlay.header-mode .call-info-group{min-width:0}.incoming-call-overlay.header-mode .call-title,.incoming-call-overlay.header-mode .call-subtitle{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}@media (width<=640px){.incoming-call-container{align-items:flex-start;gap:10px;padding:12px 14px}.incoming-call-container.connected-layout{align-items:stretch}.call-connected-top{flex-direction:column;align-items:flex-start;gap:10px}.call-connected-identity{width:100%}.call-info-group{margin-right:0}.call-actions{flex-wrap:wrap;align-self:stretch;gap:6px}.call-actions.connected{justify-content:stretch}.call-actions.connected .flowengage-call-btn{flex:1}.flowengage-call-btn{min-width:78px;padding:8px 10px}}@keyframes slideUpBanner{0%{transform:translateY(100%)}to{transform:translateY(0)}}@keyframes slideDownBanner{0%{transform:translateY(-100%)}to{transform:translateY(0)}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-10px)}}@keyframes pulse{0%{opacity:1;transform:scale(.8)}to{opacity:0;transform:scale(2)}}@keyframes spin{to{transform:rotate(360deg)}}.fe-screen-fade-in{animation:.4s cubic-bezier(.16,1,.3,1) forwards feFadeIn}@keyframes feFadeIn{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.flowengage-initial-bg{background-color:#fff;position:relative;overflow:hidden}.flowengage-initial-bg:before{content:"";background:linear-gradient(to bottom, var(--flowengage-primary) 0%, var(--flowengage-accent) 55%, white 82%);opacity:0;pointer-events:none;z-index:0;transition:opacity .6s cubic-bezier(.4,0,.2,1);position:absolute;inset:0}.flowengage-initial-bg.is-initial:before{opacity:1}.flowengage-content-wrapper{z-index:1;flex-direction:column;flex:1;min-height:0;display:flex;position:relative}`,g_=null,__=!1;function v_(){let e=document.createElement(`div`);e.id=`flowengage-root`;let t=e.attachShadow({mode:`open`}),n=document.createElement(`style`);n.textContent=h_,t.appendChild(n);let r=document.createElement(`div`);return r.setAttribute(`data-flowengage-mount`,`true`),r.className=`flowengage-widget-root`,t.appendChild(r),{host:e,mount:r}}function y_(e){if(document.body){e();return}let t=new MutationObserver(()=>{document.body&&(t.disconnect(),e())});t.observe(document.documentElement,{childList:!0})}function b_({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}){if(__){console.warn(`[FlowEngage] Already initialized. Call FlowEngage.destroy() first to re-initialize.`);return}if(!e){console.error(`[FlowEngage] siteId is required. Pass it via data-site-id attribute or FlowEngage.init({ siteId: 'YOUR_SITE_ID' }).`);return}if(!document.body){console.error(`[FlowEngage] document.body is not available yet. The widget will auto-retry once the DOM is ready.`),y_(()=>b_({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}));return}if(document.getElementById(`flowengage-root`)){console.warn(`[FlowEngage] #flowengage-root already exists. Skipping duplicate mount.`);return}let{host:i,mount:a}=v_();document.body.appendChild(i),g_=(0,x.createRoot)(a);let o={widgetSettings:n,...r&&{apiBaseUrl:r}};g_.render(b.createElement(m_,null,b.createElement(gi,{siteId:e,language:t,config:o},b.createElement(p_)))),__=!0}var x_={init({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}={}){document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>y_(()=>b_({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))):y_(()=>b_({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))},destroy(){g_&&=(g_.unmount(),null);let e=document.getElementById(`flowengage-root`);e&&e.remove();let t=document.getElementById(`flowengage-styles`);t&&t.remove(),__=!1}},S_=()=>{let e=document.currentScript;(!e||!e.getAttribute(`data-site-id`)&&!e.getAttribute(`data-shop-domain`))&&(e=document.querySelector(`script[data-site-id], script[data-shop-domain]`));let t=e?.getAttribute(`data-site-id`),n=e?.getAttribute(`data-shop-domain`);if(!t&&!n)return;let r=e?.getAttribute(`data-language`)||`en`,i=e?.getAttribute(`data-api-url`)||void 0,a={};try{let t=e?.getAttribute(`data-widget-settings`);t&&(a=JSON.parse(t))}catch{}if(t){y_(()=>b_({siteId:t,language:r,widgetSettings:a,apiBaseUrl:i}));return}let o=(i||`https://be-flowengage-dev.oslabs.app`).replace(/\/+$/,``);fetch(`${o}/api/widget/resolve-shopify-tenant?shopDomain=${encodeURIComponent(n)}`).then(e=>e.json()).then(e=>{if(!e?.success||!e.siteId){console.error(`[FlowEngage] Could not resolve a FlowEngage account for shop:`,n,e?.message);return}y_(()=>b_({siteId:e.siteId,language:r,widgetSettings:a,apiBaseUrl:i}))}).catch(e=>console.error(`[FlowEngage] Failed to resolve shop tenant:`,e))};return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,S_):S_(),typeof window<`u`&&(window.FlowEngage=x_),x_})();
|