@flowengage/react-chatbot 1.8.13 → 1.8.15

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.
@@ -461,9 +461,10 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
461
461
 
462
462
  gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
463
463
  }
464
- `;function lD(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 uD({size:e=94,voiceState:t=`idle`,isMuted:n=!1,colors:r,onClick:i,style:a,className:o}){let[s,c,l]=rD(r),u=t===`speaking`,d=e<=50,f=(0,b.useRef)(null),p=(0,b.useRef)(iD[t]??.35);(0,b.useEffect)(()=>{p.current=iD[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=lD(r,sD,cD);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,aD(s)),r.uniform3fv(u.c2,aD(c)),r.uniform3fv(u.c3,aD(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,M.jsxs)(`div`,{style:{position:`relative`,width:e,height:e,flexShrink:0,cursor:i?`pointer`:`default`,...a},className:o,onClick:i,children:[u&&!d&&(0,M.jsx)(jp.div,{style:{position:`absolute`,inset:-10,borderRadius:`50%`,background:`radial-gradient(circle, ${oD(s,.18)} 0%, transparent 70%)`,pointerEvents:`none`},animate:{opacity:[.3,.75]},transition:{duration:1,repeat:1/0,repeatType:`mirror`,ease:`easeInOut`}}),(0,M.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,M.jsx)(`canvas`,{ref:f,style:{width:`100%`,height:`100%`,display:`block`}})}),u&&(0,M.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,pointerEvents:`none`,zIndex:1},children:(0,M.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`3px`},children:[4,8,12,8,4].map((e,t)=>(0,M.jsx)(jp.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 dD=`fe_voice_session`,fD=`fe_tab_id`,pD=40,mD=2e3,hD=300*1e3,gD=60*1e3,_D=30*1e3;function vD(){let e=new Uint8Array(16);try{crypto.getRandomValues(e)}catch{for(let t=0;t<16;t++)e[t]=Math.floor(Math.random()*256)}return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function yD(){try{let e=sessionStorage.getItem(fD);return e||(e=vD(),sessionStorage.setItem(fD,e)),e}catch{return vD()}}function bD(e,t){return`${(e||[]).length}:${t%1e5}`}function xD(e,t){return Array.isArray(e)?e.length<=t?e:e.slice(e.length-t):[]}function SD(){if(typeof document>`u`)return{headings:[],activeHighlightText:null,activeHighlightId:null};let e=document.querySelector(`.fe-highlight-section`);return{headings:Array.from(document.querySelectorAll(`h1,h2,h3,h4`)).filter(e=>!e.closest(`#flowengage-root`)).map(e=>({tag:e.tagName,text:e.textContent.trim().slice(0,100),id:e.id||null})).slice(0,25),activeHighlightText:e?.textContent?.trim().slice(0,100)||null,activeHighlightId:e?.id||null}}function CD(e){if(!e)return`Unknown state.`;let{state:t,lastAgentText:n,lastUserText:r,toolName:i,toolParams:a,estimatedSpokenWords:o,agentTextWordCount:s,unspokenSuffix:c}=e,l=[];return t===`speaking`?(l.push(`You were SPEAKING.`),n&&(l.push(`You had spoken approximately ${o??`?`} of ${s??`?`} words.`),l.push(`Your response text: "${n}"`),c&&l.push(`Estimated unspoken remainder: "${c}"`))):t===`listening`?(l.push(`You were LISTENING for the user's response.`),r&&l.push(`Last user message: "${r}"`)):t===`tool_calling`?i===`flowengage_navigate`?(l.push(`Navigation ALREADY COMPLETED — you successfully navigated to this page.`),l.push(`DO NOT call flowengage_navigate again. You are already on the destination.`),n&&l.push(`Before navigating you said: "${n}"`)):(l.push(`You were executing tool: ${i||`unknown`}`),a&&l.push(`Tool parameters: ${JSON.stringify(a)}`),n&&l.push(`Your last spoken text before the tool call: "${n}"`)):l.push(`Session state at capture: ${t||`idle`}`),l.join(`
464
+ `;function lD(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 uD({size:e=94,voiceState:t=`idle`,isMuted:n=!1,colors:r,onClick:i,style:a,className:o}){let[s,c,l]=rD(r),u=t===`speaking`,d=e<=50,f=(0,b.useRef)(null),p=(0,b.useRef)(iD[t]??.35);(0,b.useEffect)(()=>{p.current=iD[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=lD(r,sD,cD);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,aD(s)),r.uniform3fv(u.c2,aD(c)),r.uniform3fv(u.c3,aD(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,M.jsxs)(`div`,{style:{position:`relative`,width:e,height:e,flexShrink:0,cursor:i?`pointer`:`default`,...a},className:o,onClick:i,children:[u&&!d&&(0,M.jsx)(jp.div,{style:{position:`absolute`,inset:-10,borderRadius:`50%`,background:`radial-gradient(circle, ${oD(s,.18)} 0%, transparent 70%)`,pointerEvents:`none`},animate:{opacity:[.3,.75]},transition:{duration:1,repeat:1/0,repeatType:`mirror`,ease:`easeInOut`}}),(0,M.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,M.jsx)(`canvas`,{ref:f,style:{width:`100%`,height:`100%`,display:`block`}})}),u&&(0,M.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,pointerEvents:`none`,zIndex:1},children:(0,M.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`3px`},children:[4,8,12,8,4].map((e,t)=>(0,M.jsx)(jp.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 dD=`fe_voice_session`,fD=`fe_tab_id`,pD=40,mD=2e3,hD=300*1e3,gD=60*1e3,_D=30*1e3;function vD(){let e=new Uint8Array(16);try{crypto.getRandomValues(e)}catch{for(let t=0;t<16;t++)e[t]=Math.floor(Math.random()*256)}return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function yD(){try{let e=sessionStorage.getItem(fD);return e||(e=vD(),sessionStorage.setItem(fD,e)),e}catch{return vD()}}function bD(e,t){return`${(e||[]).length}:${t%1e5}`}function xD(e,t){return Array.isArray(e)?e.length<=t?e:e.slice(e.length-t):[]}function SD(){if(typeof document>`u`)return{headings:[],activeHighlightText:null,activeHighlightId:null};let e=document.querySelector(`.fe-highlight-section`);return{headings:Array.from(document.querySelectorAll(`h1,h2,h3,h4`)).filter(e=>!e.closest(`#flowengage-root`)).map(e=>({tag:e.tagName,text:e.textContent.trim().slice(0,100),id:e.id||null})).slice(0,25),activeHighlightText:e?.textContent?.trim().slice(0,100)||null,activeHighlightId:e?.id||null}}function CD(e){if(!e)return`Unknown state.`;let{state:t,lastAgentText:n,lastUserText:r,toolName:i,toolParams:a,estimatedSpokenWords:o,agentTextWordCount:s,unspokenSuffix:c}=e,l=[];return t===`speaking`?(l.push(`You were SPEAKING.`),n&&(l.push(`You had spoken approximately ${o??`?`} of ${s??`?`} words.`),l.push(`Your response text: "${n}"`),c&&l.push(`Estimated unspoken remainder: "${c}"`))):t===`listening`?(l.push(`You were LISTENING for the user's response.`),r&&l.push(`Last user message: "${r}"`)):t===`tool_calling`?i===`flowengage_navigate`?(l.push(`Navigation ALREADY COMPLETED — you successfully navigated to this page.`),l.push(`DO NOT call flowengage_navigate again. You are already on the destination.`),r&&l.push(`The user's last request was: "${r}"`),n&&l.push(`Before navigating you said: "${n}"`)):(l.push(`You were executing tool: ${i||`unknown`}`),a&&l.push(`Tool parameters: ${JSON.stringify(a)}`),n&&l.push(`Your last spoken text before the tool call: "${n}"`)):l.push(`Session state at capture: ${t||`idle`}`),l.join(`
465
465
  `)}function wD(e,t){try{let n={v:2,sid:e.siteId||``,aid:e.agentId||``,ut:(e.interruption?.lastUserText||``).slice(0,50),ts:Math.floor(t/1e3)};return`compact:${btoa(unescape(encodeURIComponent(JSON.stringify(n))))}`}catch{return null}}function TD(e,t){if(!t)return e;try{let n=new URL(e,window.location.href);return n.searchParams.set(`_fe_resume`,t),n.href}catch{return e+(e.includes(`?`)?`&`:`?`)+`_fe_resume=`+t}}function ED(){if(typeof window>`u`)return null;try{let e=new URL(window.location.href),t=e.searchParams.get(`_fe_resume`);if(!t)return null;e.searchParams.delete(`_fe_resume`);let n=e.pathname+(e.search?e.search:``)+(e.hash?e.hash:``);return window.history.replaceState(window.history.state,``,n),t}catch{return null}}var DD={capture(e){let t=vD(),n=Date.now(),r=xD(e.history,pD),i=(e.interruption?.lastAgentText||``).slice(0,mD),a=e.interruption?.estimatedSpokenWords||0,o=e.interruption?.agentTextWordCount||i.split(/\s+/).filter(Boolean).length,s=``;e.interruption?.state===`speaking`&&i&&a>0&&(s=i.split(/\s+/).slice(a).join(` `));let c={version:2,sessionKey:t,tabId:yD(),siteId:e.siteId,chatId:e.chatId||null,agentId:e.agentId,ts:n,expiresAt:n+hD,resumeAttempts:0,consumed:!1,trigger:e.trigger,navigationConfidence:e.navigationConfidence||`medium`,fromUrl:typeof window<`u`?window.location.href:``,targetUrl:e.targetUrl||null,interruption:{...e.interruption,lastAgentText:i,estimatedSpokenWords:a,agentTextWordCount:o,unspokenSuffix:s,micWasGranted:!0,isMuted:e.interruption?.isMuted||!1,hadError:e.interruption?.hadError||!1},fromPageContext:SD(),history:r,historyTotalTurns:(e.history||[]).length,storageChecksum:bD(r,n)};try{return sessionStorage.setItem(dD,JSON.stringify(c)),{ok:!0,sessionKey:t,compact:null}}catch{return{ok:!1,sessionKey:null,compact:wD(e,n)}}},read(e){if(typeof window>`u`)return null;let t=ED();if(t?.startsWith(`compact:`)){try{let n=JSON.parse(decodeURIComponent(escape(atob(t.slice(8))))),r=Date.now()/1e3-(n.ts||0);if(n.v===2&&n.sid===e&&r<300)return{_compact:!0,_resumeMode:`auto`,siteId:n.sid,agentId:n.aid,chatId:null,history:[],historyTotalTurns:0,trigger:`agent_navigate`,navigationConfidence:`medium`,fromUrl:``,interruption:{state:`listening`,lastUserText:n.ut||``,lastAgentText:``},fromPageContext:{headings:[],activeHighlightText:null}}}catch{}return null}let n;try{n=JSON.parse(sessionStorage.getItem(dD)||`null`)}catch{return null}if(!n)return null;if(n.version!==2)return this._discard(`version`);if(n.siteId!==e)return this._discard(`siteId`);if(Date.now()>n.expiresAt)return this._discard(`expired`);if(n.consumed)return this._discard(`consumed`);if(n.resumeAttempts>=2)return this._discard(`loop_guard`);if(bD(n.history,n.ts)!==n.storageChecksum)return this._discard(`checksum`);if(n.trigger===`agent_navigate`&&t&&t!==n.sessionKey)return this._discard(`key_mismatch`);if(n.trigger===`pagehide`){if(Date.now()-n.ts>_D)return this._discard(`pagehide_stale`);n._resumeMode=`banner`}else if(n.trigger===`user_link_click`){if(Date.now()-n.ts>gD)return this._discard(`user_nav_stale`);n._resumeMode=`auto`}else n._resumeMode=`auto`;n.resumeAttempts+=1;try{sessionStorage.setItem(dD,JSON.stringify(n))}catch{}return n},clear(){try{sessionStorage.removeItem(dD)}catch{}},buildResumePrompt(e,t,n){let r=(e.history||[]).map(e=>`[${e.sender===`user`?`User`:`Agent`}]: ${e.message}`).join(`
466
- `),i=CD(e.interruption),a=(t||[]).map(e=>e.text).join(`, `),o=``,s=``;try{o=new URL(e.fromUrl||``).pathname}catch{o=e.fromUrl||``}try{s=new URL(n||window.location.href).pathname}catch{s=n||``}return[`VOICE SESSION AUTO-RESUMED AFTER PAGE NAVIGATION.`,`Navigation confidence: ${(e.navigationConfidence||`medium`).toUpperCase()}`,`Navigation: ${o} → ${s}`,``,`── Prior Conversation (${e.historyTotalTurns} turns) ──`,r||`(no prior turns)`,``,`── Your State at Interruption ──`,i,``,`── Current Page ──`,`URL: ${n||(typeof window<`u`?window.location.href:``)}`,`Sections: ${a||`none detected`}`,``,`── CRITICAL INSTRUCTIONS ──`,`1. DO NOT re-introduce yourself.`,`2. DO NOT ask the user what they need — you already know from the conversation above.`,`3. Continue the conversation naturally as if the navigation was seamless.`,`4. If you were mid-sentence, complete your thought naturally.`,`5. The navigation has ALREADY COMPLETED — you are now on the destination page. Do NOT call flowengage_navigate again.`,`6. Only acknowledge the page change if it adds meaningful context.`,`7. The user may speak at any time — stop immediately and listen.`,`8. Use the sections listed above to guide what you highlight next.`].join(`
466
+ `),i=e.interruption?.lastUserText;if(i){let t=[...e.history||[]].reverse().find(e=>e.sender===`user`);(!t||t.message!==i)&&(r+=(r?`
467
+ `:``)+`[User]: ${i}`)}let a=CD(e.interruption),o=(t||[]).map(e=>e.text).join(`, `),s=``,c=``;try{s=new URL(e.fromUrl||``).pathname}catch{s=e.fromUrl||``}try{c=new URL(n||window.location.href).pathname}catch{c=n||``}return[`VOICE SESSION AUTO-RESUMED AFTER PAGE NAVIGATION.`,`Navigation confidence: ${(e.navigationConfidence||`medium`).toUpperCase()}`,`Navigation: ${s} → ${c}`,``,`── Prior Conversation (${e.historyTotalTurns} turns) ──`,r||`(no prior turns)`,``,`── Your State at Interruption ──`,a,``,`── Current Page ──`,`URL: ${n||(typeof window<`u`?window.location.href:``)}`,`Sections: ${o||`none detected`}`,``,`── CRITICAL INSTRUCTIONS ──`,`1. DO NOT re-introduce yourself.`,`2. DO NOT ask the user what they need — you already know from the conversation above.`,`3. Continue the conversation naturally as if the navigation was seamless.`,`4. If you were mid-sentence, complete your thought naturally.`,`5. The navigation has ALREADY COMPLETED — you are now on the destination page. Do NOT call flowengage_navigate again.`,`6. Only acknowledge the page change if it adds meaningful context.`,`7. The user may speak at any time — stop immediately and listen.`,`8. Use the sections listed above to guide what you highlight next.`].join(`
467
468
  `)},_discard(e){try{sessionStorage.removeItem(dD)}catch{}return null}};function OD(){try{let e=JSON.parse(sessionStorage.getItem(dD)||`null`);return e?.trigger===`agent_navigate`&&Date.now()-(e.ts||0)<1e4}catch{return!1}}var kD={wordsSoFar:0,speechStartTime:0,isSpeaking:!1,items:[],timers:[],lastHighlightId:null,isVoiceMode:!1};function AD(){return kD.wordsSoFar}function jD(){kD.timers.forEach(clearTimeout),kD.wordsSoFar=0,kD.speechStartTime=0,kD.isSpeaking=!1,kD.items=[],kD.timers=[],kD.lastHighlightId=null}var MD=80;function ND(e){requestAnimationFrame(()=>{let t=e.getBoundingClientRect(),n=t.top+t.height/2,r=MD,i=r+(window.innerHeight-r)/2,a=window.pageYOffset+n-i;window.scrollTo({top:Math.max(0,a),behavior:`smooth`})})}function PD(e){if(!e||e.hasAttribute(`data-fe-highlighted`))return;FD(),e.classList?.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`),ND(e);let t=e.style.cssText;e.setAttribute(`data-fe-highlighted`,`true`),e.setAttribute(`data-fe-orig-style`,t),e.style.outline=`3px solid #2563eb`,e.style.outlineOffset=`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.padding=`12px 16px`,e.style.transition=`all 0.4s ease`}function FD(){let e=document.querySelector(`[data-fe-highlighted]`);e&&(e.style.cssText=e.getAttribute(`data-fe-orig-style`)||``,e.removeAttribute(`data-fe-highlighted`),e.removeAttribute(`data-fe-orig-style`))}var Q=`fe-vv`;function ID(){if(typeof document>`u`||document.getElementById(`${Q}-styles`))return;let e=`
468
469
  /* ── Action toast ───────────────────────────────────────────────────────────── */
469
470
  #${Q}-toast {
@@ -611,8 +612,8 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
611
612
  <path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
612
613
  fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
613
614
  filter="url(#${Q}-csh)"/>
614
- </svg>`,ZD=null,QD=!1;function $D(){return(!ZD||!ZD.isConnected)&&(ZD=document.createElement(`div`),ZD.id=`${Q}-cursor`,ZD.innerHTML=XD,document.body.appendChild(ZD),QD=!1),ZD}async function eO(e){if(typeof document>`u`||!e)return;ID();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=$D();QD||=(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 iO(360)}function tO(e=!1){ZD&&(e?(ZD.classList.remove(`${Q}-cursor-visible`),QD=!1):(ZD.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{QD=!1},250)))}async function nO(e){ZD&&(ZD.classList.add(`${Q}-cursor-click`),await iO(280),ZD.classList.remove(`${Q}-cursor-click`))}function rO(e){if(!e||typeof document>`u`)return;ID();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 iO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){pn()&&console.log(`[FlowEngage:voice-tools]`,...e)}function aO(e){return new Promise(t=>setTimeout(t,e))}var oO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function sO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(oO)}catch{return!1}}function cO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function lO(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(!sO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function uO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function dO(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 uO(r.join(` `))}if(e.labels&&e.labels.length)return uO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return uO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return uO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return uO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=uO(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 uO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return uO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?uO(o):null}function fO(){let e=[];return lO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(sO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=cO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function pO(){return fO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:dO(e),placeholder:e.placeholder||null}))}function mO(){let e=[];return lO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(sO(e)||e.disabled)return!1;try{let t=cO(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 hO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function gO(e){let t=hO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function _O(e,t){let n=gO(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,dO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>hO(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var vO=28;function yO(e,t){let n=null,r=0;for(let i of e){let e=_O(i,t);e>r&&(r=e,n=i)}return!n||r<vO?null:n}function bO(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,dO(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function xO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function SO(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function CO(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function wO(e){if(!CO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,dO(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function TO(e,t,n){let r=String(t??``),i=String(n??``),a=OO(e,r)||yO(e,r)||bO(e,r,i);if(!a)return[];let o=new Set([a]);if(xO(i)&&SO(r))for(let t of e)t!==a&&wO(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function EO(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 DO(e){if(!e||typeof e!=`string`)return null;let t=null;return lO(n=>{try{let r=n.getElementById(e);r&&!sO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function OO(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=DO(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=DO(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function kO(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function AO(e,t){let n=[];lO(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(sO(e)||e.disabled)return!1;try{let t=cO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:kO(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=EO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function jO(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 MO(e){let t=jO(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function NO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function PO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function FO(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 IO(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function LO(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function RO(){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 zO(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let r=jO(n),i=FO(r),a=r.section_text??r.sectionText??r.section;if($(`flowengage_navigate · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(i,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(i=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,i))}catch{}if(typeof window<`u`)try{let e=new URL(i,window.location.href),t=window.location;if(e.pathname===t.pathname&&e.search===t.search&&(e.hash===t.hash||!e.hash))return $(`flowengage_navigate · already on target page, skipping navigation`),`Already on that page. Continue the conversation naturally without calling flowengage_navigate again.`}catch{}if(!await Hn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${i}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{BD(`Navigating to ${i}...`,{spinner:!0}),GD();let t=typeof e.getSessionCaptureData==`function`?e.getSessionCaptureData():null,n=i;if(t){let{ok:e,sessionKey:r,compact:o}=DD.capture({siteId:t.siteId,chatId:t.chatId,agentId:t.agentId,trigger:`agent_navigate`,navigationConfidence:`high`,targetUrl:i,interruption:{state:`tool_calling`,toolName:`flowengage_navigate`,toolParams:{url:i,section_text:a||null},lastAgentText:t.lastAgentText,lastUserText:t.lastUserText,estimatedSpokenWords:t.estimatedSpokenWords,agentTextWordCount:t.agentTextWordCount,isMuted:t.isMuted||!1},history:t.history});e&&r?n=TD(i,r):o&&(n=TD(i,o)),$(`flowengage_navigate · session captured, resumeUrl:`,n)}return jD(),await aO(300),$(`flowengage_navigate → location.assign`,n),window.location.assign(n),`Navigating...`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),BD(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{KD(),VD(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=jO(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;RO();let i=Rn(n||null,r||null);return!i&&r&&(await new Promise(e=>setTimeout(e,500)),RO(),i=Rn(null,r)),i?(PD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}"`):($(`flowengage_highlight ✖ no element for:`,r||n),`Could not find "${r||n}" on the current page. Try a shorter phrase matching a visible heading.`)},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=jO(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=Rn(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
615
- `)}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`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=IO(jO(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → 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($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=jO(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → 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($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`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 $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=pO(),t=mO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),qD();let t=MO(e);if(!t.length&&r){let e=r(),n=NO(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=PO(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;BD(`Filling ${String(t)}...`,{spinner:!0});let a=fO(),o=TO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())JD(t),await eO(t),LO(t,r,{skipScroll:e>0}),YD(t),await aO(120);i=o,n.push(String(t));continue}let s=OO(a,String(t));s||=yO(a,String(t)),s||=bO(a,String(t),r),s&&(JD(s),await eO(s),LO(s,r),YD(s),await aO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),BD(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),BD(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{tO(),qD(),VD(700)}},flowengage_click_button:async e=>{let t=jO(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=AO(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{BD(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await eO(r),r.focus?.(),await nO(r),rO(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),BD(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),BD(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{tO(),VD(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function BO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=pn();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 VO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function HO(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 UO(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 WO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,M.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?b.createElement(e):b.isValidElement(e)?e:null;return n?(0,M.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function GO({title:e}){return(0,M.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 KO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\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))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function qO({orbColors:e,...t}){return(0,M.jsx)(uD,{colors:e,...t})}function JO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||VO.green,s=UO(o),c=a?72:94,l=(0,M.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,M.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,M.jsx)(jp.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:a?void 0:`210px`},children:e.entryPrompt}),(0,M.jsxs)(jp.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,M.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:o,color:s,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}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,M.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,M.jsx)(jp.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,M.jsx)(qO,{size:c,orbColors:t})})]});return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(jp.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,M.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function YO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o}){let s=n||VO.green,c=UO(s);return(0,M.jsxs)(jp.div,{initial:{scale:50/350,borderRadius:`50%`},animate:{scale:1,borderRadius:`16px`},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,M.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,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,M.jsx)(qO,{size:72,orbColors:t}),(0,M.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,M.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,M.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${s}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,M.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 XO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s,pendingResume:c,chatId:l}){let[u,d]=(0,b.useState)(`idle`),[f,p]=(0,b.useState)(!1),[m,h]=(0,b.useState)(!1),g=(0,b.useRef)(null),_=(0,b.useRef)(``),v=(0,b.useRef)(async()=>{}),y=(0,b.useRef)(!1),x=(0,b.useRef)(!1),ee=(0,b.useRef)(`idle`),S=(0,b.useRef)(!1),C=(0,b.useRef)(!1),te=(0,b.useRef)(`minimized`),w=(0,b.useRef)(0),ne=(0,b.useRef)(null),re=(0,b.useCallback)((e=`minimized`)=>{te.current=e,C.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),ie=(0,b.useCallback)(async e=>{C.current=!0;try{await g.current?.endSession?.()}catch{}if(g.current=null,d(`idle`),p(!1),y.current=!1,typeof s==`function`){let e=w.current;await s(e>0?o.current.slice(e):o.current)}e?.()},[o,s]);return v.current=()=>ie(te.current===`chat`?t:n),(0,b.useEffect)(()=>{x.current=f},[f]),(0,b.useEffect)(()=>{ee.current=u},[u]),(0,b.useEffect)(()=>{let e=()=>!!g.current,t=()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``},n=e=>{let n=t(),a=n.split(/\s+/).filter(Boolean).length;return{siteId:i,chatId:l||null,agentId:r,trigger:e,navigationConfidence:e===`agent_navigate`?`high`:`medium`,interruption:{state:ee.current,lastAgentText:n,lastUserText:_.current,estimatedSpokenWords:AD(),agentTextWordCount:a,isMuted:x.current},history:o.current||[]}},a=()=>{e()&&(OD()||DD.capture(n(`user_link_click`)))},s=t=>{e()&&(t.persisted||OD()||DD.capture(n(`pagehide`)))};return window.addEventListener(`beforeunload`,a),window.addEventListener(`pagehide`,s),()=>{window.removeEventListener(`beforeunload`,a),window.removeEventListener(`pagehide`,s)}},[i,l,r,o]),(0,b.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){d(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;c?(o.current=Array.isArray(c.history)?[...c.history]:[],w.current=o.current.length,c.interruption?.lastUserText&&(_.current=c.interruption.lastUserText)):(o.current=[],w.current=0,_.current=``),y.current=!1,S.current=!1,C.current=!1,te.current=`minimized`;let t=BO(zO({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,requestEndSession:()=>{re()},getSessionCaptureData:()=>{let e=(()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``})();return{siteId:i,chatId:l||null,agentId:r,history:o.current||[],lastAgentText:e,agentTextWordCount:e.split(/\s+/).filter(Boolean).length,lastUserText:_.current,estimatedSpokenWords:AD(),isMuted:x.current}}})),s=typeof window<`u`?window.location.href:``,u,f=null;if(c&&!c.consumed){let e=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().slice(0,100),id:e.id||null})).filter(e=>e.text.length>0).slice(0,25):[];f=DD.buildResumePrompt(c,e,s);let t=e[0]?.text||``;u={agent:{firstMessage:t?`I'm now on the ${t} page. Let me walk you through it.`:`I've navigated to the new page. Let me continue our conversation.`}}}let m=await EE.startSession({agentId:r,...u?{overrides:u}:{},clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||d(t===`speaking`?`speaking`:`listening`)},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(!r)return;let i=o.current,a=i.length>0?i[i.length-1]:null;a&&a.sender===n&&a.message===r||(n===`user`&&(_.current=r),o.current=[...i,{sender:n,message:r,timestamp:new Date().toISOString()}],KO(n,r)&&re(`minimized`))},onError:t=>{if(!e&&!C.current&&!S.current){S.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),d(`error`),re(`minimized`)}},onDisconnect:()=>{if(!e&&!C.current&&!S.current){S.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:_.current||``,wasMuted:x.current});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),re(`minimized`)}}});if(e){m.endSession().catch(()=>{});return}n=m,g.current=m,d(`listening`);try{if(f)m.sendContextualUpdate(f),DD.clear();else{let e=`[]`;try{e=await t.flowengage_list_forms()}catch{}let n=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, nav, footer, header`)).map(e=>({tag:e.tagName,text:e.textContent.trim(),id:e.id||null})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,25):[];m.sendContextualUpdate(`Page: ${s}. SiteId: ${i||`unknown`}. Sections on this page: ${JSON.stringify(n)}. IMPORTANT: Call flowengage_highlight with section_text from the list above as you explain each section. Forms: ${e}. Navigation: flowengage_navigate — use for cross-page navigation. End call: flowengage_end_session.`)}}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),d(`error`),te.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,C.current=!0,(n||g.current)?.endSession?.().catch(()=>{})}},[r,i,a,re]),(0,b.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ne.current&&!ne.current.contains(t)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,M.jsxs)(`div`,{ref:ne,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:[(0,M.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&(0,M.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:`Listening...`}),(0,M.jsx)(qO,{size:72,voiceState:u,isMuted:f,orbColors:e})]}),u===`error`&&(0,M.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,M.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,M.jsx)(`button`,{onClick:async()=>{if(g.current)try{f?(await g.current.setMicMuted?.(!1),p(!1)):(await g.current.setMicMuted?.(!0),p(!0))}catch{}},title:f?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:f?`#7f1d1d`:`#1f2937`,border:f?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:f?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:f?(0,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,M.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,M.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,M.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,M.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,M.jsx)(DE,{size:16,color:`currentColor`})}),(0,M.jsx)(`button`,{onClick:()=>h(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,M.jsx)(FE,{size:16,color:`currentColor`})})]}),m&&(0,M.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,M.jsxs)(`button`,{onClick:()=>{h(!1),te.current=`chat`,ie(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,M.jsx)(IE,{}),`Enter Chat Mode`]}),(0,M.jsxs)(`button`,{onClick:()=>{h(!1),te.current=`minimized`,ie(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,M.jsx)(LE,{}),`End Conversation`]}),(0,M.jsx)(`button`,{onClick:()=>h(!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,M.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,M.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function ZO({orbColors:e}){return(0,M.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,M.jsx)(qO,{size:36,orbColors:e})})}var QO=()=>(0,M.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,M.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,M.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 $O({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:ee,selectedFile:S,onFileSelect:C,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:ae,emailError:oe,replyContext:se,setReplyContext:ce,webRTCError:le,micError:ue,setMicError:T,dismissCallError:E,incomingCall:de,rejectCall:fe,acceptCall:pe,activeCallId:me,callConnectionState:he,isCallMuted:ge,toggleCallMute:_e,endWebRTCCall:ve,formatCallDuration:ye,callDurationSeconds:be,onCollapse:xe,onStartVoice:Se,showPoweredBy:Ce}){let we=c.length>0,Te=y||x||v,Ee=!!(de||me),[De,Oe]=(0,b.useState)(!1),ke=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(!De)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ke.current&&!ke.current.contains(t)&&Oe(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[De]),(0,M.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:0,width:`calc(100% - 16px)`,height:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`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:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,M.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0},children:[(0,M.jsx)(`button`,{onClick:xe,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,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,M.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,M.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,M.jsx)(WO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,M.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,M.jsx)(GO,{title:e.chatTitle})})}),(0,M.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,M.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,M.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:ke,children:[(0,M.jsx)(`button`,{type:`button`,onClick:()=>Oe(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,M.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,M.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,M.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,M.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),De&&(0,M.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:[(0,M.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),Se?.()},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,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,M.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,M.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),xe?.()},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,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.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,M.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,M.jsx)(tD,{webRTCError:le,micError:ue,setMicError:T,dismissCallError:E,incomingCall:de,rejectCall:fe,acceptCall:pe,activeCallId:me,callConnectionState:he,formatCallDuration:ye,callDurationSeconds:be,endWebRTCCall:ve,isCallMuted:ge,toggleCallMute:_e,isAIVoiceActive:!1,currentCallAgentName:f||m,isRateLimited:x,rateLimitMessage:ee}),(0,M.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:we?(0,M.jsx)(ZE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ce,TypingDots:QO,primaryColor:n,agentHeadshot:p,agentDisplayName:f||m,botAvatarNode:(0,M.jsx)(ZO,{orbColors:t})}):(0,M.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,M.jsx)(qO,{size:94,orbColors:t}),(0,M.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,M.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,M.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))})]})}),(0,M.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:re?`6px 0 0`:`12px 0 0`},children:(0,M.jsx)(QE,{input:h,setInput:g,onSubmit:_,isConversationEnded:v,callUiActive:Ee,handleToggleVoice:Se,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Te,replyContext:se,clearReplyContext:()=>ce(null),onFileSelect:C,selectedFile:S,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:ae,emailError:oe,inputPlaceholder:e.inputPlaceholder})}),(0,M.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:Ce&&(0,M.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,M.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function ek(){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:ee,language:S,historyRef:C,onMessageSync:te,sendMessage:w,uploadChatFile:ne,openWidget:re,captureVisitorEmail:ie,setVoiceMode:ae,endConversation:oe,acceptCall:se,rejectCall:ce,endWebRTCCall:le,toggleCallMute:ue,dismissCallError:de,startTyping:pe,stopTyping:me,updateTypingDraft:he}=fn();(0,b.useEffect)(()=>{try{In()}catch{}},[]);let ge=t?.widgetSettings||{},_e=n?.widgetSettings||{},ve={...ge.branding||{},..._e.branding||{}},ye={...ge.theme||{},..._e.theme||{}},be={...ge.features||{},..._e.features||{}},xe=be.voice!==!1,Se=Array.isArray(ye.orbColors)&&ye.orbColors.length>0?ye.orbColors:null,Ce=Se?.[0]||ye.primaryColor||`#3B82F6`,we=ye.position||`bottom-right`,Te=ve.fallbackAgentName||`Agent`,Ee=HO(Se??ye.chatBgColors),De=ve.logo||ve.logoUrl||null,Oe=S||`en`,ke=ge.recommendations?.[Oe]||[],Ae=(_e.recommendations?.[Oe]??ke).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),je=Array.isArray(ve.quickChatOptions)&&ve.quickChatOptions.length>0?ve.quickChatOptions:Ae,Me=ve.hideWatermark===!0?!1:ve.showPoweredBy!==!1,D=ve.chatbotEnabled!==!1&&ye.chatbotEnabled!==!1,Ne=ge.greetings?.[S]||_e.greetings?.[S]||ve.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Pe={entryPrompt:ve.entryPrompt||`Do you want to explore in a new way?`,yesLabel:ve.yesLabel||`Yes`,laterLabel:ve.laterLabel||`Later`,connectionTitle:ve.connectionTitle||`How would you like to connect?`,voiceLabel:ve.voiceLabel||`Voice`,textLabel:ve.textLabel||`Text`,chatTitle:ve.headerName||`Chat with FlowEngage`,introGreeting:Ne,inputPlaceholder:ve.inputPlaceholder||`Type your message`,analysingLabel:ve.analysingLabel||`analysing...`},Fe=_e.elevenLabsAgentId||t?.elevenLabsAgentId||null,Ie=t?.siteId||n?.siteId||null,Le=t?.apiBaseUrl||``,Re=(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]),ze=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Be=r.some(e=>e.sender===`user`),Ve=(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]),He=!l&&Be&&Ve,Ue=!!(_e._dashboardLivePreview||ge._dashboardLivePreview),[We,O]=(0,b.useState)(()=>Ue?`text_chat`:`entry_prompt`),[k,Ge]=(0,b.useState)(``),[A,Ke]=(0,b.useState)(null),[qe,Je]=(0,b.useState)(l||``),[Ye,Xe]=(0,b.useState)(``),[Ze,Qe]=(0,b.useState)(0),[$e,et]=(0,b.useState)(null),[tt,nt]=(0,b.useState)(null),[rt,it]=(0,b.useState)(``),[at,ot]=(0,b.useState)(!1),st=(0,b.useRef)(null),ct=(0,b.useRef)(!1),lt=(0,b.useRef)(null),ut=(0,b.useMemo)(()=>fe(Ie),[Ie]);(0,b.useLayoutEffect)(()=>{if(!(e!==`ready`||ct.current)){ct.current=!0;try{let e=DD.read(Ie);if(e&&e._resumeMode===`auto`){lt.current=e,re({notifyChatInitiated:!0}),ae?.(!0),O(`voice_mode`);return}}catch{}if(T(Ie)||!xe){O(`minimized_orb`);return}}},[e,r]);let[dt,ft]=(0,b.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,b.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>ft(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,b.useEffect)(()=>{Je(l||``),l&&Xe(``)},[l]);let pt=(0,b.useCallback)(()=>{nt(null),it(``)},[]),mt=(0,b.useCallback)(e=>{let t=KE(e);if(t){nt(null),it(t);return}nt(e),it(``)},[]);(0,b.useEffect)(()=>{if(!y||v!==`connected`){Qe(0);return}let e=()=>{let e=new Date(y).getTime();isNaN(e)||Qe(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[y,v]),(0,b.useEffect)(()=>{let e=g?.callId||_||null;if(!e){st.current=null;return}(g?.callId||v===`connecting`||v===`connected`)&&(!(!i||We===`minimized_orb`||We===`voice_mode`)&&st.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:We,hasIncomingCall:!!g?.callId,activeCallId:_,callConnectionState:v}),st.current=e,We===`voice_mode`&&ae?.(!1),re?.(),O(`text_chat`)))},[_,v,g?.callId,i,re,ae,We]),(0,b.useEffect)(()=>{if(!o||h){he?.(``),me?.();return}if(!k.trim()||tt){he?.(``),me?.();return}pe?.();let e=window.setTimeout(()=>he?.(k),120),t=window.setTimeout(()=>me?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[k,tt,o,h,pe,me,he]);let ht=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,gt=async e=>{if(e.preventDefault(),h)return;if(He){let e=qe.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Xe(`Please enter a valid email so we can continue helping you.`);return}await ie(e),Xe(``);return}let t=ht(A);if(!k.trim()&&!tt)return;if(tt){try{ot(!0),it(``);let e=await ne(tt),n=e?.data||e,r=k.trim()||`Shared file: ${JE(tt)}`;Ge(``),Ke(null),pt(),await w(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||tt.name,fileType:n?.fileType||tt.type,fileSize:n?.fileSize||tt.size}})}catch(e){it(e?.message||`Failed to upload the selected file.`)}finally{ot(!1)}return}let n=k.trim();Ge(``),Ke(null),await w(n,``,t)},_t=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},vt=(0,b.useCallback)(async e=>{if(h||f)return;let t=e.message||e.label||e.text||``;t.trim()&&await w(t.trim(),``)},[h,f,w]),yt=dt&&We===`entry_prompt`?{inset:0}:dt&&We===`text_chat`?{left:0,right:0,bottom:0}:dt&&We===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:we===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},bt=()=>O(`minimized_orb`),xt=()=>O(`connection_modal`),St=()=>{re({notifyChatInitiated:!0}),ae?.(!0),O(`voice_mode`)},Ct=()=>{re({notifyChatInitiated:!0}),ae?.(!1),O(`text_chat`)},wt=()=>{ae?.(!1),bt()};return e!==`ready`||!D||be.chat===!1?null:(0,M.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...yt},children:[We===`entry_prompt`&&(0,M.jsx)(JO,{copy:Pe,orbColors:Se,primaryColor:Ce,onYes:()=>{E(Ie),St()},onLater:()=>{E(Ie),bt()},isMobile:dt}),We===`minimized_orb`&&(0,M.jsx)(jp.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,M.jsx)(qO,{size:50,orbColors:Se,onClick:xe?xt:Ct})}),We===`connection_modal`&&(0,M.jsx)(YO,{copy:Pe,orbColors:Se,primaryColor:Ce,onVoice:St,onText:Ct,onClose:bt,isMobile:dt}),We===`voice_mode`&&(0,M.jsx)(XO,{orbColors:Se,onEnterChat:Ct,onEndChat:wt,agentId:Fe,siteId:Ie,apiBaseUrl:Le,historyRef:C,onMessageSync:te,pendingResume:lt.current,chatId:ut},`voice`),We===`text_chat`&&(0,M.jsx)($O,{copy:Pe,orbColors:Se,primaryColor:Ce,chatBgGradient:Ee,logo:De,quickChatOptions:je,onQuickChatSelect:vt,isMobile:dt,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Re,agentHeadshot:ze,fallbackAgentName:Te,input:k,setInput:Ge,onSubmit:gt,isConversationEnded:h,isLoading:f,isRateLimited:p,rateLimitMessage:m,selectedFile:tt,onFileSelect:mt,onRemoveSelectedFile:pt,attachmentError:rt,isUploadingAttachment:at,requiresEmail:He,emailInput:qe,setEmailInput:Je,emailError:Ye,replyContext:A,setReplyContext:Ke,webRTCError:ee,micError:$e,setMicError:et,dismissCallError:de,incomingCall:g,rejectCall:ce,acceptCall:se,activeCallId:_,callConnectionState:v,isCallMuted:x,toggleCallMute:ue,endWebRTCCall:le,formatCallDuration:_t,callDurationSeconds:Ze,onCollapse:bt,onStartVoice:St,onEndConversation:oe,showPoweredBy:Me}),(0,M.jsx)(`style`,{children:`
615
+ </svg>`,ZD=null,QD=!1;function $D(){return(!ZD||!ZD.isConnected)&&(ZD=document.createElement(`div`),ZD.id=`${Q}-cursor`,ZD.innerHTML=XD,document.body.appendChild(ZD),QD=!1),ZD}async function eO(e){if(typeof document>`u`||!e)return;ID();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=$D();QD||=(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 iO(360)}function tO(e=!1){ZD&&(e?(ZD.classList.remove(`${Q}-cursor-visible`),QD=!1):(ZD.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{QD=!1},250)))}async function nO(e){ZD&&(ZD.classList.add(`${Q}-cursor-click`),await iO(280),ZD.classList.remove(`${Q}-cursor-click`))}function rO(e){if(!e||typeof document>`u`)return;ID();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 iO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){pn()&&console.log(`[FlowEngage:voice-tools]`,...e)}function aO(e){return new Promise(t=>setTimeout(t,e))}var oO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function sO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(oO)}catch{return!1}}function cO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function lO(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(!sO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function uO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function dO(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 uO(r.join(` `))}if(e.labels&&e.labels.length)return uO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return uO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return uO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return uO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=uO(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 uO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return uO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?uO(o):null}function fO(){let e=[];return lO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(sO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=cO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function pO(){return fO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:dO(e),placeholder:e.placeholder||null}))}function mO(){let e=[];return lO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(sO(e)||e.disabled)return!1;try{let t=cO(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 hO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function gO(e){let t=hO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function _O(e,t){let n=gO(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,dO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>hO(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var vO=28;function yO(e,t){let n=null,r=0;for(let i of e){let e=_O(i,t);e>r&&(r=e,n=i)}return!n||r<vO?null:n}function bO(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,dO(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function xO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function SO(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function CO(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function wO(e){if(!CO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,dO(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function TO(e,t,n){let r=String(t??``),i=String(n??``),a=OO(e,r)||yO(e,r)||bO(e,r,i);if(!a)return[];let o=new Set([a]);if(xO(i)&&SO(r))for(let t of e)t!==a&&wO(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function EO(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 DO(e){if(!e||typeof e!=`string`)return null;let t=null;return lO(n=>{try{let r=n.getElementById(e);r&&!sO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function OO(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=DO(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=DO(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function kO(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function AO(e,t){let n=[];lO(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(sO(e)||e.disabled)return!1;try{let t=cO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:kO(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=EO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function jO(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 MO(e){let t=jO(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function NO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function PO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function FO(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 IO(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function LO(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function RO(){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 zO(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{if($(`flowengage_navigate ▶ raw parameters:`,n),typeof e.getPostResumeNavLocked==`function`&&e.getPostResumeNavLocked())return $(`flowengage_navigate · blocked (post-resume lock active)`,n),`Navigation is not needed — you just arrived at this page via the user's navigation request. Stay here and continue the conversation naturally.`;let r=jO(n),i=FO(r),a=r.section_text??r.sectionText??r.section;if($(`flowengage_navigate · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(i,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(i=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,i))}catch{}if(typeof window<`u`)try{let e=new URL(i,window.location.href),t=window.location;if(e.pathname===t.pathname&&e.search===t.search&&(e.hash===t.hash||!e.hash))return $(`flowengage_navigate · already on target page, skipping navigation`),`Already on that page. Continue the conversation naturally without calling flowengage_navigate again.`}catch{}if(!await Hn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${i}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{BD(`Navigating to ${i}...`,{spinner:!0}),GD();let t=typeof e.getSessionCaptureData==`function`?e.getSessionCaptureData():null,n=i;if(t){let{ok:e,sessionKey:r,compact:o}=DD.capture({siteId:t.siteId,chatId:t.chatId,agentId:t.agentId,trigger:`agent_navigate`,navigationConfidence:`high`,targetUrl:i,interruption:{state:`tool_calling`,toolName:`flowengage_navigate`,toolParams:{url:i,section_text:a||null},lastAgentText:t.lastAgentText,lastUserText:t.lastUserText,estimatedSpokenWords:t.estimatedSpokenWords,agentTextWordCount:t.agentTextWordCount,isMuted:t.isMuted||!1},history:t.history});e&&r?n=TD(i,r):o&&(n=TD(i,o)),$(`flowengage_navigate · session captured, resumeUrl:`,n)}return jD(),await aO(300),$(`flowengage_navigate → location.assign`,n),window.location.assign(n),`Navigating...`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),BD(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{KD(),VD(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=jO(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;RO();let i=Rn(n||null,r||null);return!i&&r&&(await new Promise(e=>setTimeout(e,500)),RO(),i=Rn(null,r)),i?(PD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}"`):($(`flowengage_highlight ✖ no element for:`,r||n),`Could not find "${r||n}" on the current page. Try a shorter phrase matching a visible heading.`)},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=jO(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=Rn(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
616
+ `)}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`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=IO(jO(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → 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($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=jO(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → 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($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`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 $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=pO(),t=mO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),qD();let t=MO(e);if(!t.length&&r){let e=r(),n=NO(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=PO(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;BD(`Filling ${String(t)}...`,{spinner:!0});let a=fO(),o=TO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())JD(t),await eO(t),LO(t,r,{skipScroll:e>0}),YD(t),await aO(120);i=o,n.push(String(t));continue}let s=OO(a,String(t));s||=yO(a,String(t)),s||=bO(a,String(t),r),s&&(JD(s),await eO(s),LO(s,r),YD(s),await aO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),BD(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),BD(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{tO(),qD(),VD(700)}},flowengage_click_button:async e=>{let t=jO(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=AO(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{BD(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await eO(r),r.focus?.(),await nO(r),rO(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),BD(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),BD(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{tO(),VD(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function BO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=pn();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 VO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function HO(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 UO(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 WO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,M.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?b.createElement(e):b.isValidElement(e)?e:null;return n?(0,M.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function GO({title:e}){return(0,M.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 KO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\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))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function qO({orbColors:e,...t}){return(0,M.jsx)(uD,{colors:e,...t})}function JO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||VO.green,s=UO(o),c=a?72:94,l=(0,M.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,M.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,M.jsx)(jp.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:a?void 0:`210px`},children:e.entryPrompt}),(0,M.jsxs)(jp.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,M.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:o,color:s,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}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,M.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,M.jsx)(jp.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,M.jsx)(qO,{size:c,orbColors:t})})]});return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(jp.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,M.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function YO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o}){let s=n||VO.green,c=UO(s);return(0,M.jsxs)(jp.div,{initial:{scale:50/350,borderRadius:`50%`},animate:{scale:1,borderRadius:`16px`},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,M.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,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,M.jsx)(qO,{size:72,orbColors:t}),(0,M.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,M.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,M.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${s}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,M.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 XO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s,pendingResume:c,chatId:l}){let[u,d]=(0,b.useState)(`idle`),[f,p]=(0,b.useState)(!1),[m,h]=(0,b.useState)(!1),g=(0,b.useRef)(null),_=(0,b.useRef)(``),v=(0,b.useRef)(async()=>{}),y=(0,b.useRef)(!1),x=(0,b.useRef)(!1),ee=(0,b.useRef)(`idle`),S=(0,b.useRef)(!1),C=(0,b.useRef)(!1),te=(0,b.useRef)(`minimized`),w=(0,b.useRef)(0),ne=(0,b.useRef)(!1),re=(0,b.useRef)(null),ie=(0,b.useCallback)((e=`minimized`)=>{te.current=e,C.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),ae=(0,b.useCallback)(async e=>{C.current=!0;try{await g.current?.endSession?.()}catch{}if(g.current=null,d(`idle`),p(!1),y.current=!1,typeof s==`function`){let e=w.current;await s(e>0?o.current.slice(e):o.current)}e?.()},[o,s]);return v.current=()=>ae(te.current===`chat`?t:n),(0,b.useEffect)(()=>{x.current=f},[f]),(0,b.useEffect)(()=>{ee.current=u},[u]),(0,b.useEffect)(()=>{let e=()=>!!g.current,t=()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``},n=e=>{let n=t(),a=n.split(/\s+/).filter(Boolean).length;return{siteId:i,chatId:l||null,agentId:r,trigger:e,navigationConfidence:e===`agent_navigate`?`high`:`medium`,interruption:{state:ee.current,lastAgentText:n,lastUserText:_.current,estimatedSpokenWords:AD(),agentTextWordCount:a,isMuted:x.current},history:o.current||[]}},a=()=>{e()&&(OD()||DD.capture(n(`user_link_click`)))},s=t=>{e()&&(t.persisted||OD()||DD.capture(n(`pagehide`)))};return window.addEventListener(`beforeunload`,a),window.addEventListener(`pagehide`,s),()=>{window.removeEventListener(`beforeunload`,a),window.removeEventListener(`pagehide`,s)}},[i,l,r,o]),(0,b.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){d(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;c?(o.current=Array.isArray(c.history)?[...c.history]:[],w.current=o.current.length,c.interruption?.lastUserText&&(_.current=c.interruption.lastUserText),ne.current=!0,setTimeout(()=>{ne.current=!1},5e3)):(o.current=[],w.current=0,_.current=``,ne.current=!1),y.current=!1,S.current=!1,C.current=!1,te.current=`minimized`;let t=BO(zO({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,getPostResumeNavLocked:()=>ne.current,requestEndSession:()=>{ie()},getSessionCaptureData:()=>{let e=(()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``})();return{siteId:i,chatId:l||null,agentId:r,history:o.current||[],lastAgentText:e,agentTextWordCount:e.split(/\s+/).filter(Boolean).length,lastUserText:_.current,estimatedSpokenWords:AD(),isMuted:x.current}}})),s=typeof window<`u`?window.location.href:``,u,f=null;if(c&&!c.consumed){let e=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().slice(0,100),id:e.id||null})).filter(e=>e.text.length>0).slice(0,25):[];f=DD.buildResumePrompt(c,e,s);let t=e[0]?.text||``;u={agent:{firstMessage:t?`I've arrived on the ${t} page. What would you like to know?`:`I've arrived on the new page. What would you like to know?`}}}let m=await EE.startSession({agentId:r,...u?{overrides:u}:{},clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||d(t===`speaking`?`speaking`:`listening`)},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(!r)return;let i=o.current,a=i.length>0?i[i.length-1]:null;a&&a.sender===n&&a.message===r||(n===`user`&&(_.current=r),o.current=[...i,{sender:n,message:r,timestamp:new Date().toISOString()}],KO(n,r)&&ie(`minimized`))},onError:t=>{if(!e&&!C.current&&!S.current){S.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),d(`error`),ie(`minimized`)}},onDisconnect:()=>{if(!e&&!C.current&&!S.current){S.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:_.current||``,wasMuted:x.current});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),ie(`minimized`)}}});if(e){m.endSession().catch(()=>{});return}n=m,g.current=m,d(`listening`);try{if(f)m.sendContextualUpdate(f),DD.clear();else{let e=`[]`;try{e=await t.flowengage_list_forms()}catch{}let n=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, nav, footer, header`)).map(e=>({tag:e.tagName,text:e.textContent.trim(),id:e.id||null})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,25):[];m.sendContextualUpdate(`Page: ${s}. SiteId: ${i||`unknown`}. Sections on this page: ${JSON.stringify(n)}. IMPORTANT: Call flowengage_highlight with section_text from the list above as you explain each section. Forms: ${e}. Navigation: flowengage_navigate — use for cross-page navigation. End call: flowengage_end_session.`)}}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),d(`error`),te.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,C.current=!0,(n||g.current)?.endSession?.().catch(()=>{})}},[r,i,a,ie]),(0,b.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;re.current&&!re.current.contains(t)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,M.jsxs)(`div`,{ref:re,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:[(0,M.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&(0,M.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:`Listening...`}),(0,M.jsx)(qO,{size:72,voiceState:u,isMuted:f,orbColors:e})]}),u===`error`&&(0,M.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,M.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,M.jsx)(`button`,{onClick:async()=>{if(g.current)try{f?(await g.current.setMicMuted?.(!1),p(!1)):(await g.current.setMicMuted?.(!0),p(!0))}catch{}},title:f?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:f?`#7f1d1d`:`#1f2937`,border:f?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:f?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:f?(0,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,M.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,M.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,M.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,M.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,M.jsx)(DE,{size:16,color:`currentColor`})}),(0,M.jsx)(`button`,{onClick:()=>h(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,M.jsx)(FE,{size:16,color:`currentColor`})})]}),m&&(0,M.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,M.jsxs)(`button`,{onClick:()=>{h(!1),te.current=`chat`,ae(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,M.jsx)(IE,{}),`Enter Chat Mode`]}),(0,M.jsxs)(`button`,{onClick:()=>{h(!1),te.current=`minimized`,ae(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,M.jsx)(LE,{}),`End Conversation`]}),(0,M.jsx)(`button`,{onClick:()=>h(!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,M.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,M.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function ZO({orbColors:e}){return(0,M.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,M.jsx)(qO,{size:36,orbColors:e})})}var QO=()=>(0,M.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,M.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,M.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 $O({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:ee,selectedFile:S,onFileSelect:C,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:ae,emailError:oe,replyContext:se,setReplyContext:ce,webRTCError:le,micError:ue,setMicError:T,dismissCallError:E,incomingCall:de,rejectCall:fe,acceptCall:pe,activeCallId:me,callConnectionState:he,isCallMuted:ge,toggleCallMute:_e,endWebRTCCall:ve,formatCallDuration:ye,callDurationSeconds:be,onCollapse:xe,onStartVoice:Se,showPoweredBy:Ce}){let we=c.length>0,Te=y||x||v,Ee=!!(de||me),[De,Oe]=(0,b.useState)(!1),ke=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(!De)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ke.current&&!ke.current.contains(t)&&Oe(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[De]),(0,M.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:0,width:`calc(100% - 16px)`,height:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`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:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,M.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0},children:[(0,M.jsx)(`button`,{onClick:xe,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,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,M.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,M.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,M.jsx)(WO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,M.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,M.jsx)(GO,{title:e.chatTitle})})}),(0,M.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,M.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,M.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:ke,children:[(0,M.jsx)(`button`,{type:`button`,onClick:()=>Oe(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,M.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,M.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,M.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,M.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),De&&(0,M.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:[(0,M.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),Se?.()},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,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,M.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,M.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),xe?.()},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,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.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,M.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,M.jsx)(tD,{webRTCError:le,micError:ue,setMicError:T,dismissCallError:E,incomingCall:de,rejectCall:fe,acceptCall:pe,activeCallId:me,callConnectionState:he,formatCallDuration:ye,callDurationSeconds:be,endWebRTCCall:ve,isCallMuted:ge,toggleCallMute:_e,isAIVoiceActive:!1,currentCallAgentName:f||m,isRateLimited:x,rateLimitMessage:ee}),(0,M.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:we?(0,M.jsx)(ZE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ce,TypingDots:QO,primaryColor:n,agentHeadshot:p,agentDisplayName:f||m,botAvatarNode:(0,M.jsx)(ZO,{orbColors:t})}):(0,M.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,M.jsx)(qO,{size:94,orbColors:t}),(0,M.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,M.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,M.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))})]})}),(0,M.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:re?`6px 0 0`:`12px 0 0`},children:(0,M.jsx)(QE,{input:h,setInput:g,onSubmit:_,isConversationEnded:v,callUiActive:Ee,handleToggleVoice:Se,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Te,replyContext:se,clearReplyContext:()=>ce(null),onFileSelect:C,selectedFile:S,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:ae,emailError:oe,inputPlaceholder:e.inputPlaceholder})}),(0,M.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:Ce&&(0,M.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,M.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function ek(){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:ee,language:S,historyRef:C,onMessageSync:te,sendMessage:w,uploadChatFile:ne,openWidget:re,captureVisitorEmail:ie,setVoiceMode:ae,endConversation:oe,acceptCall:se,rejectCall:ce,endWebRTCCall:le,toggleCallMute:ue,dismissCallError:de,startTyping:pe,stopTyping:me,updateTypingDraft:he}=fn();(0,b.useEffect)(()=>{try{In()}catch{}},[]);let ge=t?.widgetSettings||{},_e=n?.widgetSettings||{},ve={...ge.branding||{},..._e.branding||{}},ye={...ge.theme||{},..._e.theme||{}},be={...ge.features||{},..._e.features||{}},xe=be.voice!==!1,Se=Array.isArray(ye.orbColors)&&ye.orbColors.length>0?ye.orbColors:null,Ce=Se?.[0]||ye.primaryColor||`#3B82F6`,we=ye.position||`bottom-right`,Te=ve.fallbackAgentName||`Agent`,Ee=HO(Se??ye.chatBgColors),De=ve.logo||ve.logoUrl||null,Oe=S||`en`,ke=ge.recommendations?.[Oe]||[],Ae=(_e.recommendations?.[Oe]??ke).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),je=Array.isArray(ve.quickChatOptions)&&ve.quickChatOptions.length>0?ve.quickChatOptions:Ae,Me=ve.hideWatermark===!0?!1:ve.showPoweredBy!==!1,D=ve.chatbotEnabled!==!1&&ye.chatbotEnabled!==!1,Ne=ge.greetings?.[S]||_e.greetings?.[S]||ve.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Pe={entryPrompt:ve.entryPrompt||`Do you want to explore in a new way?`,yesLabel:ve.yesLabel||`Yes`,laterLabel:ve.laterLabel||`Later`,connectionTitle:ve.connectionTitle||`How would you like to connect?`,voiceLabel:ve.voiceLabel||`Voice`,textLabel:ve.textLabel||`Text`,chatTitle:ve.headerName||`Chat with FlowEngage`,introGreeting:Ne,inputPlaceholder:ve.inputPlaceholder||`Type your message`,analysingLabel:ve.analysingLabel||`analysing...`},Fe=_e.elevenLabsAgentId||t?.elevenLabsAgentId||null,Ie=t?.siteId||n?.siteId||null,Le=t?.apiBaseUrl||``,Re=(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]),ze=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Be=r.some(e=>e.sender===`user`),Ve=(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]),He=!l&&Be&&Ve,Ue=!!(_e._dashboardLivePreview||ge._dashboardLivePreview),[We,O]=(0,b.useState)(()=>Ue?`text_chat`:`entry_prompt`),[k,Ge]=(0,b.useState)(``),[A,Ke]=(0,b.useState)(null),[qe,Je]=(0,b.useState)(l||``),[Ye,Xe]=(0,b.useState)(``),[Ze,Qe]=(0,b.useState)(0),[$e,et]=(0,b.useState)(null),[tt,nt]=(0,b.useState)(null),[rt,it]=(0,b.useState)(``),[at,ot]=(0,b.useState)(!1),st=(0,b.useRef)(null),ct=(0,b.useRef)(!1),lt=(0,b.useRef)(null),ut=(0,b.useMemo)(()=>fe(Ie),[Ie]);(0,b.useLayoutEffect)(()=>{if(!(e!==`ready`||ct.current)){ct.current=!0;try{let e=DD.read(Ie);if(e&&e._resumeMode===`auto`){lt.current=e,re({notifyChatInitiated:!0}),ae?.(!0),O(`voice_mode`);return}}catch{}if(T(Ie)||!xe){O(`minimized_orb`);return}}},[e,r]);let[dt,ft]=(0,b.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,b.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>ft(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,b.useEffect)(()=>{Je(l||``),l&&Xe(``)},[l]);let pt=(0,b.useCallback)(()=>{nt(null),it(``)},[]),mt=(0,b.useCallback)(e=>{let t=KE(e);if(t){nt(null),it(t);return}nt(e),it(``)},[]);(0,b.useEffect)(()=>{if(!y||v!==`connected`){Qe(0);return}let e=()=>{let e=new Date(y).getTime();isNaN(e)||Qe(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[y,v]),(0,b.useEffect)(()=>{let e=g?.callId||_||null;if(!e){st.current=null;return}(g?.callId||v===`connecting`||v===`connected`)&&(!(!i||We===`minimized_orb`||We===`voice_mode`)&&st.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:We,hasIncomingCall:!!g?.callId,activeCallId:_,callConnectionState:v}),st.current=e,We===`voice_mode`&&ae?.(!1),re?.(),O(`text_chat`)))},[_,v,g?.callId,i,re,ae,We]),(0,b.useEffect)(()=>{if(!o||h){he?.(``),me?.();return}if(!k.trim()||tt){he?.(``),me?.();return}pe?.();let e=window.setTimeout(()=>he?.(k),120),t=window.setTimeout(()=>me?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[k,tt,o,h,pe,me,he]);let ht=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,gt=async e=>{if(e.preventDefault(),h)return;if(He){let e=qe.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Xe(`Please enter a valid email so we can continue helping you.`);return}await ie(e),Xe(``);return}let t=ht(A);if(!k.trim()&&!tt)return;if(tt){try{ot(!0),it(``);let e=await ne(tt),n=e?.data||e,r=k.trim()||`Shared file: ${JE(tt)}`;Ge(``),Ke(null),pt(),await w(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||tt.name,fileType:n?.fileType||tt.type,fileSize:n?.fileSize||tt.size}})}catch(e){it(e?.message||`Failed to upload the selected file.`)}finally{ot(!1)}return}let n=k.trim();Ge(``),Ke(null),await w(n,``,t)},_t=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},vt=(0,b.useCallback)(async e=>{if(h||f)return;let t=e.message||e.label||e.text||``;t.trim()&&await w(t.trim(),``)},[h,f,w]),yt=dt&&We===`entry_prompt`?{inset:0}:dt&&We===`text_chat`?{left:0,right:0,bottom:0}:dt&&We===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:we===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},bt=()=>O(`minimized_orb`),xt=()=>O(`connection_modal`),St=()=>{re({notifyChatInitiated:!0}),ae?.(!0),O(`voice_mode`)},Ct=()=>{re({notifyChatInitiated:!0}),ae?.(!1),O(`text_chat`)},wt=()=>{ae?.(!1),bt()};return e!==`ready`||!D||be.chat===!1?null:(0,M.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...yt},children:[We===`entry_prompt`&&(0,M.jsx)(JO,{copy:Pe,orbColors:Se,primaryColor:Ce,onYes:()=>{E(Ie),St()},onLater:()=>{E(Ie),bt()},isMobile:dt}),We===`minimized_orb`&&(0,M.jsx)(jp.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,M.jsx)(qO,{size:50,orbColors:Se,onClick:xe?xt:Ct})}),We===`connection_modal`&&(0,M.jsx)(YO,{copy:Pe,orbColors:Se,primaryColor:Ce,onVoice:St,onText:Ct,onClose:bt,isMobile:dt}),We===`voice_mode`&&(0,M.jsx)(XO,{orbColors:Se,onEnterChat:Ct,onEndChat:wt,agentId:Fe,siteId:Ie,apiBaseUrl:Le,historyRef:C,onMessageSync:te,pendingResume:lt.current,chatId:ut},`voice`),We===`text_chat`&&(0,M.jsx)($O,{copy:Pe,orbColors:Se,primaryColor:Ce,chatBgGradient:Ee,logo:De,quickChatOptions:je,onQuickChatSelect:vt,isMobile:dt,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Re,agentHeadshot:ze,fallbackAgentName:Te,input:k,setInput:Ge,onSubmit:gt,isConversationEnded:h,isLoading:f,isRateLimited:p,rateLimitMessage:m,selectedFile:tt,onFileSelect:mt,onRemoveSelectedFile:pt,attachmentError:rt,isUploadingAttachment:at,requiresEmail:He,emailInput:qe,setEmailInput:Je,emailError:Ye,replyContext:A,setReplyContext:Ke,webRTCError:ee,micError:$e,setMicError:et,dismissCallError:de,incomingCall:g,rejectCall:ce,acceptCall:se,activeCallId:_,callConnectionState:v,isCallMuted:x,toggleCallMute:ue,endWebRTCCall:le,formatCallDuration:_t,callDurationSeconds:Ze,onCollapse:bt,onStartVoice:St,onEndConversation:oe,showPoweredBy:Me}),(0,M.jsx)(`style`,{children:`
616
617
  /* Force any SVG (or img) inside LogoSlot to fill the container height
617
618
  regardless of whether the component forwards its style prop. */
618
619
  .fe-logo-slot svg,
@@ -453,9 +453,10 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
453
453
 
454
454
  gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
455
455
  }
456
- `;function iD(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 aD({size:e=94,voiceState:t=`idle`,isMuted:n=!1,colors:r,onClick:i,style:a,className:o}){let[s,c,l]=QE(r),u=t===`speaking`,p=e<=50,m=(0,d.useRef)(null),h=(0,d.useRef)($E[t]??.35);(0,d.useEffect)(()=>{h.current=$E[t]??.35},[t]),(0,d.useEffect)(()=>{let t=m.current;if(!t)return;let n=Math.min(window.devicePixelRatio||1,2);t.width=e*n,t.height=e*n;let r=t.getContext(`webgl`,{alpha:!0,antialias:!0})||t.getContext(`experimental-webgl`,{alpha:!0,antialias:!0});if(!r){console.warn(`[AnimatedOrb] WebGL unavailable.`);return}let i=iD(r,nD,rD);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,eD(s)),r.uniform3fv(u.c2,eD(c)),r.uniform3fv(u.c3,eD(l)),r.viewport(0,0,t.width,t.height);let d=performance.now(),f,p=e=>{r.uniform1f(u.time,(e-d)/1e3),r.uniform1f(u.speed,h.current),r.drawArrays(r.TRIANGLES,0,6),f=requestAnimationFrame(p)};return f=requestAnimationFrame(p),()=>{cancelAnimationFrame(f),r.deleteProgram(i),r.deleteBuffer(a)}},[s,c,l,e]);let g=n?`saturate(0.3) brightness(1.1)`:t===`error`?`saturate(0.4) hue-rotate(28deg)`:`none`;return(0,f.jsxs)(`div`,{style:{position:`relative`,width:e,height:e,flexShrink:0,cursor:i?`pointer`:`default`,...a},className:o,onClick:i,children:[u&&!p&&(0,f.jsx)(Mp.div,{style:{position:`absolute`,inset:-10,borderRadius:`50%`,background:`radial-gradient(circle, ${tD(s,.18)} 0%, transparent 70%)`,pointerEvents:`none`},animate:{opacity:[.3,.75]},transition:{duration:1,repeat:1/0,repeatType:`mirror`,ease:`easeInOut`}}),(0,f.jsx)(`div`,{style:{width:e,height:e,borderRadius:`50%`,overflow:`hidden`,WebkitMaskImage:`-webkit-radial-gradient(white, black)`,filter:g,transition:`filter 1.2s ease`},children:(0,f.jsx)(`canvas`,{ref:m,style:{width:`100%`,height:`100%`,display:`block`}})}),u&&(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,pointerEvents:`none`,zIndex:1},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`3px`},children:[4,8,12,8,4].map((e,t)=>(0,f.jsx)(Mp.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 oD=`fe_voice_session`,sD=`fe_tab_id`,cD=40,lD=2e3,uD=300*1e3,dD=60*1e3,fD=30*1e3;function pD(){let e=new Uint8Array(16);try{crypto.getRandomValues(e)}catch{for(let t=0;t<16;t++)e[t]=Math.floor(Math.random()*256)}return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function mD(){try{let e=sessionStorage.getItem(sD);return e||(e=pD(),sessionStorage.setItem(sD,e)),e}catch{return pD()}}function hD(e,t){return`${(e||[]).length}:${t%1e5}`}function gD(e,t){return Array.isArray(e)?e.length<=t?e:e.slice(e.length-t):[]}function _D(){if(typeof document>`u`)return{headings:[],activeHighlightText:null,activeHighlightId:null};let e=document.querySelector(`.fe-highlight-section`);return{headings:Array.from(document.querySelectorAll(`h1,h2,h3,h4`)).filter(e=>!e.closest(`#flowengage-root`)).map(e=>({tag:e.tagName,text:e.textContent.trim().slice(0,100),id:e.id||null})).slice(0,25),activeHighlightText:e?.textContent?.trim().slice(0,100)||null,activeHighlightId:e?.id||null}}function vD(e){if(!e)return`Unknown state.`;let{state:t,lastAgentText:n,lastUserText:r,toolName:i,toolParams:a,estimatedSpokenWords:o,agentTextWordCount:s,unspokenSuffix:c}=e,l=[];return t===`speaking`?(l.push(`You were SPEAKING.`),n&&(l.push(`You had spoken approximately ${o??`?`} of ${s??`?`} words.`),l.push(`Your response text: "${n}"`),c&&l.push(`Estimated unspoken remainder: "${c}"`))):t===`listening`?(l.push(`You were LISTENING for the user's response.`),r&&l.push(`Last user message: "${r}"`)):t===`tool_calling`?i===`flowengage_navigate`?(l.push(`Navigation ALREADY COMPLETED — you successfully navigated to this page.`),l.push(`DO NOT call flowengage_navigate again. You are already on the destination.`),n&&l.push(`Before navigating you said: "${n}"`)):(l.push(`You were executing tool: ${i||`unknown`}`),a&&l.push(`Tool parameters: ${JSON.stringify(a)}`),n&&l.push(`Your last spoken text before the tool call: "${n}"`)):l.push(`Session state at capture: ${t||`idle`}`),l.join(`
456
+ `;function iD(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 aD({size:e=94,voiceState:t=`idle`,isMuted:n=!1,colors:r,onClick:i,style:a,className:o}){let[s,c,l]=QE(r),u=t===`speaking`,p=e<=50,m=(0,d.useRef)(null),h=(0,d.useRef)($E[t]??.35);(0,d.useEffect)(()=>{h.current=$E[t]??.35},[t]),(0,d.useEffect)(()=>{let t=m.current;if(!t)return;let n=Math.min(window.devicePixelRatio||1,2);t.width=e*n,t.height=e*n;let r=t.getContext(`webgl`,{alpha:!0,antialias:!0})||t.getContext(`experimental-webgl`,{alpha:!0,antialias:!0});if(!r){console.warn(`[AnimatedOrb] WebGL unavailable.`);return}let i=iD(r,nD,rD);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,eD(s)),r.uniform3fv(u.c2,eD(c)),r.uniform3fv(u.c3,eD(l)),r.viewport(0,0,t.width,t.height);let d=performance.now(),f,p=e=>{r.uniform1f(u.time,(e-d)/1e3),r.uniform1f(u.speed,h.current),r.drawArrays(r.TRIANGLES,0,6),f=requestAnimationFrame(p)};return f=requestAnimationFrame(p),()=>{cancelAnimationFrame(f),r.deleteProgram(i),r.deleteBuffer(a)}},[s,c,l,e]);let g=n?`saturate(0.3) brightness(1.1)`:t===`error`?`saturate(0.4) hue-rotate(28deg)`:`none`;return(0,f.jsxs)(`div`,{style:{position:`relative`,width:e,height:e,flexShrink:0,cursor:i?`pointer`:`default`,...a},className:o,onClick:i,children:[u&&!p&&(0,f.jsx)(Mp.div,{style:{position:`absolute`,inset:-10,borderRadius:`50%`,background:`radial-gradient(circle, ${tD(s,.18)} 0%, transparent 70%)`,pointerEvents:`none`},animate:{opacity:[.3,.75]},transition:{duration:1,repeat:1/0,repeatType:`mirror`,ease:`easeInOut`}}),(0,f.jsx)(`div`,{style:{width:e,height:e,borderRadius:`50%`,overflow:`hidden`,WebkitMaskImage:`-webkit-radial-gradient(white, black)`,filter:g,transition:`filter 1.2s ease`},children:(0,f.jsx)(`canvas`,{ref:m,style:{width:`100%`,height:`100%`,display:`block`}})}),u&&(0,f.jsx)(`div`,{style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,pointerEvents:`none`,zIndex:1},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`3px`},children:[4,8,12,8,4].map((e,t)=>(0,f.jsx)(Mp.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 oD=`fe_voice_session`,sD=`fe_tab_id`,cD=40,lD=2e3,uD=300*1e3,dD=60*1e3,fD=30*1e3;function pD(){let e=new Uint8Array(16);try{crypto.getRandomValues(e)}catch{for(let t=0;t<16;t++)e[t]=Math.floor(Math.random()*256)}return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function mD(){try{let e=sessionStorage.getItem(sD);return e||(e=pD(),sessionStorage.setItem(sD,e)),e}catch{return pD()}}function hD(e,t){return`${(e||[]).length}:${t%1e5}`}function gD(e,t){return Array.isArray(e)?e.length<=t?e:e.slice(e.length-t):[]}function _D(){if(typeof document>`u`)return{headings:[],activeHighlightText:null,activeHighlightId:null};let e=document.querySelector(`.fe-highlight-section`);return{headings:Array.from(document.querySelectorAll(`h1,h2,h3,h4`)).filter(e=>!e.closest(`#flowengage-root`)).map(e=>({tag:e.tagName,text:e.textContent.trim().slice(0,100),id:e.id||null})).slice(0,25),activeHighlightText:e?.textContent?.trim().slice(0,100)||null,activeHighlightId:e?.id||null}}function vD(e){if(!e)return`Unknown state.`;let{state:t,lastAgentText:n,lastUserText:r,toolName:i,toolParams:a,estimatedSpokenWords:o,agentTextWordCount:s,unspokenSuffix:c}=e,l=[];return t===`speaking`?(l.push(`You were SPEAKING.`),n&&(l.push(`You had spoken approximately ${o??`?`} of ${s??`?`} words.`),l.push(`Your response text: "${n}"`),c&&l.push(`Estimated unspoken remainder: "${c}"`))):t===`listening`?(l.push(`You were LISTENING for the user's response.`),r&&l.push(`Last user message: "${r}"`)):t===`tool_calling`?i===`flowengage_navigate`?(l.push(`Navigation ALREADY COMPLETED — you successfully navigated to this page.`),l.push(`DO NOT call flowengage_navigate again. You are already on the destination.`),r&&l.push(`The user's last request was: "${r}"`),n&&l.push(`Before navigating you said: "${n}"`)):(l.push(`You were executing tool: ${i||`unknown`}`),a&&l.push(`Tool parameters: ${JSON.stringify(a)}`),n&&l.push(`Your last spoken text before the tool call: "${n}"`)):l.push(`Session state at capture: ${t||`idle`}`),l.join(`
457
457
  `)}function yD(e,t){try{let n={v:2,sid:e.siteId||``,aid:e.agentId||``,ut:(e.interruption?.lastUserText||``).slice(0,50),ts:Math.floor(t/1e3)};return`compact:${btoa(unescape(encodeURIComponent(JSON.stringify(n))))}`}catch{return null}}function bD(e,t){if(!t)return e;try{let n=new URL(e,window.location.href);return n.searchParams.set(`_fe_resume`,t),n.href}catch{return e+(e.includes(`?`)?`&`:`?`)+`_fe_resume=`+t}}function xD(){if(typeof window>`u`)return null;try{let e=new URL(window.location.href),t=e.searchParams.get(`_fe_resume`);if(!t)return null;e.searchParams.delete(`_fe_resume`);let n=e.pathname+(e.search?e.search:``)+(e.hash?e.hash:``);return window.history.replaceState(window.history.state,``,n),t}catch{return null}}var SD={capture(e){let t=pD(),n=Date.now(),r=gD(e.history,cD),i=(e.interruption?.lastAgentText||``).slice(0,lD),a=e.interruption?.estimatedSpokenWords||0,o=e.interruption?.agentTextWordCount||i.split(/\s+/).filter(Boolean).length,s=``;e.interruption?.state===`speaking`&&i&&a>0&&(s=i.split(/\s+/).slice(a).join(` `));let c={version:2,sessionKey:t,tabId:mD(),siteId:e.siteId,chatId:e.chatId||null,agentId:e.agentId,ts:n,expiresAt:n+uD,resumeAttempts:0,consumed:!1,trigger:e.trigger,navigationConfidence:e.navigationConfidence||`medium`,fromUrl:typeof window<`u`?window.location.href:``,targetUrl:e.targetUrl||null,interruption:{...e.interruption,lastAgentText:i,estimatedSpokenWords:a,agentTextWordCount:o,unspokenSuffix:s,micWasGranted:!0,isMuted:e.interruption?.isMuted||!1,hadError:e.interruption?.hadError||!1},fromPageContext:_D(),history:r,historyTotalTurns:(e.history||[]).length,storageChecksum:hD(r,n)};try{return sessionStorage.setItem(oD,JSON.stringify(c)),{ok:!0,sessionKey:t,compact:null}}catch{return{ok:!1,sessionKey:null,compact:yD(e,n)}}},read(e){if(typeof window>`u`)return null;let t=xD();if(t?.startsWith(`compact:`)){try{let n=JSON.parse(decodeURIComponent(escape(atob(t.slice(8))))),r=Date.now()/1e3-(n.ts||0);if(n.v===2&&n.sid===e&&r<300)return{_compact:!0,_resumeMode:`auto`,siteId:n.sid,agentId:n.aid,chatId:null,history:[],historyTotalTurns:0,trigger:`agent_navigate`,navigationConfidence:`medium`,fromUrl:``,interruption:{state:`listening`,lastUserText:n.ut||``,lastAgentText:``},fromPageContext:{headings:[],activeHighlightText:null}}}catch{}return null}let n;try{n=JSON.parse(sessionStorage.getItem(oD)||`null`)}catch{return null}if(!n)return null;if(n.version!==2)return this._discard(`version`);if(n.siteId!==e)return this._discard(`siteId`);if(Date.now()>n.expiresAt)return this._discard(`expired`);if(n.consumed)return this._discard(`consumed`);if(n.resumeAttempts>=2)return this._discard(`loop_guard`);if(hD(n.history,n.ts)!==n.storageChecksum)return this._discard(`checksum`);if(n.trigger===`agent_navigate`&&t&&t!==n.sessionKey)return this._discard(`key_mismatch`);if(n.trigger===`pagehide`){if(Date.now()-n.ts>fD)return this._discard(`pagehide_stale`);n._resumeMode=`banner`}else if(n.trigger===`user_link_click`){if(Date.now()-n.ts>dD)return this._discard(`user_nav_stale`);n._resumeMode=`auto`}else n._resumeMode=`auto`;n.resumeAttempts+=1;try{sessionStorage.setItem(oD,JSON.stringify(n))}catch{}return n},clear(){try{sessionStorage.removeItem(oD)}catch{}},buildResumePrompt(e,t,n){let r=(e.history||[]).map(e=>`[${e.sender===`user`?`User`:`Agent`}]: ${e.message}`).join(`
458
- `),i=vD(e.interruption),a=(t||[]).map(e=>e.text).join(`, `),o=``,s=``;try{o=new URL(e.fromUrl||``).pathname}catch{o=e.fromUrl||``}try{s=new URL(n||window.location.href).pathname}catch{s=n||``}return[`VOICE SESSION AUTO-RESUMED AFTER PAGE NAVIGATION.`,`Navigation confidence: ${(e.navigationConfidence||`medium`).toUpperCase()}`,`Navigation: ${o} → ${s}`,``,`── Prior Conversation (${e.historyTotalTurns} turns) ──`,r||`(no prior turns)`,``,`── Your State at Interruption ──`,i,``,`── Current Page ──`,`URL: ${n||(typeof window<`u`?window.location.href:``)}`,`Sections: ${a||`none detected`}`,``,`── CRITICAL INSTRUCTIONS ──`,`1. DO NOT re-introduce yourself.`,`2. DO NOT ask the user what they need — you already know from the conversation above.`,`3. Continue the conversation naturally as if the navigation was seamless.`,`4. If you were mid-sentence, complete your thought naturally.`,`5. The navigation has ALREADY COMPLETED — you are now on the destination page. Do NOT call flowengage_navigate again.`,`6. Only acknowledge the page change if it adds meaningful context.`,`7. The user may speak at any time — stop immediately and listen.`,`8. Use the sections listed above to guide what you highlight next.`].join(`
458
+ `),i=e.interruption?.lastUserText;if(i){let t=[...e.history||[]].reverse().find(e=>e.sender===`user`);(!t||t.message!==i)&&(r+=(r?`
459
+ `:``)+`[User]: ${i}`)}let a=vD(e.interruption),o=(t||[]).map(e=>e.text).join(`, `),s=``,c=``;try{s=new URL(e.fromUrl||``).pathname}catch{s=e.fromUrl||``}try{c=new URL(n||window.location.href).pathname}catch{c=n||``}return[`VOICE SESSION AUTO-RESUMED AFTER PAGE NAVIGATION.`,`Navigation confidence: ${(e.navigationConfidence||`medium`).toUpperCase()}`,`Navigation: ${s} → ${c}`,``,`── Prior Conversation (${e.historyTotalTurns} turns) ──`,r||`(no prior turns)`,``,`── Your State at Interruption ──`,a,``,`── Current Page ──`,`URL: ${n||(typeof window<`u`?window.location.href:``)}`,`Sections: ${o||`none detected`}`,``,`── CRITICAL INSTRUCTIONS ──`,`1. DO NOT re-introduce yourself.`,`2. DO NOT ask the user what they need — you already know from the conversation above.`,`3. Continue the conversation naturally as if the navigation was seamless.`,`4. If you were mid-sentence, complete your thought naturally.`,`5. The navigation has ALREADY COMPLETED — you are now on the destination page. Do NOT call flowengage_navigate again.`,`6. Only acknowledge the page change if it adds meaningful context.`,`7. The user may speak at any time — stop immediately and listen.`,`8. Use the sections listed above to guide what you highlight next.`].join(`
459
460
  `)},_discard(e){typeof process<`u`&&process.env.NODE_ENV!==`production`&&console.log(`[VoiceSessionStore] discarded: ${e}`);try{sessionStorage.removeItem(oD)}catch{}return null}};function CD(){try{let e=JSON.parse(sessionStorage.getItem(oD)||`null`);return e?.trigger===`agent_navigate`&&Date.now()-(e.ts||0)<1e4}catch{return!1}}var wD={wordsSoFar:0,speechStartTime:0,isSpeaking:!1,items:[],timers:[],lastHighlightId:null,isVoiceMode:!1};function TD(){return wD.wordsSoFar}function ED(){wD.timers.forEach(clearTimeout),wD.wordsSoFar=0,wD.speechStartTime=0,wD.isSpeaking=!1,wD.items=[],wD.timers=[],wD.lastHighlightId=null}var DD=80;function OD(e){requestAnimationFrame(()=>{let t=e.getBoundingClientRect(),n=t.top+t.height/2,r=DD,i=r+(window.innerHeight-r)/2,a=window.pageYOffset+n-i;window.scrollTo({top:Math.max(0,a),behavior:`smooth`})})}function kD(e){if(!e||e.hasAttribute(`data-fe-highlighted`))return;AD(),e.classList?.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`),OD(e);let t=e.style.cssText;e.setAttribute(`data-fe-highlighted`,`true`),e.setAttribute(`data-fe-orig-style`,t),e.style.outline=`3px solid #2563eb`,e.style.outlineOffset=`8px`,e.style.background=`rgba(37, 99, 235, 0.08)`,e.style.borderRadius=`8px`,e.style.padding=`12px 16px`,e.style.transition=`all 0.4s ease`}function AD(){let e=document.querySelector(`[data-fe-highlighted]`);e&&(e.style.cssText=e.getAttribute(`data-fe-orig-style`)||``,e.removeAttribute(`data-fe-highlighted`),e.removeAttribute(`data-fe-orig-style`))}var Q=`fe-vv`;function jD(){if(typeof document>`u`||document.getElementById(`${Q}-styles`))return;let e=`
460
461
  /* ── Action toast ───────────────────────────────────────────────────────────── */
461
462
  #${Q}-toast {
@@ -603,8 +604,8 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
603
604
  <path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
604
605
  fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
605
606
  filter="url(#${Q}-csh)"/>
606
- </svg>`,KD=null,qD=!1;function JD(){return(!KD||!KD.isConnected)&&(KD=document.createElement(`div`),KD.id=`${Q}-cursor`,KD.innerHTML=GD,document.body.appendChild(KD),qD=!1),KD}async function YD(e){if(typeof document>`u`||!e)return;jD();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=JD();qD||=(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 $D(360)}function XD(e=!1){KD&&(e?(KD.classList.remove(`${Q}-cursor-visible`),qD=!1):(KD.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{qD=!1},250)))}async function ZD(e){KD&&(KD.classList.add(`${Q}-cursor-click`),await $D(280),KD.classList.remove(`${Q}-cursor-click`))}function QD(e){if(!e||typeof document>`u`)return;jD();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 $D(e){return new Promise(t=>setTimeout(t,e))}function $(...e){an()&&console.log(`[FlowEngage:voice-tools]`,...e)}function eO(e){return new Promise(t=>setTimeout(t,e))}var tO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function nO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(tO)}catch{return!1}}function rO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function iO(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(!nO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function aO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function oO(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 aO(r.join(` `))}if(e.labels&&e.labels.length)return aO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return aO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return aO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return aO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=aO(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 aO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return aO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?aO(o):null}function sO(){let e=[];return iO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(nO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=rO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function cO(){return sO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:oO(e),placeholder:e.placeholder||null}))}function lO(){let e=[];return iO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(nO(e)||e.disabled)return!1;try{let t=rO(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 uO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function dO(e){let t=uO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function fO(e,t){let n=dO(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,oO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>uO(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var pO=28;function mO(e,t){let n=null,r=0;for(let i of e){let e=fO(i,t);e>r&&(r=e,n=i)}return!n||r<pO?null:n}function hO(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,oO(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function gO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function _O(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function vO(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function yO(e){if(!vO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,oO(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function bO(e,t,n){let r=String(t??``),i=String(n??``),a=CO(e,r)||mO(e,r)||hO(e,r,i);if(!a)return[];let o=new Set([a]);if(gO(i)&&_O(r))for(let t of e)t!==a&&yO(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function xO(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 SO(e){if(!e||typeof e!=`string`)return null;let t=null;return iO(n=>{try{let r=n.getElementById(e);r&&!nO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function CO(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=SO(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=SO(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function wO(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function TO(e,t){let n=[];iO(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(nO(e)||e.disabled)return!1;try{let t=rO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:wO(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=xO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function EO(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 DO(e){let t=EO(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function OO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function kO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function AO(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 jO(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function MO(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function NO(){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 PO(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let r=EO(n),i=AO(r),a=r.section_text??r.sectionText??r.section;if($(`flowengage_navigate · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(i,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(i=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,i))}catch{}if(typeof window<`u`)try{let e=new URL(i,window.location.href),t=window.location;if(e.pathname===t.pathname&&e.search===t.search&&(e.hash===t.hash||!e.hash))return $(`flowengage_navigate · already on target page, skipping navigation`),`Already on that page. Continue the conversation naturally without calling flowengage_navigate again.`}catch{}if(!await Pn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${i}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{FD(`Navigating to ${i}...`,{spinner:!0}),BD();let t=typeof e.getSessionCaptureData==`function`?e.getSessionCaptureData():null,n=i;if(t){let{ok:e,sessionKey:r,compact:o}=SD.capture({siteId:t.siteId,chatId:t.chatId,agentId:t.agentId,trigger:`agent_navigate`,navigationConfidence:`high`,targetUrl:i,interruption:{state:`tool_calling`,toolName:`flowengage_navigate`,toolParams:{url:i,section_text:a||null},lastAgentText:t.lastAgentText,lastUserText:t.lastUserText,estimatedSpokenWords:t.estimatedSpokenWords,agentTextWordCount:t.agentTextWordCount,isMuted:t.isMuted||!1},history:t.history});e&&r?n=bD(i,r):o&&(n=bD(i,o)),$(`flowengage_navigate · session captured, resumeUrl:`,n)}return ED(),await eO(300),$(`flowengage_navigate → location.assign`,n),window.location.assign(n),`Navigating...`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),FD(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{VD(),ID(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=EO(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;NO();let i=An(n||null,r||null);return!i&&r&&(await new Promise(e=>setTimeout(e,500)),NO(),i=An(null,r)),i?(kD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}"`):($(`flowengage_highlight ✖ no element for:`,r||n),`Could not find "${r||n}" on the current page. Try a shorter phrase matching a visible heading.`)},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=EO(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=An(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
607
- `)}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`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=jO(EO(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → 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($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=EO(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → 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($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`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 $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=cO(),t=lO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),HD();let t=DO(e);if(!t.length&&r){let e=r(),n=OO(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=kO(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;FD(`Filling ${String(t)}...`,{spinner:!0});let a=sO(),o=bO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())UD(t),await YD(t),MO(t,r,{skipScroll:e>0}),WD(t),await eO(120);i=o,n.push(String(t));continue}let s=CO(a,String(t));s||=mO(a,String(t)),s||=hO(a,String(t),r),s&&(UD(s),await YD(s),MO(s,r),WD(s),await eO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),FD(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),FD(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{XD(),HD(),ID(700)}},flowengage_click_button:async e=>{let t=EO(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=TO(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{FD(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await YD(r),r.focus?.(),await ZD(r),QD(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),FD(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),FD(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{XD(),ID(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function FO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=an();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 IO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function LO(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 RO(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 zO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,f.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return n?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function BO({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function VO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\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))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function HO({orbColors:e,...t}){return(0,f.jsx)(aD,{colors:e,...t})}function UO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||IO.green,s=RO(o),c=a?72:94,l=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(Mp.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:a?void 0:`210px`},children:e.entryPrompt}),(0,f.jsxs)(Mp.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:o,color:s,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(Mp.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,f.jsx)(HO,{size:c,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(Mp.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,f.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function WO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o}){let s=n||IO.green,c=RO(s);return(0,f.jsxs)(Mp.div,{initial:{scale:50/350,borderRadius:`50%`},animate:{scale:1,borderRadius:`16px`},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(HO,{size:72,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${s}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function GO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s,pendingResume:c,chatId:l}){let[u,p]=(0,d.useState)(`idle`),[m,h]=(0,d.useState)(!1),[g,_]=(0,d.useState)(!1),v=(0,d.useRef)(null),y=(0,d.useRef)(``),b=(0,d.useRef)(async()=>{}),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(`idle`),te=(0,d.useRef)(!1),C=(0,d.useRef)(!1),ne=(0,d.useRef)(`minimized`),re=(0,d.useRef)(0),ie=(0,d.useRef)(null),ae=(0,d.useCallback)((e=`minimized`)=>{ne.current=e,C.current=!0,queueMicrotask(()=>{x.current||(x.current=!0,b.current?.())})},[o]),oe=(0,d.useCallback)(async e=>{C.current=!0;try{await v.current?.endSession?.()}catch{}if(v.current=null,p(`idle`),h(!1),x.current=!1,typeof s==`function`){let e=re.current;await s(e>0?o.current.slice(e):o.current)}e?.()},[o,s]);return b.current=()=>oe(ne.current===`chat`?t:n),(0,d.useEffect)(()=>{S.current=m},[m]),(0,d.useEffect)(()=>{ee.current=u},[u]),(0,d.useEffect)(()=>{let e=()=>!!v.current,t=()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``},n=e=>{let n=t(),a=n.split(/\s+/).filter(Boolean).length;return{siteId:i,chatId:l||null,agentId:r,trigger:e,navigationConfidence:e===`agent_navigate`?`high`:`medium`,interruption:{state:ee.current,lastAgentText:n,lastUserText:y.current,estimatedSpokenWords:TD(),agentTextWordCount:a,isMuted:S.current},history:o.current||[]}},a=()=>{e()&&(CD()||SD.capture(n(`user_link_click`)))},s=t=>{e()&&(t.persisted||CD()||SD.capture(n(`pagehide`)))};return window.addEventListener(`beforeunload`,a),window.addEventListener(`pagehide`,s),()=>{window.removeEventListener(`beforeunload`,a),window.removeEventListener(`pagehide`,s)}},[i,l,r,o]),(0,d.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){p(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;c?(o.current=Array.isArray(c.history)?[...c.history]:[],re.current=o.current.length,c.interruption?.lastUserText&&(y.current=c.interruption.lastUserText)):(o.current=[],re.current=0,y.current=``),x.current=!1,te.current=!1,C.current=!1,ne.current=`minimized`;let t=FO(PO({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>y.current,requestEndSession:()=>{ae()},getSessionCaptureData:()=>{let e=(()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``})();return{siteId:i,chatId:l||null,agentId:r,history:o.current||[],lastAgentText:e,agentTextWordCount:e.split(/\s+/).filter(Boolean).length,lastUserText:y.current,estimatedSpokenWords:TD(),isMuted:S.current}}})),s=typeof window<`u`?window.location.href:``,u,d=null;if(c&&!c.consumed){let e=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().slice(0,100),id:e.id||null})).filter(e=>e.text.length>0).slice(0,25):[];d=SD.buildResumePrompt(c,e,s);let t=e[0]?.text||``;u={agent:{firstMessage:t?`I'm now on the ${t} page. Let me walk you through it.`:`I've navigated to the new page. Let me continue our conversation.`}}}let f=await xE.startSession({agentId:r,...u?{overrides:u}:{},clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||p(t===`speaking`?`speaking`:`listening`)},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(!r)return;let i=o.current,a=i.length>0?i[i.length-1]:null;a&&a.sender===n&&a.message===r||(n===`user`&&(y.current=r),o.current=[...i,{sender:n,message:r,timestamp:new Date().toISOString()}],VO(n,r)&&ae(`minimized`))},onError:t=>{if(!e&&!C.current&&!te.current){te.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),p(`error`),ae(`minimized`)}},onDisconnect:()=>{if(!e&&!C.current&&!te.current){te.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:y.current||``,wasMuted:S.current});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),ae(`minimized`)}}});if(e){f.endSession().catch(()=>{});return}n=f,v.current=f,p(`listening`);try{if(d)f.sendContextualUpdate(d),SD.clear();else{let e=`[]`;try{e=await t.flowengage_list_forms()}catch{}let n=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, nav, footer, header`)).map(e=>({tag:e.tagName,text:e.textContent.trim(),id:e.id||null})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,25):[];f.sendContextualUpdate(`Page: ${s}. SiteId: ${i||`unknown`}. Sections on this page: ${JSON.stringify(n)}. IMPORTANT: Call flowengage_highlight with section_text from the list above as you explain each section. Forms: ${e}. Navigation: flowengage_navigate — use for cross-page navigation. End call: flowengage_end_session.`)}}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),p(`error`),ne.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,C.current=!0,(n||v.current)?.endSession?.().catch(()=>{})}},[r,i,a,ae]),(0,d.useEffect)(()=>{if(!g)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ie.current&&!ie.current.contains(t)&&_(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[g]),(0,f.jsxs)(`div`,{ref:ie,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:[(0,f.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),(0,f.jsx)(HO,{size:72,voiceState:u,isMuted:m,orbColors:e})]}),u===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:async()=>{if(v.current)try{m?(await v.current.setMicMuted?.(!1),h(!1)):(await v.current.setMicMuted?.(!0),h(!0))}catch{}},title:m?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:m?`#7f1d1d`:`#1f2937`,border:m?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:m?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:m?(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsx)(SE,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>_(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,f.jsx)(AE,{size:16,color:`currentColor`})})]}),g&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`chat`,oe(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(jE,{}),`Enter Chat Mode`]}),(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`minimized`,oe(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(ME,{}),`End Conversation`]}),(0,f.jsx)(`button`,{onClick:()=>_(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function KO({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(HO,{size:36,orbColors:e})})}var qO=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function JO({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:ee,selectedFile:te,onFileSelect:C,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,replyContext:le,setReplyContext:ue,webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:ye,isCallMuted:be,toggleCallMute:xe,endWebRTCCall:w,formatCallDuration:Se,callDurationSeconds:Ce,onCollapse:we,onStartVoice:Te,showPoweredBy:Ee}){let De=c.length>0,Oe=x||S||b,ke=!!(he||ve),[Ae,je]=(0,d.useState)(!1),Me=(0,d.useRef)(null);return(0,d.useEffect)(()=>{if(!Ae)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Me.current&&!Me.current.contains(t)&&je(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Ae]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:0,width:`calc(100% - 16px)`,height:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`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:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0},children:[(0,f.jsx)(`button`,{onClick:we,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(zO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(BO,{title:e.chatTitle})})}),(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Me,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>je(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Ae&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),we?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,f.jsx)(XE,{webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:ye,formatCallDuration:Se,callDurationSeconds:Ce,endWebRTCCall:w,isCallMuted:be,toggleCallMute:xe,isAIVoiceActive:!1,currentCallAgentName:m||g,isRateLimited:S,rateLimitMessage:ee}),(0,f.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:De?(0,f.jsx)(KE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ue,TypingDots:qO,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(KO,{orbColors:t})}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(HO,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:ae?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(qE,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:ke,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Oe,replyContext:le,clearReplyContext:()=>ue(null),onFileSelect:C,selectedFile:te,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),(0,f.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:Ee&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function YO(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:ee,language:te,historyRef:C,onMessageSync:ne,sendMessage:ae,uploadChatFile:se,openWidget:ce,captureVisitorEmail:le,setVoiceMode:ue,endConversation:de,acceptCall:fe,rejectCall:pe,endWebRTCCall:me,toggleCallMute:he,dismissCallError:ge,startTyping:_e,stopTyping:ve,updateTypingDraft:ye}=rn();(0,d.useEffect)(()=>{try{On()}catch{}},[]);let be=t?.widgetSettings||{},xe=n?.widgetSettings||{},w={...be.branding||{},...xe.branding||{}},Se={...be.theme||{},...xe.theme||{}},Ce={...be.features||{},...xe.features||{}},we=Ce.voice!==!1,Te=Array.isArray(Se.orbColors)&&Se.orbColors.length>0?Se.orbColors:null,Ee=Te?.[0]||Se.primaryColor||`#3B82F6`,De=Se.position||`bottom-right`,Oe=w.fallbackAgentName||`Agent`,ke=LO(Te??Se.chatBgColors),Ae=w.logo||w.logoUrl||null,je=te||`en`,Me=be.recommendations?.[je]||[],Ne=(xe.recommendations?.[je]??Me).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Pe=Array.isArray(w.quickChatOptions)&&w.quickChatOptions.length>0?w.quickChatOptions:Ne,Fe=w.hideWatermark===!0?!1:w.showPoweredBy!==!1,T=w.chatbotEnabled!==!1&&Se.chatbotEnabled!==!1,Ie=be.greetings?.[te]||xe.greetings?.[te]||w.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Le={entryPrompt:w.entryPrompt||`Do you want to explore in a new way?`,yesLabel:w.yesLabel||`Yes`,laterLabel:w.laterLabel||`Later`,connectionTitle:w.connectionTitle||`How would you like to connect?`,voiceLabel:w.voiceLabel||`Voice`,textLabel:w.textLabel||`Text`,chatTitle:w.headerName||`Chat with FlowEngage`,introGreeting:Ie,inputPlaceholder:w.inputPlaceholder||`Type your message`,analysingLabel:w.analysingLabel||`analysing...`},Re=xe.elevenLabsAgentId||t?.elevenLabsAgentId||null,ze=t?.siteId||n?.siteId||null,Be=t?.apiBaseUrl||``,E=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Ve=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,He=r.some(e=>e.sender===`user`),Ue=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),We=!l&&He&&Ue,Ge=!!(xe._dashboardLivePreview||be._dashboardLivePreview),[D,O]=(0,d.useState)(()=>Ge?`text_chat`:`entry_prompt`),[k,Ke]=(0,d.useState)(``),[qe,Je]=(0,d.useState)(null),[Ye,Xe]=(0,d.useState)(l||``),[Ze,Qe]=(0,d.useState)(``),[$e,et]=(0,d.useState)(0),[tt,nt]=(0,d.useState)(null),[rt,it]=(0,d.useState)(null),[at,ot]=(0,d.useState)(``),[st,ct]=(0,d.useState)(!1),lt=(0,d.useRef)(null),ut=(0,d.useRef)(!1),dt=(0,d.useRef)(null),ft=(0,d.useMemo)(()=>oe(ze),[ze]);(0,d.useLayoutEffect)(()=>{if(!(e!==`ready`||ut.current)){ut.current=!0;try{let e=SD.read(ze);if(e&&e._resumeMode===`auto`){dt.current=e,ce({notifyChatInitiated:!0}),ue?.(!0),O(`voice_mode`);return}}catch{}if(re(ze)||!we){O(`minimized_orb`);return}}},[e,r]);let[pt,mt]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>mt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{Xe(l||``),l&&Qe(``)},[l]);let ht=(0,d.useCallback)(()=>{it(null),ot(``)},[]),gt=(0,d.useCallback)(e=>{let t=VE(e);if(t){it(null),ot(t);return}it(e),ot(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){et(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||et(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]),(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){lt.current=null;return}(v?.callId||b===`connecting`||b===`connected`)&&(!(!i||D===`minimized_orb`||D===`voice_mode`)&&lt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:D,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),lt.current=e,D===`voice_mode`&&ue?.(!1),ce?.(),O(`text_chat`)))},[y,b,v?.callId,i,ce,ue,D]),(0,d.useEffect)(()=>{if(!o||_){ye?.(``),ve?.();return}if(!k.trim()||rt){ye?.(``),ve?.();return}_e?.();let e=window.setTimeout(()=>ye?.(k),120),t=window.setTimeout(()=>ve?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[k,rt,o,_,_e,ve,ye]);let _t=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,vt=async e=>{if(e.preventDefault(),_)return;if(We){let e=Ye.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Qe(`Please enter a valid email so we can continue helping you.`);return}await le(e),Qe(``);return}let t=_t(qe);if(!k.trim()&&!rt)return;if(rt){try{ct(!0),ot(``);let e=await se(rt),n=e?.data||e,r=k.trim()||`Shared file: ${UE(rt)}`;Ke(``),Je(null),ht(),await ae(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||rt.name,fileType:n?.fileType||rt.type,fileSize:n?.fileSize||rt.size}})}catch(e){ot(e?.message||`Failed to upload the selected file.`)}finally{ct(!1)}return}let n=k.trim();Ke(``),Je(null),await ae(n,``,t)},yt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},bt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await ae(t.trim(),``)},[_,m,ae]),xt=pt&&D===`entry_prompt`?{inset:0}:pt&&D===`text_chat`?{left:0,right:0,bottom:0}:pt&&D===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:De===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},St=()=>O(`minimized_orb`),Ct=()=>O(`connection_modal`),wt=()=>{ce({notifyChatInitiated:!0}),ue?.(!0),O(`voice_mode`)},Tt=()=>{ce({notifyChatInitiated:!0}),ue?.(!1),O(`text_chat`)},Et=()=>{ue?.(!1),St()};return e!==`ready`||!T||Ce.chat===!1?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...xt},children:[D===`entry_prompt`&&(0,f.jsx)(UO,{copy:Le,orbColors:Te,primaryColor:Ee,onYes:()=>{ie(ze),wt()},onLater:()=>{ie(ze),St()},isMobile:pt}),D===`minimized_orb`&&(0,f.jsx)(Mp.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,f.jsx)(HO,{size:50,orbColors:Te,onClick:we?Ct:Tt})}),D===`connection_modal`&&(0,f.jsx)(WO,{copy:Le,orbColors:Te,primaryColor:Ee,onVoice:wt,onText:Tt,onClose:St,isMobile:pt}),D===`voice_mode`&&(0,f.jsx)(GO,{orbColors:Te,onEnterChat:Tt,onEndChat:Et,agentId:Re,siteId:ze,apiBaseUrl:Be,historyRef:C,onMessageSync:ne,pendingResume:dt.current,chatId:ft},`voice`),D===`text_chat`&&(0,f.jsx)(JO,{copy:Le,orbColors:Te,primaryColor:Ee,chatBgGradient:ke,logo:Ae,quickChatOptions:Pe,onQuickChatSelect:bt,isMobile:pt,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:E,agentHeadshot:Ve,fallbackAgentName:Oe,input:k,setInput:Ke,onSubmit:vt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:rt,onFileSelect:gt,onRemoveSelectedFile:ht,attachmentError:at,isUploadingAttachment:st,requiresEmail:We,emailInput:Ye,setEmailInput:Xe,emailError:Ze,replyContext:qe,setReplyContext:Je,webRTCError:ee,micError:tt,setMicError:nt,dismissCallError:ge,incomingCall:v,rejectCall:pe,acceptCall:fe,activeCallId:y,callConnectionState:b,isCallMuted:S,toggleCallMute:he,endWebRTCCall:me,formatCallDuration:yt,callDurationSeconds:$e,onCollapse:St,onStartVoice:wt,onEndConversation:de,showPoweredBy:Fe}),(0,f.jsx)(`style`,{children:`
607
+ </svg>`,KD=null,qD=!1;function JD(){return(!KD||!KD.isConnected)&&(KD=document.createElement(`div`),KD.id=`${Q}-cursor`,KD.innerHTML=GD,document.body.appendChild(KD),qD=!1),KD}async function YD(e){if(typeof document>`u`||!e)return;jD();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=JD();qD||=(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 $D(360)}function XD(e=!1){KD&&(e?(KD.classList.remove(`${Q}-cursor-visible`),qD=!1):(KD.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{qD=!1},250)))}async function ZD(e){KD&&(KD.classList.add(`${Q}-cursor-click`),await $D(280),KD.classList.remove(`${Q}-cursor-click`))}function QD(e){if(!e||typeof document>`u`)return;jD();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 $D(e){return new Promise(t=>setTimeout(t,e))}function $(...e){an()&&console.log(`[FlowEngage:voice-tools]`,...e)}function eO(e){return new Promise(t=>setTimeout(t,e))}var tO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function nO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(tO)}catch{return!1}}function rO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function iO(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(!nO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function aO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function oO(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 aO(r.join(` `))}if(e.labels&&e.labels.length)return aO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return aO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return aO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return aO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=aO(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 aO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return aO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?aO(o):null}function sO(){let e=[];return iO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(nO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=rO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function cO(){return sO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:oO(e),placeholder:e.placeholder||null}))}function lO(){let e=[];return iO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(nO(e)||e.disabled)return!1;try{let t=rO(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 uO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function dO(e){let t=uO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function fO(e,t){let n=dO(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,oO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>uO(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var pO=28;function mO(e,t){let n=null,r=0;for(let i of e){let e=fO(i,t);e>r&&(r=e,n=i)}return!n||r<pO?null:n}function hO(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,oO(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function gO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function _O(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function vO(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function yO(e){if(!vO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,oO(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function bO(e,t,n){let r=String(t??``),i=String(n??``),a=CO(e,r)||mO(e,r)||hO(e,r,i);if(!a)return[];let o=new Set([a]);if(gO(i)&&_O(r))for(let t of e)t!==a&&yO(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function xO(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 SO(e){if(!e||typeof e!=`string`)return null;let t=null;return iO(n=>{try{let r=n.getElementById(e);r&&!nO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function CO(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=SO(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=SO(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function wO(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function TO(e,t){let n=[];iO(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(nO(e)||e.disabled)return!1;try{let t=rO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:wO(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=xO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function EO(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 DO(e){let t=EO(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function OO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function kO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function AO(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 jO(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function MO(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function NO(){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 PO(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{if($(`flowengage_navigate ▶ raw parameters:`,n),typeof e.getPostResumeNavLocked==`function`&&e.getPostResumeNavLocked())return $(`flowengage_navigate · blocked (post-resume lock active)`,n),`Navigation is not needed — you just arrived at this page via the user's navigation request. Stay here and continue the conversation naturally.`;let r=EO(n),i=AO(r),a=r.section_text??r.sectionText??r.section;if($(`flowengage_navigate · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(i,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(i=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,i))}catch{}if(typeof window<`u`)try{let e=new URL(i,window.location.href),t=window.location;if(e.pathname===t.pathname&&e.search===t.search&&(e.hash===t.hash||!e.hash))return $(`flowengage_navigate · already on target page, skipping navigation`),`Already on that page. Continue the conversation naturally without calling flowengage_navigate again.`}catch{}if(!await Pn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${i}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{FD(`Navigating to ${i}...`,{spinner:!0}),BD();let t=typeof e.getSessionCaptureData==`function`?e.getSessionCaptureData():null,n=i;if(t){let{ok:e,sessionKey:r,compact:o}=SD.capture({siteId:t.siteId,chatId:t.chatId,agentId:t.agentId,trigger:`agent_navigate`,navigationConfidence:`high`,targetUrl:i,interruption:{state:`tool_calling`,toolName:`flowengage_navigate`,toolParams:{url:i,section_text:a||null},lastAgentText:t.lastAgentText,lastUserText:t.lastUserText,estimatedSpokenWords:t.estimatedSpokenWords,agentTextWordCount:t.agentTextWordCount,isMuted:t.isMuted||!1},history:t.history});e&&r?n=bD(i,r):o&&(n=bD(i,o)),$(`flowengage_navigate · session captured, resumeUrl:`,n)}return ED(),await eO(300),$(`flowengage_navigate → location.assign`,n),window.location.assign(n),`Navigating...`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),FD(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{VD(),ID(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=EO(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;NO();let i=An(n||null,r||null);return!i&&r&&(await new Promise(e=>setTimeout(e,500)),NO(),i=An(null,r)),i?(kD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}"`):($(`flowengage_highlight ✖ no element for:`,r||n),`Could not find "${r||n}" on the current page. Try a shorter phrase matching a visible heading.`)},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=EO(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=An(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
608
+ `)}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`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=jO(EO(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → 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($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=EO(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → 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($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`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 $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=cO(),t=lO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),HD();let t=DO(e);if(!t.length&&r){let e=r(),n=OO(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=kO(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;FD(`Filling ${String(t)}...`,{spinner:!0});let a=sO(),o=bO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())UD(t),await YD(t),MO(t,r,{skipScroll:e>0}),WD(t),await eO(120);i=o,n.push(String(t));continue}let s=CO(a,String(t));s||=mO(a,String(t)),s||=hO(a,String(t),r),s&&(UD(s),await YD(s),MO(s,r),WD(s),await eO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),FD(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),FD(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{XD(),HD(),ID(700)}},flowengage_click_button:async e=>{let t=EO(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=TO(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{FD(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await YD(r),r.focus?.(),await ZD(r),QD(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),FD(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),FD(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{XD(),ID(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function FO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=an();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 IO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function LO(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 RO(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 zO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,f.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return n?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function BO({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function VO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\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))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function HO({orbColors:e,...t}){return(0,f.jsx)(aD,{colors:e,...t})}function UO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||IO.green,s=RO(o),c=a?72:94,l=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(Mp.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:a?void 0:`210px`},children:e.entryPrompt}),(0,f.jsxs)(Mp.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:o,color:s,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(Mp.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,f.jsx)(HO,{size:c,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(Mp.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,f.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function WO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o}){let s=n||IO.green,c=RO(s);return(0,f.jsxs)(Mp.div,{initial:{scale:50/350,borderRadius:`50%`},animate:{scale:1,borderRadius:`16px`},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(HO,{size:72,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${s}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function GO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s,pendingResume:c,chatId:l}){let[u,p]=(0,d.useState)(`idle`),[m,h]=(0,d.useState)(!1),[g,_]=(0,d.useState)(!1),v=(0,d.useRef)(null),y=(0,d.useRef)(``),b=(0,d.useRef)(async()=>{}),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(`idle`),te=(0,d.useRef)(!1),C=(0,d.useRef)(!1),ne=(0,d.useRef)(`minimized`),re=(0,d.useRef)(0),ie=(0,d.useRef)(!1),ae=(0,d.useRef)(null),oe=(0,d.useCallback)((e=`minimized`)=>{ne.current=e,C.current=!0,queueMicrotask(()=>{x.current||(x.current=!0,b.current?.())})},[o]),se=(0,d.useCallback)(async e=>{C.current=!0;try{await v.current?.endSession?.()}catch{}if(v.current=null,p(`idle`),h(!1),x.current=!1,typeof s==`function`){let e=re.current;await s(e>0?o.current.slice(e):o.current)}e?.()},[o,s]);return b.current=()=>se(ne.current===`chat`?t:n),(0,d.useEffect)(()=>{S.current=m},[m]),(0,d.useEffect)(()=>{ee.current=u},[u]),(0,d.useEffect)(()=>{let e=()=>!!v.current,t=()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``},n=e=>{let n=t(),a=n.split(/\s+/).filter(Boolean).length;return{siteId:i,chatId:l||null,agentId:r,trigger:e,navigationConfidence:e===`agent_navigate`?`high`:`medium`,interruption:{state:ee.current,lastAgentText:n,lastUserText:y.current,estimatedSpokenWords:TD(),agentTextWordCount:a,isMuted:S.current},history:o.current||[]}},a=()=>{e()&&(CD()||SD.capture(n(`user_link_click`)))},s=t=>{e()&&(t.persisted||CD()||SD.capture(n(`pagehide`)))};return window.addEventListener(`beforeunload`,a),window.addEventListener(`pagehide`,s),()=>{window.removeEventListener(`beforeunload`,a),window.removeEventListener(`pagehide`,s)}},[i,l,r,o]),(0,d.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){p(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;c?(o.current=Array.isArray(c.history)?[...c.history]:[],re.current=o.current.length,c.interruption?.lastUserText&&(y.current=c.interruption.lastUserText),ie.current=!0,setTimeout(()=>{ie.current=!1},5e3)):(o.current=[],re.current=0,y.current=``,ie.current=!1),x.current=!1,te.current=!1,C.current=!1,ne.current=`minimized`;let t=FO(PO({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>y.current,getPostResumeNavLocked:()=>ie.current,requestEndSession:()=>{oe()},getSessionCaptureData:()=>{let e=(()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``})();return{siteId:i,chatId:l||null,agentId:r,history:o.current||[],lastAgentText:e,agentTextWordCount:e.split(/\s+/).filter(Boolean).length,lastUserText:y.current,estimatedSpokenWords:TD(),isMuted:S.current}}})),s=typeof window<`u`?window.location.href:``,u,d=null;if(c&&!c.consumed){let e=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().slice(0,100),id:e.id||null})).filter(e=>e.text.length>0).slice(0,25):[];d=SD.buildResumePrompt(c,e,s);let t=e[0]?.text||``;u={agent:{firstMessage:t?`I've arrived on the ${t} page. What would you like to know?`:`I've arrived on the new page. What would you like to know?`}}}let f=await xE.startSession({agentId:r,...u?{overrides:u}:{},clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||p(t===`speaking`?`speaking`:`listening`)},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(!r)return;let i=o.current,a=i.length>0?i[i.length-1]:null;a&&a.sender===n&&a.message===r||(n===`user`&&(y.current=r),o.current=[...i,{sender:n,message:r,timestamp:new Date().toISOString()}],VO(n,r)&&oe(`minimized`))},onError:t=>{if(!e&&!C.current&&!te.current){te.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),p(`error`),oe(`minimized`)}},onDisconnect:()=>{if(!e&&!C.current&&!te.current){te.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:y.current||``,wasMuted:S.current});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),oe(`minimized`)}}});if(e){f.endSession().catch(()=>{});return}n=f,v.current=f,p(`listening`);try{if(d)f.sendContextualUpdate(d),SD.clear();else{let e=`[]`;try{e=await t.flowengage_list_forms()}catch{}let n=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, nav, footer, header`)).map(e=>({tag:e.tagName,text:e.textContent.trim(),id:e.id||null})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,25):[];f.sendContextualUpdate(`Page: ${s}. SiteId: ${i||`unknown`}. Sections on this page: ${JSON.stringify(n)}. IMPORTANT: Call flowengage_highlight with section_text from the list above as you explain each section. Forms: ${e}. Navigation: flowengage_navigate — use for cross-page navigation. End call: flowengage_end_session.`)}}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),p(`error`),ne.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,C.current=!0,(n||v.current)?.endSession?.().catch(()=>{})}},[r,i,a,oe]),(0,d.useEffect)(()=>{if(!g)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ae.current&&!ae.current.contains(t)&&_(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[g]),(0,f.jsxs)(`div`,{ref:ae,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:[(0,f.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),(0,f.jsx)(HO,{size:72,voiceState:u,isMuted:m,orbColors:e})]}),u===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:async()=>{if(v.current)try{m?(await v.current.setMicMuted?.(!1),h(!1)):(await v.current.setMicMuted?.(!0),h(!0))}catch{}},title:m?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:m?`#7f1d1d`:`#1f2937`,border:m?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:m?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:m?(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsx)(SE,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>_(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,f.jsx)(AE,{size:16,color:`currentColor`})})]}),g&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`chat`,se(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(jE,{}),`Enter Chat Mode`]}),(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`minimized`,se(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(ME,{}),`End Conversation`]}),(0,f.jsx)(`button`,{onClick:()=>_(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function KO({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(HO,{size:36,orbColors:e})})}var qO=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function JO({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:ee,selectedFile:te,onFileSelect:C,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,replyContext:le,setReplyContext:ue,webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:ye,isCallMuted:be,toggleCallMute:xe,endWebRTCCall:w,formatCallDuration:Se,callDurationSeconds:Ce,onCollapse:we,onStartVoice:Te,showPoweredBy:Ee}){let De=c.length>0,Oe=x||S||b,ke=!!(he||ve),[Ae,je]=(0,d.useState)(!1),Me=(0,d.useRef)(null);return(0,d.useEffect)(()=>{if(!Ae)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Me.current&&!Me.current.contains(t)&&je(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Ae]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:0,width:`calc(100% - 16px)`,height:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`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:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0},children:[(0,f.jsx)(`button`,{onClick:we,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(zO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(BO,{title:e.chatTitle})})}),(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Me,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>je(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Ae&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),we?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,f.jsx)(XE,{webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:ye,formatCallDuration:Se,callDurationSeconds:Ce,endWebRTCCall:w,isCallMuted:be,toggleCallMute:xe,isAIVoiceActive:!1,currentCallAgentName:m||g,isRateLimited:S,rateLimitMessage:ee}),(0,f.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:De?(0,f.jsx)(KE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ue,TypingDots:qO,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(KO,{orbColors:t})}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(HO,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:ae?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(qE,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:ke,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Oe,replyContext:le,clearReplyContext:()=>ue(null),onFileSelect:C,selectedFile:te,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),(0,f.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:Ee&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function YO(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:ee,language:te,historyRef:C,onMessageSync:ne,sendMessage:ae,uploadChatFile:se,openWidget:ce,captureVisitorEmail:le,setVoiceMode:ue,endConversation:de,acceptCall:fe,rejectCall:pe,endWebRTCCall:me,toggleCallMute:he,dismissCallError:ge,startTyping:_e,stopTyping:ve,updateTypingDraft:ye}=rn();(0,d.useEffect)(()=>{try{On()}catch{}},[]);let be=t?.widgetSettings||{},xe=n?.widgetSettings||{},w={...be.branding||{},...xe.branding||{}},Se={...be.theme||{},...xe.theme||{}},Ce={...be.features||{},...xe.features||{}},we=Ce.voice!==!1,Te=Array.isArray(Se.orbColors)&&Se.orbColors.length>0?Se.orbColors:null,Ee=Te?.[0]||Se.primaryColor||`#3B82F6`,De=Se.position||`bottom-right`,Oe=w.fallbackAgentName||`Agent`,ke=LO(Te??Se.chatBgColors),Ae=w.logo||w.logoUrl||null,je=te||`en`,Me=be.recommendations?.[je]||[],Ne=(xe.recommendations?.[je]??Me).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Pe=Array.isArray(w.quickChatOptions)&&w.quickChatOptions.length>0?w.quickChatOptions:Ne,Fe=w.hideWatermark===!0?!1:w.showPoweredBy!==!1,T=w.chatbotEnabled!==!1&&Se.chatbotEnabled!==!1,Ie=be.greetings?.[te]||xe.greetings?.[te]||w.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Le={entryPrompt:w.entryPrompt||`Do you want to explore in a new way?`,yesLabel:w.yesLabel||`Yes`,laterLabel:w.laterLabel||`Later`,connectionTitle:w.connectionTitle||`How would you like to connect?`,voiceLabel:w.voiceLabel||`Voice`,textLabel:w.textLabel||`Text`,chatTitle:w.headerName||`Chat with FlowEngage`,introGreeting:Ie,inputPlaceholder:w.inputPlaceholder||`Type your message`,analysingLabel:w.analysingLabel||`analysing...`},Re=xe.elevenLabsAgentId||t?.elevenLabsAgentId||null,ze=t?.siteId||n?.siteId||null,Be=t?.apiBaseUrl||``,E=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Ve=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,He=r.some(e=>e.sender===`user`),Ue=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),We=!l&&He&&Ue,Ge=!!(xe._dashboardLivePreview||be._dashboardLivePreview),[D,O]=(0,d.useState)(()=>Ge?`text_chat`:`entry_prompt`),[k,Ke]=(0,d.useState)(``),[qe,Je]=(0,d.useState)(null),[Ye,Xe]=(0,d.useState)(l||``),[Ze,Qe]=(0,d.useState)(``),[$e,et]=(0,d.useState)(0),[tt,nt]=(0,d.useState)(null),[rt,it]=(0,d.useState)(null),[at,ot]=(0,d.useState)(``),[st,ct]=(0,d.useState)(!1),lt=(0,d.useRef)(null),ut=(0,d.useRef)(!1),dt=(0,d.useRef)(null),ft=(0,d.useMemo)(()=>oe(ze),[ze]);(0,d.useLayoutEffect)(()=>{if(!(e!==`ready`||ut.current)){ut.current=!0;try{let e=SD.read(ze);if(e&&e._resumeMode===`auto`){dt.current=e,ce({notifyChatInitiated:!0}),ue?.(!0),O(`voice_mode`);return}}catch{}if(re(ze)||!we){O(`minimized_orb`);return}}},[e,r]);let[pt,mt]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>mt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{Xe(l||``),l&&Qe(``)},[l]);let ht=(0,d.useCallback)(()=>{it(null),ot(``)},[]),gt=(0,d.useCallback)(e=>{let t=VE(e);if(t){it(null),ot(t);return}it(e),ot(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){et(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||et(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]),(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){lt.current=null;return}(v?.callId||b===`connecting`||b===`connected`)&&(!(!i||D===`minimized_orb`||D===`voice_mode`)&&lt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:D,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),lt.current=e,D===`voice_mode`&&ue?.(!1),ce?.(),O(`text_chat`)))},[y,b,v?.callId,i,ce,ue,D]),(0,d.useEffect)(()=>{if(!o||_){ye?.(``),ve?.();return}if(!k.trim()||rt){ye?.(``),ve?.();return}_e?.();let e=window.setTimeout(()=>ye?.(k),120),t=window.setTimeout(()=>ve?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[k,rt,o,_,_e,ve,ye]);let _t=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,vt=async e=>{if(e.preventDefault(),_)return;if(We){let e=Ye.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Qe(`Please enter a valid email so we can continue helping you.`);return}await le(e),Qe(``);return}let t=_t(qe);if(!k.trim()&&!rt)return;if(rt){try{ct(!0),ot(``);let e=await se(rt),n=e?.data||e,r=k.trim()||`Shared file: ${UE(rt)}`;Ke(``),Je(null),ht(),await ae(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||rt.name,fileType:n?.fileType||rt.type,fileSize:n?.fileSize||rt.size}})}catch(e){ot(e?.message||`Failed to upload the selected file.`)}finally{ct(!1)}return}let n=k.trim();Ke(``),Je(null),await ae(n,``,t)},yt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},bt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await ae(t.trim(),``)},[_,m,ae]),xt=pt&&D===`entry_prompt`?{inset:0}:pt&&D===`text_chat`?{left:0,right:0,bottom:0}:pt&&D===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:De===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},St=()=>O(`minimized_orb`),Ct=()=>O(`connection_modal`),wt=()=>{ce({notifyChatInitiated:!0}),ue?.(!0),O(`voice_mode`)},Tt=()=>{ce({notifyChatInitiated:!0}),ue?.(!1),O(`text_chat`)},Et=()=>{ue?.(!1),St()};return e!==`ready`||!T||Ce.chat===!1?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...xt},children:[D===`entry_prompt`&&(0,f.jsx)(UO,{copy:Le,orbColors:Te,primaryColor:Ee,onYes:()=>{ie(ze),wt()},onLater:()=>{ie(ze),St()},isMobile:pt}),D===`minimized_orb`&&(0,f.jsx)(Mp.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,f.jsx)(HO,{size:50,orbColors:Te,onClick:we?Ct:Tt})}),D===`connection_modal`&&(0,f.jsx)(WO,{copy:Le,orbColors:Te,primaryColor:Ee,onVoice:wt,onText:Tt,onClose:St,isMobile:pt}),D===`voice_mode`&&(0,f.jsx)(GO,{orbColors:Te,onEnterChat:Tt,onEndChat:Et,agentId:Re,siteId:ze,apiBaseUrl:Be,historyRef:C,onMessageSync:ne,pendingResume:dt.current,chatId:ft},`voice`),D===`text_chat`&&(0,f.jsx)(JO,{copy:Le,orbColors:Te,primaryColor:Ee,chatBgGradient:ke,logo:Ae,quickChatOptions:Pe,onQuickChatSelect:bt,isMobile:pt,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:E,agentHeadshot:Ve,fallbackAgentName:Oe,input:k,setInput:Ke,onSubmit:vt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:rt,onFileSelect:gt,onRemoveSelectedFile:ht,attachmentError:at,isUploadingAttachment:st,requiresEmail:We,emailInput:Ye,setEmailInput:Xe,emailError:Ze,replyContext:qe,setReplyContext:Je,webRTCError:ee,micError:tt,setMicError:nt,dismissCallError:ge,incomingCall:v,rejectCall:pe,acceptCall:fe,activeCallId:y,callConnectionState:b,isCallMuted:S,toggleCallMute:he,endWebRTCCall:me,formatCallDuration:yt,callDurationSeconds:$e,onCollapse:St,onStartVoice:wt,onEndConversation:de,showPoweredBy:Fe}),(0,f.jsx)(`style`,{children:`
608
609
  /* Force any SVG (or img) inside LogoSlot to fill the container height
609
610
  regardless of whether the component forwards its style prop. */
610
611
  .fe-logo-slot svg,
@@ -27722,7 +27722,7 @@ function AD() {
27722
27722
  function jD(e) {
27723
27723
  if (!e) return "Unknown state.";
27724
27724
  let { state: t, lastAgentText: n, lastUserText: r, toolName: i, toolParams: a, estimatedSpokenWords: o, agentTextWordCount: s, unspokenSuffix: c } = e, l = [];
27725
- return t === "speaking" ? (l.push("You were SPEAKING."), n && (l.push(`You had spoken approximately ${o ?? "?"} of ${s ?? "?"} words.`), l.push(`Your response text: "${n}"`), c && l.push(`Estimated unspoken remainder: "${c}"`))) : t === "listening" ? (l.push("You were LISTENING for the user's response."), r && l.push(`Last user message: "${r}"`)) : t === "tool_calling" ? i === "flowengage_navigate" ? (l.push("Navigation ALREADY COMPLETED — you successfully navigated to this page."), l.push("DO NOT call flowengage_navigate again. You are already on the destination."), n && l.push(`Before navigating you said: "${n}"`)) : (l.push(`You were executing tool: ${i || "unknown"}`), a && l.push(`Tool parameters: ${JSON.stringify(a)}`), n && l.push(`Your last spoken text before the tool call: "${n}"`)) : l.push(`Session state at capture: ${t || "idle"}`), l.join("\n");
27725
+ return t === "speaking" ? (l.push("You were SPEAKING."), n && (l.push(`You had spoken approximately ${o ?? "?"} of ${s ?? "?"} words.`), l.push(`Your response text: "${n}"`), c && l.push(`Estimated unspoken remainder: "${c}"`))) : t === "listening" ? (l.push("You were LISTENING for the user's response."), r && l.push(`Last user message: "${r}"`)) : t === "tool_calling" ? i === "flowengage_navigate" ? (l.push("Navigation ALREADY COMPLETED — you successfully navigated to this page."), l.push("DO NOT call flowengage_navigate again. You are already on the destination."), r && l.push(`The user's last request was: "${r}"`), n && l.push(`Before navigating you said: "${n}"`)) : (l.push(`You were executing tool: ${i || "unknown"}`), a && l.push(`Tool parameters: ${JSON.stringify(a)}`), n && l.push(`Your last spoken text before the tool call: "${n}"`)) : l.push(`Session state at capture: ${t || "idle"}`), l.join("\n");
27726
27726
  }
27727
27727
  function MD(e, t) {
27728
27728
  try {
@@ -27870,31 +27870,36 @@ var FD = {
27870
27870
  } catch {}
27871
27871
  },
27872
27872
  buildResumePrompt(e, t, n) {
27873
- let r = (e.history || []).map((e) => `[${e.sender === "user" ? "User" : "Agent"}]: ${e.message}`).join("\n"), i = jD(e.interruption), a = (t || []).map((e) => e.text).join(", "), o = "", s = "";
27873
+ let r = (e.history || []).map((e) => `[${e.sender === "user" ? "User" : "Agent"}]: ${e.message}`).join("\n"), i = e.interruption?.lastUserText;
27874
+ if (i) {
27875
+ let t = [...e.history || []].reverse().find((e) => e.sender === "user");
27876
+ (!t || t.message !== i) && (r += (r ? "\n" : "") + `[User]: ${i}`);
27877
+ }
27878
+ let a = jD(e.interruption), o = (t || []).map((e) => e.text).join(", "), s = "", c = "";
27874
27879
  try {
27875
- o = new URL(e.fromUrl || "").pathname;
27880
+ s = new URL(e.fromUrl || "").pathname;
27876
27881
  } catch {
27877
- o = e.fromUrl || "";
27882
+ s = e.fromUrl || "";
27878
27883
  }
27879
27884
  try {
27880
- s = new URL(n || window.location.href).pathname;
27885
+ c = new URL(n || window.location.href).pathname;
27881
27886
  } catch {
27882
- s = n || "";
27887
+ c = n || "";
27883
27888
  }
27884
27889
  return [
27885
27890
  "VOICE SESSION AUTO-RESUMED AFTER PAGE NAVIGATION.",
27886
27891
  `Navigation confidence: ${(e.navigationConfidence || "medium").toUpperCase()}`,
27887
- `Navigation: ${o} → ${s}`,
27892
+ `Navigation: ${s} → ${c}`,
27888
27893
  "",
27889
27894
  `── Prior Conversation (${e.historyTotalTurns} turns) ──`,
27890
27895
  r || "(no prior turns)",
27891
27896
  "",
27892
27897
  "── Your State at Interruption ──",
27893
- i,
27898
+ a,
27894
27899
  "",
27895
27900
  "── Current Page ──",
27896
27901
  `URL: ${n || (typeof window < "u" ? window.location.href : "")}`,
27897
- `Sections: ${a || "none detected"}`,
27902
+ `Sections: ${o || "none detected"}`,
27898
27903
  "",
27899
27904
  "── CRITICAL INSTRUCTIONS ──",
27900
27905
  "1. DO NOT re-introduce yourself.",
@@ -28752,7 +28757,7 @@ function KO() {
28752
28757
  function qO(e) {
28753
28758
  let t = e.siteId || null, n = (e.apiBaseUrl || "").replace(/\/$/, ""), r = typeof e.getLastUserVoiceText == "function" ? e.getLastUserVoiceText : null, i = [], a = {
28754
28759
  flowengage_navigate: async (n) => {
28755
- $("flowengage_navigate ▶ raw parameters:", n);
28760
+ if ($("flowengage_navigate ▶ raw parameters:", n), typeof e.getPostResumeNavLocked == "function" && e.getPostResumeNavLocked()) return $("flowengage_navigate · blocked (post-resume lock active)", n), "Navigation is not needed — you just arrived at this page via the user's navigation request. Stay here and continue the conversation naturally.";
28756
28761
  let r = zO(n), i = UO(r), a = r.section_text ?? r.sectionText ?? r.section;
28757
28762
  if ($("flowengage_navigate · coerced:", {
28758
28763
  url: i,
@@ -29389,11 +29394,11 @@ function rk({ copy: e, orbColors: t, primaryColor: n, onVoice: r, onText: i, onC
29389
29394
  });
29390
29395
  }
29391
29396
  function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i, apiBaseUrl: a, historyRef: s, onMessageSync: l, pendingResume: u, chatId: d }) {
29392
- let [f, h] = m("idle"), [v, y] = m(!1), [b, x] = m(!1), S = p(null), C = p(""), ee = p(async () => {}), w = p(!1), te = p(!1), ne = p("idle"), re = p(!1), ie = p(!1), T = p("minimized"), ae = p(0), oe = p(null), se = o((e = "minimized") => {
29397
+ let [f, h] = m("idle"), [v, y] = m(!1), [b, x] = m(!1), S = p(null), C = p(""), ee = p(async () => {}), w = p(!1), te = p(!1), ne = p("idle"), re = p(!1), ie = p(!1), T = p("minimized"), ae = p(0), oe = p(!1), se = p(null), ce = o((e = "minimized") => {
29393
29398
  T.current = e, ie.current = !0, queueMicrotask(() => {
29394
29399
  w.current || (w.current = !0, ee.current?.());
29395
29400
  });
29396
- }, [s]), ce = o(async (e) => {
29401
+ }, [s]), le = o(async (e) => {
29397
29402
  ie.current = !0;
29398
29403
  try {
29399
29404
  await S.current?.endSession?.();
@@ -29404,7 +29409,7 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
29404
29409
  }
29405
29410
  e?.();
29406
29411
  }, [s, l]);
29407
- return ee.current = () => ce(T.current === "chat" ? t : n), c(() => {
29412
+ return ee.current = () => le(T.current === "chat" ? t : n), c(() => {
29408
29413
  te.current = v;
29409
29414
  }, [v]), c(() => {
29410
29415
  ne.current = f;
@@ -29453,13 +29458,16 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
29453
29458
  }
29454
29459
  try {
29455
29460
  if ((await navigator.mediaDevices.getUserMedia({ audio: !0 })).getTracks().forEach((e) => e.stop()), e) return;
29456
- u ? (s.current = Array.isArray(u.history) ? [...u.history] : [], ae.current = s.current.length, u.interruption?.lastUserText && (C.current = u.interruption.lastUserText)) : (s.current = [], ae.current = 0, C.current = ""), w.current = !1, re.current = !1, ie.current = !1, T.current = "minimized";
29461
+ u ? (s.current = Array.isArray(u.history) ? [...u.history] : [], ae.current = s.current.length, u.interruption?.lastUserText && (C.current = u.interruption.lastUserText), oe.current = !0, setTimeout(() => {
29462
+ oe.current = !1;
29463
+ }, 5e3)) : (s.current = [], ae.current = 0, C.current = "", oe.current = !1), w.current = !1, re.current = !1, ie.current = !1, T.current = "minimized";
29457
29464
  let t = JO(qO({
29458
29465
  siteId: i || null,
29459
29466
  apiBaseUrl: a || null,
29460
29467
  getLastUserVoiceText: () => C.current,
29468
+ getPostResumeNavLocked: () => oe.current,
29461
29469
  requestEndSession: () => {
29462
- se();
29470
+ ce();
29463
29471
  },
29464
29472
  getSessionCaptureData: () => {
29465
29473
  let e = (() => {
@@ -29488,7 +29496,7 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
29488
29496
  })).filter((e) => e.text.length > 0).slice(0, 25) : [];
29489
29497
  l = FD.buildResumePrompt(u, e, o);
29490
29498
  let t = e[0]?.text || "";
29491
- c = { agent: { firstMessage: t ? `I'm now on the ${t} page. Let me walk you through it.` : "I've navigated to the new page. Let me continue our conversation." } };
29499
+ c = { agent: { firstMessage: t ? `I've arrived on the ${t} page. What would you like to know?` : "I've arrived on the new page. What would you like to know?" } };
29492
29500
  }
29493
29501
  let f = await PE.startSession({
29494
29502
  agentId: r,
@@ -29507,7 +29515,7 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
29507
29515
  sender: n,
29508
29516
  message: r,
29509
29517
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
29510
- }], ek(n, r) && se("minimized"));
29518
+ }], ek(n, r) && ce("minimized"));
29511
29519
  },
29512
29520
  onError: (t) => {
29513
29521
  if (!e && !ie.current && !re.current) {
@@ -29519,7 +29527,7 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
29519
29527
  try {
29520
29528
  S.current?.setMicMuted?.(!0);
29521
29529
  } catch {}
29522
- y(!0), h("error"), se("minimized");
29530
+ y(!0), h("error"), ce("minimized");
29523
29531
  }
29524
29532
  },
29525
29533
  onDisconnect: () => {
@@ -29532,7 +29540,7 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
29532
29540
  try {
29533
29541
  S.current?.setMicMuted?.(!0);
29534
29542
  } catch {}
29535
- y(!0), se("minimized");
29543
+ y(!0), ce("minimized");
29536
29544
  }
29537
29545
  }
29538
29546
  });
@@ -29568,16 +29576,16 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
29568
29576
  r,
29569
29577
  i,
29570
29578
  a,
29571
- se
29579
+ ce
29572
29580
  ]), c(() => {
29573
29581
  if (!b) return;
29574
29582
  let e = (e) => {
29575
29583
  let t = e.composedPath?.()?.[0] || e.target;
29576
- oe.current && !oe.current.contains(t) && x(!1);
29584
+ se.current && !se.current.contains(t) && x(!1);
29577
29585
  };
29578
29586
  return document.addEventListener("mousedown", e), () => document.removeEventListener("mousedown", e);
29579
29587
  }, [b]), /* @__PURE__ */ _("div", {
29580
- ref: oe,
29588
+ ref: se,
29581
29589
  style: {
29582
29590
  position: "relative",
29583
29591
  display: "flex",
@@ -29725,7 +29733,7 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
29725
29733
  children: [
29726
29734
  /* @__PURE__ */ _("button", {
29727
29735
  onClick: () => {
29728
- x(!1), T.current = "chat", ce(t);
29736
+ x(!1), T.current = "chat", le(t);
29729
29737
  },
29730
29738
  style: {
29731
29739
  display: "flex",
@@ -29754,7 +29762,7 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
29754
29762
  }),
29755
29763
  /* @__PURE__ */ _("button", {
29756
29764
  onClick: () => {
29757
- x(!1), T.current = "minimized", ce(n);
29765
+ x(!1), T.current = "minimized", le(n);
29758
29766
  },
29759
29767
  style: {
29760
29768
  display: "flex",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowengage/react-chatbot",
3
- "version": "1.8.13",
3
+ "version": "1.8.15",
4
4
  "description": "Embeddable AI chat widget for React — powered by FlowEngage. Drop it in with a single siteId.",
5
5
  "keywords": [
6
6
  "chatbot",