@flowengage/react-chatbot 1.8.12 → 1.8.13

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,9 @@ 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`?(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.`),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. Only acknowledge the page change if it adds meaningful context.`,`6. The user may speak at any time — stop immediately and listen.`,`7. Use the sections listed above to guide what you highlight next.`].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(`
467
467
  `)},_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
468
  /* ── Action toast ───────────────────────────────────────────────────────────── */
469
469
  #${Q}-toast {
@@ -611,8 +611,8 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
611
611
  <path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
612
612
  fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
613
613
  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(!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)(null),ne=(0,b.useCallback)((e=`minimized`)=>{te.current=e,C.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),re=(0,b.useCallback)(async e=>{C.current=!0;try{await g.current?.endSession?.()}catch{}g.current=null,d(`idle`),p(!1),y.current=!1,typeof s==`function`&&await s(o.current),e?.()},[o,s]);return v.current=()=>re(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?c.interruption?.lastUserText&&(_.current=c.interruption.lastUserText):(o.current=[],_.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:()=>{ne()},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)&&ne(`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`),ne(`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),ne(`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,ne]),(0,b.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;w.current&&!w.current.contains(t)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,M.jsxs)(`div`,{ref:w,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`,re(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`,re(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,Array.isArray(e.history)&&e.history.length>0&&(C.current=e.history),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:`
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:`
616
616
  /* Force any SVG (or img) inside LogoSlot to fill the container height
617
617
  regardless of whether the component forwards its style prop. */
618
618
  .fe-logo-slot svg,