@flowengage/react-chatbot 8.0.82 → 8.0.83
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.
package/dist/flowengage-embed.js
CHANGED
|
@@ -342,7 +342,7 @@ Error generating stack: `+e.message+`
|
|
|
342
342
|
`).trim()}function pg(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={"fwh-navigate-mvp":async n=>{if($(`fwh-navigate-mvp ▶ raw parameters:`,n),e?.isWalkthroughActive?.())return $(`fwh-navigate-mvp ✖ blocked — walkthrough in progress`),`NAVIGATION_BLOCKED_DURING_WALKTHROUGH. A walkthrough of the current page is in progress, so navigation is not allowed. Do NOT tell the visitor you navigated or offer to. Describe the requested section using the CURRENT page's own content (fwh-read-content-mvp), then stop.`;let i=cg(n),a=lg(i),o=i.section_text??i.sectionText??i.section,s=Array.isArray(i.expected_landmarks)?i.expected_landmarks:Array.isArray(i.expectedLandmarks)?i.expectedLandmarks:[];if($(`fwh-navigate-mvp · coerced:`,{url:a,sectionText:o,expectedLandmarks:s}),!a){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`fwh-navigate-mvp ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);if(e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)){let t=e.hostname;return $(`fwh-navigate-mvp ✖ external URL blocked:`,e.href),`EXTERNAL_LINK_BLOCKED: The URL "${a}" points to an external site (${t}) that opens in a new tab. I cannot open new tabs or navigate to external sites. Tell the visitor exactly this: "That link opens an external app — I'm not able to open it for you, but you can click the link directly in the navigation header."`}}catch{}if(typeof window<`u`){try{let e=new URL(a,window.location.href);if(e.pathname===window.location.pathname&&e.search===window.location.search)return $(`fwh-navigate-mvp ✖ already on page, skipping`),`OK_ALREADY_ON_PAGE. The visitor is already on this page. Do not navigate. Proceed directly with highlights, answering the question, or reading page content.`}catch{}let e=window.__fe_user_nav_during_speech;if(e&&Date.now()-e.ts<3e4)try{if(new URL(a,window.location.href).pathname===e.fromPath)return $(`flowengage_navigate ✖ blocked — would navigate back to page visitor just left`,e),`NAV_BLOCKED: The visitor just left "${e.fromPageName}" and is now on "${e.toPageName}". Do NOT navigate them back. If they said "continue", resume verbally from where you left off — no navigation needed. If they want to return, they will navigate themselves.`}catch{}}let{allowed:c,correctedUrl:l}=await hr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl});if(!c){let e=`PAGE_NOT_IN_SITE: "${a}" is NOT a real page on this site — do NOT guess or invent URL paths. Do NOT tell the visitor you are taking them there. Instead, find the REAL page: look at your Popular Pages / Site Pages list for the closest actual match, or call fwh-list-nav-links-mvp (to read the site's real menu links) or fwh-search-mvp (to find the right page). If a close match exists (e.g. the visitor said "support" and the site has "Technical Support"), tell them the ACTUAL page name and ask "we don't have a page called that, but we do have [real page] — would you like me to take you there?" Then navigate only to that verified URL.`;return $(`fwh-navigate-mvp ✖ blocked`,e),e}l&&l!==a&&($(`fwh-navigate-mvp · corrected url:`,{requested:a,correctedUrl:l}),a=l);try{Mh(`Navigating to ${a}...`,{spinner:!0}),Lh(),kn();try{let e=r?r():``;if(e&&t){let n=Dh([{sender:`user`,message:e}]);n&&ye(t,n)}}catch{}Ce();let e=a;try{e=new URL(a,typeof window<`u`?window.location.href:``).href}catch{}let n=`this`;try{let e=new URL(a,window.location.href).pathname.split(`/`).filter(Boolean).pop()||``;n=e?e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()):`Home`}catch{}t&&typeof window<`u`&&ke(t,window.location.href,e,n),vr(e),$(`fwh-navigate-mvp → real navigation`,a);let i=typeof window<`u`&&!!Yn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),i&&Bn(12e3),Sr(a,{voiceActive:!0}).catch(()=>{}),i)try{let e=new URL(a,window.location.origin).pathname,t=window.location.pathname,n=Date.now()+2e3;for(;Date.now()<n&&!(typeof window<`u`&&window.location.pathname===e);)await new Promise(e=>setTimeout(e,80));let r=typeof window<`u`?window.location.pathname:e,i=typeof window<`u`?window.location.href:a;(r.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),$(`fwh-navigate-mvp → SPA nav complete. target:`,e,`actual:`,r);try{typeof window<`u`&&window.scrollTo(0,0)}catch{}let o=[],s=null,c=``,l=Date.now()+12e3;for(;Date.now()<l&&(await new Promise(e=>setTimeout(e,300)),{headings:o,pageTitleHeading:s,introText:c}=dg(),!(o.length>=1)););ug(),$(`fwh-navigate-mvp → page headings collected:`,o,`titleHeading:`,s);let u=o.length?o.join(` | `):`none`,d=o.length?`Use ONLY these exact heading strings for fwh-highlight-mvp — never invent or abbreviate.`:`No headings collected yet — call fwh-get-current-page-mvp immediately (no speech) to get the live headings before speaking or highlighting.`,f=s?` "${s}" is the PAGE TITLE, not a content section — do not fwh-highlight-mvp it separately; if doing a walkthrough, just fold this intro into your opening line: "${c||`(no intro text found)`}"`:c?` No separate page-title heading detected, but this intro text precedes the first section — mention it briefly before covering sections: "${c}"`:``,p=``;try{if(o.length>0){let e=o.slice(0,3),t=[];for(let n of e){let e=ur(null,n);if(e){let r=fg(e).substring(0,800);r&&t.push(`[Section: ${n}] ${r}`)}}t.length>0&&(p=` CONTENT FOR FIRST FEW SECTIONS: ${t.join(` | `)}. Use this content to answer immediately if the visitor asks about one of these sections.`)}}catch{}if(xr())return yr(),$(`fwh-navigate-mvp ✖ landed on a not-found/404 page:`,i),`NAVIGATION_PAGE_NOT_FOUND. The page at ${i} does not exist — it shows a "not found"/404 error, not real content. Do NOT offer a page overview, do NOT describe or highlight any sections, do NOT claim the navigation succeeded. Tell the visitor EXACTLY: "It looks like that page doesn't exist — I couldn't find it. Would you like me to take you somewhere else?" Then STOP and wait for their reply.`;let m=Date.now()+4e3,h=typeof window<`u`?window.location.pathname:r;for(;Date.now()<m&&!Xh(h,e)&&Xh(h,t);)await new Promise(e=>setTimeout(e,120)),h=window.location.pathname;$(`fwh-navigate-mvp route settle:`,{startPath:t,targetPath:e,settledPath:h});let g=typeof window<`u`?window.location.href:i,_=(h.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,v=Xh(h,e),y=!Xh(h,t),b=v||y;return $(`fwh-navigate-mvp settled:`,h,`target:`,e,`match:`,b),b?(yr(),`OK_NAVIGATE_SPA. Visitor is now on: ${g} (page: "${_}") | Section headings: ${u}.${f} ${d}${p} Now confirm the arrival in ONE short sentence phrased for what the visitor actually asked for — mention the page by name and what it lets them do (e.g. for a contact request: "I've taken you to the Contact Us page — filling in this form sends your query straight to our team."). Do NOT use a fixed template. Then, in the same breath, offer either a specific section or a full overview. Then STOP — wait for their reply.`):(yr(),`NAVIGATION_DID_NOT_HAPPEN. The visitor is STILL on ${g} (page: "${_}") — the navigation did not go through. Do NOT say "I have navigated you". Do NOT claim success. Tell the visitor EXACTLY: "Sorry, I couldn't open that page just now. Would you like me to try again, or is there something else I can help with?" Then STOP and wait for their reply.`)}catch{}let o=`this`;try{let e=new URL(a,window.location.href).pathname.split(`/`).filter(Boolean).pop()||``;o=e?e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()):`Home`}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, say EXACTLY: "I have navigated you on ${o} page. Do you want to know about any specific section or want a complete overview?" Then STOP — wait for the visitor's reply.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`fwh-navigate-mvp ✖`,t),Mh(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{Rh(),Nh(900)}},"fwh-highlight-mvp":async e=>{$(`fwh-highlight-mvp ▶`,e);let t=cg(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(Bn(3e3),typeof window<`u`&&window.__fe_user_nav_during_speech){let e=window.__fe_user_nav_during_speech,t=window.location.pathname;if(Date.now()-e.ts>=3e4)window.__fe_user_nav_during_speech=null;else return $(`flowengage_highlight ✖ blocked — user navigated during speech`,e),`NAV_CHANGED: The visitor navigated from "${e.fromPageName}" to "${e.toPageName}" (current path: ${t}) while you were speaking. STOP the current walkthrough immediately. DO NOT call fwh-highlight-mvp again. Say out loud: "I see you've navigated to the ${e.toPageName} page — do you want me to continue what I was explaining, or shall I guide you through this page?" Wait for the visitor's answer before doing anything else.`}ug();let i=(e=>e&&e.replace(/^\d+\.\s*/,``).replace(/^["']|["']$/g,``).trim())(r),a=ur(n||null,i||null);if(!a&&i){let e=Date.now()+600;for(;!a&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),ug(),a=ur(null,i)}if(!a){$(`fwh-highlight-mvp ✖ no element for:`,i||n);let{headings:e}=dg(),t=e.length?`Page headings: ${e.map(e=>`"${e}"`).join(` | `)}. Use one of these EXACT strings for section_text — no numbers, no quotes around them.`:`No headings found — skip highlight and continue speaking.`;return`HIGHLIGHT_NOT_FOUND: "${i||n}" on the current page. ${t}`}return On(a),$(`fwh-highlight-mvp ✓`,i||n),`OK_HIGHLIGHT: "${i||n}". Your NEXT response must be speech only (no tool call) describing THIS section — "${i||n}" — using its own content. Do not ask whether to continue.`},"fwh-read-content-mvp":async e=>{$(`fwh-read-content-mvp ▶`,e);let t=cg(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=ur(null,n);if(!t)return`Could not find section "${n}" on the page.`;e=fg(t)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar, #flowengage-root, .flowengage-shell, .flowengage-widget-root`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`fwh-read-content-mvp ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`fwh-read-content-mvp ✖`,e.message),`Could not read page content: ${e.message}`}},"fwh-page-content-mvp":async e=>{$(`fwh-page-content-mvp ▶`,e);let r=cg(e),i=r?.url||r?.page_url||``;if($(`fwh-page-content-mvp · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`fwh-page-content-mvp ✖ missing url`),`Missing url parameter.`;if(!t)return $(`fwh-page-content-mvp ✖ no siteId`),`Site is not configured.`;if(!n)return $(`fwh-page-content-mvp ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`fwh-page-content-mvp → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`fwh-page-content-mvp · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`fwh-page-content-mvp ✖`,e),`${e} FALLBACK REQUIRED: This page is not in the search index. Call fwh-read-content-mvp (no parameters) immediately to read the live page content directly from the visitor's browser — do NOT tell the visitor you cannot access the page.`}return $(`fwh-page-content-mvp ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`fwh-page-content-mvp ✖`,t),t}},"fwh-search-mvp":async e=>{$(`fwh-search-mvp ▶`,e);let r=cg(e).query;if(!r)return $(`fwh-search-mvp ✖ missing query`),`Missing query parameter.`;if(!t)return $(`fwh-search-mvp ✖ no siteId`),`Search unavailable (no siteId configured).`;if(!n)return $(`fwh-search-mvp ✖ no api base`),`Search unavailable (no API base URL).`;try{let e=`${n}/api/site-tools/search`;$(`fwh-search-mvp → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`fwh-search-mvp · HTTP`,i.status,`success:`,a.success),!a.success||!a.results?.length)return`No results found for that query. Try rephrasing, or use fwh-read-content-mvp to read the current page.`;let o=a.results.slice(0,5).map((e,t)=>`${t+1}. ${e.title||e.url} (${e.url})${e.snippet?` — ${e.snippet}`:``}`).join(`
|
|
343
343
|
`);return $(`fwh-search-mvp ✓`,`${a.results.length} result(s)`),`SEARCH_RESULTS:\n${o}`}catch(e){return $(`fwh-search-mvp ✖`,e.message),`Search failed. Use fwh-read-content-mvp to read the current page instead.`}},"fwh-list-nav-links-mvp":async()=>{if($(`fwh-list-nav-links-mvp ▶`),typeof window>`u`)return`Cannot read navigation (no browser context).`;let e=new Map,t=[],n=[`nav a`,`[role='navigation'] a`,`header a`,`.navbar a`,`.nav a`,`.menu a`,`.navigation a`,`.header a`,`[class*='nav'] a`,`[class*='menu'] a`,`[class*='header'] a`];if(Qh(t=>{for(let r of n)try{t.querySelectorAll(r).forEach(t=>{if(jn(t))return;let n=t.getAttribute(`href`),r=(t.textContent||``).replace(/\s+/g,` `).trim();if(!r||!n||n===`#`||n.startsWith(`javascript:`))return;try{let e=t.parentElement;if(e&&Zh(e).display===`none`&&!e.closest(`nav, [role='navigation'], header, [class*='nav'], [class*='menu']`))return}catch{}let i=r.toLowerCase()+`|`+n;e.has(i)||e.set(i,{text:r,href:n})})}catch{}t.querySelectorAll(`select`).forEach(t=>{if(jn(t))return;let n=eg(t);/nav|menu|page|section|go to/i.test(n||t.name||t.id||``)&&Array.from(t.options).forEach(r=>{if(!r.value||r.disabled)return;let i=r.text.trim();if(!i)return;let a=i.toLowerCase()+`|`+r.value;e.has(a)||e.set(a,{text:i,href:r.value,isSelectOption:!0,selectLabel:n||t.name||`dropdown`})})})}),e.forEach(e=>t.push(e)),!t.length)return`NAV_LINKS: No navigation links found on this page. Use fwh-read-content-mvp to read page content or fwh-search-mvp to search the site.`;let r=t.slice(0,50).map((e,t)=>`${t+1}. "${e.text}"${e.isSelectOption?` (dropdown option in "${e.selectLabel}")`:``} → ${e.href}`).join(`
|
|
344
344
|
`);return $(`fwh-list-nav-links-mvp ✓`,`${t.length} links`),`NAV_LINKS (${t.length} total, showing up to 50):\n${r}\n\nIMPORTANT: Use the EXACT text shown above when reading link names to the visitor. Do NOT rename, abbreviate, or invent options not listed here. To navigate, call fwh-navigate-mvp with the href value.`},"fwh-end-session-mvp":async()=>($(`fwh-end-session-mvp ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),"fwh-request-email-mvp":async()=>($(`fwh-request-email-mvp ▶`),typeof e.requestEmailCollection==`function`&&e.requestEmailCollection(),`EMAIL_BOX_SHOWN. An email input text box is now visible to the visitor. Say EXACTLY: "Please enter your email in the text box to continue." Then stop and wait silently — do NOT ask them to say it aloud, do NOT repeat, and do NOT answer any other question until you receive the EMAIL_SAVED message.`),"fwh-get-current-page-mvp":async()=>{if($(`fwh-get-current-page-mvp ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``;if(xr())return $(`fwh-get-current-page-mvp ✓ 404 detected`,{url:e}),`CURRENT_PAGE_NOT_FOUND. The visitor is currently on a 404 / page-not-found error page (${e}). There is no real content here. Do NOT describe this page, do NOT list sections, do NOT offer a walkthrough, and do NOT describe it from your own knowledge. Tell the visitor plainly that the page they are on doesn't exist, and offer to take them somewhere that does.`;let{headings:r,pageTitleHeading:i,introText:a}=dg();$(`fwh-get-current-page-mvp ✓`,{url:e,path:t,title:n}),$(`fwh-get-current-page-mvp → page headings collected:`,r,`titleHeading:`,i);let o=i?` NOTE: "${i}" is the PAGE TITLE, not a content section — do NOT fwh-highlight-mvp it or list it as a separate section in a walkthrough. Instead, open with a brief 1-2 sentence summary of this intro text before covering the real sections: "${a||`(no intro text captured)`}"`:a?` NOTE: no separate page-title heading was detected, but this intro text appears before the first section — open your walkthrough with a brief 1-2 sentence summary of it before covering sections: "${a}"`:``;if(!r.length)return`CURRENT_PAGE. URL: ${e} | Title: ${n} |${o} No structured section headings found on this page. If there is intro text above, describe it; otherwise describe the page from your knowledge. Do not call this tool again.`;let s=r.map(e=>`"${e}"`).join(` | `);return`CURRENT_PAGE. URL: ${e} | Title: ${n} | Page sections (${r.length} total): ${s}.${o} *** WALKTHROUGH: do NOT drive it yourself. Do not call fwh-highlight-mvp and do not decide the order — highlighting and section order are handled for you. You will be told which section to describe, one at a time. When told, describe ONLY that section in 3-4 sentences and then stop; never announce another section, never ask whether to continue. ***`},"fwh-list-forms-mvp":async()=>{let e=ng(),t=rg();$(`fwh-list-forms-mvp ✓`,`${e.length} field(s)`,`${t.length} button(s)`);let n=e.map(e=>({...e,inputCategory:e.tag===`SELECT`?`dropdown_select`:`text_input`}));return JSON.stringify({fields:n,buttons:t,hint:`field_key: use the label/placeholder/name shown above. CRITICAL: fields with inputCategory='dropdown_select' are SELECT elements — their field_key must match the SELECT's own label (e.g. 'Company Size'), NOT the option text (e.g. 'Small Business') and NOT a nearby text input label. Never fill a SELECT option value into a text input.`})},"fwh-fill-form-mvp":async()=>`FORM_FILLING_DISABLED: Form filling is not available at this time. Tell the visitor what fields are present (use fwh-list-forms-mvp) and ask them to fill the form themselves.`,"fwh-click-button-mvp":async e=>{let t=cg(e),n=(t.button_text??t.buttonText??t.text??``).trim(),r=(t.card_context??t.cardContext??``).trim();if($(`fwh-click-button-mvp ▶`,n,r?`(card_context: ${r})`:``),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let a=sg(n,i,r);if(!a)return $(`fwh-click-button-mvp ✖ no match`),`Could not find a button matching "${n}". Call fwh-list-forms-mvp to see button texts.`;try{Mh(`Clicking ${n}...`,{spinner:!0});try{a.scrollIntoView({block:`center`,inline:`nearest`})}catch{a.scrollIntoView(!0)}await Uh(a),a.focus?.(),await Gh(a),Kh(a),a.click();let e=(a.textContent||a.value||a.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`fwh-click-button-mvp ✓`,t),Mh(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`fwh-click-button-mvp ✖`,t),Mh(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{Wh(),Nh(700)}}};return{...a,highlightOnPage:a[`fwh-highlight-mvp`],getPageContent:a[`fwh-page-content-mvp`],endVoiceSession:a[`fwh-end-session-mvp`],listPageForms:a[`fwh-list-forms-mvp`],fillFormFields:a[`fwh-fill-form-mvp`],clickPageButton:a[`fwh-click-button-mvp`]}}var mg=/^(get in touch|contact us|let'?s (talk|connect)|subscribe|newsletter|follow us|quick links|company|solutions|what we do|resources|legal|sitemap|share this)/i;function hg(){try{let{headings:e,pageTitleHeading:t}=dg();return(e||[]).map(e=>typeof e==`string`?e:e?.text||``).filter(Boolean).filter(e=>!t||e.trim()!==t.trim()).filter(e=>!mg.test(e.trim()))}catch{return[]}}function gg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Tn();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var _g={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function vg(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function yg(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function bg(e){let[t,n]=b.useState(null),r=typeof e==`string`?e.trim():``;return b.useEffect(()=>{if(!r){n(null);return}n(null);let e=!1,t=new window.Image;return t.onload=()=>{e||n(r)},t.onerror=()=>{e||n(null)},t.src=r,()=>{e=!0}},[r]),t}function xg({logo:e,style:t}){let n=bg(typeof e==`string`?e:null);if(!e)return null;if(typeof e==`string`)return n?(0,H.jsx)(`img`,{src:n,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}}):null;let r=typeof e==`function`?b.createElement(e):b.isValidElement(e)?e:null;return r?(0,H.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:r}):null}function Sg({title:e}){return(0,H.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function Cg(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||e===`bot`&&(/\b(that'?s all|we'?re done)\b/i.test(n)||/\b(goodbye|bye)\b/i.test(n)||/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))):!1}function wg({orbColors:e,...t}){return(0,H.jsx)(vh,{colors:e,...t})}function Tg({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||_g.green,c=yg(s),l=a?72:94,u=(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,H.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,H.jsx)(dm.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:`210px`,wordBreak:`break-word`,overflow:`hidden`,display:`-webkit-box`,WebkitLineClamp:4,WebkitBoxOrient:`vertical`},children:e.entryPrompt}),(0,H.jsxs)(dm.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,H.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${s}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,H.jsx)(`button`,{onClick:i,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,H.jsx)(dm.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,H.jsx)(wg,{size:l,orbColors:t})})]});return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(dm.div,{initial:{opacity:0},animate:{opacity:o?0:1},transition:{duration:.28},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,H.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`,animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u}):(0,H.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function Eg({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||_g.green,l=yg(c);return(0,H.jsxs)(dm.div,{initial:{scale:50/350,borderRadius:`50%`},animate:s?{scale:50/350,opacity:0,borderRadius:`50%`}:{scale:1,borderRadius:`16px`,opacity:1},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,H.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,H.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,H.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,H.jsx)(wg,{size:72,orbColors:t}),(0,H.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,H.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,lineHeight:1.4},children:e.connectionTitle}),e.connectionSubtitle&&(0,H.jsx)(`p`,{style:{margin:`6px 0 0`,fontSize:`13px`,fontWeight:400,color:`#6b7280`,lineHeight:1.4},children:e.connectionSubtitle})]}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,H.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:c,color:l,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${c}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,H.jsx)(`button`,{onClick:i,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function Dg({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l,websiteName:u,voiceFirstMessage:d,captureVisitorEmail:f,emailRequired:p,emailCaptureEnabled:m=!0,listeningLabel:h=`Listening...`,thinkingLabel:g=`Thinking...`,enterChatModeLabel:_=`Enter Chat Mode`,endConversationLabel:v=`End Conversation`}){(0,b.useEffect)(()=>(console.log(`[FlowEngage:VoiceDebug] 🔵 VoiceMode MOUNTED`),()=>console.log(`[FlowEngage:VoiceDebug] 🔴 VoiceMode UNMOUNTED`)),[]);let[y,x]=(0,b.useState)(`idle`),[S,C]=(0,b.useState)(!1),[w,T]=(0,b.useState)(!1),[E,ee]=(0,b.useState)(!1),[te,D]=(0,b.useState)(``),[O,ne]=(0,b.useState)(``),re=(0,b.useRef)(!1),ie=(0,b.useRef)(!1),ae=(0,b.useRef)(null),oe=(0,b.useRef)(0),k=(0,b.useRef)(``),A=(0,b.useRef)(!1),se=(0,b.useRef)(0),ce=(0,b.useRef)(!1),le=(0,b.useRef)(!1),ue=(0,b.useRef)(!1),j=(0,b.useRef)([]),M=(0,b.useRef)(null),de=e=>{ce.current=e,e||(le.current=!1),N.current?.setWalkthroughActive?.(e)};M.current=async()=>{if(le.current)return;let e=j.current;fe.current+=1;let t=fe.current,n=e[t];if(!n){de(!1),e.length&&N.current?.sendUserMessage?.(`That was the last section. Say so in one short sentence and ask if they want to explore any section further.`);return}try{await toolsRef.current?.highlightOnPage?.({section_text:n})}catch{}console.debug(`[FlowEngage] walkthrough step ${t+1}/${e.length}: ${n}`),N.current?.sendUserMessage?.(`Describe the section titled "${n}" in 3-4 sentences, starting with ${t===0?`Starting with`:`Next —`} ${n}. Describe ONLY this section. If this section contains named sub-items (steps, checklist entries, cards, plans, FAQs, team members), name EVERY one of them in order with a short phrase each — never skip or collapse them into a summary; read the section's content silently first (fwh-read-content-mvp) if you don't already have it. This section is ON THE PAGE THE VISITOR IS ALREADY ON — do NOT call fwh-navigate-mvp, do not go to a product/detail page, and do not offer to, even if this section's name also matches a page name. Do not mention any other section, do not ask whether to continue, then stop.`,{suppressQuestion:!0})};let fe=(0,b.useRef)(0),N=(0,b.useRef)(null),pe=(0,b.useRef)(``),me=(0,b.useRef)(async()=>{}),he=(0,b.useRef)(!1),ge=(0,b.useRef)(!1),P=(0,b.useRef)(!1),_e=(0,b.useRef)(!1),ve=(0,b.useRef)(`minimized`),Se=(0,b.useRef)(null),we=(0,b.useRef)(null),Te=(0,b.useRef)(null),Ee=(0,b.useRef)(0),De=(0,b.useRef)(!1),F=(0,b.useRef)(`idle`),ke=(0,b.useRef)(null),je=(0,b.useRef)(!1),I=(0,b.useRef)(null),Me=(0,b.useCallback)((e=`minimized`)=>{console.warn(`[FlowEngage:VoiceDebug] 🛑 requestSessionShutdown called`,{destination:e,stack:Error().stack?.split(`
|
|
345
|
-
`).slice(1,4).join(` | `)}),ve.current=e,_e.current=!0,queueMicrotask(()=>{he.current||(he.current=!0,me.current?.())})},[s]),Ne=(0,b.useCallback)(()=>{ae.current&&=(clearTimeout(ae.current),null)},[]);(0,b.useEffect)(()=>{if(p){re.current=!1;return}if(re.current=!0,ie.current=!1,ee(!1),Ne(),A.current){A.current=!1,N.current?.setMicMuted?.(!1);let e=k.current;k.current=``,N.current?.injectAgentSpeech?.(`Thanks — I already have your email on file.`,`interrupt`),e&&N.current?.sendUserMessage?.(`The visitor's email is already on file — do not ask for it. Answer their question now: "${e}"`)}N.current?.sendContextualUpdate?.(`EMAIL REQUIREMENT SATISFIED — the visitor's email is already on file. All earlier instructions about requiring or asking for an email are VOID. Never ask for it again.`)},[p,Ne]);let Pe=/(walk\s*(me\s*)?through|walkthrough|take me through|(complete|full|detailed) (overview|understanding|walkthrough|picture|breakdown|explanation)|give me (a|an|the) (overview|tour|walk)|tell me about (each|all)|go through (it|them|each|all)|overview of|one by one|tell me everything|explain (me )?(this|the) (whole |entire |full )?page|everything (about|on) this page|show me (each|all|around))/i,Fe=/(that covers everything|that was all|covered everything|that(?:'|’)?s everything)/i,Ie=/^((uh+|um+|so|well|okay|ok|yeah)[,.\s]+)*(yes|yeah|yep|yup|sure|ok(ay)?|please|continue|go on|next|keep going|carry on|go ahead|resume|back to the tour)[\s.!,]*$/i,Le=(0,b.useCallback)(()=>{Ne(),ae.current=setTimeout(()=>{if(!(!ie.current||re.current))if(oe.current<3){oe.current+=1;try{N.current?.injectAgentSpeech?.(`I still need your email in the box below to continue — could you enter it, please?`,`queue`)}catch{}Le()}else{try{N.current?.injectAgentSpeech?.(`Since I haven't received your email, I'll close this session for now. Feel free to come back anytime — take care!`,`queue`)}catch{}ie.current=!1,ee(!1),Ne(),De.current=!0}},1e4)},[Ne]),Re=(0,b.useCallback)(async e=>{_e.current=!0;try{kn()}catch{}if(i)try{Ae(i)}catch{}try{await N.current?.endSession?.()}catch{}let t=Se.current,n=we.current;if(t&&o&&a){let e=n?Math.round((Date.now()-n)/1e3):0;fetch(`${a}/api/voice/save-chat-recording`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({chatId:o,voiceSessionId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(Se.current=null,we.current=null,N.current=null,x(`idle`),C(!1),he.current=!1,Er(),i)try{xe(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);me.current=()=>Re(ve.current===`chat`?t:n),(0,b.useEffect)(()=>{ge.current=S},[S]),(0,b.useEffect)(()=>{l&&Me(`chat`)},[l]),(0,b.useEffect)(()=>{let e=!1,l=null,f=null,h=null;return(async()=>{if(!i){x(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],pe.current=``,he.current=!1,P.current=!1,_e.current=!1,ve.current=`minimized`,Tr({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=Dh(s.current);e&&ye(i,e)}catch{}if(!Yn()){let e=Se.current,t=we.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,voiceSessionId:e,duration:n,siteId:i}),s=`${a}/api/voice/save-chat-recording`;fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:r,keepalive:!0}).catch(()=>{}),Se.current=null,we.current=null}catch{}}Ce()}});let t=gg(pg({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>pe.current,isWalkthroughActive:()=>ce.current&&!le.current,requestEndSession:()=>{De.current=!0},requestEmailCollection:()=>{m&&(re.current||ie.current||(ie.current=!0,oe.current=0,ee(!0),Le()))}})),n=i?be(i):null,r=!!n?.transcript,c=i?Ae(i):null,g=!!c,_=typeof window<`u`?window.location.pathname:`/`,v=typeof document<`u`?document.title:``,y=_.replace(/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i,``)||`/`,b=y===`/`||y===``,S={apiBaseUrl:a,siteId:i,chatId:o,clientTools:t},w=(_.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),T=``;v&&v.includes(`|`)&&(T=v.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let E=T||w||`this page`,te=(()=>{if(!c?.targetUrl)return!0;try{return new URL(c.targetUrl,window.location.href).pathname.replace(/\/$/,``)===window.location.pathname.replace(/\/$/,``)}catch{return!0}})(),D=(()=>{if(!c?.targetUrl)return null;try{return new URL(c.targetUrl,window.location.href).pathname}catch{return null}})();if(g&&!te)S.greeting=`You're on the ${E} page. What would you like to know?`,console.warn(`[FlowEngage] nav target "${c?.pageName}" not reached — on "${E}" instead; not claiming navigation`);else if(g){let e=c?.pageName||E;S.greeting=`I have navigated you on ${e} page. Do you want to know about any specific section or want a complete overview?`,console.log(`[FlowEngage] 🔄 Agent-nav resume: greeting set for "${e}" (${_})`)}else if(r)S.greeting=`Welcome back! I see you're now on the ${E} page. Would you like me to continue what I was explaining before, or would you like to know about this page instead?`;else{let e=u||``;S.greeting=d||(b?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to the ${E} page!`),b||console.log(`[FlowEngage] 🏠 Page-context greeting: "${E}" for ${_}`)}let O=!1,ne=g?`NAVIGATION COMPLETE — The exact phrase "I have navigated you on [page] page. Do you want to know about any specific section or want a complete overview?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until the visitor responds. When they reply: if they name a specific section → call fwh-get-current-page-mvp then answer immediately; if they say "overview" or anything non-specific → call fwh-get-current-page-mvp (zero speech) then do a full highlighted walkthrough.`:null,ae=!1,me=!g&&!r?`Your greeting has been spoken. Wait for the visitor to ask a question or tell you what they need. Do NOT auto-start a walkthrough or highlight any sections — let the visitor lead.`:null,xe=r&&!g,Te=!1,Re=xe?`The question "Would you like me to continue what I was explaining before, or would you like to know about this page instead?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript, or the visitor navigated before saying much)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until they respond. When they reply: if they want you to CONTINUE the previous topic → resume verbally from the prior transcript above, do NOT call fwh-get-current-page-mvp or describe the new page unless they ask. If they want to know about THIS page → call fwh-get-current-page-mvp (zero speech) then proceed as a normal fresh-page walkthrough/description. If their reply is ambiguous, ask them to clarify which they'd prefer rather than guessing.`:null,L=!1,ze=!1,Be=m&&!!p&&!ue.current,Ve=await Am.startSession({...S,onConnect:({conversationId:e})=>{Se.current=e,we.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onSessionInfo:({emailOnFile:e})=>{ue.current=!!e,e&&(re.current=!0,ie.current=!1,ee(!1),Ne(),console.log(`[FlowEngage] email already on file per server — gate disabled`))},onAgentTurnEnd:()=>{e||ce.current&&(le.current||A.current||setTimeout(()=>M.current?.(),250))},onSessionEnding:()=>{e||Me(`minimized`)},onModeChange:({mode:t,tentative:n})=>{if(!e){if(t===`speaking`){ke.current&&=(clearTimeout(ke.current),null),I.current&&=(clearTimeout(I.current),null),x(`speaking`),F.current=`speaking`,je.current=!1;return}if(t===`user-speaking`){try{kn()}catch{}if(I.current&&=(clearTimeout(I.current),null),F.current===`speaking`)return;ke.current&&=(clearTimeout(ke.current),null),F.current!==`listening`&&(x(`listening`),F.current=`listening`);return}if(t===`thinking`){if(ke.current&&=(clearTimeout(ke.current),null),I.current&&=(clearTimeout(I.current),null),F.current===`speaking`)return;x(`thinking`),F.current=`thinking`,n&&(I.current=setTimeout(()=>{I.current=null,!(e||F.current!==`thinking`)&&(F.current=`listening`,x(`listening`))},4e3));return}if(F.current=`listening`,De.current){De.current=!1,Me();return}if(Be&&!ze&&!re.current&&!ue.current){ze=!0,O=!0,ae=!0;try{N.current?.sendContextualUpdate?.(`CRITICAL — EMAIL REQUIRED BEFORE ANYTHING ELSE. The visitor has not provided their email. Do NOT speak right now. Wait silently for the visitor to speak first. The MOMENT the visitor says ANYTHING — a question, a request, or just a greeting — your ENTIRE next response must be EXACTLY this one sentence: "Before I answer that, could you please enter your email in the text box below?" Do NOT answer their question. Do NOT say anything about the topic. Do NOT begin an answer and then switch — your first word must be "Before". After you say that sentence, stay completely silent until you receive an EMAIL_SAVED message, then thank them briefly and answer their question in full.`)}catch{}}if(ne&&!O){O=!0;try{N.current?.sendContextualUpdate?.(ne)}catch{}}if(Re&&!Te){Te=!0;try{N.current?.sendContextualUpdate?.(Re)}catch{}}if(me&&!ae){ae=!0;try{N.current?.sendContextualUpdate?.(me)}catch{}}ke.current&&clearTimeout(ke.current),ke.current=setTimeout(()=>{e||F.current!==`speaking`&&(je.current||(ke.current=null,F.current=`listening`,x(`listening`)))},1200)}},onMessage:t=>{if(e||A.current&&t.role!==`user`&&!/email/i.test(String(t.message||``)))return;if(t.role===`user`&&Pe.test(String(t.message||``)))typeof window<`u`&&(window.__fe_user_nav_during_speech=null),de(!0),le.current=!1,se.current=0,fe.current=-1,j.current=hg(),setTimeout(()=>M.current?.(),400),console.log(`[FlowEngage] walkthrough armed — ${j.current.length} sections on this page`);else if(t.role===`user`&&ce.current){let e=String(t.message||``).trim();Ie.test(e)?le.current&&(le.current=!1,console.debug(`[FlowEngage] walkthrough resumed by visitor`),setTimeout(()=>M.current?.(),300)):(le.current=!0,console.debug(`[FlowEngage] walkthrough paused — visitor interjected`))}if(t.role!==`user`&&Fe.test(String(t.message||``))){let e=j.current.length;!e||fe.current>=e-1?de(!1):console.debug(`[FlowEngage] agent claimed completion at step ${fe.current+1}/${e} — ignoring, tour continues`)}let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(r){if(n===`user`&&(pe.current=r,typeof window<`u`&&(window.__fe_user_nav_during_speech=null),je.current=!0,ke.current&&=(clearTimeout(ke.current),null),F.current!==`speaking`&&(x(`thinking`),F.current=`thinking`),Be&&!L&&!re.current&&!ue.current&&(L=!0,k.current=r,A.current=!0,N.current?.injectAgentSpeech?.(`Before I answer that, could you please enter your email in the text box below?`,`interrupt`),N.current?.setMicMuted?.(!0),ie.current||(ie.current=!0,oe.current=0,ee(!0),Le()))),s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString(),debug:t.debug}],i)try{let e=Dh(s.current);e&&ye(i,e)}catch{}if(Cg(n,r)){De.current=!0;return}if(ge.current&&n===`bot`&&/are you still there|still there\??|hello\?|anyone there|checking in|you there|are you available|is anyone|did you step away/i.test(r))if(Ee.current+=1,Ee.current===2)try{N.current?.sendContextualUpdate?.(`IMPORTANT: The visitor is muted and has not responded to your last 2 checks. Make exactly ONE more check. If there is still no response, say: 'I feel like you are not active, so I'm ending this session. You can connect with me anytime.' then immediately call the fwh-end-session-mvp tool to end the voice session. Do NOT ask again after that.`)}catch{}else Ee.current>=5&&Me(`minimized`)}},onError:t=>{if(!e&&!_e.current&&!P.current&&!Oe()){P.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{N.current?.setMicMuted?.(!0)}catch{}C(!0),x(`error`),Me(`chat`)}},onDisconnect:t=>{if(e||_e.current||P.current||Oe())return;let n=s.current?.length||0;console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:n,reason:t?.reason,closeCode:t?.context?.code,closeReason:t?.context?.reason||t?.message,lastUserText:pe.current||``,wasMuted:ge.current}),P.current=!0;try{N.current?.setMicMuted?.(!0)}catch{}C(!0),Me(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),Ve.endSession().catch(()=>{});return}l=Ve,N.current=Ve,x(`listening`);try{let e=typeof window<`u`?window.location.href:``,a=`[]`;try{a=await t[`fwh-list-forms-mvp`]()}catch{}let o=`none`;if(typeof window<`u`&&typeof document<`u`)try{let e=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`,t=document.querySelector(`main, [role='main']`)||document.body,n=Array.from(t.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200);n.length||(n=Array.from(document.body.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200)),n.length&&(o=[...new Set(n)].slice(0,15).join(` | `))}catch{}let s=r&&!g?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${n?.transcript||``}\n\n`:``;Ve.sendContextualUpdate(`${s}SESSION_CONTEXT (NOT a tool result — do NOT treat as CURRENT_PAGE): Visitor is on: ${e} | Approx headings for awareness only: ${o}. SiteId: ${i||`unknown`}. Forms: ${a}. ${p?``:`Visitor's email is already on file from a prior session — do NOT ask for it again. `}The visitor is ALREADY on this page — do NOT offer to navigate there. WALKTHROUGH RULE: When the visitor asks for a walkthrough or overview of this page, you MUST IMMEDIATELY call fwh-get-current-page-mvp (zero speech — call it silently with NO words before it) to get the exact highlightable headings. The approximate headings above are for routing awareness ONLY — they are NOT precise enough for fwh-highlight-mvp. Do NOT skip fwh-get-current-page-mvp. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}if(typeof window<`u`){let t=window.location.pathname,n=Date.now(),r=e=>{try{return(decodeURIComponent(e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}catch{return((e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}},i=()=>{if(e)return;let i=window.location.pathname;if(r(i)===r(t)){t=i;return}if(D&&r(i)===r(D)){t=i;return}if(Date.now()-n<8e3){t=i;return}if(Vn()){t=i;return}let a=t;t=i;let o=window.location.href,s=typeof document<`u`?document.title:``,c=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.trim()})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,20):[];try{kn()}catch{}let l=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,u=l(a),d=l(i);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:a,toPath:i,fromPageName:u,toPageName:d,ts:Date.now()}),console.log(`[FlowEngage] visitor navigation detected: "${a}" → "${i}" (agent target: ${D||`none`})`);try{N.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${d}" page (${o}). Page title: "${s}". Sections: ${JSON.stringify(c)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${d} page — would you like me to continue what I was explaining, or shall I walk you through this page?" Then wait for my answer. IF I say continue/yes/carry on: resume speaking verbally from where you left off — do NOT call fwh-navigate-mvp, do NOT call fwh-highlight-mvp, the visitor will navigate themselves if needed. IF I want to hear about this page: call fwh-highlight-mvp for sections of "${d}" only.]`)}catch{}};f=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{f(...e),setTimeout(i,50)},h=()=>setTimeout(i,50),window.addEventListener(`popstate`,h)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(x(`error`),ve.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{console.warn(`[FlowEngage:VoiceDebug] ⚠️ useEffect CLEANUP fired — session will be killed`,{agentId:r,siteId:i,apiBaseUrl:a}),e=!0,_e.current=!0;try{kn()}catch{}if(i)try{Ae(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Er(),ke.current&&=(clearTimeout(ke.current),null),I.current&&=(clearTimeout(I.current),null),ae.current&&=(clearTimeout(ae.current),null),je.current=!1,F.current=`idle`,f&&typeof window<`u`&&(window.history.pushState=f),h&&typeof window<`u`&&window.removeEventListener(`popstate`,h);let t=l||N.current,n=Se.current,u=we.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=u?Math.round((Date.now()-u)/1e3):0,t=JSON.stringify({chatId:o,voiceSessionId:n,duration:e,siteId:i}),r=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(r,new Blob([t],{type:`application/json`}))||fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),Se.current=null,we.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Me]),(0,b.useEffect)(()=>{if(!w)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Te.current&&!Te.current.contains(t)&&T(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[w]);let L=async()=>{if(N.current)try{if(S){Ee.current=0,await N.current.setMicMuted?.(!1),C(!1);try{N.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{Ee.current=0,await N.current.setMicMuted?.(!0),C(!0);try{N.current.sendContextualUpdate?.(`The visitor has muted their microphone. Do NOT speak, ask if they are there, or prompt them in any way. Stay completely silent until they unmute.`)}catch{}}}catch{}},ze=(0,b.useCallback)(async e=>{e?.preventDefault?.();let t=te.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){ne(`Please enter a valid email address.`);return}ne(``),re.current=!0,ie.current=!1,Ne(),ee(!1),D(``),A.current=!1;try{typeof f==`function`&&await f(t)}catch{}N.current?.setMicMuted?.(!1);let n=k.current;k.current=``;try{N.current?.injectAgentSpeech?.(`Thank you for submitting your email.`),N.current?.sendUserMessage?.(n||`The visitor's email is on file. Carry on helping them and never ask for it again.`)}catch{}},[te,f,Ne]),Be=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,H.jsxs)(`div`,{ref:Te,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[E&&(0,H.jsxs)(`form`,{onSubmit:ze,style:{width:`270px`,maxWidth:`calc(100vw - 40px)`,boxSizing:`border-box`,background:`rgba(15,22,36,0.97)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,padding:`16px`,display:`flex`,flexDirection:`column`,gap:`10px`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,H.jsx)(`span`,{style:{color:`white`,fontSize:`13px`,fontWeight:600,lineHeight:1.4},children:`Please enter your email to continue`}),(0,H.jsx)(`input`,{type:`email`,inputMode:`email`,autoComplete:`email`,autoFocus:!0,value:te,onChange:e=>{D(e.target.value),O&&ne(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:O?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),O&&(0,H.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:O}),(0,H.jsx)(`button`,{type:`submit`,disabled:!te.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:te.trim()?Be:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:te.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,H.jsxs)(`div`,{style:{position:`relative`},children:[(y===`listening`||y===`thinking`)&&!S&&(0,H.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:y===`thinking`?g:h}),S&&(0,H.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`#f87171`,fontSize:`16px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Muted`}),(0,H.jsx)(wg,{size:72,voiceState:y,isMuted:S,orbColors:e})]}),y===`error`&&(0,H.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,H.jsx)(`button`,{onClick:L,title:S?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:S?`#7f1d1d`:`#1f2937`,border:S?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:S?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:S?(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,H.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,H.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,H.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,H.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,H.jsx)(jm,{size:16,color:`currentColor`})}),(0,H.jsx)(`button`,{onClick:()=>T(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,H.jsx)(zm,{size:16,color:`currentColor`})})]}),w&&(0,H.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,H.jsxs)(`button`,{onClick:()=>{T(!1),ve.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,H.jsx)(Bm,{}),_]}),(0,H.jsxs)(`button`,{onClick:()=>{T(!1),ve.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,H.jsx)(Vm,{}),v]}),(0,H.jsx)(`button`,{onClick:()=>T(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,H.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,H.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function Og({orbColors:e}){let t=Array.isArray(e)&&e.length>0?e:[`#135bd8`,`#ef334b`,`#ffbd2e`],n=t[0],r=t[1]||t[0],i=t[2]||t[0];return(0,H.jsx)(`div`,{style:{width:`32px`,height:`32px`,borderRadius:`50%`,flexShrink:0,background:`
|
|
345
|
+
`).slice(1,4).join(` | `)}),ve.current=e,_e.current=!0,queueMicrotask(()=>{he.current||(he.current=!0,me.current?.())})},[s]),Ne=(0,b.useCallback)(()=>{ae.current&&=(clearTimeout(ae.current),null)},[]);(0,b.useEffect)(()=>{if(p){re.current=!1;return}if(re.current=!0,ie.current=!1,ee(!1),Ne(),A.current){A.current=!1,N.current?.setMicMuted?.(!1);let e=k.current;k.current=``,N.current?.injectAgentSpeech?.(`Thanks — I already have your email on file.`,`interrupt`),e&&N.current?.sendUserMessage?.(`The visitor's email is already on file — do not ask for it. Answer their question now: "${e}"`)}N.current?.sendContextualUpdate?.(`EMAIL REQUIREMENT SATISFIED — the visitor's email is already on file. All earlier instructions about requiring or asking for an email are VOID. Never ask for it again.`)},[p,Ne]);let Pe=/(walk\s*(me\s*)?through|walkthrough|take me through|(complete|full|detailed) (overview|understanding|walkthrough|picture|breakdown|explanation)|give me (a|an|the) (overview|tour|walk)|tell me about (each|all)|go through (it|them|each|all)|overview of|one by one|tell me everything|explain (me )?(this|the) (whole |entire |full )?page|everything (about|on) this page|show me (each|all|around))/i,Fe=/(that covers everything|that was all|covered everything|that(?:'|’)?s everything)/i,Ie=/^((uh+|um+|so|well|okay|ok|yeah)[,.\s]+)*(yes|yeah|yep|yup|sure|ok(ay)?|please|continue|go on|next|keep going|carry on|go ahead|resume|back to the tour)[\s.!,]*$/i,Le=(0,b.useCallback)(()=>{Ne(),ae.current=setTimeout(()=>{if(!(!ie.current||re.current))if(oe.current<3){oe.current+=1;try{N.current?.injectAgentSpeech?.(`I still need your email in the box below to continue — could you enter it, please?`,`queue`)}catch{}Le()}else{try{N.current?.injectAgentSpeech?.(`Since I haven't received your email, I'll close this session for now. Feel free to come back anytime — take care!`,`queue`)}catch{}ie.current=!1,ee(!1),Ne(),De.current=!0}},1e4)},[Ne]),Re=(0,b.useCallback)(async e=>{_e.current=!0;try{kn()}catch{}if(i)try{Ae(i)}catch{}try{await N.current?.endSession?.()}catch{}let t=Se.current,n=we.current;if(t&&o&&a){let e=n?Math.round((Date.now()-n)/1e3):0;fetch(`${a}/api/voice/save-chat-recording`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({chatId:o,voiceSessionId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(Se.current=null,we.current=null,N.current=null,x(`idle`),C(!1),he.current=!1,Er(),i)try{xe(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);me.current=()=>Re(ve.current===`chat`?t:n),(0,b.useEffect)(()=>{ge.current=S},[S]),(0,b.useEffect)(()=>{l&&Me(`chat`)},[l]),(0,b.useEffect)(()=>{let e=!1,l=null,f=null,h=null;return(async()=>{if(!i){x(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],pe.current=``,he.current=!1,P.current=!1,_e.current=!1,ve.current=`minimized`,Tr({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=Dh(s.current);e&&ye(i,e)}catch{}if(!Yn()){let e=Se.current,t=we.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,voiceSessionId:e,duration:n,siteId:i}),s=`${a}/api/voice/save-chat-recording`;fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:r,keepalive:!0}).catch(()=>{}),Se.current=null,we.current=null}catch{}}Ce()}});let t=gg(pg({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>pe.current,isWalkthroughActive:()=>ce.current&&!le.current,requestEndSession:()=>{De.current=!0},requestEmailCollection:()=>{m&&(re.current||ie.current||(ie.current=!0,oe.current=0,ee(!0),Le()))}})),n=i?be(i):null,r=!!n?.transcript,c=i?Ae(i):null,g=!!c,_=typeof window<`u`?window.location.pathname:`/`,v=typeof document<`u`?document.title:``,y=_.replace(/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i,``)||`/`,b=y===`/`||y===``,S={apiBaseUrl:a,siteId:i,chatId:o,clientTools:t},w=(_.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),T=``;v&&v.includes(`|`)&&(T=v.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let E=T||w||`this page`,te=(()=>{if(!c?.targetUrl)return!0;try{return new URL(c.targetUrl,window.location.href).pathname.replace(/\/$/,``)===window.location.pathname.replace(/\/$/,``)}catch{return!0}})(),D=(()=>{if(!c?.targetUrl)return null;try{return new URL(c.targetUrl,window.location.href).pathname}catch{return null}})();if(g&&!te)S.greeting=`You're on the ${E} page. What would you like to know?`,console.warn(`[FlowEngage] nav target "${c?.pageName}" not reached — on "${E}" instead; not claiming navigation`);else if(g){let e=c?.pageName||E;S.greeting=`I have navigated you on ${e} page. Do you want to know about any specific section or want a complete overview?`,console.log(`[FlowEngage] 🔄 Agent-nav resume: greeting set for "${e}" (${_})`)}else if(r)S.greeting=`Welcome back! I see you're now on the ${E} page. Would you like me to continue what I was explaining before, or would you like to know about this page instead?`;else{let e=u||``;S.greeting=d||(b?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to the ${E} page!`),b||console.log(`[FlowEngage] 🏠 Page-context greeting: "${E}" for ${_}`)}let O=!1,ne=g?`NAVIGATION COMPLETE — The exact phrase "I have navigated you on [page] page. Do you want to know about any specific section or want a complete overview?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until the visitor responds. When they reply: if they name a specific section → call fwh-get-current-page-mvp then answer immediately; if they say "overview" or anything non-specific → call fwh-get-current-page-mvp (zero speech) then do a full highlighted walkthrough.`:null,ae=!1,me=!g&&!r?`Your greeting has been spoken. Wait for the visitor to ask a question or tell you what they need. Do NOT auto-start a walkthrough or highlight any sections — let the visitor lead.`:null,xe=r&&!g,Te=!1,Re=xe?`The question "Would you like me to continue what I was explaining before, or would you like to know about this page instead?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript, or the visitor navigated before saying much)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until they respond. When they reply: if they want you to CONTINUE the previous topic → resume verbally from the prior transcript above, do NOT call fwh-get-current-page-mvp or describe the new page unless they ask. If they want to know about THIS page → call fwh-get-current-page-mvp (zero speech) then proceed as a normal fresh-page walkthrough/description. If their reply is ambiguous, ask them to clarify which they'd prefer rather than guessing.`:null,L=!1,ze=!1,Be=m&&!!p&&!ue.current,Ve=await Am.startSession({...S,onConnect:({conversationId:e})=>{Se.current=e,we.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onSessionInfo:({emailOnFile:e})=>{ue.current=!!e,e&&(re.current=!0,ie.current=!1,ee(!1),Ne(),console.log(`[FlowEngage] email already on file per server — gate disabled`))},onAgentTurnEnd:()=>{e||ce.current&&(le.current||A.current||setTimeout(()=>M.current?.(),250))},onSessionEnding:()=>{e||Me(`minimized`)},onModeChange:({mode:t,tentative:n})=>{if(!e){if(t===`speaking`){ke.current&&=(clearTimeout(ke.current),null),I.current&&=(clearTimeout(I.current),null),x(`speaking`),F.current=`speaking`,je.current=!1;return}if(t===`user-speaking`){if(I.current&&=(clearTimeout(I.current),null),F.current===`speaking`)return;try{kn()}catch{}ke.current&&=(clearTimeout(ke.current),null),F.current!==`listening`&&(x(`listening`),F.current=`listening`);return}if(t===`thinking`){if(ke.current&&=(clearTimeout(ke.current),null),I.current&&=(clearTimeout(I.current),null),F.current===`speaking`)return;x(`thinking`),F.current=`thinking`,n&&(I.current=setTimeout(()=>{I.current=null,!(e||F.current!==`thinking`)&&(F.current=`listening`,x(`listening`))},4e3));return}if(F.current=`listening`,De.current){De.current=!1,Me();return}if(Be&&!ze&&!re.current&&!ue.current){ze=!0,O=!0,ae=!0;try{N.current?.sendContextualUpdate?.(`CRITICAL — EMAIL REQUIRED BEFORE ANYTHING ELSE. The visitor has not provided their email. Do NOT speak right now. Wait silently for the visitor to speak first. The MOMENT the visitor says ANYTHING — a question, a request, or just a greeting — your ENTIRE next response must be EXACTLY this one sentence: "Before I answer that, could you please enter your email in the text box below?" Do NOT answer their question. Do NOT say anything about the topic. Do NOT begin an answer and then switch — your first word must be "Before". After you say that sentence, stay completely silent until you receive an EMAIL_SAVED message, then thank them briefly and answer their question in full.`)}catch{}}if(ne&&!O){O=!0;try{N.current?.sendContextualUpdate?.(ne)}catch{}}if(Re&&!Te){Te=!0;try{N.current?.sendContextualUpdate?.(Re)}catch{}}if(me&&!ae){ae=!0;try{N.current?.sendContextualUpdate?.(me)}catch{}}ke.current&&clearTimeout(ke.current),ke.current=setTimeout(()=>{e||F.current!==`speaking`&&(je.current||(ke.current=null,F.current=`listening`,x(`listening`)))},1200)}},onMessage:t=>{if(e||A.current&&t.role!==`user`&&!/email/i.test(String(t.message||``)))return;if(t.role===`user`&&Pe.test(String(t.message||``)))typeof window<`u`&&(window.__fe_user_nav_during_speech=null),de(!0),le.current=!1,se.current=0,fe.current=-1,j.current=hg(),setTimeout(()=>M.current?.(),400),console.log(`[FlowEngage] walkthrough armed — ${j.current.length} sections on this page`);else if(t.role===`user`&&ce.current){let e=String(t.message||``).trim();Ie.test(e)?le.current&&(le.current=!1,console.debug(`[FlowEngage] walkthrough resumed by visitor`),setTimeout(()=>M.current?.(),300)):(le.current=!0,console.debug(`[FlowEngage] walkthrough paused — visitor interjected`))}if(t.role!==`user`&&Fe.test(String(t.message||``))){let e=j.current.length;!e||fe.current>=e-1?de(!1):console.debug(`[FlowEngage] agent claimed completion at step ${fe.current+1}/${e} — ignoring, tour continues`)}let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(r){if(n===`user`&&(pe.current=r,typeof window<`u`&&(window.__fe_user_nav_during_speech=null),je.current=!0,ke.current&&=(clearTimeout(ke.current),null),F.current!==`speaking`&&(x(`thinking`),F.current=`thinking`),Be&&!L&&!re.current&&!ue.current&&(L=!0,k.current=r,A.current=!0,N.current?.injectAgentSpeech?.(`Before I answer that, could you please enter your email in the text box below?`,`interrupt`),N.current?.setMicMuted?.(!0),ie.current||(ie.current=!0,oe.current=0,ee(!0),Le()))),s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString(),debug:t.debug}],i)try{let e=Dh(s.current);e&&ye(i,e)}catch{}if(Cg(n,r)){De.current=!0;return}if(ge.current&&n===`bot`&&/are you still there|still there\??|hello\?|anyone there|checking in|you there|are you available|is anyone|did you step away/i.test(r))if(Ee.current+=1,Ee.current===2)try{N.current?.sendContextualUpdate?.(`IMPORTANT: The visitor is muted and has not responded to your last 2 checks. Make exactly ONE more check. If there is still no response, say: 'I feel like you are not active, so I'm ending this session. You can connect with me anytime.' then immediately call the fwh-end-session-mvp tool to end the voice session. Do NOT ask again after that.`)}catch{}else Ee.current>=5&&Me(`minimized`)}},onError:t=>{if(!e&&!_e.current&&!P.current&&!Oe()){P.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{N.current?.setMicMuted?.(!0)}catch{}C(!0),x(`error`),Me(`chat`)}},onDisconnect:t=>{if(e||_e.current||P.current||Oe())return;let n=s.current?.length||0;console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:n,reason:t?.reason,closeCode:t?.context?.code,closeReason:t?.context?.reason||t?.message,lastUserText:pe.current||``,wasMuted:ge.current}),P.current=!0;try{N.current?.setMicMuted?.(!0)}catch{}C(!0),Me(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),Ve.endSession().catch(()=>{});return}l=Ve,N.current=Ve,x(`listening`);try{let e=typeof window<`u`?window.location.href:``,a=`[]`;try{a=await t[`fwh-list-forms-mvp`]()}catch{}let o=`none`;if(typeof window<`u`&&typeof document<`u`)try{let e=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`,t=document.querySelector(`main, [role='main']`)||document.body,n=Array.from(t.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200);n.length||(n=Array.from(document.body.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200)),n.length&&(o=[...new Set(n)].slice(0,15).join(` | `))}catch{}let s=r&&!g?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${n?.transcript||``}\n\n`:``;Ve.sendContextualUpdate(`${s}SESSION_CONTEXT (NOT a tool result — do NOT treat as CURRENT_PAGE): Visitor is on: ${e} | Approx headings for awareness only: ${o}. SiteId: ${i||`unknown`}. Forms: ${a}. ${p?``:`Visitor's email is already on file from a prior session — do NOT ask for it again. `}The visitor is ALREADY on this page — do NOT offer to navigate there. WALKTHROUGH RULE: When the visitor asks for a walkthrough or overview of this page, you MUST IMMEDIATELY call fwh-get-current-page-mvp (zero speech — call it silently with NO words before it) to get the exact highlightable headings. The approximate headings above are for routing awareness ONLY — they are NOT precise enough for fwh-highlight-mvp. Do NOT skip fwh-get-current-page-mvp. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}if(typeof window<`u`){let t=window.location.pathname,n=Date.now(),r=e=>{try{return(decodeURIComponent(e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}catch{return((e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}},i=()=>{if(e)return;let i=window.location.pathname;if(r(i)===r(t)){t=i;return}if(D&&r(i)===r(D)){t=i;return}if(Date.now()-n<8e3){t=i;return}if(Vn()){t=i;return}let a=t;t=i;let o=window.location.href,s=typeof document<`u`?document.title:``,c=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.trim()})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,20):[];try{kn()}catch{}let l=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,u=l(a),d=l(i);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:a,toPath:i,fromPageName:u,toPageName:d,ts:Date.now()}),console.log(`[FlowEngage] visitor navigation detected: "${a}" → "${i}" (agent target: ${D||`none`})`);try{N.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${d}" page (${o}). Page title: "${s}". Sections: ${JSON.stringify(c)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${d} page — would you like me to continue what I was explaining, or shall I walk you through this page?" Then wait for my answer. IF I say continue/yes/carry on: resume speaking verbally from where you left off — do NOT call fwh-navigate-mvp, do NOT call fwh-highlight-mvp, the visitor will navigate themselves if needed. IF I want to hear about this page: call fwh-highlight-mvp for sections of "${d}" only.]`)}catch{}};f=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{f(...e),setTimeout(i,50)},h=()=>setTimeout(i,50),window.addEventListener(`popstate`,h)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(x(`error`),ve.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{console.warn(`[FlowEngage:VoiceDebug] ⚠️ useEffect CLEANUP fired — session will be killed`,{agentId:r,siteId:i,apiBaseUrl:a}),e=!0,_e.current=!0;try{kn()}catch{}if(i)try{Ae(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Er(),ke.current&&=(clearTimeout(ke.current),null),I.current&&=(clearTimeout(I.current),null),ae.current&&=(clearTimeout(ae.current),null),je.current=!1,F.current=`idle`,f&&typeof window<`u`&&(window.history.pushState=f),h&&typeof window<`u`&&window.removeEventListener(`popstate`,h);let t=l||N.current,n=Se.current,u=we.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=u?Math.round((Date.now()-u)/1e3):0,t=JSON.stringify({chatId:o,voiceSessionId:n,duration:e,siteId:i}),r=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(r,new Blob([t],{type:`application/json`}))||fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),Se.current=null,we.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Me]),(0,b.useEffect)(()=>{if(!w)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Te.current&&!Te.current.contains(t)&&T(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[w]);let L=async()=>{if(N.current)try{if(S){Ee.current=0,await N.current.setMicMuted?.(!1),C(!1);try{N.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{Ee.current=0,await N.current.setMicMuted?.(!0),C(!0);try{N.current.sendContextualUpdate?.(`The visitor has muted their microphone. Do NOT speak, ask if they are there, or prompt them in any way. Stay completely silent until they unmute.`)}catch{}}}catch{}},ze=(0,b.useCallback)(async e=>{e?.preventDefault?.();let t=te.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){ne(`Please enter a valid email address.`);return}ne(``),re.current=!0,ie.current=!1,Ne(),ee(!1),D(``),A.current=!1;try{typeof f==`function`&&await f(t)}catch{}N.current?.setMicMuted?.(!1);let n=k.current;k.current=``;try{N.current?.injectAgentSpeech?.(`Thank you for submitting your email.`),N.current?.sendUserMessage?.(n||`The visitor's email is on file. Carry on helping them and never ask for it again.`)}catch{}},[te,f,Ne]),Be=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,H.jsxs)(`div`,{ref:Te,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[E&&(0,H.jsxs)(`form`,{onSubmit:ze,style:{width:`270px`,maxWidth:`calc(100vw - 40px)`,boxSizing:`border-box`,background:`rgba(15,22,36,0.97)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,padding:`16px`,display:`flex`,flexDirection:`column`,gap:`10px`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,H.jsx)(`span`,{style:{color:`white`,fontSize:`13px`,fontWeight:600,lineHeight:1.4},children:`Please enter your email to continue`}),(0,H.jsx)(`input`,{type:`email`,inputMode:`email`,autoComplete:`email`,autoFocus:!0,value:te,onChange:e=>{D(e.target.value),O&&ne(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:O?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),O&&(0,H.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:O}),(0,H.jsx)(`button`,{type:`submit`,disabled:!te.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:te.trim()?Be:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:te.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,H.jsxs)(`div`,{style:{position:`relative`},children:[(y===`listening`||y===`thinking`)&&!S&&(0,H.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:y===`thinking`?g:h}),S&&(0,H.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`#f87171`,fontSize:`16px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Muted`}),(0,H.jsx)(wg,{size:72,voiceState:y,isMuted:S,orbColors:e})]}),y===`error`&&(0,H.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,H.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,H.jsx)(`button`,{onClick:L,title:S?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:S?`#7f1d1d`:`#1f2937`,border:S?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:S?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:S?(0,H.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,H.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,H.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,H.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,H.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,H.jsx)(jm,{size:16,color:`currentColor`})}),(0,H.jsx)(`button`,{onClick:()=>T(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,H.jsx)(zm,{size:16,color:`currentColor`})})]}),w&&(0,H.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,H.jsxs)(`button`,{onClick:()=>{T(!1),ve.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,H.jsx)(Bm,{}),_]}),(0,H.jsxs)(`button`,{onClick:()=>{T(!1),ve.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,H.jsx)(Vm,{}),v]}),(0,H.jsx)(`button`,{onClick:()=>T(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,H.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,H.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,H.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function Og({orbColors:e}){let t=Array.isArray(e)&&e.length>0?e:[`#135bd8`,`#ef334b`,`#ffbd2e`],n=t[0],r=t[1]||t[0],i=t[2]||t[0];return(0,H.jsx)(`div`,{style:{width:`32px`,height:`32px`,borderRadius:`50%`,flexShrink:0,background:`
|
|
346
346
|
radial-gradient(circle at 18% 50%, ${n} 0%, ${n}99 35%, transparent 65%),
|
|
347
347
|
radial-gradient(circle at 82% 50%, ${r} 0%, ${r}99 35%, transparent 65%),
|
|
348
348
|
radial-gradient(circle at 50% 82%, ${i} 0%, ${i}99 30%, transparent 58%),
|
|
@@ -334,7 +334,7 @@
|
|
|
334
334
|
`).trim()}function cg(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={"fwh-navigate-mvp":async n=>{if($(`fwh-navigate-mvp ▶ raw parameters:`,n),e?.isWalkthroughActive?.())return $(`fwh-navigate-mvp ✖ blocked — walkthrough in progress`),`NAVIGATION_BLOCKED_DURING_WALKTHROUGH. A walkthrough of the current page is in progress, so navigation is not allowed. Do NOT tell the visitor you navigated or offer to. Describe the requested section using the CURRENT page's own content (fwh-read-content-mvp), then stop.`;let i=rg(n),a=ig(i),o=i.section_text??i.sectionText??i.section,s=Array.isArray(i.expected_landmarks)?i.expected_landmarks:Array.isArray(i.expectedLandmarks)?i.expectedLandmarks:[];if($(`fwh-navigate-mvp · coerced:`,{url:a,sectionText:o,expectedLandmarks:s}),!a){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`fwh-navigate-mvp ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);if(e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)){let t=e.hostname;return $(`fwh-navigate-mvp ✖ external URL blocked:`,e.href),`EXTERNAL_LINK_BLOCKED: The URL "${a}" points to an external site (${t}) that opens in a new tab. I cannot open new tabs or navigate to external sites. Tell the visitor exactly this: "That link opens an external app — I'm not able to open it for you, but you can click the link directly in the navigation header."`}}catch{}if(typeof window<`u`){try{let e=new URL(a,window.location.href);if(e.pathname===window.location.pathname&&e.search===window.location.search)return $(`fwh-navigate-mvp ✖ already on page, skipping`),`OK_ALREADY_ON_PAGE. The visitor is already on this page. Do not navigate. Proceed directly with highlights, answering the question, or reading page content.`}catch{}let e=window.__fe_user_nav_during_speech;if(e&&Date.now()-e.ts<3e4)try{if(new URL(a,window.location.href).pathname===e.fromPath)return $(`flowengage_navigate ✖ blocked — would navigate back to page visitor just left`,e),`NAV_BLOCKED: The visitor just left "${e.fromPageName}" and is now on "${e.toPageName}". Do NOT navigate them back. If they said "continue", resume verbally from where you left off — no navigation needed. If they want to return, they will navigate themselves.`}catch{}}let{allowed:c,correctedUrl:l}=await er(a,{siteId:t,apiBaseUrl:e.apiBaseUrl});if(!c){let e=`PAGE_NOT_IN_SITE: "${a}" is NOT a real page on this site — do NOT guess or invent URL paths. Do NOT tell the visitor you are taking them there. Instead, find the REAL page: look at your Popular Pages / Site Pages list for the closest actual match, or call fwh-list-nav-links-mvp (to read the site's real menu links) or fwh-search-mvp (to find the right page). If a close match exists (e.g. the visitor said "support" and the site has "Technical Support"), tell them the ACTUAL page name and ask "we don't have a page called that, but we do have [real page] — would you like me to take you there?" Then navigate only to that verified URL.`;return $(`fwh-navigate-mvp ✖ blocked`,e),e}l&&l!==a&&($(`fwh-navigate-mvp · corrected url:`,{requested:a,correctedUrl:l}),a=l);try{Dh(`Navigating to ${a}...`,{spinner:!0}),Mh(),hn();try{let e=r?r():``;if(e&&t){let n=Sh([{sender:`user`,message:e}]);n&&ue(t,n)}}catch{}me();let e=a;try{e=new URL(a,typeof window<`u`?window.location.href:``).href}catch{}let n=`this`;try{let e=new URL(a,window.location.href).pathname.split(`/`).filter(Boolean).pop()||``;n=e?e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()):`Home`}catch{}t&&typeof window<`u`&&I(t,window.location.href,e,n),rr(e),$(`fwh-navigate-mvp → real navigation`,a);let i=typeof window<`u`&&!!Pn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),i&&Tn(12e3),sr(a,{voiceActive:!0}).catch(()=>{}),i)try{let e=new URL(a,window.location.origin).pathname,t=window.location.pathname,n=Date.now()+2e3;for(;Date.now()<n&&!(typeof window<`u`&&window.location.pathname===e);)await new Promise(e=>setTimeout(e,80));let r=typeof window<`u`?window.location.pathname:e,i=typeof window<`u`?window.location.href:a;(r.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),$(`fwh-navigate-mvp → SPA nav complete. target:`,e,`actual:`,r);try{typeof window<`u`&&window.scrollTo(0,0)}catch{}let o=[],s=null,c=``,l=Date.now()+12e3;for(;Date.now()<l&&(await new Promise(e=>setTimeout(e,300)),{headings:o,pageTitleHeading:s,introText:c}=og(),!(o.length>=1)););ag(),$(`fwh-navigate-mvp → page headings collected:`,o,`titleHeading:`,s);let u=o.length?o.join(` | `):`none`,d=o.length?`Use ONLY these exact heading strings for fwh-highlight-mvp — never invent or abbreviate.`:`No headings collected yet — call fwh-get-current-page-mvp immediately (no speech) to get the live headings before speaking or highlighting.`,f=s?` "${s}" is the PAGE TITLE, not a content section — do not fwh-highlight-mvp it separately; if doing a walkthrough, just fold this intro into your opening line: "${c||`(no intro text found)`}"`:c?` No separate page-title heading detected, but this intro text precedes the first section — mention it briefly before covering sections: "${c}"`:``,p=``;try{if(o.length>0){let e=o.slice(0,3),t=[];for(let n of e){let e=Yn(null,n);if(e){let r=sg(e).substring(0,800);r&&t.push(`[Section: ${n}] ${r}`)}}t.length>0&&(p=` CONTENT FOR FIRST FEW SECTIONS: ${t.join(` | `)}. Use this content to answer immediately if the visitor asks about one of these sections.`)}}catch{}if(or())return ir(),$(`fwh-navigate-mvp ✖ landed on a not-found/404 page:`,i),`NAVIGATION_PAGE_NOT_FOUND. The page at ${i} does not exist — it shows a "not found"/404 error, not real content. Do NOT offer a page overview, do NOT describe or highlight any sections, do NOT claim the navigation succeeded. Tell the visitor EXACTLY: "It looks like that page doesn't exist — I couldn't find it. Would you like me to take you somewhere else?" Then STOP and wait for their reply.`;let m=Date.now()+4e3,h=typeof window<`u`?window.location.pathname:r;for(;Date.now()<m&&!Gh(h,e)&&Gh(h,t);)await new Promise(e=>setTimeout(e,120)),h=window.location.pathname;$(`fwh-navigate-mvp route settle:`,{startPath:t,targetPath:e,settledPath:h});let g=typeof window<`u`?window.location.href:i,_=(h.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,v=Gh(h,e),y=!Gh(h,t),b=v||y;return $(`fwh-navigate-mvp settled:`,h,`target:`,e,`match:`,b),b?(ir(),`OK_NAVIGATE_SPA. Visitor is now on: ${g} (page: "${_}") | Section headings: ${u}.${f} ${d}${p} Now confirm the arrival in ONE short sentence phrased for what the visitor actually asked for — mention the page by name and what it lets them do (e.g. for a contact request: "I've taken you to the Contact Us page — filling in this form sends your query straight to our team."). Do NOT use a fixed template. Then, in the same breath, offer either a specific section or a full overview. Then STOP — wait for their reply.`):(ir(),`NAVIGATION_DID_NOT_HAPPEN. The visitor is STILL on ${g} (page: "${_}") — the navigation did not go through. Do NOT say "I have navigated you". Do NOT claim success. Tell the visitor EXACTLY: "Sorry, I couldn't open that page just now. Would you like me to try again, or is there something else I can help with?" Then STOP and wait for their reply.`)}catch{}let o=`this`;try{let e=new URL(a,window.location.href).pathname.split(`/`).filter(Boolean).pop()||``;o=e?e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()):`Home`}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, say EXACTLY: "I have navigated you on ${o} page. Do you want to know about any specific section or want a complete overview?" Then STOP — wait for the visitor's reply.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`fwh-navigate-mvp ✖`,t),Dh(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{Nh(),Oh(900)}},"fwh-highlight-mvp":async e=>{$(`fwh-highlight-mvp ▶`,e);let t=rg(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(Tn(3e3),typeof window<`u`&&window.__fe_user_nav_during_speech){let e=window.__fe_user_nav_during_speech,t=window.location.pathname;if(Date.now()-e.ts>=3e4)window.__fe_user_nav_during_speech=null;else return $(`flowengage_highlight ✖ blocked — user navigated during speech`,e),`NAV_CHANGED: The visitor navigated from "${e.fromPageName}" to "${e.toPageName}" (current path: ${t}) while you were speaking. STOP the current walkthrough immediately. DO NOT call fwh-highlight-mvp again. Say out loud: "I see you've navigated to the ${e.toPageName} page — do you want me to continue what I was explaining, or shall I guide you through this page?" Wait for the visitor's answer before doing anything else.`}ag();let i=(e=>e&&e.replace(/^\d+\.\s*/,``).replace(/^["']|["']$/g,``).trim())(r),a=Yn(n||null,i||null);if(!a&&i){let e=Date.now()+600;for(;!a&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),ag(),a=Yn(null,i)}if(!a){$(`fwh-highlight-mvp ✖ no element for:`,i||n);let{headings:e}=og(),t=e.length?`Page headings: ${e.map(e=>`"${e}"`).join(` | `)}. Use one of these EXACT strings for section_text — no numbers, no quotes around them.`:`No headings found — skip highlight and continue speaking.`;return`HIGHLIGHT_NOT_FOUND: "${i||n}" on the current page. ${t}`}return mn(a),$(`fwh-highlight-mvp ✓`,i||n),`OK_HIGHLIGHT: "${i||n}". Your NEXT response must be speech only (no tool call) describing THIS section — "${i||n}" — using its own content. Do not ask whether to continue.`},"fwh-read-content-mvp":async e=>{$(`fwh-read-content-mvp ▶`,e);let t=rg(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=Yn(null,n);if(!t)return`Could not find section "${n}" on the page.`;e=sg(t)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar, #flowengage-root, .flowengage-shell, .flowengage-widget-root`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`fwh-read-content-mvp ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`fwh-read-content-mvp ✖`,e.message),`Could not read page content: ${e.message}`}},"fwh-page-content-mvp":async e=>{$(`fwh-page-content-mvp ▶`,e);let r=rg(e),i=r?.url||r?.page_url||``;if($(`fwh-page-content-mvp · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`fwh-page-content-mvp ✖ missing url`),`Missing url parameter.`;if(!t)return $(`fwh-page-content-mvp ✖ no siteId`),`Site is not configured.`;if(!n)return $(`fwh-page-content-mvp ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`fwh-page-content-mvp → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`fwh-page-content-mvp · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`fwh-page-content-mvp ✖`,e),`${e} FALLBACK REQUIRED: This page is not in the search index. Call fwh-read-content-mvp (no parameters) immediately to read the live page content directly from the visitor's browser — do NOT tell the visitor you cannot access the page.`}return $(`fwh-page-content-mvp ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`fwh-page-content-mvp ✖`,t),t}},"fwh-search-mvp":async e=>{$(`fwh-search-mvp ▶`,e);let r=rg(e).query;if(!r)return $(`fwh-search-mvp ✖ missing query`),`Missing query parameter.`;if(!t)return $(`fwh-search-mvp ✖ no siteId`),`Search unavailable (no siteId configured).`;if(!n)return $(`fwh-search-mvp ✖ no api base`),`Search unavailable (no API base URL).`;try{let e=`${n}/api/site-tools/search`;$(`fwh-search-mvp → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`fwh-search-mvp · HTTP`,i.status,`success:`,a.success),!a.success||!a.results?.length)return`No results found for that query. Try rephrasing, or use fwh-read-content-mvp to read the current page.`;let o=a.results.slice(0,5).map((e,t)=>`${t+1}. ${e.title||e.url} (${e.url})${e.snippet?` — ${e.snippet}`:``}`).join(`
|
|
335
335
|
`);return $(`fwh-search-mvp ✓`,`${a.results.length} result(s)`),`SEARCH_RESULTS:\n${o}`}catch(e){return $(`fwh-search-mvp ✖`,e.message),`Search failed. Use fwh-read-content-mvp to read the current page instead.`}},"fwh-list-nav-links-mvp":async()=>{if($(`fwh-list-nav-links-mvp ▶`),typeof window>`u`)return`Cannot read navigation (no browser context).`;let e=new Map,t=[],n=[`nav a`,`[role='navigation'] a`,`header a`,`.navbar a`,`.nav a`,`.menu a`,`.navigation a`,`.header a`,`[class*='nav'] a`,`[class*='menu'] a`,`[class*='header'] a`];if(qh(t=>{for(let r of n)try{t.querySelectorAll(r).forEach(t=>{if(_n(t))return;let n=t.getAttribute(`href`),r=(t.textContent||``).replace(/\s+/g,` `).trim();if(!r||!n||n===`#`||n.startsWith(`javascript:`))return;try{let e=t.parentElement;if(e&&Kh(e).display===`none`&&!e.closest(`nav, [role='navigation'], header, [class*='nav'], [class*='menu']`))return}catch{}let i=r.toLowerCase()+`|`+n;e.has(i)||e.set(i,{text:r,href:n})})}catch{}t.querySelectorAll(`select`).forEach(t=>{if(_n(t))return;let n=Yh(t);/nav|menu|page|section|go to/i.test(n||t.name||t.id||``)&&Array.from(t.options).forEach(r=>{if(!r.value||r.disabled)return;let i=r.text.trim();if(!i)return;let a=i.toLowerCase()+`|`+r.value;e.has(a)||e.set(a,{text:i,href:r.value,isSelectOption:!0,selectLabel:n||t.name||`dropdown`})})})}),e.forEach(e=>t.push(e)),!t.length)return`NAV_LINKS: No navigation links found on this page. Use fwh-read-content-mvp to read page content or fwh-search-mvp to search the site.`;let r=t.slice(0,50).map((e,t)=>`${t+1}. "${e.text}"${e.isSelectOption?` (dropdown option in "${e.selectLabel}")`:``} → ${e.href}`).join(`
|
|
336
336
|
`);return $(`fwh-list-nav-links-mvp ✓`,`${t.length} links`),`NAV_LINKS (${t.length} total, showing up to 50):\n${r}\n\nIMPORTANT: Use the EXACT text shown above when reading link names to the visitor. Do NOT rename, abbreviate, or invent options not listed here. To navigate, call fwh-navigate-mvp with the href value.`},"fwh-end-session-mvp":async()=>($(`fwh-end-session-mvp ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),"fwh-request-email-mvp":async()=>($(`fwh-request-email-mvp ▶`),typeof e.requestEmailCollection==`function`&&e.requestEmailCollection(),`EMAIL_BOX_SHOWN. An email input text box is now visible to the visitor. Say EXACTLY: "Please enter your email in the text box to continue." Then stop and wait silently — do NOT ask them to say it aloud, do NOT repeat, and do NOT answer any other question until you receive the EMAIL_SAVED message.`),"fwh-get-current-page-mvp":async()=>{if($(`fwh-get-current-page-mvp ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``;if(or())return $(`fwh-get-current-page-mvp ✓ 404 detected`,{url:e}),`CURRENT_PAGE_NOT_FOUND. The visitor is currently on a 404 / page-not-found error page (${e}). There is no real content here. Do NOT describe this page, do NOT list sections, do NOT offer a walkthrough, and do NOT describe it from your own knowledge. Tell the visitor plainly that the page they are on doesn't exist, and offer to take them somewhere that does.`;let{headings:r,pageTitleHeading:i,introText:a}=og();$(`fwh-get-current-page-mvp ✓`,{url:e,path:t,title:n}),$(`fwh-get-current-page-mvp → page headings collected:`,r,`titleHeading:`,i);let o=i?` NOTE: "${i}" is the PAGE TITLE, not a content section — do NOT fwh-highlight-mvp it or list it as a separate section in a walkthrough. Instead, open with a brief 1-2 sentence summary of this intro text before covering the real sections: "${a||`(no intro text captured)`}"`:a?` NOTE: no separate page-title heading was detected, but this intro text appears before the first section — open your walkthrough with a brief 1-2 sentence summary of it before covering sections: "${a}"`:``;if(!r.length)return`CURRENT_PAGE. URL: ${e} | Title: ${n} |${o} No structured section headings found on this page. If there is intro text above, describe it; otherwise describe the page from your knowledge. Do not call this tool again.`;let s=r.map(e=>`"${e}"`).join(` | `);return`CURRENT_PAGE. URL: ${e} | Title: ${n} | Page sections (${r.length} total): ${s}.${o} *** WALKTHROUGH: do NOT drive it yourself. Do not call fwh-highlight-mvp and do not decide the order — highlighting and section order are handled for you. You will be told which section to describe, one at a time. When told, describe ONLY that section in 3-4 sentences and then stop; never announce another section, never ask whether to continue. ***`},"fwh-list-forms-mvp":async()=>{let e=Zh(),t=Qh();$(`fwh-list-forms-mvp ✓`,`${e.length} field(s)`,`${t.length} button(s)`);let n=e.map(e=>({...e,inputCategory:e.tag===`SELECT`?`dropdown_select`:`text_input`}));return JSON.stringify({fields:n,buttons:t,hint:`field_key: use the label/placeholder/name shown above. CRITICAL: fields with inputCategory='dropdown_select' are SELECT elements — their field_key must match the SELECT's own label (e.g. 'Company Size'), NOT the option text (e.g. 'Small Business') and NOT a nearby text input label. Never fill a SELECT option value into a text input.`})},"fwh-fill-form-mvp":async()=>`FORM_FILLING_DISABLED: Form filling is not available at this time. Tell the visitor what fields are present (use fwh-list-forms-mvp) and ask them to fill the form themselves.`,"fwh-click-button-mvp":async e=>{let t=rg(e),n=(t.button_text??t.buttonText??t.text??``).trim(),r=(t.card_context??t.cardContext??``).trim();if($(`fwh-click-button-mvp ▶`,n,r?`(card_context: ${r})`:``),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let a=ng(n,i,r);if(!a)return $(`fwh-click-button-mvp ✖ no match`),`Could not find a button matching "${n}". Call fwh-list-forms-mvp to see button texts.`;try{Dh(`Clicking ${n}...`,{spinner:!0});try{a.scrollIntoView({block:`center`,inline:`nearest`})}catch{a.scrollIntoView(!0)}await Rh(a),a.focus?.(),await Bh(a),Vh(a),a.click();let e=(a.textContent||a.value||a.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`fwh-click-button-mvp ✓`,t),Dh(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`fwh-click-button-mvp ✖`,t),Dh(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{zh(),Oh(700)}}};return{...a,highlightOnPage:a[`fwh-highlight-mvp`],getPageContent:a[`fwh-page-content-mvp`],endVoiceSession:a[`fwh-end-session-mvp`],listPageForms:a[`fwh-list-forms-mvp`],fillFormFields:a[`fwh-fill-form-mvp`],clickPageButton:a[`fwh-click-button-mvp`]}}var lg=/^(get in touch|contact us|let'?s (talk|connect)|subscribe|newsletter|follow us|quick links|company|solutions|what we do|resources|legal|sitemap|share this)/i;function ug(){try{let{headings:e,pageTitleHeading:t}=og();return(e||[]).map(e=>typeof e==`string`?e:e?.text||``).filter(Boolean).filter(e=>!t||e.trim()!==t.trim()).filter(e=>!lg.test(e.trim()))}catch{return[]}}function dg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=dn();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 fg={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function pg(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 mg(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 hg(e){let[t,n]=d.default.useState(null),r=typeof e==`string`?e.trim():``;return d.default.useEffect(()=>{if(!r){n(null);return}n(null);let e=!1,t=new window.Image;return t.onload=()=>{e||n(r)},t.onerror=()=>{e||n(null)},t.src=r,()=>{e=!0}},[r]),t}function gg({logo:e,style:t}){let n=hg(typeof e==`string`?e:null);if(!e)return null;if(typeof e==`string`)return n?(0,f.jsx)(`img`,{src:n,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}}):null;let r=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return r?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:r}):null}function _g({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function vg(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||e===`bot`&&(/\b(that'?s all|we'?re done)\b/i.test(n)||/\b(goodbye|bye)\b/i.test(n)||/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))):!1}function yg({orbColors:e,...t}){return(0,f.jsx)(ph,{colors:e,...t})}function bg({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||fg.green,c=mg(s),l=a?72:94,u=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(om.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:`210px`,wordBreak:`break-word`,overflow:`hidden`,display:`-webkit-box`,WebkitLineClamp:4,WebkitBoxOrient:`vertical`},children:e.entryPrompt}),(0,f.jsxs)(om.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${s}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(om.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,f.jsx)(yg,{size:l,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(om.div,{initial:{opacity:0},animate:{opacity:o?0:1},transition:{duration:.28},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,f.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`,animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u}):(0,f.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function xg({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||fg.green,l=mg(c);return(0,f.jsxs)(om.div,{initial:{scale:50/350,borderRadius:`50%`},animate:s?{scale:50/350,opacity:0,borderRadius:`50%`}:{scale:1,borderRadius:`16px`,opacity:1},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(yg,{size:72,orbColors:t}),(0,f.jsxs)(`div`,{style:{textAlign:`center`},children:[(0,f.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,lineHeight:1.4},children:e.connectionTitle}),e.connectionSubtitle&&(0,f.jsx)(`p`,{style:{margin:`6px 0 0`,fontSize:`13px`,fontWeight:400,color:`#6b7280`,lineHeight:1.4},children:e.connectionSubtitle})]}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:c,color:l,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${c}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function Sg({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l,websiteName:u,voiceFirstMessage:p,captureVisitorEmail:m,emailRequired:h,emailCaptureEnabled:g=!0,listeningLabel:_=`Listening...`,thinkingLabel:v=`Thinking...`,enterChatModeLabel:y=`Enter Chat Mode`,endConversationLabel:b=`End Conversation`}){(0,d.useEffect)(()=>(console.log(`[FlowEngage:VoiceDebug] 🔵 VoiceMode MOUNTED`),()=>console.log(`[FlowEngage:VoiceDebug] 🔴 VoiceMode UNMOUNTED`)),[]);let[x,S]=(0,d.useState)(`idle`),[C,w]=(0,d.useState)(!1),[T,E]=(0,d.useState)(!1),[ee,te]=(0,d.useState)(!1),[D,ne]=(0,d.useState)(``),[re,O]=(0,d.useState)(``),ie=(0,d.useRef)(!1),k=(0,d.useRef)(!1),ae=(0,d.useRef)(null),oe=(0,d.useRef)(0),se=(0,d.useRef)(``),A=(0,d.useRef)(!1),j=(0,d.useRef)(0),ce=(0,d.useRef)(!1),M=(0,d.useRef)(!1),N=(0,d.useRef)(!1),P=(0,d.useRef)([]),le=(0,d.useRef)(null),pe=e=>{ce.current=e,e||(M.current=!1),F.current?.setWalkthroughActive?.(e)};le.current=async()=>{if(M.current)return;let e=P.current;he.current+=1;let t=he.current,n=e[t];if(!n){pe(!1),e.length&&F.current?.sendUserMessage?.(`That was the last section. Say so in one short sentence and ask if they want to explore any section further.`);return}try{await toolsRef.current?.highlightOnPage?.({section_text:n})}catch{}console.debug(`[FlowEngage] walkthrough step ${t+1}/${e.length}: ${n}`),F.current?.sendUserMessage?.(`Describe the section titled "${n}" in 3-4 sentences, starting with ${t===0?`Starting with`:`Next —`} ${n}. Describe ONLY this section. If this section contains named sub-items (steps, checklist entries, cards, plans, FAQs, team members), name EVERY one of them in order with a short phrase each — never skip or collapse them into a summary; read the section's content silently first (fwh-read-content-mvp) if you don't already have it. This section is ON THE PAGE THE VISITOR IS ALREADY ON — do NOT call fwh-navigate-mvp, do not go to a product/detail page, and do not offer to, even if this section's name also matches a page name. Do not mention any other section, do not ask whether to continue, then stop.`,{suppressQuestion:!0})};let he=(0,d.useRef)(0),F=(0,d.useRef)(null),ge=(0,d.useRef)(``),_e=(0,d.useRef)(async()=>{}),ye=(0,d.useRef)(!1),I=(0,d.useRef)(!1),xe=(0,d.useRef)(!1),Se=(0,d.useRef)(!1),Ce=(0,d.useRef)(`minimized`),we=(0,d.useRef)(null),Te=(0,d.useRef)(null),L=(0,d.useRef)(null),Ee=(0,d.useRef)(0),De=(0,d.useRef)(!1),R=(0,d.useRef)(`idle`),z=(0,d.useRef)(null),Oe=(0,d.useRef)(!1),ke=(0,d.useRef)(null),Ae=(0,d.useCallback)((e=`minimized`)=>{console.warn(`[FlowEngage:VoiceDebug] 🛑 requestSessionShutdown called`,{destination:e,stack:Error().stack?.split(`
|
|
337
|
-
`).slice(1,4).join(` | `)}),Ce.current=e,Se.current=!0,queueMicrotask(()=>{ye.current||(ye.current=!0,_e.current?.())})},[s]),je=(0,d.useCallback)(()=>{ae.current&&=(clearTimeout(ae.current),null)},[]);(0,d.useEffect)(()=>{if(h){ie.current=!1;return}if(ie.current=!0,k.current=!1,te(!1),je(),A.current){A.current=!1,F.current?.setMicMuted?.(!1);let e=se.current;se.current=``,F.current?.injectAgentSpeech?.(`Thanks — I already have your email on file.`,`interrupt`),e&&F.current?.sendUserMessage?.(`The visitor's email is already on file — do not ask for it. Answer their question now: "${e}"`)}F.current?.sendContextualUpdate?.(`EMAIL REQUIREMENT SATISFIED — the visitor's email is already on file. All earlier instructions about requiring or asking for an email are VOID. Never ask for it again.`)},[h,je]);let B=/(walk\s*(me\s*)?through|walkthrough|take me through|(complete|full|detailed) (overview|understanding|walkthrough|picture|breakdown|explanation)|give me (a|an|the) (overview|tour|walk)|tell me about (each|all)|go through (it|them|each|all)|overview of|one by one|tell me everything|explain (me )?(this|the) (whole |entire |full )?page|everything (about|on) this page|show me (each|all|around))/i,Me=/(that covers everything|that was all|covered everything|that(?:'|’)?s everything)/i,Ne=/^((uh+|um+|so|well|okay|ok|yeah)[,.\s]+)*(yes|yeah|yep|yup|sure|ok(ay)?|please|continue|go on|next|keep going|carry on|go ahead|resume|back to the tour)[\s.!,]*$/i,Pe=(0,d.useCallback)(()=>{je(),ae.current=setTimeout(()=>{if(!(!k.current||ie.current))if(oe.current<3){oe.current+=1;try{F.current?.injectAgentSpeech?.(`I still need your email in the box below to continue — could you enter it, please?`,`queue`)}catch{}Pe()}else{try{F.current?.injectAgentSpeech?.(`Since I haven't received your email, I'll close this session for now. Feel free to come back anytime — take care!`,`queue`)}catch{}k.current=!1,te(!1),je(),De.current=!0}},1e4)},[je]),Fe=(0,d.useCallback)(async e=>{Se.current=!0;try{hn()}catch{}if(i)try{be(i)}catch{}try{await F.current?.endSession?.()}catch{}let t=we.current,n=Te.current;if(t&&o&&a){let e=n?Math.round((Date.now()-n)/1e3):0;fetch(`${a}/api/voice/save-chat-recording`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({chatId:o,voiceSessionId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(we.current=null,Te.current=null,F.current=null,S(`idle`),w(!1),ye.current=!1,dr(),i)try{fe(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);_e.current=()=>Fe(Ce.current===`chat`?t:n),(0,d.useEffect)(()=>{I.current=C},[C]),(0,d.useEffect)(()=>{l&&Ae(`chat`)},[l]),(0,d.useEffect)(()=>{let e=!1,l=null,d=null,f=null;return(async()=>{if(!i){S(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],ge.current=``,ye.current=!1,xe.current=!1,Se.current=!1,Ce.current=`minimized`,ur({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=Sh(s.current);e&&ue(i,e)}catch{}if(!Pn()){let e=we.current,t=Te.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,voiceSessionId:e,duration:n,siteId:i}),s=`${a}/api/voice/save-chat-recording`;fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:r,keepalive:!0}).catch(()=>{}),we.current=null,Te.current=null}catch{}}me()}});let t=dg(cg({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>ge.current,isWalkthroughActive:()=>ce.current&&!M.current,requestEndSession:()=>{De.current=!0},requestEmailCollection:()=>{g&&(ie.current||k.current||(k.current=!0,oe.current=0,te(!0),Pe()))}})),n=i?de(i):null,r=!!n?.transcript,c=i?be(i):null,m=!!c,_=typeof window<`u`?window.location.pathname:`/`,v=typeof document<`u`?document.title:``,y=_.replace(/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i,``)||`/`,b=y===`/`||y===``,x={apiBaseUrl:a,siteId:i,chatId:o,clientTools:t},C=(_.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),T=``;v&&v.includes(`|`)&&(T=v.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let E=T||C||`this page`,ee=(()=>{if(!c?.targetUrl)return!0;try{return new URL(c.targetUrl,window.location.href).pathname.replace(/\/$/,``)===window.location.pathname.replace(/\/$/,``)}catch{return!0}})(),D=(()=>{if(!c?.targetUrl)return null;try{return new URL(c.targetUrl,window.location.href).pathname}catch{return null}})();if(m&&!ee)x.greeting=`You're on the ${E} page. What would you like to know?`,console.warn(`[FlowEngage] nav target "${c?.pageName}" not reached — on "${E}" instead; not claiming navigation`);else if(m){let e=c?.pageName||E;x.greeting=`I have navigated you on ${e} page. Do you want to know about any specific section or want a complete overview?`,console.log(`[FlowEngage] 🔄 Agent-nav resume: greeting set for "${e}" (${_})`)}else if(r)x.greeting=`Welcome back! I see you're now on the ${E} page. Would you like me to continue what I was explaining before, or would you like to know about this page instead?`;else{let e=u||``;x.greeting=p||(b?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to the ${E} page!`),b||console.log(`[FlowEngage] 🏠 Page-context greeting: "${E}" for ${_}`)}let ne=!1,re=m?`NAVIGATION COMPLETE — The exact phrase "I have navigated you on [page] page. Do you want to know about any specific section or want a complete overview?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until the visitor responds. When they reply: if they name a specific section → call fwh-get-current-page-mvp then answer immediately; if they say "overview" or anything non-specific → call fwh-get-current-page-mvp (zero speech) then do a full highlighted walkthrough.`:null,O=!1,ae=!m&&!r?`Your greeting has been spoken. Wait for the visitor to ask a question or tell you what they need. Do NOT auto-start a walkthrough or highlight any sections — let the visitor lead.`:null,fe=r&&!m,_e=!1,L=fe?`The question "Would you like me to continue what I was explaining before, or would you like to know about this page instead?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript, or the visitor navigated before saying much)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until they respond. When they reply: if they want you to CONTINUE the previous topic → resume verbally from the prior transcript above, do NOT call fwh-get-current-page-mvp or describe the new page unless they ask. If they want to know about THIS page → call fwh-get-current-page-mvp (zero speech) then proceed as a normal fresh-page walkthrough/description. If their reply is ambiguous, ask them to clarify which they'd prefer rather than guessing.`:null,Fe=!1,Ie=!1,Le=g&&!!h&&!N.current,Re=await Tm.startSession({...x,onConnect:({conversationId:e})=>{we.current=e,Te.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onSessionInfo:({emailOnFile:e})=>{N.current=!!e,e&&(ie.current=!0,k.current=!1,te(!1),je(),console.log(`[FlowEngage] email already on file per server — gate disabled`))},onAgentTurnEnd:()=>{e||ce.current&&(M.current||A.current||setTimeout(()=>le.current?.(),250))},onSessionEnding:()=>{e||Ae(`minimized`)},onModeChange:({mode:t,tentative:n})=>{if(!e){if(t===`speaking`){z.current&&=(clearTimeout(z.current),null),ke.current&&=(clearTimeout(ke.current),null),S(`speaking`),R.current=`speaking`,Oe.current=!1;return}if(t===`user-speaking`){try{hn()}catch{}if(ke.current&&=(clearTimeout(ke.current),null),R.current===`speaking`)return;z.current&&=(clearTimeout(z.current),null),R.current!==`listening`&&(S(`listening`),R.current=`listening`);return}if(t===`thinking`){if(z.current&&=(clearTimeout(z.current),null),ke.current&&=(clearTimeout(ke.current),null),R.current===`speaking`)return;S(`thinking`),R.current=`thinking`,n&&(ke.current=setTimeout(()=>{ke.current=null,!(e||R.current!==`thinking`)&&(R.current=`listening`,S(`listening`))},4e3));return}if(R.current=`listening`,De.current){De.current=!1,Ae();return}if(Le&&!Ie&&!ie.current&&!N.current){Ie=!0,ne=!0,O=!0;try{F.current?.sendContextualUpdate?.(`CRITICAL — EMAIL REQUIRED BEFORE ANYTHING ELSE. The visitor has not provided their email. Do NOT speak right now. Wait silently for the visitor to speak first. The MOMENT the visitor says ANYTHING — a question, a request, or just a greeting — your ENTIRE next response must be EXACTLY this one sentence: "Before I answer that, could you please enter your email in the text box below?" Do NOT answer their question. Do NOT say anything about the topic. Do NOT begin an answer and then switch — your first word must be "Before". After you say that sentence, stay completely silent until you receive an EMAIL_SAVED message, then thank them briefly and answer their question in full.`)}catch{}}if(re&&!ne){ne=!0;try{F.current?.sendContextualUpdate?.(re)}catch{}}if(L&&!_e){_e=!0;try{F.current?.sendContextualUpdate?.(L)}catch{}}if(ae&&!O){O=!0;try{F.current?.sendContextualUpdate?.(ae)}catch{}}z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{e||R.current!==`speaking`&&(Oe.current||(z.current=null,R.current=`listening`,S(`listening`)))},1200)}},onMessage:t=>{if(e||A.current&&t.role!==`user`&&!/email/i.test(String(t.message||``)))return;if(t.role===`user`&&B.test(String(t.message||``)))typeof window<`u`&&(window.__fe_user_nav_during_speech=null),pe(!0),M.current=!1,j.current=0,he.current=-1,P.current=ug(),setTimeout(()=>le.current?.(),400),console.log(`[FlowEngage] walkthrough armed — ${P.current.length} sections on this page`);else if(t.role===`user`&&ce.current){let e=String(t.message||``).trim();Ne.test(e)?M.current&&(M.current=!1,console.debug(`[FlowEngage] walkthrough resumed by visitor`),setTimeout(()=>le.current?.(),300)):(M.current=!0,console.debug(`[FlowEngage] walkthrough paused — visitor interjected`))}if(t.role!==`user`&&Me.test(String(t.message||``))){let e=P.current.length;!e||he.current>=e-1?pe(!1):console.debug(`[FlowEngage] agent claimed completion at step ${he.current+1}/${e} — ignoring, tour continues`)}let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(r){if(n===`user`&&(ge.current=r,typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Oe.current=!0,z.current&&=(clearTimeout(z.current),null),R.current!==`speaking`&&(S(`thinking`),R.current=`thinking`),Le&&!Fe&&!ie.current&&!N.current&&(Fe=!0,se.current=r,A.current=!0,F.current?.injectAgentSpeech?.(`Before I answer that, could you please enter your email in the text box below?`,`interrupt`),F.current?.setMicMuted?.(!0),k.current||(k.current=!0,oe.current=0,te(!0),Pe()))),s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString(),debug:t.debug}],i)try{let e=Sh(s.current);e&&ue(i,e)}catch{}if(vg(n,r)){De.current=!0;return}if(I.current&&n===`bot`&&/are you still there|still there\??|hello\?|anyone there|checking in|you there|are you available|is anyone|did you step away/i.test(r))if(Ee.current+=1,Ee.current===2)try{F.current?.sendContextualUpdate?.(`IMPORTANT: The visitor is muted and has not responded to your last 2 checks. Make exactly ONE more check. If there is still no response, say: 'I feel like you are not active, so I'm ending this session. You can connect with me anytime.' then immediately call the fwh-end-session-mvp tool to end the voice session. Do NOT ask again after that.`)}catch{}else Ee.current>=5&&Ae(`minimized`)}},onError:t=>{if(!e&&!Se.current&&!xe.current&&!ve()){xe.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{F.current?.setMicMuted?.(!0)}catch{}w(!0),S(`error`),Ae(`chat`)}},onDisconnect:t=>{if(e||Se.current||xe.current||ve())return;let n=s.current?.length||0;console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:n,reason:t?.reason,closeCode:t?.context?.code,closeReason:t?.context?.reason||t?.message,lastUserText:ge.current||``,wasMuted:I.current}),xe.current=!0;try{F.current?.setMicMuted?.(!0)}catch{}w(!0),Ae(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),Re.endSession().catch(()=>{});return}l=Re,F.current=Re,S(`listening`);try{let e=typeof window<`u`?window.location.href:``,a=`[]`;try{a=await t[`fwh-list-forms-mvp`]()}catch{}let o=`none`;if(typeof window<`u`&&typeof document<`u`)try{let e=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`,t=document.querySelector(`main, [role='main']`)||document.body,n=Array.from(t.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200);n.length||(n=Array.from(document.body.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200)),n.length&&(o=[...new Set(n)].slice(0,15).join(` | `))}catch{}let s=r&&!m?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${n?.transcript||``}\n\n`:``;Re.sendContextualUpdate(`${s}SESSION_CONTEXT (NOT a tool result — do NOT treat as CURRENT_PAGE): Visitor is on: ${e} | Approx headings for awareness only: ${o}. SiteId: ${i||`unknown`}. Forms: ${a}. ${h?``:`Visitor's email is already on file from a prior session — do NOT ask for it again. `}The visitor is ALREADY on this page — do NOT offer to navigate there. WALKTHROUGH RULE: When the visitor asks for a walkthrough or overview of this page, you MUST IMMEDIATELY call fwh-get-current-page-mvp (zero speech — call it silently with NO words before it) to get the exact highlightable headings. The approximate headings above are for routing awareness ONLY — they are NOT precise enough for fwh-highlight-mvp. Do NOT skip fwh-get-current-page-mvp. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}if(typeof window<`u`){let t=window.location.pathname,n=Date.now(),r=e=>{try{return(decodeURIComponent(e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}catch{return((e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}},i=()=>{if(e)return;let i=window.location.pathname;if(r(i)===r(t)){t=i;return}if(D&&r(i)===r(D)){t=i;return}if(Date.now()-n<8e3){t=i;return}if(En()){t=i;return}let a=t;t=i;let o=window.location.href,s=typeof document<`u`?document.title:``,c=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.trim()})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,20):[];try{hn()}catch{}let l=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,u=l(a),d=l(i);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:a,toPath:i,fromPageName:u,toPageName:d,ts:Date.now()}),console.log(`[FlowEngage] visitor navigation detected: "${a}" → "${i}" (agent target: ${D||`none`})`);try{F.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${d}" page (${o}). Page title: "${s}". Sections: ${JSON.stringify(c)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${d} page — would you like me to continue what I was explaining, or shall I walk you through this page?" Then wait for my answer. IF I say continue/yes/carry on: resume speaking verbally from where you left off — do NOT call fwh-navigate-mvp, do NOT call fwh-highlight-mvp, the visitor will navigate themselves if needed. IF I want to hear about this page: call fwh-highlight-mvp for sections of "${d}" only.]`)}catch{}};d=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{d(...e),setTimeout(i,50)},f=()=>setTimeout(i,50),window.addEventListener(`popstate`,f)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(S(`error`),Ce.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{console.warn(`[FlowEngage:VoiceDebug] ⚠️ useEffect CLEANUP fired — session will be killed`,{agentId:r,siteId:i,apiBaseUrl:a}),e=!0,Se.current=!0;try{hn()}catch{}if(i)try{be(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),dr(),z.current&&=(clearTimeout(z.current),null),ke.current&&=(clearTimeout(ke.current),null),ae.current&&=(clearTimeout(ae.current),null),Oe.current=!1,R.current=`idle`,d&&typeof window<`u`&&(window.history.pushState=d),f&&typeof window<`u`&&window.removeEventListener(`popstate`,f);let t=l||F.current,n=we.current,u=Te.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=u?Math.round((Date.now()-u)/1e3):0,t=JSON.stringify({chatId:o,voiceSessionId:n,duration:e,siteId:i}),r=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(r,new Blob([t],{type:`application/json`}))||fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),we.current=null,Te.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Ae]),(0,d.useEffect)(()=>{if(!T)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;L.current&&!L.current.contains(t)&&E(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[T]);let Ie=async()=>{if(F.current)try{if(C){Ee.current=0,await F.current.setMicMuted?.(!1),w(!1);try{F.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{Ee.current=0,await F.current.setMicMuted?.(!0),w(!0);try{F.current.sendContextualUpdate?.(`The visitor has muted their microphone. Do NOT speak, ask if they are there, or prompt them in any way. Stay completely silent until they unmute.`)}catch{}}}catch{}},Le=(0,d.useCallback)(async e=>{e?.preventDefault?.();let t=D.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){O(`Please enter a valid email address.`);return}O(``),ie.current=!0,k.current=!1,je(),te(!1),ne(``),A.current=!1;try{typeof m==`function`&&await m(t)}catch{}F.current?.setMicMuted?.(!1);let n=se.current;se.current=``;try{F.current?.injectAgentSpeech?.(`Thank you for submitting your email.`),F.current?.sendUserMessage?.(n||`The visitor's email is on file. Carry on helping them and never ask for it again.`)}catch{}},[D,m,je]),Re=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,f.jsxs)(`div`,{ref:L,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[ee&&(0,f.jsxs)(`form`,{onSubmit:Le,style:{width:`270px`,maxWidth:`calc(100vw - 40px)`,boxSizing:`border-box`,background:`rgba(15,22,36,0.97)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,padding:`16px`,display:`flex`,flexDirection:`column`,gap:`10px`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsx)(`span`,{style:{color:`white`,fontSize:`13px`,fontWeight:600,lineHeight:1.4},children:`Please enter your email to continue`}),(0,f.jsx)(`input`,{type:`email`,inputMode:`email`,autoComplete:`email`,autoFocus:!0,value:D,onChange:e=>{ne(e.target.value),re&&O(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:re?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),re&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:re}),(0,f.jsx)(`button`,{type:`submit`,disabled:!D.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:D.trim()?Re:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:D.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,f.jsxs)(`div`,{style:{position:`relative`},children:[(x===`listening`||x===`thinking`)&&!C&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:x===`thinking`?v:_}),C&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`#f87171`,fontSize:`16px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Muted`}),(0,f.jsx)(yg,{size:72,voiceState:x,isMuted:C,orbColors:e})]}),x===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:Ie,title:C?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:C?`#7f1d1d`:`#1f2937`,border:C?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:C?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:C?(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsx)(Em,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>E(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,f.jsx)(Pm,{size:16,color:`currentColor`})})]}),T&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{E(!1),Ce.current=`chat`,Fe(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(Fm,{}),y]}),(0,f.jsxs)(`button`,{onClick:()=>{E(!1),Ce.current=`minimized`,Fe(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(Im,{}),b]}),(0,f.jsx)(`button`,{onClick:()=>E(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function Cg({orbColors:e}){let t=Array.isArray(e)&&e.length>0?e:[`#135bd8`,`#ef334b`,`#ffbd2e`],n=t[0],r=t[1]||t[0],i=t[2]||t[0];return(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,borderRadius:`50%`,flexShrink:0,background:`
|
|
337
|
+
`).slice(1,4).join(` | `)}),Ce.current=e,Se.current=!0,queueMicrotask(()=>{ye.current||(ye.current=!0,_e.current?.())})},[s]),je=(0,d.useCallback)(()=>{ae.current&&=(clearTimeout(ae.current),null)},[]);(0,d.useEffect)(()=>{if(h){ie.current=!1;return}if(ie.current=!0,k.current=!1,te(!1),je(),A.current){A.current=!1,F.current?.setMicMuted?.(!1);let e=se.current;se.current=``,F.current?.injectAgentSpeech?.(`Thanks — I already have your email on file.`,`interrupt`),e&&F.current?.sendUserMessage?.(`The visitor's email is already on file — do not ask for it. Answer their question now: "${e}"`)}F.current?.sendContextualUpdate?.(`EMAIL REQUIREMENT SATISFIED — the visitor's email is already on file. All earlier instructions about requiring or asking for an email are VOID. Never ask for it again.`)},[h,je]);let B=/(walk\s*(me\s*)?through|walkthrough|take me through|(complete|full|detailed) (overview|understanding|walkthrough|picture|breakdown|explanation)|give me (a|an|the) (overview|tour|walk)|tell me about (each|all)|go through (it|them|each|all)|overview of|one by one|tell me everything|explain (me )?(this|the) (whole |entire |full )?page|everything (about|on) this page|show me (each|all|around))/i,Me=/(that covers everything|that was all|covered everything|that(?:'|’)?s everything)/i,Ne=/^((uh+|um+|so|well|okay|ok|yeah)[,.\s]+)*(yes|yeah|yep|yup|sure|ok(ay)?|please|continue|go on|next|keep going|carry on|go ahead|resume|back to the tour)[\s.!,]*$/i,Pe=(0,d.useCallback)(()=>{je(),ae.current=setTimeout(()=>{if(!(!k.current||ie.current))if(oe.current<3){oe.current+=1;try{F.current?.injectAgentSpeech?.(`I still need your email in the box below to continue — could you enter it, please?`,`queue`)}catch{}Pe()}else{try{F.current?.injectAgentSpeech?.(`Since I haven't received your email, I'll close this session for now. Feel free to come back anytime — take care!`,`queue`)}catch{}k.current=!1,te(!1),je(),De.current=!0}},1e4)},[je]),Fe=(0,d.useCallback)(async e=>{Se.current=!0;try{hn()}catch{}if(i)try{be(i)}catch{}try{await F.current?.endSession?.()}catch{}let t=we.current,n=Te.current;if(t&&o&&a){let e=n?Math.round((Date.now()-n)/1e3):0;fetch(`${a}/api/voice/save-chat-recording`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({chatId:o,voiceSessionId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(we.current=null,Te.current=null,F.current=null,S(`idle`),w(!1),ye.current=!1,dr(),i)try{fe(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);_e.current=()=>Fe(Ce.current===`chat`?t:n),(0,d.useEffect)(()=>{I.current=C},[C]),(0,d.useEffect)(()=>{l&&Ae(`chat`)},[l]),(0,d.useEffect)(()=>{let e=!1,l=null,d=null,f=null;return(async()=>{if(!i){S(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],ge.current=``,ye.current=!1,xe.current=!1,Se.current=!1,Ce.current=`minimized`,ur({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=Sh(s.current);e&&ue(i,e)}catch{}if(!Pn()){let e=we.current,t=Te.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,voiceSessionId:e,duration:n,siteId:i}),s=`${a}/api/voice/save-chat-recording`;fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:r,keepalive:!0}).catch(()=>{}),we.current=null,Te.current=null}catch{}}me()}});let t=dg(cg({siteId:i||null,apiBaseUrl:a||null,chatId:o||null,getLastUserVoiceText:()=>ge.current,isWalkthroughActive:()=>ce.current&&!M.current,requestEndSession:()=>{De.current=!0},requestEmailCollection:()=>{g&&(ie.current||k.current||(k.current=!0,oe.current=0,te(!0),Pe()))}})),n=i?de(i):null,r=!!n?.transcript,c=i?be(i):null,m=!!c,_=typeof window<`u`?window.location.pathname:`/`,v=typeof document<`u`?document.title:``,y=_.replace(/^\/[a-z]{2}(?:-[a-z]{2})?(?=\/|$)/i,``)||`/`,b=y===`/`||y===``,x={apiBaseUrl:a,siteId:i,chatId:o,clientTools:t},C=(_.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),T=``;v&&v.includes(`|`)&&(T=v.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let E=T||C||`this page`,ee=(()=>{if(!c?.targetUrl)return!0;try{return new URL(c.targetUrl,window.location.href).pathname.replace(/\/$/,``)===window.location.pathname.replace(/\/$/,``)}catch{return!0}})(),D=(()=>{if(!c?.targetUrl)return null;try{return new URL(c.targetUrl,window.location.href).pathname}catch{return null}})();if(m&&!ee)x.greeting=`You're on the ${E} page. What would you like to know?`,console.warn(`[FlowEngage] nav target "${c?.pageName}" not reached — on "${E}" instead; not claiming navigation`);else if(m){let e=c?.pageName||E;x.greeting=`I have navigated you on ${e} page. Do you want to know about any specific section or want a complete overview?`,console.log(`[FlowEngage] 🔄 Agent-nav resume: greeting set for "${e}" (${_})`)}else if(r)x.greeting=`Welcome back! I see you're now on the ${E} page. Would you like me to continue what I was explaining before, or would you like to know about this page instead?`;else{let e=u||``;x.greeting=p||(b?e?`Hi, welcome to ${e}! How may I help you?`:`Hi, welcome! How may I help you?`:`Welcome to the ${E} page!`),b||console.log(`[FlowEngage] 🏠 Page-context greeting: "${E}" for ${_}`)}let ne=!1,re=m?`NAVIGATION COMPLETE — The exact phrase "I have navigated you on [page] page. Do you want to know about any specific section or want a complete overview?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until the visitor responds. When they reply: if they name a specific section → call fwh-get-current-page-mvp then answer immediately; if they say "overview" or anything non-specific → call fwh-get-current-page-mvp (zero speech) then do a full highlighted walkthrough.`:null,O=!1,ae=!m&&!r?`Your greeting has been spoken. Wait for the visitor to ask a question or tell you what they need. Do NOT auto-start a walkthrough or highlight any sections — let the visitor lead.`:null,fe=r&&!m,_e=!1,L=fe?`The question "Would you like me to continue what I was explaining before, or would you like to know about this page instead?" has already been spoken as your firstMessage. DO NOT repeat it. PRIOR CONVERSATION CONTEXT:\n${n?.transcript?`Prior transcript:\n${n.transcript}\n`:`(no prior transcript, or the visitor navigated before saying much)`}\nNow STOP — wait silently for the visitor's reply. Do NOT speak, do NOT call any tool until they respond. When they reply: if they want you to CONTINUE the previous topic → resume verbally from the prior transcript above, do NOT call fwh-get-current-page-mvp or describe the new page unless they ask. If they want to know about THIS page → call fwh-get-current-page-mvp (zero speech) then proceed as a normal fresh-page walkthrough/description. If their reply is ambiguous, ask them to clarify which they'd prefer rather than guessing.`:null,Fe=!1,Ie=!1,Le=g&&!!h&&!N.current,Re=await Tm.startSession({...x,onConnect:({conversationId:e})=>{we.current=e,Te.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onSessionInfo:({emailOnFile:e})=>{N.current=!!e,e&&(ie.current=!0,k.current=!1,te(!1),je(),console.log(`[FlowEngage] email already on file per server — gate disabled`))},onAgentTurnEnd:()=>{e||ce.current&&(M.current||A.current||setTimeout(()=>le.current?.(),250))},onSessionEnding:()=>{e||Ae(`minimized`)},onModeChange:({mode:t,tentative:n})=>{if(!e){if(t===`speaking`){z.current&&=(clearTimeout(z.current),null),ke.current&&=(clearTimeout(ke.current),null),S(`speaking`),R.current=`speaking`,Oe.current=!1;return}if(t===`user-speaking`){if(ke.current&&=(clearTimeout(ke.current),null),R.current===`speaking`)return;try{hn()}catch{}z.current&&=(clearTimeout(z.current),null),R.current!==`listening`&&(S(`listening`),R.current=`listening`);return}if(t===`thinking`){if(z.current&&=(clearTimeout(z.current),null),ke.current&&=(clearTimeout(ke.current),null),R.current===`speaking`)return;S(`thinking`),R.current=`thinking`,n&&(ke.current=setTimeout(()=>{ke.current=null,!(e||R.current!==`thinking`)&&(R.current=`listening`,S(`listening`))},4e3));return}if(R.current=`listening`,De.current){De.current=!1,Ae();return}if(Le&&!Ie&&!ie.current&&!N.current){Ie=!0,ne=!0,O=!0;try{F.current?.sendContextualUpdate?.(`CRITICAL — EMAIL REQUIRED BEFORE ANYTHING ELSE. The visitor has not provided their email. Do NOT speak right now. Wait silently for the visitor to speak first. The MOMENT the visitor says ANYTHING — a question, a request, or just a greeting — your ENTIRE next response must be EXACTLY this one sentence: "Before I answer that, could you please enter your email in the text box below?" Do NOT answer their question. Do NOT say anything about the topic. Do NOT begin an answer and then switch — your first word must be "Before". After you say that sentence, stay completely silent until you receive an EMAIL_SAVED message, then thank them briefly and answer their question in full.`)}catch{}}if(re&&!ne){ne=!0;try{F.current?.sendContextualUpdate?.(re)}catch{}}if(L&&!_e){_e=!0;try{F.current?.sendContextualUpdate?.(L)}catch{}}if(ae&&!O){O=!0;try{F.current?.sendContextualUpdate?.(ae)}catch{}}z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{e||R.current!==`speaking`&&(Oe.current||(z.current=null,R.current=`listening`,S(`listening`)))},1200)}},onMessage:t=>{if(e||A.current&&t.role!==`user`&&!/email/i.test(String(t.message||``)))return;if(t.role===`user`&&B.test(String(t.message||``)))typeof window<`u`&&(window.__fe_user_nav_during_speech=null),pe(!0),M.current=!1,j.current=0,he.current=-1,P.current=ug(),setTimeout(()=>le.current?.(),400),console.log(`[FlowEngage] walkthrough armed — ${P.current.length} sections on this page`);else if(t.role===`user`&&ce.current){let e=String(t.message||``).trim();Ne.test(e)?M.current&&(M.current=!1,console.debug(`[FlowEngage] walkthrough resumed by visitor`),setTimeout(()=>le.current?.(),300)):(M.current=!0,console.debug(`[FlowEngage] walkthrough paused — visitor interjected`))}if(t.role!==`user`&&Me.test(String(t.message||``))){let e=P.current.length;!e||he.current>=e-1?pe(!1):console.debug(`[FlowEngage] agent claimed completion at step ${he.current+1}/${e} — ignoring, tour continues`)}let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(r){if(n===`user`&&(ge.current=r,typeof window<`u`&&(window.__fe_user_nav_during_speech=null),Oe.current=!0,z.current&&=(clearTimeout(z.current),null),R.current!==`speaking`&&(S(`thinking`),R.current=`thinking`),Le&&!Fe&&!ie.current&&!N.current&&(Fe=!0,se.current=r,A.current=!0,F.current?.injectAgentSpeech?.(`Before I answer that, could you please enter your email in the text box below?`,`interrupt`),F.current?.setMicMuted?.(!0),k.current||(k.current=!0,oe.current=0,te(!0),Pe()))),s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString(),debug:t.debug}],i)try{let e=Sh(s.current);e&&ue(i,e)}catch{}if(vg(n,r)){De.current=!0;return}if(I.current&&n===`bot`&&/are you still there|still there\??|hello\?|anyone there|checking in|you there|are you available|is anyone|did you step away/i.test(r))if(Ee.current+=1,Ee.current===2)try{F.current?.sendContextualUpdate?.(`IMPORTANT: The visitor is muted and has not responded to your last 2 checks. Make exactly ONE more check. If there is still no response, say: 'I feel like you are not active, so I'm ending this session. You can connect with me anytime.' then immediately call the fwh-end-session-mvp tool to end the voice session. Do NOT ask again after that.`)}catch{}else Ee.current>=5&&Ae(`minimized`)}},onError:t=>{if(!e&&!Se.current&&!xe.current&&!ve()){xe.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{F.current?.setMicMuted?.(!0)}catch{}w(!0),S(`error`),Ae(`chat`)}},onDisconnect:t=>{if(e||Se.current||xe.current||ve())return;let n=s.current?.length||0;console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:n,reason:t?.reason,closeCode:t?.context?.code,closeReason:t?.context?.reason||t?.message,lastUserText:ge.current||``,wasMuted:I.current}),xe.current=!0;try{F.current?.setMicMuted?.(!0)}catch{}w(!0),Ae(`chat`)}});if(e){console.warn(`[FlowEngage:VoiceDebug] ❌ cancelled=true after startSession resolved — killing session immediately`),Re.endSession().catch(()=>{});return}l=Re,F.current=Re,S(`listening`);try{let e=typeof window<`u`?window.location.href:``,a=`[]`;try{a=await t[`fwh-list-forms-mvp`]()}catch{}let o=`none`;if(typeof window<`u`&&typeof document<`u`)try{let e=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`,t=document.querySelector(`main, [role='main']`)||document.body,n=Array.from(t.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200);n.length||(n=Array.from(document.body.querySelectorAll(`h1, h2, h3`)).filter(t=>!t.closest(e)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200)),n.length&&(o=[...new Set(n)].slice(0,15).join(` | `))}catch{}let s=r&&!m?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${n?.transcript||``}\n\n`:``;Re.sendContextualUpdate(`${s}SESSION_CONTEXT (NOT a tool result — do NOT treat as CURRENT_PAGE): Visitor is on: ${e} | Approx headings for awareness only: ${o}. SiteId: ${i||`unknown`}. Forms: ${a}. ${h?``:`Visitor's email is already on file from a prior session — do NOT ask for it again. `}The visitor is ALREADY on this page — do NOT offer to navigate there. WALKTHROUGH RULE: When the visitor asks for a walkthrough or overview of this page, you MUST IMMEDIATELY call fwh-get-current-page-mvp (zero speech — call it silently with NO words before it) to get the exact highlightable headings. The approximate headings above are for routing awareness ONLY — they are NOT precise enough for fwh-highlight-mvp. Do NOT skip fwh-get-current-page-mvp. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}if(typeof window<`u`){let t=window.location.pathname,n=Date.now(),r=e=>{try{return(decodeURIComponent(e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}catch{return((e||`/`).replace(/\/+$/,``)||`/`).toLowerCase()}},i=()=>{if(e)return;let i=window.location.pathname;if(r(i)===r(t)){t=i;return}if(D&&r(i)===r(D)){t=i;return}if(Date.now()-n<8e3){t=i;return}if(En()){t=i;return}let a=t;t=i;let o=window.location.href,s=typeof document<`u`?document.title:``,c=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.trim()})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,20):[];try{hn()}catch{}let l=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,u=l(a),d=l(i);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:a,toPath:i,fromPageName:u,toPageName:d,ts:Date.now()}),console.log(`[FlowEngage] visitor navigation detected: "${a}" → "${i}" (agent target: ${D||`none`})`);try{F.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${d}" page (${o}). Page title: "${s}". Sections: ${JSON.stringify(c)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${d} page — would you like me to continue what I was explaining, or shall I walk you through this page?" Then wait for my answer. IF I say continue/yes/carry on: resume speaking verbally from where you left off — do NOT call fwh-navigate-mvp, do NOT call fwh-highlight-mvp, the visitor will navigate themselves if needed. IF I want to hear about this page: call fwh-highlight-mvp for sections of "${d}" only.]`)}catch{}};d=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{d(...e),setTimeout(i,50)},f=()=>setTimeout(i,50),window.addEventListener(`popstate`,f)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(S(`error`),Ce.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{console.warn(`[FlowEngage:VoiceDebug] ⚠️ useEffect CLEANUP fired — session will be killed`,{agentId:r,siteId:i,apiBaseUrl:a}),e=!0,Se.current=!0;try{hn()}catch{}if(i)try{be(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),dr(),z.current&&=(clearTimeout(z.current),null),ke.current&&=(clearTimeout(ke.current),null),ae.current&&=(clearTimeout(ae.current),null),Oe.current=!1,R.current=`idle`,d&&typeof window<`u`&&(window.history.pushState=d),f&&typeof window<`u`&&window.removeEventListener(`popstate`,f);let t=l||F.current,n=we.current,u=Te.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=u?Math.round((Date.now()-u)/1e3):0,t=JSON.stringify({chatId:o,voiceSessionId:n,duration:e,siteId:i}),r=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(r,new Blob([t],{type:`application/json`}))||fetch(r,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),we.current=null,Te.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,Ae]),(0,d.useEffect)(()=>{if(!T)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;L.current&&!L.current.contains(t)&&E(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[T]);let Ie=async()=>{if(F.current)try{if(C){Ee.current=0,await F.current.setMicMuted?.(!1),w(!1);try{F.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{Ee.current=0,await F.current.setMicMuted?.(!0),w(!0);try{F.current.sendContextualUpdate?.(`The visitor has muted their microphone. Do NOT speak, ask if they are there, or prompt them in any way. Stay completely silent until they unmute.`)}catch{}}}catch{}},Le=(0,d.useCallback)(async e=>{e?.preventDefault?.();let t=D.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){O(`Please enter a valid email address.`);return}O(``),ie.current=!0,k.current=!1,je(),te(!1),ne(``),A.current=!1;try{typeof m==`function`&&await m(t)}catch{}F.current?.setMicMuted?.(!1);let n=se.current;se.current=``;try{F.current?.injectAgentSpeech?.(`Thank you for submitting your email.`),F.current?.sendUserMessage?.(n||`The visitor's email is on file. Carry on helping them and never ask for it again.`)}catch{}},[D,m,je]),Re=Array.isArray(e)&&e[0]||`#3B82F6`;return(0,f.jsxs)(`div`,{ref:L,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[ee&&(0,f.jsxs)(`form`,{onSubmit:Le,style:{width:`270px`,maxWidth:`calc(100vw - 40px)`,boxSizing:`border-box`,background:`rgba(15,22,36,0.97)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,padding:`16px`,display:`flex`,flexDirection:`column`,gap:`10px`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsx)(`span`,{style:{color:`white`,fontSize:`13px`,fontWeight:600,lineHeight:1.4},children:`Please enter your email to continue`}),(0,f.jsx)(`input`,{type:`email`,inputMode:`email`,autoComplete:`email`,autoFocus:!0,value:D,onChange:e=>{ne(e.target.value),re&&O(``)},placeholder:`you@example.com`,style:{width:`100%`,boxSizing:`border-box`,padding:`10px 12px`,borderRadius:`10px`,border:re?`1.5px solid #ef4444`:`1.5px solid #4b5563`,background:`#1f2937`,color:`white`,fontSize:`14px`,outline:`none`}}),re&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`12px`},children:re}),(0,f.jsx)(`button`,{type:`submit`,disabled:!D.trim(),style:{width:`100%`,padding:`10px 12px`,borderRadius:`10px`,border:`none`,background:D.trim()?Re:`#374151`,color:`white`,fontSize:`14px`,fontWeight:600,cursor:D.trim()?`pointer`:`default`,transition:`background 0.2s ease`},children:`Submit`})]}),(0,f.jsxs)(`div`,{style:{position:`relative`},children:[(x===`listening`||x===`thinking`)&&!C&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:x===`thinking`?v:_}),C&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`#f87171`,fontSize:`16px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Muted`}),(0,f.jsx)(yg,{size:72,voiceState:x,isMuted:C,orbColors:e})]}),x===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:Ie,title:C?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:C?`#7f1d1d`:`#1f2937`,border:C?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:C?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:C?(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsx)(Em,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>E(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,f.jsx)(Pm,{size:16,color:`currentColor`})})]}),T&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{E(!1),Ce.current=`chat`,Fe(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(Fm,{}),y]}),(0,f.jsxs)(`button`,{onClick:()=>{E(!1),Ce.current=`minimized`,Fe(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(Im,{}),b]}),(0,f.jsx)(`button`,{onClick:()=>E(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function Cg({orbColors:e}){let t=Array.isArray(e)&&e.length>0?e:[`#135bd8`,`#ef334b`,`#ffbd2e`],n=t[0],r=t[1]||t[0],i=t[2]||t[0];return(0,f.jsx)(`div`,{style:{width:`32px`,height:`32px`,borderRadius:`50%`,flexShrink:0,background:`
|
|
338
338
|
radial-gradient(circle at 18% 50%, ${n} 0%, ${n}99 35%, transparent 65%),
|
|
339
339
|
radial-gradient(circle at 82% 50%, ${r} 0%, ${r}99 35%, transparent 65%),
|
|
340
340
|
radial-gradient(circle at 50% 82%, ${i} 0%, ${i}99 30%, transparent 58%),
|
|
@@ -13027,10 +13027,10 @@ function Fg({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
|
|
|
13027
13027
|
return;
|
|
13028
13028
|
}
|
|
13029
13029
|
if (t === "user-speaking") {
|
|
13030
|
+
if (Pe.current &&= (clearTimeout(Pe.current), null), je.current === "speaking") return;
|
|
13030
13031
|
try {
|
|
13031
13032
|
On();
|
|
13032
13033
|
} catch {}
|
|
13033
|
-
if (Pe.current &&= (clearTimeout(Pe.current), null), je.current === "speaking") return;
|
|
13034
13034
|
R.current &&= (clearTimeout(R.current), null), je.current !== "listening" && (E("listening"), je.current = "listening");
|
|
13035
13035
|
return;
|
|
13036
13036
|
}
|