@flowengage/react-chatbot 6.0.41 → 6.0.42
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
|
@@ -639,8 +639,8 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
639
639
|
<path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
|
|
640
640
|
fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
|
|
641
641
|
filter="url(#${Q}-csh)"/>
|
|
642
|
-
</svg>`,EO=null,DO=!1;function OO(){return(!EO||!EO.isConnected)&&(EO=document.createElement(`div`),EO.id=`${Q}-cursor`,EO.innerHTML=TO,document.body.appendChild(EO),DO=!1),EO}async function kO(e){if(typeof document>`u`||!e)return;dO();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=OO();DO||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await NO(360)}function AO(e=!1){EO&&(e?(EO.classList.remove(`${Q}-cursor-visible`),DO=!1):(EO.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{DO=!1},250)))}async function jO(e){EO&&(EO.classList.add(`${Q}-cursor-click`),await NO(280),EO.classList.remove(`${Q}-cursor-click`))}function MO(e){if(!e||typeof document>`u`)return;dO();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function NO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){Ln()&&console.log(`[FlowEngage:voice-tools]`,...e)}function PO(e){return new Promise(t=>setTimeout(t,e))}var FO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function IO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(FO)}catch{return!1}}function LO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function RO(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!IO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function zO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function BO(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return zO(r.join(` `))}if(e.labels&&e.labels.length)return zO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return zO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return zO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return zO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=zO(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return zO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return zO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?zO(o):null}function VO(){let e=[];return RO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(IO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=LO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function HO(){return VO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:BO(e),placeholder:e.placeholder||null}))}function UO(){let e=[];return RO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(IO(e)||e.disabled)return!1;try{let t=LO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function WO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function GO(e){let t=WO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function KO(e,t){let n=GO(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,BO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>WO(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var qO=28;function JO(e,t){let n=null,r=0;for(let i of e){let e=KO(i,t);e>r&&(r=e,n=i)}return!n||r<qO?null:n}function YO(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,BO(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function XO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function ZO(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function QO(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function $O(e){if(!QO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,BO(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function ek(e,t,n){let r=String(t??``),i=String(n??``),a=rk(e,r)||JO(e,r)||YO(e,r,i);if(!a)return[];let o=new Set([a]);if(XO(i)&&ZO(r))for(let t of e)t!==a&&$O(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function tk(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function nk(e){if(!e||typeof e!=`string`)return null;let t=null;return RO(n=>{try{let r=n.getElementById(e);r&&!IO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function rk(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=nk(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=nk(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function ik(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=(e.innerText||e.textContent||``).replace(/\s+/g,` `).trim(),i=[r,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-text`),e.getAttribute(`data-label`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(i.includes(n)||r.toLowerCase()===n)return 100;let a=n.split(/\s+/).filter(e=>e.length>1);if(!a.length)return 0;let o=0;for(let e of a)i.includes(e)&&(o+=1);return o/a.length*92}function ak(e,t){let n=[];RO(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));n.push(...t.filter(e=>{if(IO(e)||e.disabled)return!1;try{let t=LO(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:ik(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<28)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=tk(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function ok(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function sk(e){let t=ok(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function ck(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function lk(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function uk(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function dk(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function fk(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function pk(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function mk(){let e=document.querySelector(`main, [role='main'], article`)||document.body;return Array.from(e.querySelectorAll(`h1, h2, h3`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200).slice(0,12)}function hk(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let i=ok(n),a=uk(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($(`flowengage_navigate · 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 $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(a=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,a))}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 $(`flowengage_navigate ✖ 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{}}if(!await yr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${a}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{hO(`Navigating to ${a}...`,{spinner:!0}),bO(),mD();try{let e=r?r():``;if(e&&t){let n=uO([{sender:`user`,message:e}]);n&&Ee(t,n)}}catch{}Ae();let e=a;try{e=new URL(a,typeof window<`u`?window.location.href:``).href}catch{}t&&typeof window<`u`&&Le(t,window.location.href,e),Sr(e),$(`flowengage_navigate → real navigation`,a);let n=typeof window<`u`&&!!$n();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),n&&Kn(3e3),Tr(a,{voiceActive:!0}).catch(()=>{}),n)try{let e=new URL(a,window.location.origin).pathname,t=Date.now()+2e3;for(;Date.now()<t&&!(typeof window<`u`&&window.location.pathname===e);)await new Promise(e=>setTimeout(e,80));let n=typeof window<`u`?window.location.pathname:e,r=typeof window<`u`?window.location.href:a,i=n===e,o=(n.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`;$(`flowengage_navigate → SPA nav complete. target:`,e,`actual:`,n);let s=[],c=Date.now()+12e3;for(;Date.now()<c&&(await new Promise(e=>setTimeout(e,300)),s=mk(),!(s.length>=1)););pk(),$(`flowengage_navigate → page headings collected:`,s);let l=s.length?s.join(` | `):`none`,u=s.length?`Use ONLY these exact heading strings for flowengage_highlight — never invent or abbreviate.`:`No headings collected yet — call flowengage_get_current_page immediately (no speech) to get the live headings before speaking or highlighting.`;return i?(Cr(),`OK_NAVIGATE_SPA. Visitor is now on: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page from your knowledge, then STOP. Do NOT highlight. Do NOT walk through sections. Wait for the visitor to respond. Only do a highlighted walkthrough if they explicitly ask for one.`):(Cr(),`OK_NAVIGATE_SPA. CURRENT PAGE IS: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page from your knowledge, then STOP. Do NOT highlight or walk through sections. Describe THIS page only — do not mention the page you tried to navigate to.`)}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, immediately introduce the new page and continue guiding the visitor — do not wait for the user to speak first.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),hO(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{xO(),gO(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=ok(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(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 flowengage_highlight 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.`}pk();let i=mr(n||null,r||null);if(!i&&r){let e=Date.now()+600;for(;!i&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),pk(),i=mr(null,r)}if(!i){$(`flowengage_highlight ✖ no element for:`,r||n);let e=mk(),t=e.length?`Page headings: ${e.join(` | `)}. Use one of these exact strings for section_text.`:`No headings found — skip highlight and continue.`;return`HIGHLIGHT_NOT_FOUND: "${r||n}" on the current page. ${t}`}return pD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}". WALKTHROUGH: continue immediately to the next section — do NOT pause between sections.`},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=ok(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=mr(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
|
|
643
|
-
`)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=dk(ok(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;hO(`Searching${r?` for "${r}"`:``}…`,{spinner:!0});try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),o.length?`SEARCH_RESULTS: ${JSON.stringify(o)}. MANDATORY: Do NOT call flowengage_navigate now. Speak the answer from these results in 2-3 sentences. Then ask the visitor if they want to go to a relevant page — e.g. "Would you like me to take you to that page?" Only navigate if they say yes.`:`SEARCH_RESULTS: No results found. Answer from your knowledge base.`}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}finally{gO(600)}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=ok(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),`${e} FALLBACK REQUIRED: This page is not in the search index. Call flowengage_read_content (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 $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_get_current_page:async()=>{if($(`flowengage_get_current_page ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``,r=mk(),i=r.length?r.join(` | `):`none`;return $(`flowengage_get_current_page ✓`,{url:e,path:t,title:n}),$(`flowengage_get_current_page → page headings collected:`,r),`CURRENT_PAGE. URL: ${e} | Path: ${t} | Title: ${n} | Section headings: ${i}. These are the EXACT heading strings — use them verbatim for every flowengage_highlight call. If the visitor has already requested a walkthrough, proceed immediately with the full highlighted walkthrough using these headings. If not, give 1-2 sentences about the page and wait.`},flowengage_list_forms:async()=>{let e=HO(),t=UO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),SO();let t=sk(e);if(!t.length&&r){let e=r(),n=ck(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=lk(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key,r=e?.value;if(t==null||r==null)continue;hO(`Filling ${String(t)}...`,{spinner:!0});let a=VO(),o=ek(a,String(t),r);if(o.length){for(let[e,t]of o.entries())CO(t),await kO(t),fk(t,r,{skipScroll:e>0}),wO(t),await PO(120);i=o,n.push(String(t));continue}let s=rk(a,String(t));s||=JO(a,String(t)),s||=YO(a,String(t),r),s&&(CO(s),await kO(s),fk(s,r),wO(s),await PO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),hO(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),hO(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{AO(),SO(),gO(700)}},flowengage_click_button:async e=>{let t=ok(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=ak(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{hO(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await kO(r),r.focus?.(),await jO(r),MO(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),hO(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),hO(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{AO(),gO(700)}}};return{...a,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function gk(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Ln();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 _k={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function vk(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 yk(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 bk(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 xk({logo:e,style:t}){let n=bk(typeof e==`string`?e:null);if(!e)return null;if(typeof e==`string`)return n?(0,A.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,A.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:r}):null}function Sk({title:e}){return(0,A.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 Ck(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function wk({orbColors:e,...t}){return(0,A.jsx)(tO,{colors:e,...t})}function Tk({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||_k.green,c=yk(s),l=a?72:94,u=(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,A.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,A.jsx)(gm.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,A.jsxs)(gm.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,A.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,A.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,A.jsx)(gm.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,A.jsx)(wk,{size:l,orbColors:t})})]});return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(gm.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,A.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,A.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function Ek({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||_k.green,l=yk(c);return(0,A.jsxs)(gm.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,A.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,A.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,A.jsx)(wk,{size:72,orbColors:t}),(0,A.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,A.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,A.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,A.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 Dk({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l}){let[u,d]=(0,b.useState)(`idle`),[f,p]=(0,b.useState)(!1),[m,h]=(0,b.useState)(!1),g=(0,b.useRef)(null),_=(0,b.useRef)(``),v=(0,b.useRef)(async()=>{}),y=(0,b.useRef)(!1),x=(0,b.useRef)(!1),ee=(0,b.useRef)(!1),S=(0,b.useRef)(!1),C=(0,b.useRef)(`minimized`),te=(0,b.useRef)(null),w=(0,b.useRef)(null),ne=(0,b.useRef)(null),re=(0,b.useRef)(0),ie=(0,b.useRef)(!1),T=(0,b.useRef)(`idle`),ae=(0,b.useRef)(!1),oe=(0,b.useRef)(null),se=(0,b.useRef)(null),ce=(0,b.useRef)(!1),le=(0,b.useCallback)((e=`minimized`)=>{C.current=e,S.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[s]),E=(0,b.useCallback)(async e=>{S.current=!0;try{mD()}catch{}if(i)try{Re(i)}catch{}try{await g.current?.endSession?.()}catch{}let t=te.current,n=w.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,elevenLabsConversationId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(te.current=null,w.current=null,g.current=null,d(`idle`),p(!1),y.current=!1,kr(),i)try{Oe(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);return v.current=()=>E(C.current===`chat`?t:n),(0,b.useEffect)(()=>{x.current=f},[f]),(0,b.useEffect)(()=>{l&&le(`chat`)},[l]),(0,b.useEffect)(()=>{let e=!1,l=null,u=null,f=null;return(async()=>{if(!r){d(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],_.current=``,y.current=!1,ee.current=!1,S.current=!1,C.current=`minimized`,Or({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=uO(s.current);e&&Ee(i,e)}catch{}if(!$n()){let e=te.current,t=w.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,elevenLabsConversationId:e,duration:n,siteId:i}),s=`${a}/api/voice/save-chat-recording`;fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:r,keepalive:!0}).catch(()=>{}),te.current=null,w.current=null}catch{}}Ae()}});let t=gk(hk({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,requestEndSession:()=>{ie.current=!0}})),n=i?De(i):null,c=!!n?.transcript,m=!!(i&&Re(i)),h=typeof window<`u`?window.location.pathname:`/`,v=typeof document<`u`?document.title:``,b=h===`/`||h===``,ne=null;try{let e=await fetch(`${a}/api/voice/signed-url?siteId=${encodeURIComponent(i||``)}`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(e.ok)ne=(await e.json()).signedUrl||null,ne&&console.log(`[FlowEngage] ✅ Using signed ElevenLabs URL`);else if(e.status===429){let t=await e.json().catch(()=>({}));throw Error(t.message||`Too many voice sessions started. Please wait a minute before trying again.`)}else console.warn(`[FlowEngage] ⚠️ Signed URL fetch failed, falling back to agentId`)}catch(e){if(e.message&&e.message.includes(`Too many voice sessions`))throw e;console.warn(`[FlowEngage] ⚠️ Signed URL fetch error:`,e.message)}let E={clientTools:t,connectionType:`websocket`,minSpeechDurationMs:50,...ne?{signedUrl:ne}:{agentId:r}},D=(h.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),ue=``;v&&v.includes(`|`)&&(ue=v.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let de=ue||D||`this page`;ne?m?(E.overrides={agent:{firstMessage:`I've navigated you to the ${de} page. Let me walk you through what's here.`}},console.log(`[FlowEngage] 🔄 Agent-nav resume: firstMessage set for "${de}" (${h})`)):c?E.overrides={agent:{firstMessage:`I'm still here. Go ahead!`}}:b||(E.overrides={agent:{firstMessage:`Hi! I see you are currently on the ${de} page. Are you looking for something specific here?`}},console.log(`[FlowEngage] 🏠 Page-context override: "${de}" for ${h}`)):c&&(E.overrides={agent:{firstMessage:``}});let fe=!1,pe=m?`NAVIGATION RESUME — Your intro has been spoken. NOW — without waiting for the visitor to say anything — call flowengage_highlight for the first content section on this page, then speak one sentence about it. Continue section by section (highlight + one sentence each) until you have covered the key content. Prior conversation context:\n${(i?De(i):null)?.transcript||``}\n\n`:null,me=await uD.startSession({...E,onConnect:({conversationId:e})=>{te.current=e,w.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{if(!e){if(t===`speaking`){se.current&&=(clearTimeout(se.current),null),d(`speaking`),T.current=`speaking`,ae.current=!0,ce.current=!1,oe.current&&=(clearTimeout(oe.current),null);return}if(T.current=`listening`,ie.current){ie.current=!1,le();return}if(pe&&!fe){fe=!0;try{g.current?.sendUserMessage?.(`continue with the tour`)}catch{}}se.current&&clearTimeout(se.current),se.current=setTimeout(()=>{e||T.current!==`speaking`&&(ce.current||(se.current=null,T.current=`listening`,d(`listening`)))},1200)}},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(r){if(n===`user`&&(_.current=r,ce.current=!0,se.current&&=(clearTimeout(se.current),null),oe.current&&=(clearTimeout(oe.current),null)),s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=uO(s.current);e&&Ee(i,e)}catch{}if(Ck(n,r)){le(`minimized`);return}if(x.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(re.current+=1,re.current===2)try{g.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 flowengage_end_session tool to end the voice session. Do NOT ask again after that.`)}catch{}else re.current>=5&&le(`minimized`)}},onError:t=>{if(!e&&!S.current&&!ee.current&&!Fe()){ee.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),d(`error`),le(`chat`)}},onDisconnect:t=>{if(e||S.current||ee.current||Fe())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:_.current||``,wasMuted:x.current}),ee.current=!0;try{g.current?.setMicMuted?.(!0)}catch{}p(!0),le(`chat`)}});if(e){me.endSession().catch(()=>{});return}l=me,g.current=me,d(`listening`);try{let e=typeof window<`u`?window.location.href:``,r=`[]`;try{r=await t.list_page_forms()}catch{}let a=c&&!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`:``;me.sendContextualUpdate(`${a}Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${r}. 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=()=>{if(e)return;let n=window.location.pathname;if(n===t)return;if(qn()){t=n;return}let r=t;t=n;let i=window.location.href,a=typeof document<`u`?document.title:``,o=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{mD()}catch{}let s=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,c=s(r),l=s(n);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:r,toPath:n,fromPageName:c,toPageName:l,ts:Date.now()});try{g.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${l}" page (${i}). Page title: "${a}". Sections: ${JSON.stringify(o)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${l} 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 flowengage_navigate, do NOT call flowengage_highlight, the visitor will navigate themselves if needed. IF I want to hear about this page: call flowengage_highlight for sections of "${l}" only.]`)}catch{}};u=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{u(...e),setTimeout(n,50)},f=()=>setTimeout(n,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`)):(d(`error`),C.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{e=!0,S.current=!0;try{mD()}catch{}if(i)try{Re(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),kr(),oe.current&&=(clearTimeout(oe.current),null),se.current&&=(clearTimeout(se.current),null),ae.current=!1,ce.current=!1,T.current=`idle`,u&&typeof window<`u`&&(window.history.pushState=u),f&&typeof window<`u`&&window.removeEventListener(`popstate`,f);let t=l||g.current,n=te.current,r=w.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=r?Math.round((Date.now()-r)/1e3):0,t=JSON.stringify({chatId:o,elevenLabsConversationId:n,duration:e,siteId:i}),s=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(s,new Blob([t],{type:`application/json`}))||fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),te.current=null,w.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,le]),(0,b.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ne.current&&!ne.current.contains(t)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,A.jsxs)(`div`,{ref:ne,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,A.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&!f&&(0,A.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),f&&(0,A.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,A.jsx)(wk,{size:72,voiceState:u,isMuted:f,orbColors:e})]}),u===`error`&&(0,A.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,A.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,A.jsx)(`button`,{onClick:async()=>{if(g.current)try{if(f){re.current=0,await g.current.setMicMuted?.(!1),p(!1);try{g.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{re.current=0,await g.current.setMicMuted?.(!0),p(!0);try{g.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{}},title:f?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:f?`#7f1d1d`:`#1f2937`,border:f?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:f?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:f?(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,A.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,A.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,A.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,A.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,A.jsx)(hD,{size:16,color:`currentColor`})}),(0,A.jsx)(`button`,{onClick:()=>h(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,A.jsx)(CD,{size:16,color:`currentColor`})})]}),m&&(0,A.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,A.jsxs)(`button`,{onClick:()=>{h(!1),C.current=`chat`,E(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,A.jsx)(wD,{}),`Enter Chat Mode`]}),(0,A.jsxs)(`button`,{onClick:()=>{h(!1),C.current=`minimized`,E(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,A.jsx)(TD,{}),`End Conversation`]}),(0,A.jsx)(`button`,{onClick:()=>h(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,A.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,A.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function Ok({orbColors:e}){return(0,A.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,A.jsx)(wk,{size:36,orbColors:e})})}var kk=()=>(0,A.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,A.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,A.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function Ak({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:d,agentName:f,agentHeadshot:p,fallbackAgentName:m,input:h,setInput:g,onSubmit:_,isConversationEnded:v,isLoading:y,isRateLimited:x,rateLimitMessage:ee,selectedFile:S,onFileSelect:C,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:T,emailError:ae,emailCaptureSuccess:oe,replyContext:se,setReplyContext:ce,webRTCError:le,micError:E,setMicError:D,dismissCallError:ue,activeCallId:de,isCallMuted:fe,toggleCallMute:pe,endWebRTCCall:me,formatCallDuration:he,callDurationSeconds:ge,isCallMinimized:_e,onExpand:ve,onCollapse:ye,onStartVoice:be,onNewChat:xe,showPoweredBy:Se,getVisitorChatHistory:Ce,resumeChat:we,isSessionRestoring:Te,isClosing:Ee}){let De=c.length>0,Oe=y||x||v,ke=!!de,[Ae,je]=(0,b.useState)(!1),[Me,Ne]=(0,b.useState)(!1),[Pe,Fe]=(0,b.useState)([]),[Ie,Le]=(0,b.useState)(!1),Re=(0,b.useRef)(null),[ze,Be]=(0,b.useState)(()=>typeof window<`u`?window.visualViewport?.height??window.innerHeight:600),[Ve,He]=(0,b.useState)(0);(0,b.useEffect)(()=>{if(!s)return;let e=window.visualViewport;if(!e)return;let t=()=>{Be(e.height),He(Math.max(0,window.innerHeight-e.offsetTop-e.height))};return e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}},[s]);let Ue=s&&window.innerHeight-ze>150,We=async()=>{je(!1),Ne(!0),Le(!0);try{let e=await Ce();e?.data&&Fe(e.data)}catch(e){console.error(e)}finally{Le(!1)}},Ge=async e=>{Ne(!1),we?.(e.chatId)};return(0,b.useEffect)(()=>{if(!Ae)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Re.current&&!Re.current.contains(t)&&je(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Ae]),(0,A.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:`${Ve}px`,height:ze>0?`${Math.round(ze*.92)}px`:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:Ee?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:Ee?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,A.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0,position:`relative`,zIndex:30},children:[(0,A.jsx)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,A.jsx)(`button`,{onClick:ye,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,A.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})})}),(0,A.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,A.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,A.jsx)(xk,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,A.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,A.jsx)(Sk,{title:e.chatTitle})})}),(0,A.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,A.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,A.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Re,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>je(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,A.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,A.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,A.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,A.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Ae&&(0,A.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),be?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,A.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,A.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),xe?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,A.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new chat`]}),Ce&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,A.jsxs)(`button`,{type:`button`,onClick:We,style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,A.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`path`,{d:`M12 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,A.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),ye?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,A.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,A.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,A.jsx)(KD,{webRTCError:le,micError:E,setMicError:D,dismissCallError:ue,isRateLimited:x,rateLimitMessage:ee}),_e&&(0,A.jsx)(lO,{agentName:f,agentHeadshot:p,fallbackAgentName:m,callDurationSeconds:ge,isCallMuted:fe,formatCallDuration:he,toggleCallMute:pe,endWebRTCCall:me,onExpand:ve,primaryColor:n}),(0,A.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Me?(0,A.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,A.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:(0,A.jsxs)(`button`,{onClick:()=>Ne(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,A.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,A.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,A.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Ie?(0,A.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):Pe.length>0?(0,A.jsx)(`div`,{children:Pe.map(e=>(0,A.jsxs)(`div`,{onClick:()=>Ge(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,A.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,A.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,A.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,De?(0,A.jsx)(WD,{chatHistory:c,isAiTyping:l,isLoading:y,isAgentTyping:u,setReplyContext:ce,TypingDots:kk,primaryColor:n,agentHeadshot:p,agentDisplayName:f||m,botAvatarNode:(0,A.jsx)(Ok,{orbColors:t})}):Te?(0,A.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,A.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,A.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,A.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(0,A.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,A.jsx)(wk,{size:94,orbColors:t}),(0,A.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,A.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,A.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})]}),oe&&(0,A.jsxs)(`div`,{style:{margin:`0 16px 8px`,padding:`9px 14px`,borderRadius:`12px`,background:`#ecfdf5`,border:`1px solid #6ee7b7`,display:`flex`,alignItems:`center`,gap:`8px`,animation:`fe-orb-fade-in 0.2s ease`,flexShrink:0},children:[(0,A.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#10b981`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,A.jsx)(`polyline`,{points:`20 6 9 17 4 12`})}),(0,A.jsx)(`span`,{style:{fontSize:`13px`,fontWeight:500,color:`#065f46`},children:`Email saved — we'll be in touch!`})]}),(0,A.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:re?`6px 0 0`:`12px 0 0`},children:(0,A.jsx)(GD,{input:h,setInput:g,onSubmit:_,isConversationEnded:v,callUiActive:ke,handleToggleVoice:be,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Oe,replyContext:se,clearReplyContext:()=>ce(null),onFileSelect:C,selectedFile:S,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:T,emailError:ae,inputPlaceholder:e.inputPlaceholder})}),!Ue&&(0,A.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`8px 20px`,paddingBottom:`max(12px, env(safe-area-inset-bottom, 12px))`,pointerEvents:`none`},children:Se&&(0,A.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,A.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function jk(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:d,isLoading:f,isRateLimited:p,rateLimitMessage:m,isConversationEnded:h,incomingCall:g,activeCallId:_,callConnectionState:v,callConnectedAt:y,isCallMuted:x,webRTCError:ee,language:S,chatId:C,historyRef:te,onMessageSync:w,sendMessage:ne,uploadChatFile:re,openWidget:ie,captureVisitorEmail:T,setVoiceMode:ae,endConversation:oe,startNewChat:se,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,dismissCallError:fe,startTyping:pe,stopTyping:me,updateTypingDraft:he,getVisitorChatHistory:ge,resumeChat:_e,isSessionRestoring:ve,openToChatCounter:ye,voiceEndCounter:be}=In();(0,b.useEffect)(()=>{try{fr()}catch{}},[]),(0,b.useEffect)(()=>{ye&&O!==`text_chat`&&O!==`call_screen`&&(ae?.(!1),nt(`text_chat`))},[ye]);let xe=t?.widgetSettings||{},Se=n?.widgetSettings||{},Ce={...xe.branding||{},...Se.branding||{}},we={...xe.theme||{},...Se.theme||{}},Te={...xe.features||{},...Se.features||{}},Ee=Te.voice!==!1,ke=Array.isArray(we.orbColors)&&we.orbColors.length>0?we.orbColors:null,Ae=we.buttonColor||we.primaryColor||ke?.[0]||`#3B82F6`,Me={small:50,medium:64,large:80},Ne=Me[we.orbSize]||Me.small,Fe=we.position||`bottom-right`,Ie=Ce.fallbackAgentName||`Agent`,Le=vk(ke??we.chatBgColors),Re=Ce.logo||Ce.logoUrl||null,ze=S||`en`,Be=xe.recommendations?.[ze]||[],Ve=(Se.recommendations?.[ze]??Be).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),He=Array.isArray(Ce.quickChatOptions)&&Ce.quickChatOptions.length>0?Ce.quickChatOptions:Ve,Ue=Ce.hideWatermark===!0?!1:Ce.showPoweredBy!==!1,We=Ce.chatbotEnabled!==!1&&we.chatbotEnabled!==!1,Ge=xe.greetings?.[S]||Se.greetings?.[S]||Ce.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Ke={entryPrompt:Ce.entryPrompt||`Do you want to explore in a new way?`,yesLabel:Ce.yesLabel||`Yes`,laterLabel:Ce.laterLabel||`Later`,connectionTitle:Ce.connectionTitle||`How would you like to connect?`,voiceLabel:Ce.voiceLabel||`Voice`,textLabel:Ce.textLabel||`Text`,chatTitle:Ce.headerName||`Chat with FlowEngage`,introGreeting:Ge,inputPlaceholder:Ce.inputPlaceholder||`Type your message`,analysingLabel:Ce.analysingLabel||`analysing...`},qe=Se.elevenLabsAgentId||t?.elevenLabsAgentId||null,Je=t?.siteId||n?.siteId||null,Ye=t?.apiBaseUrl||``,Xe=(0,b.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Ze=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Qe=r.some(e=>e.sender===`user`),$e=(0,b.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),et=!l&&Qe&&$e,tt=!!(Se._dashboardLivePreview||xe._dashboardLivePreview),[O,nt]=(0,b.useState)(()=>tt?`text_chat`:`entry_prompt`),[rt,it]=(0,b.useState)(``),[at,ot]=(0,b.useState)(null),[st,ct]=(0,b.useState)(l||``),[lt,ut]=(0,b.useState)(``),[dt,ft]=(0,b.useState)(!1),[pt,mt]=(0,b.useState)(0),[ht,gt]=(0,b.useState)(null),[_t,vt]=(0,b.useState)(null),[yt,bt]=(0,b.useState)(``),[xt,St]=(0,b.useState)(!1),[Ct,wt]=(0,b.useState)(!1),[Tt,Et]=(0,b.useState)(!1),Dt=(0,b.useRef)(null),Ot=(0,b.useRef)(!1);(0,b.useLayoutEffect)(()=>{if(e!==`ready`||Ot.current)return;if(Ot.current=!0,!Ee){nt(`minimized_orb`);return}let t=!1;try{t=wr().shouldResumeVoice}catch{}let n=je(),r=Je?De(Je):null,i=n||!!r?.transcript;if(t){ie?.({notifyChatInitiated:!0}),ae?.(!0),nt(`voice_mode`);return}if(Pe()){ie?.({notifyChatInitiated:!1}),nt(`text_chat`);return}if(Je)try{Oe(Je)}catch{}if(i){nt(`minimized_orb`);return}if(E(Je)){nt(`minimized_orb`);return}},[e,r]);let[kt,At]=(0,b.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,b.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>At(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,b.useEffect)(()=>{ct(l||``),l&&ut(``)},[l]);let jt=(0,b.useCallback)(()=>{vt(null),bt(``)},[]),Mt=(0,b.useCallback)(e=>{let t=zD(e);if(t){vt(null),bt(t);return}vt(e),bt(``)},[]);(0,b.useEffect)(()=>{if(!y||v!==`connected`){mt(0);return}let e=()=>{let e=new Date(y).getTime();isNaN(e)||mt(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[y,v]);let Nt=(0,b.useCallback)(()=>{nt(`call_screen`),wt(!1)},[]),Pt=(0,b.useCallback)(()=>{nt(`text_chat`),wt(!0)},[]);(0,b.useEffect)(()=>{let e=g?.callId||_||null;if(!e){Dt.current=null;return}if(g?.callId||v===`connecting`||v===`connected`){if(O===`minimized_orb`&&Ct&&_&&!g?.callId){Dt.current=e;return}!(!i||O===`minimized_orb`||O===`voice_mode`)&&Dt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:O,hasIncomingCall:!!g?.callId,activeCallId:_,callConnectionState:v}),Dt.current=e,O===`voice_mode`&&ae?.(!1),ie?.(),Nt())}},[_,v,Nt,g?.callId,i,ie,ae,O]),(0,b.useEffect)(()=>{!g&&!_&&O===`call_screen`&&nt(`text_chat`)},[g,_,O]),(0,b.useEffect)(()=>{!_&&Ct&&wt(!1)},[_,Ct]),(0,b.useEffect)(()=>{if(!o||h){he?.(``),me?.();return}if(!rt.trim()||_t){he?.(``);let e=window.setTimeout(()=>me?.(),100);return()=>window.clearTimeout(e)}pe?.();let e=window.setTimeout(()=>he?.(rt),120),t=window.setTimeout(()=>me?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[rt,_t,o,h,pe,me,he]);let Ft=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,It=async e=>{if(e.preventDefault(),h)return;if(et){let e=st.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){ut(`Please enter a valid email so we can continue helping you.`);return}await T(e),ut(``),ft(!0),setTimeout(()=>ft(!1),3e3);return}let t=Ft(at);if(!rt.trim()&&!_t)return;if(_t){try{St(!0),bt(``);let e=await re(_t),n=e?.data||e,r=rt.trim()||`Shared file: ${VD(_t)}`;it(``),ot(null),jt(),await ne(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||_t.name,fileType:n?.fileType||_t.type,fileSize:n?.fileSize||_t.size}})}catch(e){bt(e?.message||`Failed to upload the selected file.`)}finally{St(!1)}return}let n=rt.trim();it(``),ot(null),await ne(n,``,t)},Lt=(0,b.useCallback)(()=>{r.length!==0&&se?.()},[r.length,se]),Rt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},zt=(0,b.useCallback)(async e=>{if(h||f)return;let t=e.message||e.label||e.text||``;t.trim()&&await ne(t.trim(),``)},[h,f,ne]),Bt=kt&&O===`entry_prompt`?{inset:0}:kt&&O===`text_chat`?{left:0,right:0,bottom:0}:kt&&O===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:kt&&O===`connection_modal`?{left:`12px`,right:`12px`,bottom:`12px`}:O===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Fe===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`}}:Fe===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Vt=(0,b.useCallback)(()=>{O!==`minimized_orb`&&(Et(!0),setTimeout(()=>{nt(`minimized_orb`),Et(!1),_&&wt(!0)},280))},[_,O]),Ht=()=>nt(`connection_modal`),Ut=()=>{try{let e=window.AudioContext||window.webkitAudioContext;if(e){let t=new e;t.resume().catch(()=>{}),setTimeout(()=>t.close().catch(()=>{}),3e3)}}catch{}ie({notifyChatInitiated:!0}),ae?.(!0),nt(`voice_mode`)},Wt=()=>{ie({notifyChatInitiated:!0}),ae?.(!1),nt(`text_chat`)},Gt=()=>{ae?.(!1),Vt()};return e!==`ready`||!We||Te.chat===!1?null:(0,A.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Bt},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[O===`entry_prompt`&&(0,A.jsx)(Tk,{copy:Ke,orbColors:ke,primaryColor:Ae,onYes:()=>{D(Je),Ut()},onLater:()=>{D(Je),Vt()},isMobile:kt,isClosing:Tt}),O===`minimized_orb`&&(0,A.jsxs)(gm.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Fe===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[_&&(0,A.jsxs)(`button`,{type:`button`,onClick:Nt,style:{maxWidth:kt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,A.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,A.jsxs)(`span`,{style:{minWidth:0},children:[(0,A.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:v===`connected`?`Call in progress`:`Call is active`}),(0,A.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:v===`connected`?`${Rt(pt)} with ${Xe}`:`Tap to return to ${Xe}`})]})]}),(0,A.jsx)(wk,{size:Ne,orbColors:ke,onClick:_?Nt:Ee?Ht:Wt})]}),O===`connection_modal`&&(0,A.jsx)(Ek,{copy:Ke,orbColors:ke,primaryColor:Ae,onVoice:Ut,onText:Wt,onClose:Vt,isMobile:kt,isClosing:Tt}),O===`voice_mode`&&(0,A.jsx)(Dk,{orbColors:ke,onEnterChat:Wt,onEndChat:Gt,agentId:qe,siteId:Je,apiBaseUrl:Ye,chatId:C,historyRef:te,onMessageSync:w,voiceEndCounter:be},`voice`),O===`call_screen`&&(0,A.jsx)(cO,{incomingCall:g,activeCallId:_,callConnectionState:v,callDurationSeconds:pt,isCallMuted:x,agentName:Xe,agentHeadshot:Ze,fallbackAgentName:Ie,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,formatCallDuration:Rt,onMinimize:Pt,primaryColor:Ae,orbColors:ke,chatHistory:r}),O===`text_chat`&&(0,A.jsx)(Ak,{isClosing:Tt,copy:Ke,orbColors:ke,primaryColor:Ae,chatBgGradient:Le,logo:Re,quickChatOptions:He,onQuickChatSelect:zt,isMobile:kt,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Xe,agentHeadshot:Ze,fallbackAgentName:Ie,input:rt,setInput:it,onSubmit:It,isConversationEnded:h,isLoading:f,isRateLimited:p,rateLimitMessage:m,selectedFile:_t,onFileSelect:Mt,onRemoveSelectedFile:jt,attachmentError:yt,isUploadingAttachment:xt,requiresEmail:et,emailInput:st,setEmailInput:ct,emailError:lt,emailCaptureSuccess:dt,replyContext:at,setReplyContext:ot,webRTCError:ee,micError:ht,setMicError:gt,dismissCallError:fe,activeCallId:_,isCallMuted:x,toggleCallMute:de,endWebRTCCall:ue,formatCallDuration:Rt,callDurationSeconds:pt,onCollapse:Vt,onStartVoice:Ut,onNewChat:Lt,onMinimize:Pt,onExpand:Nt,isCallMinimized:!!_,showPoweredBy:Ue,getVisitorChatHistory:ge,resumeChat:_e,isSessionRestoring:ve}),(0,A.jsx)(`style`,{children:`
|
|
642
|
+
</svg>`,EO=null,DO=!1;function OO(){return(!EO||!EO.isConnected)&&(EO=document.createElement(`div`),EO.id=`${Q}-cursor`,EO.innerHTML=TO,document.body.appendChild(EO),DO=!1),EO}async function kO(e){if(typeof document>`u`||!e)return;dO();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=OO();DO||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await NO(360)}function AO(e=!1){EO&&(e?(EO.classList.remove(`${Q}-cursor-visible`),DO=!1):(EO.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{DO=!1},250)))}async function jO(e){EO&&(EO.classList.add(`${Q}-cursor-click`),await NO(280),EO.classList.remove(`${Q}-cursor-click`))}function MO(e){if(!e||typeof document>`u`)return;dO();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function NO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){Ln()&&console.log(`[FlowEngage:voice-tools]`,...e)}function PO(e){return new Promise(t=>setTimeout(t,e))}var FO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function IO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(FO)}catch{return!1}}function LO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function RO(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!IO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function zO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function BO(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return zO(r.join(` `))}if(e.labels&&e.labels.length)return zO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return zO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return zO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return zO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=zO(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return zO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return zO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?zO(o):null}function VO(){let e=[];return RO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(IO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=LO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function HO(){return VO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:BO(e),placeholder:e.placeholder||null}))}function UO(){let e=[];return RO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(IO(e)||e.disabled)return!1;try{let t=LO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function WO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function GO(e){let t=WO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function KO(e,t){let n=GO(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,BO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>WO(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var qO=28;function JO(e,t){let n=null,r=0;for(let i of e){let e=KO(i,t);e>r&&(r=e,n=i)}return!n||r<qO?null:n}function YO(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,BO(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function XO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function ZO(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function QO(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function $O(e){if(!QO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,BO(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function ek(e,t,n){let r=String(t??``),i=String(n??``),a=rk(e,r)||JO(e,r)||YO(e,r,i);if(!a)return[];let o=new Set([a]);if(XO(i)&&ZO(r))for(let t of e)t!==a&&$O(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function tk(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function nk(e){if(!e||typeof e!=`string`)return null;let t=null;return RO(n=>{try{let r=n.getElementById(e);r&&!IO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function rk(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=nk(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=nk(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function ik(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=(e.innerText||e.textContent||``).replace(/\s+/g,` `).trim(),i=[r,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-text`),e.getAttribute(`data-label`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(i.includes(n)||r.toLowerCase()===n)return 100;let a=n.split(/\s+/).filter(e=>e.length>1);if(!a.length)return 0;let o=0;for(let e of a)i.includes(e)&&(o+=1);return o/a.length*92}function ak(e,t){let n=[];RO(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));n.push(...t.filter(e=>{if(IO(e)||e.disabled)return!1;try{let t=LO(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:ik(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<28)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=tk(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function ok(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function sk(e){let t=ok(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function ck(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function lk(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function uk(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function dk(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function fk(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function pk(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function mk(){let e=document.querySelector(`main, [role='main'], article`)||document.body;return Array.from(e.querySelectorAll(`h1, h2, h3`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200).slice(0,12)}function hk(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let i=ok(n),a=uk(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($(`flowengage_navigate · 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 $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(a=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,a))}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 $(`flowengage_navigate ✖ 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{}}if(!await yr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${a}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{hO(`Navigating to ${a}...`,{spinner:!0}),bO(),mD();try{let e=r?r():``;if(e&&t){let n=uO([{sender:`user`,message:e}]);n&&Ee(t,n)}}catch{}Ae();let e=a;try{e=new URL(a,typeof window<`u`?window.location.href:``).href}catch{}t&&typeof window<`u`&&Le(t,window.location.href,e),Sr(e),$(`flowengage_navigate → real navigation`,a);let n=typeof window<`u`&&!!$n();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),n&&Kn(3e3),Tr(a,{voiceActive:!0}).catch(()=>{}),n)try{let e=new URL(a,window.location.origin).pathname,t=Date.now()+2e3;for(;Date.now()<t&&!(typeof window<`u`&&window.location.pathname===e);)await new Promise(e=>setTimeout(e,80));let n=typeof window<`u`?window.location.pathname:e,r=typeof window<`u`?window.location.href:a,i=n===e,o=(n.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`;$(`flowengage_navigate → SPA nav complete. target:`,e,`actual:`,n);let s=[],c=Date.now()+12e3;for(;Date.now()<c&&(await new Promise(e=>setTimeout(e,300)),s=mk(),!(s.length>=1)););pk(),$(`flowengage_navigate → page headings collected:`,s);let l=s.length?s.join(` | `):`none`,u=s.length?`Use ONLY these exact heading strings for flowengage_highlight — never invent or abbreviate.`:`No headings collected yet — call flowengage_get_current_page immediately (no speech) to get the live headings before speaking or highlighting.`;return i?(Cr(),`OK_NAVIGATE_SPA. Visitor is now on: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page, then ask: "Would you like me to walk you through the sections here?"`):(Cr(),`OK_NAVIGATE_SPA. CURRENT PAGE IS: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page, then ask: "Would you like me to walk you through the sections here?"`)}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, immediately introduce the new page and continue guiding the visitor — do not wait for the user to speak first.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),hO(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{xO(),gO(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=ok(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(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 flowengage_highlight 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.`}pk();let i=mr(n||null,r||null);if(!i&&r){let e=Date.now()+600;for(;!i&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),pk(),i=mr(null,r)}if(!i){$(`flowengage_highlight ✖ no element for:`,r||n);let e=mk(),t=e.length?`Page headings: ${e.join(` | `)}. Use one of these exact strings for section_text.`:`No headings found — skip highlight and continue.`;return`HIGHLIGHT_NOT_FOUND: "${r||n}" on the current page. ${t}`}return pD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}". WALKTHROUGH: continue immediately to the next section — do NOT pause between sections.`},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=ok(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=mr(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
|
|
643
|
+
`)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=dk(ok(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;hO(`Searching${r?` for "${r}"`:``}…`,{spinner:!0});try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),o.length?`SEARCH_RESULTS: ${JSON.stringify(o)}. MANDATORY: Do NOT call flowengage_navigate now. Speak the answer from these results in 2-3 sentences. Then ask the visitor if they want to go to a relevant page — e.g. "Would you like me to take you to that page?" Only navigate if they say yes.`:`SEARCH_RESULTS: No results found. Answer from your knowledge base.`}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}finally{gO(600)}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=ok(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),`${e} FALLBACK REQUIRED: This page is not in the search index. Call flowengage_read_content (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 $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_get_current_page:async()=>{if($(`flowengage_get_current_page ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``,r=mk(),i=r.length?r.join(` | `):`none`;return $(`flowengage_get_current_page ✓`,{url:e,path:t,title:n}),$(`flowengage_get_current_page → page headings collected:`,r),`CURRENT_PAGE. URL: ${e} | Path: ${t} | Title: ${n} | Section headings: ${i}. Use these EXACT strings verbatim for every flowengage_highlight call — never paraphrase or invent headings.`},flowengage_list_forms:async()=>{let e=HO(),t=UO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),SO();let t=sk(e);if(!t.length&&r){let e=r(),n=ck(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=lk(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key,r=e?.value;if(t==null||r==null)continue;hO(`Filling ${String(t)}...`,{spinner:!0});let a=VO(),o=ek(a,String(t),r);if(o.length){for(let[e,t]of o.entries())CO(t),await kO(t),fk(t,r,{skipScroll:e>0}),wO(t),await PO(120);i=o,n.push(String(t));continue}let s=rk(a,String(t));s||=JO(a,String(t)),s||=YO(a,String(t),r),s&&(CO(s),await kO(s),fk(s,r),wO(s),await PO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),hO(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),hO(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{AO(),SO(),gO(700)}},flowengage_click_button:async e=>{let t=ok(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=ak(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{hO(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await kO(r),r.focus?.(),await jO(r),MO(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),hO(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),hO(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{AO(),gO(700)}}};return{...a,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function gk(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Ln();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 _k={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function vk(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 yk(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 bk(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 xk({logo:e,style:t}){let n=bk(typeof e==`string`?e:null);if(!e)return null;if(typeof e==`string`)return n?(0,A.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,A.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:r}):null}function Sk({title:e}){return(0,A.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 Ck(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function wk({orbColors:e,...t}){return(0,A.jsx)(tO,{colors:e,...t})}function Tk({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||_k.green,c=yk(s),l=a?72:94,u=(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,A.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,A.jsx)(gm.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,A.jsxs)(gm.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,A.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,A.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,A.jsx)(gm.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,A.jsx)(wk,{size:l,orbColors:t})})]});return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(gm.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,A.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,A.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function Ek({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||_k.green,l=yk(c);return(0,A.jsxs)(gm.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,A.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,A.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,A.jsx)(wk,{size:72,orbColors:t}),(0,A.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,A.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,A.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,A.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 Dk({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l}){let[u,d]=(0,b.useState)(`idle`),[f,p]=(0,b.useState)(!1),[m,h]=(0,b.useState)(!1),g=(0,b.useRef)(null),_=(0,b.useRef)(``),v=(0,b.useRef)(async()=>{}),y=(0,b.useRef)(!1),x=(0,b.useRef)(!1),ee=(0,b.useRef)(!1),S=(0,b.useRef)(!1),C=(0,b.useRef)(`minimized`),te=(0,b.useRef)(null),w=(0,b.useRef)(null),ne=(0,b.useRef)(null),re=(0,b.useRef)(0),ie=(0,b.useRef)(!1),T=(0,b.useRef)(`idle`),ae=(0,b.useRef)(!1),oe=(0,b.useRef)(null),se=(0,b.useRef)(null),ce=(0,b.useRef)(!1),le=(0,b.useCallback)((e=`minimized`)=>{C.current=e,S.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[s]),E=(0,b.useCallback)(async e=>{S.current=!0;try{mD()}catch{}if(i)try{Re(i)}catch{}try{await g.current?.endSession?.()}catch{}let t=te.current,n=w.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,elevenLabsConversationId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(te.current=null,w.current=null,g.current=null,d(`idle`),p(!1),y.current=!1,kr(),i)try{Oe(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);return v.current=()=>E(C.current===`chat`?t:n),(0,b.useEffect)(()=>{x.current=f},[f]),(0,b.useEffect)(()=>{l&&le(`chat`)},[l]),(0,b.useEffect)(()=>{let e=!1,l=null,u=null,f=null;return(async()=>{if(!r){d(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],_.current=``,y.current=!1,ee.current=!1,S.current=!1,C.current=`minimized`,Or({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=uO(s.current);e&&Ee(i,e)}catch{}if(!$n()){let e=te.current,t=w.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,elevenLabsConversationId:e,duration:n,siteId:i}),s=`${a}/api/voice/save-chat-recording`;fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:r,keepalive:!0}).catch(()=>{}),te.current=null,w.current=null}catch{}}Ae()}});let t=gk(hk({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,requestEndSession:()=>{ie.current=!0}})),n=i?De(i):null,c=!!n?.transcript,m=!!(i&&Re(i)),h=typeof window<`u`?window.location.pathname:`/`,v=typeof document<`u`?document.title:``,b=h===`/`||h===``,ne=null;try{let e=await fetch(`${a}/api/voice/signed-url?siteId=${encodeURIComponent(i||``)}`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(e.ok)ne=(await e.json()).signedUrl||null,ne&&console.log(`[FlowEngage] ✅ Using signed ElevenLabs URL`);else if(e.status===429){let t=await e.json().catch(()=>({}));throw Error(t.message||`Too many voice sessions started. Please wait a minute before trying again.`)}else console.warn(`[FlowEngage] ⚠️ Signed URL fetch failed, falling back to agentId`)}catch(e){if(e.message&&e.message.includes(`Too many voice sessions`))throw e;console.warn(`[FlowEngage] ⚠️ Signed URL fetch error:`,e.message)}let E={clientTools:t,connectionType:`websocket`,minSpeechDurationMs:50,...ne?{signedUrl:ne}:{agentId:r}},D=(h.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),ue=``;v&&v.includes(`|`)&&(ue=v.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let de=ue||D||`this page`;ne?m?(E.overrides={agent:{firstMessage:`I've navigated you to the ${de} page. Let me walk you through what's here.`}},console.log(`[FlowEngage] 🔄 Agent-nav resume: firstMessage set for "${de}" (${h})`)):c?E.overrides={agent:{firstMessage:`I'm still here. Go ahead!`}}:b||(E.overrides={agent:{firstMessage:`Hi! I see you are currently on the ${de} page. Are you looking for something specific here?`}},console.log(`[FlowEngage] 🏠 Page-context override: "${de}" for ${h}`)):c&&(E.overrides={agent:{firstMessage:``}});let fe=!1,pe=m?`NAVIGATION RESUME — Your intro has been spoken. NOW — without waiting for the visitor to say anything — call flowengage_highlight for the first content section on this page, then speak one sentence about it. Continue section by section (highlight + one sentence each) until you have covered the key content. Prior conversation context:\n${(i?De(i):null)?.transcript||``}\n\n`:null,me=await uD.startSession({...E,onConnect:({conversationId:e})=>{te.current=e,w.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{if(!e){if(t===`speaking`){se.current&&=(clearTimeout(se.current),null),d(`speaking`),T.current=`speaking`,ae.current=!0,ce.current=!1,oe.current&&=(clearTimeout(oe.current),null);return}if(T.current=`listening`,ie.current){ie.current=!1,le();return}if(pe&&!fe){fe=!0;try{g.current?.sendUserMessage?.(`continue with the tour`)}catch{}}se.current&&clearTimeout(se.current),se.current=setTimeout(()=>{e||T.current!==`speaking`&&(ce.current||(se.current=null,T.current=`listening`,d(`listening`)))},1200)}},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(r){if(n===`user`&&(_.current=r,ce.current=!0,se.current&&=(clearTimeout(se.current),null),oe.current&&=(clearTimeout(oe.current),null)),s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=uO(s.current);e&&Ee(i,e)}catch{}if(Ck(n,r)){le(`minimized`);return}if(x.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(re.current+=1,re.current===2)try{g.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 flowengage_end_session tool to end the voice session. Do NOT ask again after that.`)}catch{}else re.current>=5&&le(`minimized`)}},onError:t=>{if(!e&&!S.current&&!ee.current&&!Fe()){ee.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),d(`error`),le(`chat`)}},onDisconnect:t=>{if(e||S.current||ee.current||Fe())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:_.current||``,wasMuted:x.current}),ee.current=!0;try{g.current?.setMicMuted?.(!0)}catch{}p(!0),le(`chat`)}});if(e){me.endSession().catch(()=>{});return}l=me,g.current=me,d(`listening`);try{let e=typeof window<`u`?window.location.href:``,r=`[]`;try{r=await t.list_page_forms()}catch{}let a=c&&!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`:``;me.sendContextualUpdate(`${a}Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${r}. 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=()=>{if(e)return;let n=window.location.pathname;if(n===t)return;if(qn()){t=n;return}let r=t;t=n;let i=window.location.href,a=typeof document<`u`?document.title:``,o=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{mD()}catch{}let s=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,c=s(r),l=s(n);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:r,toPath:n,fromPageName:c,toPageName:l,ts:Date.now()});try{g.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${l}" page (${i}). Page title: "${a}". Sections: ${JSON.stringify(o)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${l} 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 flowengage_navigate, do NOT call flowengage_highlight, the visitor will navigate themselves if needed. IF I want to hear about this page: call flowengage_highlight for sections of "${l}" only.]`)}catch{}};u=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{u(...e),setTimeout(n,50)},f=()=>setTimeout(n,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`)):(d(`error`),C.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{e=!0,S.current=!0;try{mD()}catch{}if(i)try{Re(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),kr(),oe.current&&=(clearTimeout(oe.current),null),se.current&&=(clearTimeout(se.current),null),ae.current=!1,ce.current=!1,T.current=`idle`,u&&typeof window<`u`&&(window.history.pushState=u),f&&typeof window<`u`&&window.removeEventListener(`popstate`,f);let t=l||g.current,n=te.current,r=w.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=r?Math.round((Date.now()-r)/1e3):0,t=JSON.stringify({chatId:o,elevenLabsConversationId:n,duration:e,siteId:i}),s=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(s,new Blob([t],{type:`application/json`}))||fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),te.current=null,w.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,le]),(0,b.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ne.current&&!ne.current.contains(t)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,A.jsxs)(`div`,{ref:ne,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,A.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&!f&&(0,A.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),f&&(0,A.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,A.jsx)(wk,{size:72,voiceState:u,isMuted:f,orbColors:e})]}),u===`error`&&(0,A.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,A.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,A.jsx)(`button`,{onClick:async()=>{if(g.current)try{if(f){re.current=0,await g.current.setMicMuted?.(!1),p(!1);try{g.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{re.current=0,await g.current.setMicMuted?.(!0),p(!0);try{g.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{}},title:f?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:f?`#7f1d1d`:`#1f2937`,border:f?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:f?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:f?(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,A.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,A.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,A.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,A.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,A.jsx)(hD,{size:16,color:`currentColor`})}),(0,A.jsx)(`button`,{onClick:()=>h(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,A.jsx)(CD,{size:16,color:`currentColor`})})]}),m&&(0,A.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,A.jsxs)(`button`,{onClick:()=>{h(!1),C.current=`chat`,E(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,A.jsx)(wD,{}),`Enter Chat Mode`]}),(0,A.jsxs)(`button`,{onClick:()=>{h(!1),C.current=`minimized`,E(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,A.jsx)(TD,{}),`End Conversation`]}),(0,A.jsx)(`button`,{onClick:()=>h(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,A.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,A.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function Ok({orbColors:e}){return(0,A.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,A.jsx)(wk,{size:36,orbColors:e})})}var kk=()=>(0,A.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,A.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,A.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function Ak({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:d,agentName:f,agentHeadshot:p,fallbackAgentName:m,input:h,setInput:g,onSubmit:_,isConversationEnded:v,isLoading:y,isRateLimited:x,rateLimitMessage:ee,selectedFile:S,onFileSelect:C,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:T,emailError:ae,emailCaptureSuccess:oe,replyContext:se,setReplyContext:ce,webRTCError:le,micError:E,setMicError:D,dismissCallError:ue,activeCallId:de,isCallMuted:fe,toggleCallMute:pe,endWebRTCCall:me,formatCallDuration:he,callDurationSeconds:ge,isCallMinimized:_e,onExpand:ve,onCollapse:ye,onStartVoice:be,onNewChat:xe,showPoweredBy:Se,getVisitorChatHistory:Ce,resumeChat:we,isSessionRestoring:Te,isClosing:Ee}){let De=c.length>0,Oe=y||x||v,ke=!!de,[Ae,je]=(0,b.useState)(!1),[Me,Ne]=(0,b.useState)(!1),[Pe,Fe]=(0,b.useState)([]),[Ie,Le]=(0,b.useState)(!1),Re=(0,b.useRef)(null),[ze,Be]=(0,b.useState)(()=>typeof window<`u`?window.visualViewport?.height??window.innerHeight:600),[Ve,He]=(0,b.useState)(0);(0,b.useEffect)(()=>{if(!s)return;let e=window.visualViewport;if(!e)return;let t=()=>{Be(e.height),He(Math.max(0,window.innerHeight-e.offsetTop-e.height))};return e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}},[s]);let Ue=s&&window.innerHeight-ze>150,We=async()=>{je(!1),Ne(!0),Le(!0);try{let e=await Ce();e?.data&&Fe(e.data)}catch(e){console.error(e)}finally{Le(!1)}},Ge=async e=>{Ne(!1),we?.(e.chatId)};return(0,b.useEffect)(()=>{if(!Ae)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Re.current&&!Re.current.contains(t)&&je(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Ae]),(0,A.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:`${Ve}px`,height:ze>0?`${Math.round(ze*.92)}px`:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:Ee?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:Ee?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,A.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0,position:`relative`,zIndex:30},children:[(0,A.jsx)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,A.jsx)(`button`,{onClick:ye,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,A.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})})}),(0,A.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,A.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,A.jsx)(xk,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,A.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,A.jsx)(Sk,{title:e.chatTitle})})}),(0,A.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,A.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,A.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Re,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>je(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,A.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,A.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,A.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,A.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Ae&&(0,A.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),be?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,A.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,A.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),xe?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,A.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new chat`]}),Ce&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,A.jsxs)(`button`,{type:`button`,onClick:We,style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,A.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`path`,{d:`M12 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,A.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,A.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),ye?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,A.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,A.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,A.jsx)(KD,{webRTCError:le,micError:E,setMicError:D,dismissCallError:ue,isRateLimited:x,rateLimitMessage:ee}),_e&&(0,A.jsx)(lO,{agentName:f,agentHeadshot:p,fallbackAgentName:m,callDurationSeconds:ge,isCallMuted:fe,formatCallDuration:he,toggleCallMute:pe,endWebRTCCall:me,onExpand:ve,primaryColor:n}),(0,A.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Me?(0,A.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,A.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:(0,A.jsxs)(`button`,{onClick:()=>Ne(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,A.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,A.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,A.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Ie?(0,A.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):Pe.length>0?(0,A.jsx)(`div`,{children:Pe.map(e=>(0,A.jsxs)(`div`,{onClick:()=>Ge(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,A.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,A.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,A.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,De?(0,A.jsx)(WD,{chatHistory:c,isAiTyping:l,isLoading:y,isAgentTyping:u,setReplyContext:ce,TypingDots:kk,primaryColor:n,agentHeadshot:p,agentDisplayName:f||m,botAvatarNode:(0,A.jsx)(Ok,{orbColors:t})}):Te?(0,A.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,A.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,A.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,A.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(0,A.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,A.jsx)(wk,{size:94,orbColors:t}),(0,A.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,A.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,A.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})]}),oe&&(0,A.jsxs)(`div`,{style:{margin:`0 16px 8px`,padding:`9px 14px`,borderRadius:`12px`,background:`#ecfdf5`,border:`1px solid #6ee7b7`,display:`flex`,alignItems:`center`,gap:`8px`,animation:`fe-orb-fade-in 0.2s ease`,flexShrink:0},children:[(0,A.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#10b981`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,A.jsx)(`polyline`,{points:`20 6 9 17 4 12`})}),(0,A.jsx)(`span`,{style:{fontSize:`13px`,fontWeight:500,color:`#065f46`},children:`Email saved — we'll be in touch!`})]}),(0,A.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:re?`6px 0 0`:`12px 0 0`},children:(0,A.jsx)(GD,{input:h,setInput:g,onSubmit:_,isConversationEnded:v,callUiActive:ke,handleToggleVoice:be,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Oe,replyContext:se,clearReplyContext:()=>ce(null),onFileSelect:C,selectedFile:S,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:T,emailError:ae,inputPlaceholder:e.inputPlaceholder})}),!Ue&&(0,A.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`8px 20px`,paddingBottom:`max(12px, env(safe-area-inset-bottom, 12px))`,pointerEvents:`none`},children:Se&&(0,A.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,A.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function jk(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:d,isLoading:f,isRateLimited:p,rateLimitMessage:m,isConversationEnded:h,incomingCall:g,activeCallId:_,callConnectionState:v,callConnectedAt:y,isCallMuted:x,webRTCError:ee,language:S,chatId:C,historyRef:te,onMessageSync:w,sendMessage:ne,uploadChatFile:re,openWidget:ie,captureVisitorEmail:T,setVoiceMode:ae,endConversation:oe,startNewChat:se,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,dismissCallError:fe,startTyping:pe,stopTyping:me,updateTypingDraft:he,getVisitorChatHistory:ge,resumeChat:_e,isSessionRestoring:ve,openToChatCounter:ye,voiceEndCounter:be}=In();(0,b.useEffect)(()=>{try{fr()}catch{}},[]),(0,b.useEffect)(()=>{ye&&O!==`text_chat`&&O!==`call_screen`&&(ae?.(!1),nt(`text_chat`))},[ye]);let xe=t?.widgetSettings||{},Se=n?.widgetSettings||{},Ce={...xe.branding||{},...Se.branding||{}},we={...xe.theme||{},...Se.theme||{}},Te={...xe.features||{},...Se.features||{}},Ee=Te.voice!==!1,ke=Array.isArray(we.orbColors)&&we.orbColors.length>0?we.orbColors:null,Ae=we.buttonColor||we.primaryColor||ke?.[0]||`#3B82F6`,Me={small:50,medium:64,large:80},Ne=Me[we.orbSize]||Me.small,Fe=we.position||`bottom-right`,Ie=Ce.fallbackAgentName||`Agent`,Le=vk(ke??we.chatBgColors),Re=Ce.logo||Ce.logoUrl||null,ze=S||`en`,Be=xe.recommendations?.[ze]||[],Ve=(Se.recommendations?.[ze]??Be).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),He=Array.isArray(Ce.quickChatOptions)&&Ce.quickChatOptions.length>0?Ce.quickChatOptions:Ve,Ue=Ce.hideWatermark===!0?!1:Ce.showPoweredBy!==!1,We=Ce.chatbotEnabled!==!1&&we.chatbotEnabled!==!1,Ge=xe.greetings?.[S]||Se.greetings?.[S]||Ce.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Ke={entryPrompt:Ce.entryPrompt||`Do you want to explore in a new way?`,yesLabel:Ce.yesLabel||`Yes`,laterLabel:Ce.laterLabel||`Later`,connectionTitle:Ce.connectionTitle||`How would you like to connect?`,voiceLabel:Ce.voiceLabel||`Voice`,textLabel:Ce.textLabel||`Text`,chatTitle:Ce.headerName||`Chat with FlowEngage`,introGreeting:Ge,inputPlaceholder:Ce.inputPlaceholder||`Type your message`,analysingLabel:Ce.analysingLabel||`analysing...`},qe=Se.elevenLabsAgentId||t?.elevenLabsAgentId||null,Je=t?.siteId||n?.siteId||null,Ye=t?.apiBaseUrl||``,Xe=(0,b.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Ze=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Qe=r.some(e=>e.sender===`user`),$e=(0,b.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),et=!l&&Qe&&$e,tt=!!(Se._dashboardLivePreview||xe._dashboardLivePreview),[O,nt]=(0,b.useState)(()=>tt?`text_chat`:`entry_prompt`),[rt,it]=(0,b.useState)(``),[at,ot]=(0,b.useState)(null),[st,ct]=(0,b.useState)(l||``),[lt,ut]=(0,b.useState)(``),[dt,ft]=(0,b.useState)(!1),[pt,mt]=(0,b.useState)(0),[ht,gt]=(0,b.useState)(null),[_t,vt]=(0,b.useState)(null),[yt,bt]=(0,b.useState)(``),[xt,St]=(0,b.useState)(!1),[Ct,wt]=(0,b.useState)(!1),[Tt,Et]=(0,b.useState)(!1),Dt=(0,b.useRef)(null),Ot=(0,b.useRef)(!1);(0,b.useLayoutEffect)(()=>{if(e!==`ready`||Ot.current)return;if(Ot.current=!0,!Ee){nt(`minimized_orb`);return}let t=!1;try{t=wr().shouldResumeVoice}catch{}let n=je(),r=Je?De(Je):null,i=n||!!r?.transcript;if(t){ie?.({notifyChatInitiated:!0}),ae?.(!0),nt(`voice_mode`);return}if(Pe()){ie?.({notifyChatInitiated:!1}),nt(`text_chat`);return}if(Je)try{Oe(Je)}catch{}if(i){nt(`minimized_orb`);return}if(E(Je)){nt(`minimized_orb`);return}},[e,r]);let[kt,At]=(0,b.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,b.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>At(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,b.useEffect)(()=>{ct(l||``),l&&ut(``)},[l]);let jt=(0,b.useCallback)(()=>{vt(null),bt(``)},[]),Mt=(0,b.useCallback)(e=>{let t=zD(e);if(t){vt(null),bt(t);return}vt(e),bt(``)},[]);(0,b.useEffect)(()=>{if(!y||v!==`connected`){mt(0);return}let e=()=>{let e=new Date(y).getTime();isNaN(e)||mt(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[y,v]);let Nt=(0,b.useCallback)(()=>{nt(`call_screen`),wt(!1)},[]),Pt=(0,b.useCallback)(()=>{nt(`text_chat`),wt(!0)},[]);(0,b.useEffect)(()=>{let e=g?.callId||_||null;if(!e){Dt.current=null;return}if(g?.callId||v===`connecting`||v===`connected`){if(O===`minimized_orb`&&Ct&&_&&!g?.callId){Dt.current=e;return}!(!i||O===`minimized_orb`||O===`voice_mode`)&&Dt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:O,hasIncomingCall:!!g?.callId,activeCallId:_,callConnectionState:v}),Dt.current=e,O===`voice_mode`&&ae?.(!1),ie?.(),Nt())}},[_,v,Nt,g?.callId,i,ie,ae,O]),(0,b.useEffect)(()=>{!g&&!_&&O===`call_screen`&&nt(`text_chat`)},[g,_,O]),(0,b.useEffect)(()=>{!_&&Ct&&wt(!1)},[_,Ct]),(0,b.useEffect)(()=>{if(!o||h){he?.(``),me?.();return}if(!rt.trim()||_t){he?.(``);let e=window.setTimeout(()=>me?.(),100);return()=>window.clearTimeout(e)}pe?.();let e=window.setTimeout(()=>he?.(rt),120),t=window.setTimeout(()=>me?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[rt,_t,o,h,pe,me,he]);let Ft=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,It=async e=>{if(e.preventDefault(),h)return;if(et){let e=st.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){ut(`Please enter a valid email so we can continue helping you.`);return}await T(e),ut(``),ft(!0),setTimeout(()=>ft(!1),3e3);return}let t=Ft(at);if(!rt.trim()&&!_t)return;if(_t){try{St(!0),bt(``);let e=await re(_t),n=e?.data||e,r=rt.trim()||`Shared file: ${VD(_t)}`;it(``),ot(null),jt(),await ne(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||_t.name,fileType:n?.fileType||_t.type,fileSize:n?.fileSize||_t.size}})}catch(e){bt(e?.message||`Failed to upload the selected file.`)}finally{St(!1)}return}let n=rt.trim();it(``),ot(null),await ne(n,``,t)},Lt=(0,b.useCallback)(()=>{r.length!==0&&se?.()},[r.length,se]),Rt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},zt=(0,b.useCallback)(async e=>{if(h||f)return;let t=e.message||e.label||e.text||``;t.trim()&&await ne(t.trim(),``)},[h,f,ne]),Bt=kt&&O===`entry_prompt`?{inset:0}:kt&&O===`text_chat`?{left:0,right:0,bottom:0}:kt&&O===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:kt&&O===`connection_modal`?{left:`12px`,right:`12px`,bottom:`12px`}:O===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Fe===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`}}:Fe===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Vt=(0,b.useCallback)(()=>{O!==`minimized_orb`&&(Et(!0),setTimeout(()=>{nt(`minimized_orb`),Et(!1),_&&wt(!0)},280))},[_,O]),Ht=()=>nt(`connection_modal`),Ut=()=>{try{let e=window.AudioContext||window.webkitAudioContext;if(e){let t=new e;t.resume().catch(()=>{}),setTimeout(()=>t.close().catch(()=>{}),3e3)}}catch{}ie({notifyChatInitiated:!0}),ae?.(!0),nt(`voice_mode`)},Wt=()=>{ie({notifyChatInitiated:!0}),ae?.(!1),nt(`text_chat`)},Gt=()=>{ae?.(!1),Vt()};return e!==`ready`||!We||Te.chat===!1?null:(0,A.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Bt},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[O===`entry_prompt`&&(0,A.jsx)(Tk,{copy:Ke,orbColors:ke,primaryColor:Ae,onYes:()=>{D(Je),Ut()},onLater:()=>{D(Je),Vt()},isMobile:kt,isClosing:Tt}),O===`minimized_orb`&&(0,A.jsxs)(gm.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Fe===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[_&&(0,A.jsxs)(`button`,{type:`button`,onClick:Nt,style:{maxWidth:kt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,A.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,A.jsxs)(`span`,{style:{minWidth:0},children:[(0,A.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:v===`connected`?`Call in progress`:`Call is active`}),(0,A.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:v===`connected`?`${Rt(pt)} with ${Xe}`:`Tap to return to ${Xe}`})]})]}),(0,A.jsx)(wk,{size:Ne,orbColors:ke,onClick:_?Nt:Ee?Ht:Wt})]}),O===`connection_modal`&&(0,A.jsx)(Ek,{copy:Ke,orbColors:ke,primaryColor:Ae,onVoice:Ut,onText:Wt,onClose:Vt,isMobile:kt,isClosing:Tt}),O===`voice_mode`&&(0,A.jsx)(Dk,{orbColors:ke,onEnterChat:Wt,onEndChat:Gt,agentId:qe,siteId:Je,apiBaseUrl:Ye,chatId:C,historyRef:te,onMessageSync:w,voiceEndCounter:be},`voice`),O===`call_screen`&&(0,A.jsx)(cO,{incomingCall:g,activeCallId:_,callConnectionState:v,callDurationSeconds:pt,isCallMuted:x,agentName:Xe,agentHeadshot:Ze,fallbackAgentName:Ie,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,formatCallDuration:Rt,onMinimize:Pt,primaryColor:Ae,orbColors:ke,chatHistory:r}),O===`text_chat`&&(0,A.jsx)(Ak,{isClosing:Tt,copy:Ke,orbColors:ke,primaryColor:Ae,chatBgGradient:Le,logo:Re,quickChatOptions:He,onQuickChatSelect:zt,isMobile:kt,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Xe,agentHeadshot:Ze,fallbackAgentName:Ie,input:rt,setInput:it,onSubmit:It,isConversationEnded:h,isLoading:f,isRateLimited:p,rateLimitMessage:m,selectedFile:_t,onFileSelect:Mt,onRemoveSelectedFile:jt,attachmentError:yt,isUploadingAttachment:xt,requiresEmail:et,emailInput:st,setEmailInput:ct,emailError:lt,emailCaptureSuccess:dt,replyContext:at,setReplyContext:ot,webRTCError:ee,micError:ht,setMicError:gt,dismissCallError:fe,activeCallId:_,isCallMuted:x,toggleCallMute:de,endWebRTCCall:ue,formatCallDuration:Rt,callDurationSeconds:pt,onCollapse:Vt,onStartVoice:Ut,onNewChat:Lt,onMinimize:Pt,onExpand:Nt,isCallMinimized:!!_,showPoweredBy:Ue,getVisitorChatHistory:ge,resumeChat:_e,isSessionRestoring:ve}),(0,A.jsx)(`style`,{children:`
|
|
644
644
|
/* Force any SVG (or img) inside LogoSlot to fill the container height
|
|
645
645
|
regardless of whether the component forwards its style prop. */
|
|
646
646
|
.fe-logo-slot svg,
|
|
@@ -631,8 +631,8 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
631
631
|
<path d="M4 2L19 10.5L11 12.8L8 20L4 2Z"
|
|
632
632
|
fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
|
|
633
633
|
filter="url(#${Q}-csh)"/>
|
|
634
|
-
</svg>`,xO=null,SO=!1;function CO(){return(!xO||!xO.isConnected)&&(xO=document.createElement(`div`),xO.id=`${Q}-cursor`,xO.innerHTML=bO,document.body.appendChild(xO),SO=!1),xO}async function wO(e){if(typeof document>`u`||!e)return;oO();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=CO();SO||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await OO(360)}function TO(e=!1){xO&&(e?(xO.classList.remove(`${Q}-cursor-visible`),SO=!1):(xO.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{SO=!1},250)))}async function EO(e){xO&&(xO.classList.add(`${Q}-cursor-click`),await OO(280),xO.classList.remove(`${Q}-cursor-click`))}function DO(e){if(!e||typeof document>`u`)return;oO();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function OO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){An()&&console.log(`[FlowEngage:voice-tools]`,...e)}function kO(e){return new Promise(t=>setTimeout(t,e))}var AO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function jO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(AO)}catch{return!1}}function MO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function NO(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!jO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function PO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function FO(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return PO(r.join(` `))}if(e.labels&&e.labels.length)return PO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return PO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return PO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return PO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=PO(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return PO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return PO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?PO(o):null}function IO(){let e=[];return NO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(jO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=MO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function LO(){return IO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:FO(e),placeholder:e.placeholder||null}))}function RO(){let e=[];return NO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(jO(e)||e.disabled)return!1;try{let t=MO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function zO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function BO(e){let t=zO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function VO(e,t){let n=BO(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,FO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>zO(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var HO=28;function UO(e,t){let n=null,r=0;for(let i of e){let e=VO(i,t);e>r&&(r=e,n=i)}return!n||r<HO?null:n}function WO(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,FO(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function GO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function KO(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function qO(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function JO(e){if(!qO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,FO(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function YO(e,t,n){let r=String(t??``),i=String(n??``),a=QO(e,r)||UO(e,r)||WO(e,r,i);if(!a)return[];let o=new Set([a]);if(GO(i)&&KO(r))for(let t of e)t!==a&&JO(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function XO(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function ZO(e){if(!e||typeof e!=`string`)return null;let t=null;return NO(n=>{try{let r=n.getElementById(e);r&&!jO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function QO(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=ZO(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=ZO(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function $O(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=(e.innerText||e.textContent||``).replace(/\s+/g,` `).trim(),i=[r,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-text`),e.getAttribute(`data-label`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(i.includes(n)||r.toLowerCase()===n)return 100;let a=n.split(/\s+/).filter(e=>e.length>1);if(!a.length)return 0;let o=0;for(let e of a)i.includes(e)&&(o+=1);return o/a.length*92}function ek(e,t){let n=[];NO(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));n.push(...t.filter(e=>{if(jO(e)||e.disabled)return!1;try{let t=MO(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:$O(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<28)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=XO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function tk(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function nk(e){let t=tk(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function rk(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function ik(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function ak(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function ok(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function sk(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function ck(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function lk(){let e=document.querySelector(`main, [role='main'], article`)||document.body;return Array.from(e.querySelectorAll(`h1, h2, h3`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200).slice(0,12)}function uk(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let i=tk(n),a=ak(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($(`flowengage_navigate · 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 $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(a=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,a))}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 $(`flowengage_navigate ✖ 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{}}if(!await dr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${a}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{uO(`Navigating to ${a}...`,{spinner:!0}),hO(),lD();try{let e=r?r():``;if(e&&t){let n=aO([{sender:`user`,message:e}]);n&&xe(t,n)}}catch{}Te();let e=a;try{e=new URL(a,typeof window<`u`?window.location.href:``).href}catch{}t&&typeof window<`u`&&Me(t,window.location.href,e),mr(e),$(`flowengage_navigate → real navigation`,a);let n=typeof window<`u`&&!!Gn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),n&&Rn(3e3),_r(a,{voiceActive:!0}).catch(()=>{}),n)try{let e=new URL(a,window.location.origin).pathname,t=Date.now()+2e3;for(;Date.now()<t&&!(typeof window<`u`&&window.location.pathname===e);)await new Promise(e=>setTimeout(e,80));let n=typeof window<`u`?window.location.pathname:e,r=typeof window<`u`?window.location.href:a,i=n===e,o=(n.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`;$(`flowengage_navigate → SPA nav complete. target:`,e,`actual:`,n);let s=[],c=Date.now()+12e3;for(;Date.now()<c&&(await new Promise(e=>setTimeout(e,300)),s=lk(),!(s.length>=1)););ck(),$(`flowengage_navigate → page headings collected:`,s);let l=s.length?s.join(` | `):`none`,u=s.length?`Use ONLY these exact heading strings for flowengage_highlight — never invent or abbreviate.`:`No headings collected yet — call flowengage_get_current_page immediately (no speech) to get the live headings before speaking or highlighting.`;return i?(hr(),`OK_NAVIGATE_SPA. Visitor is now on: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page from your knowledge, then STOP. Do NOT highlight. Do NOT walk through sections. Wait for the visitor to respond. Only do a highlighted walkthrough if they explicitly ask for one.`):(hr(),`OK_NAVIGATE_SPA. CURRENT PAGE IS: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page from your knowledge, then STOP. Do NOT highlight or walk through sections. Describe THIS page only — do not mention the page you tried to navigate to.`)}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, immediately introduce the new page and continue guiding the visitor — do not wait for the user to speak first.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),uO(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{gO(),dO(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=tk(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(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 flowengage_highlight 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.`}ck();let i=or(n||null,r||null);if(!i&&r){let e=Date.now()+600;for(;!i&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),ck(),i=or(null,r)}if(!i){$(`flowengage_highlight ✖ no element for:`,r||n);let e=lk(),t=e.length?`Page headings: ${e.join(` | `)}. Use one of these exact strings for section_text.`:`No headings found — skip highlight and continue.`;return`HIGHLIGHT_NOT_FOUND: "${r||n}" on the current page. ${t}`}return cD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}". WALKTHROUGH: continue immediately to the next section — do NOT pause between sections.`},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=tk(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=or(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
|
|
635
|
-
`)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=ok(tk(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;uO(`Searching${r?` for "${r}"`:``}…`,{spinner:!0});try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),o.length?`SEARCH_RESULTS: ${JSON.stringify(o)}. MANDATORY: Do NOT call flowengage_navigate now. Speak the answer from these results in 2-3 sentences. Then ask the visitor if they want to go to a relevant page — e.g. "Would you like me to take you to that page?" Only navigate if they say yes.`:`SEARCH_RESULTS: No results found. Answer from your knowledge base.`}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}finally{dO(600)}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=tk(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),`${e} FALLBACK REQUIRED: This page is not in the search index. Call flowengage_read_content (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 $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_get_current_page:async()=>{if($(`flowengage_get_current_page ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``,r=lk(),i=r.length?r.join(` | `):`none`;return $(`flowengage_get_current_page ✓`,{url:e,path:t,title:n}),$(`flowengage_get_current_page → page headings collected:`,r),`CURRENT_PAGE. URL: ${e} | Path: ${t} | Title: ${n} | Section headings: ${i}. These are the EXACT heading strings — use them verbatim for every flowengage_highlight call. If the visitor has already requested a walkthrough, proceed immediately with the full highlighted walkthrough using these headings. If not, give 1-2 sentences about the page and wait.`},flowengage_list_forms:async()=>{let e=LO(),t=RO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),_O();let t=nk(e);if(!t.length&&r){let e=r(),n=rk(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=ik(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key,r=e?.value;if(t==null||r==null)continue;uO(`Filling ${String(t)}...`,{spinner:!0});let a=IO(),o=YO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())vO(t),await wO(t),sk(t,r,{skipScroll:e>0}),yO(t),await kO(120);i=o,n.push(String(t));continue}let s=QO(a,String(t));s||=UO(a,String(t)),s||=WO(a,String(t),r),s&&(vO(s),await wO(s),sk(s,r),yO(s),await kO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),uO(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),uO(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{TO(),_O(),dO(700)}},flowengage_click_button:async e=>{let t=tk(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=ek(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{uO(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await wO(r),r.focus?.(),await EO(r),DO(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),uO(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),uO(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{TO(),dO(700)}}};return{...a,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function dk(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=An();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var fk={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function pk(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 mk(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 hk(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 gk({logo:e,style:t}){let n=hk(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 _k({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 vk(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function yk({orbColors:e,...t}){return(0,f.jsx)(XD,{colors:e,...t})}function bk({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||fk.green,c=mk(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)(_m.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,f.jsxs)(_m.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)(_m.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)(yk,{size:l,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(_m.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 xk({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||fk.green,l=mk(c);return(0,f.jsxs)(_m.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)(yk,{size:72,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background: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 Sk({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l}){let[u,p]=(0,d.useState)(`idle`),[m,h]=(0,d.useState)(!1),[g,_]=(0,d.useState)(!1),v=(0,d.useRef)(null),y=(0,d.useRef)(``),b=(0,d.useRef)(async()=>{}),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(!1),te=(0,d.useRef)(!1),ne=(0,d.useRef)(`minimized`),re=(0,d.useRef)(null),C=(0,d.useRef)(null),ie=(0,d.useRef)(null),ae=(0,d.useRef)(0),oe=(0,d.useRef)(!1),se=(0,d.useRef)(`idle`),ce=(0,d.useRef)(!1),le=(0,d.useRef)(null),ue=(0,d.useRef)(null),de=(0,d.useRef)(!1),fe=(0,d.useCallback)((e=`minimized`)=>{ne.current=e,te.current=!0,queueMicrotask(()=>{x.current||(x.current=!0,b.current?.())})},[s]),pe=(0,d.useCallback)(async e=>{te.current=!0;try{lD()}catch{}if(i)try{Ne(i)}catch{}try{await v.current?.endSession?.()}catch{}let t=re.current,n=C.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,elevenLabsConversationId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(re.current=null,C.current=null,v.current=null,p(`idle`),h(!1),x.current=!1,xr(),i)try{Ce(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);return b.current=()=>pe(ne.current===`chat`?t:n),(0,d.useEffect)(()=>{S.current=m},[m]),(0,d.useEffect)(()=>{l&&fe(`chat`)},[l]),(0,d.useEffect)(()=>{let e=!1,l=null,u=null,d=null;return(async()=>{if(!r){p(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],y.current=``,x.current=!1,ee.current=!1,te.current=!1,ne.current=`minimized`,br({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=aO(s.current);e&&xe(i,e)}catch{}if(!Gn()){let e=re.current,t=C.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,elevenLabsConversationId: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(()=>{}),re.current=null,C.current=null}catch{}}Te()}});let t=dk(uk({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>y.current,requestEndSession:()=>{oe.current=!0}})),n=i?Se(i):null,c=!!n?.transcript,f=!!(i&&Ne(i)),m=typeof window<`u`?window.location.pathname:`/`,g=typeof document<`u`?document.title:``,_=m===`/`||m===``,b=null;try{let e=await fetch(`${a}/api/voice/signed-url?siteId=${encodeURIComponent(i||``)}`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(e.ok)b=(await e.json()).signedUrl||null,b&&console.log(`[FlowEngage] ✅ Using signed ElevenLabs URL`);else if(e.status===429){let t=await e.json().catch(()=>({}));throw Error(t.message||`Too many voice sessions started. Please wait a minute before trying again.`)}else console.warn(`[FlowEngage] ⚠️ Signed URL fetch failed, falling back to agentId`)}catch(e){if(e.message&&e.message.includes(`Too many voice sessions`))throw e;console.warn(`[FlowEngage] ⚠️ Signed URL fetch error:`,e.message)}let ie={clientTools:t,connectionType:`websocket`,minSpeechDurationMs:50,...b?{signedUrl:b}:{agentId:r}},pe=(m.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),me=``;g&&g.includes(`|`)&&(me=g.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let he=me||pe||`this page`;b?f?(ie.overrides={agent:{firstMessage:`I've navigated you to the ${he} page. Let me walk you through what's here.`}},console.log(`[FlowEngage] 🔄 Agent-nav resume: firstMessage set for "${he}" (${m})`)):c?ie.overrides={agent:{firstMessage:`I'm still here. Go ahead!`}}:_||(ie.overrides={agent:{firstMessage:`Hi! I see you are currently on the ${he} page. Are you looking for something specific here?`}},console.log(`[FlowEngage] 🏠 Page-context override: "${he}" for ${m}`)):c&&(ie.overrides={agent:{firstMessage:``}});let ge=!1,_e=f?`NAVIGATION RESUME — Your intro has been spoken. NOW — without waiting for the visitor to say anything — call flowengage_highlight for the first content section on this page, then speak one sentence about it. Continue section by section (highlight + one sentence each) until you have covered the key content. Prior conversation context:\n${(i?Se(i):null)?.transcript||``}\n\n`:null,ve=await aD.startSession({...ie,onConnect:({conversationId:e})=>{re.current=e,C.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{if(!e){if(t===`speaking`){ue.current&&=(clearTimeout(ue.current),null),p(`speaking`),se.current=`speaking`,ce.current=!0,de.current=!1,le.current&&=(clearTimeout(le.current),null);return}if(se.current=`listening`,oe.current){oe.current=!1,fe();return}if(_e&&!ge){ge=!0;try{v.current?.sendUserMessage?.(`continue with the tour`)}catch{}}ue.current&&clearTimeout(ue.current),ue.current=setTimeout(()=>{e||se.current!==`speaking`&&(de.current||(ue.current=null,se.current=`listening`,p(`listening`)))},1200)}},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(r){if(n===`user`&&(y.current=r,de.current=!0,ue.current&&=(clearTimeout(ue.current),null),le.current&&=(clearTimeout(le.current),null)),s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=aO(s.current);e&&xe(i,e)}catch{}if(vk(n,r)){fe(`minimized`);return}if(S.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(ae.current+=1,ae.current===2)try{v.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 flowengage_end_session tool to end the voice session. Do NOT ask again after that.`)}catch{}else ae.current>=5&&fe(`minimized`)}},onError:t=>{if(!e&&!te.current&&!ee.current&&!Ae()){ee.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),p(`error`),fe(`chat`)}},onDisconnect:t=>{if(e||te.current||ee.current||Ae())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:y.current||``,wasMuted:S.current}),ee.current=!0;try{v.current?.setMicMuted?.(!0)}catch{}h(!0),fe(`chat`)}});if(e){ve.endSession().catch(()=>{});return}l=ve,v.current=ve,p(`listening`);try{let e=typeof window<`u`?window.location.href:``,r=`[]`;try{r=await t.list_page_forms()}catch{}let a=c&&!f?`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(`${a}Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${r}. 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=()=>{if(e)return;let n=window.location.pathname;if(n===t)return;if(zn()){t=n;return}let r=t;t=n;let i=window.location.href,a=typeof document<`u`?document.title:``,o=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{lD()}catch{}let s=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,c=s(r),l=s(n);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:r,toPath:n,fromPageName:c,toPageName:l,ts:Date.now()});try{v.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${l}" page (${i}). Page title: "${a}". Sections: ${JSON.stringify(o)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${l} 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 flowengage_navigate, do NOT call flowengage_highlight, the visitor will navigate themselves if needed. IF I want to hear about this page: call flowengage_highlight for sections of "${l}" only.]`)}catch{}};u=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{u(...e),setTimeout(n,50)},d=()=>setTimeout(n,50),window.addEventListener(`popstate`,d)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(p(`error`),ne.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{e=!0,te.current=!0;try{lD()}catch{}if(i)try{Ne(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),xr(),le.current&&=(clearTimeout(le.current),null),ue.current&&=(clearTimeout(ue.current),null),ce.current=!1,de.current=!1,se.current=`idle`,u&&typeof window<`u`&&(window.history.pushState=u),d&&typeof window<`u`&&window.removeEventListener(`popstate`,d);let t=l||v.current,n=re.current,r=C.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=r?Math.round((Date.now()-r)/1e3):0,t=JSON.stringify({chatId:o,elevenLabsConversationId:n,duration:e,siteId:i}),s=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(s,new Blob([t],{type:`application/json`}))||fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),re.current=null,C.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,fe]),(0,d.useEffect)(()=>{if(!g)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ie.current&&!ie.current.contains(t)&&_(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[g]),(0,f.jsxs)(`div`,{ref:ie,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&!m&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),m&&(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)(yk,{size:72,voiceState:u,isMuted:m,orbColors:e})]}),u===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:async()=>{if(v.current)try{if(m){ae.current=0,await v.current.setMicMuted?.(!1),h(!1);try{v.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{ae.current=0,await v.current.setMicMuted?.(!0),h(!0);try{v.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{}},title:m?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:m?`#7f1d1d`:`#1f2937`,border:m?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:m?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:m?(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsx)(uD,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>_(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,f.jsx)(vD,{size:16,color:`currentColor`})})]}),g&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`chat`,pe(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)(yD,{}),`Enter Chat Mode`]}),(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`minimized`,pe(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)(bD,{}),`End Conversation`]}),(0,f.jsx)(`button`,{onClick:()=>_(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function Ck({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(yk,{size:36,orbColors:e})})}var wk=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function Tk({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:ee,selectedFile:te,onFileSelect:ne,onRemoveSelectedFile:re,attachmentError:C,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,emailCaptureSuccess:le,replyContext:ue,setReplyContext:de,webRTCError:fe,micError:pe,setMicError:me,dismissCallError:he,activeCallId:ge,isCallMuted:_e,toggleCallMute:ve,endWebRTCCall:ye,formatCallDuration:be,callDurationSeconds:xe,isCallMinimized:Se,onExpand:Ce,onCollapse:we,onStartVoice:Te,onNewChat:Ee,showPoweredBy:De,getVisitorChatHistory:Oe,resumeChat:ke,isSessionRestoring:Ae,isClosing:je}){let Me=c.length>0,Ne=x||S||b,Pe=!!ge,[Fe,Ie]=(0,d.useState)(!1),[Le,Re]=(0,d.useState)(!1),[ze,Be]=(0,d.useState)([]),[Ve,He]=(0,d.useState)(!1),Ue=(0,d.useRef)(null),[We,Ge]=(0,d.useState)(()=>typeof window<`u`?window.visualViewport?.height??window.innerHeight:600),[Ke,qe]=(0,d.useState)(0);(0,d.useEffect)(()=>{if(!s)return;let e=window.visualViewport;if(!e)return;let t=()=>{Ge(e.height),qe(Math.max(0,window.innerHeight-e.offsetTop-e.height))};return e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}},[s]);let Je=s&&window.innerHeight-We>150,Ye=async()=>{Ie(!1),Re(!0),He(!0);try{let e=await Oe();e?.data&&Be(e.data)}catch(e){console.error(e)}finally{He(!1)}},Xe=async e=>{Re(!1),ke?.(e.chatId)};return(0,d.useEffect)(()=>{if(!Fe)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Ue.current&&!Ue.current.contains(t)&&Ie(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Fe]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:`${Ke}px`,height:We>0?`${Math.round(We*.92)}px`:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:je?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:je?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0,position:`relative`,zIndex:30},children:[(0,f.jsx)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,f.jsx)(`button`,{onClick:we,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})})}),(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(gk,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(_k,{title:e.chatTitle})})}),(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Ue,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>Ie(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Fe&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Ie(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Ie(!1),Ee?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,f.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new chat`]}),Oe&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:Ye,style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M12 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Ie(!1),we?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,f.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,f.jsx)(VD,{webRTCError:fe,micError:pe,setMicError:me,dismissCallError:he,isRateLimited:S,rateLimitMessage:ee}),Se&&(0,f.jsx)(iO,{agentName:m,agentHeadshot:h,fallbackAgentName:g,callDurationSeconds:xe,isCallMuted:_e,formatCallDuration:be,toggleCallMute:ve,endWebRTCCall:ye,onExpand:Ce,primaryColor:n}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Le?(0,f.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:(0,f.jsxs)(`button`,{onClick:()=>Re(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,f.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,f.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Ve?(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):ze.length>0?(0,f.jsx)(`div`,{children:ze.map(e=>(0,f.jsxs)(`div`,{onClick:()=>Xe(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,f.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,Me?(0,f.jsx)(zD,{chatHistory:c,isAiTyping:l,isLoading:x,isAgentTyping:u,setReplyContext:de,TypingDots:wk,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(Ck,{orbColors:t})}):Ae?(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,f.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,f.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,f.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(yk,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})]}),le&&(0,f.jsxs)(`div`,{style:{margin:`0 16px 8px`,padding:`9px 14px`,borderRadius:`12px`,background:`#ecfdf5`,border:`1px solid #6ee7b7`,display:`flex`,alignItems:`center`,gap:`8px`,animation:`fe-orb-fade-in 0.2s ease`,flexShrink:0},children:[(0,f.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#10b981`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,f.jsx)(`polyline`,{points:`20 6 9 17 4 12`})}),(0,f.jsx)(`span`,{style:{fontSize:`13px`,fontWeight:500,color:`#065f46`},children:`Email saved — we'll be in touch!`})]}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:ae?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(BD,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Pe,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Ne,replyContext:ue,clearReplyContext:()=>de(null),onFileSelect:ne,selectedFile:te,onRemoveSelectedFile:re,attachmentError:C,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),!Je&&(0,f.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`8px 20px`,paddingBottom:`max(12px, env(safe-area-inset-bottom, 12px))`,pointerEvents:`none`},children:De&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function Ek(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:ee,language:te,chatId:ne,historyRef:re,onMessageSync:ae,sendMessage:oe,uploadChatFile:se,openWidget:ce,captureVisitorEmail:le,setVoiceMode:ue,endConversation:de,startNewChat:fe,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,dismissCallError:_e,startTyping:ve,stopTyping:ye,updateTypingDraft:be,getVisitorChatHistory:xe,resumeChat:we,isSessionRestoring:Te,openToChatCounter:De,voiceEndCounter:Oe}=kn();(0,d.useEffect)(()=>{try{ir()}catch{}},[]),(0,d.useEffect)(()=>{De&&w!==`text_chat`&&w!==`call_screen`&&(ue?.(!1),T(`text_chat`))},[De]);let Ae=t?.widgetSettings||{},je=n?.widgetSettings||{},Me={...Ae.branding||{},...je.branding||{}},Ne={...Ae.theme||{},...je.theme||{}},Pe={...Ae.features||{},...je.features||{}},Fe=Pe.voice!==!1,Ie=Array.isArray(Ne.orbColors)&&Ne.orbColors.length>0?Ne.orbColors:null,Le=Ne.buttonColor||Ne.primaryColor||Ie?.[0]||`#3B82F6`,Re={small:50,medium:64,large:80},ze=Re[Ne.orbSize]||Re.small,Be=Ne.position||`bottom-right`,Ve=Me.fallbackAgentName||`Agent`,He=pk(Ie??Ne.chatBgColors),Ue=Me.logo||Me.logoUrl||null,We=te||`en`,Ge=Ae.recommendations?.[We]||[],Ke=(je.recommendations?.[We]??Ge).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),qe=Array.isArray(Me.quickChatOptions)&&Me.quickChatOptions.length>0?Me.quickChatOptions:Ke,Je=Me.hideWatermark===!0?!1:Me.showPoweredBy!==!1,Ye=Me.chatbotEnabled!==!1&&Ne.chatbotEnabled!==!1,Xe=Ae.greetings?.[te]||je.greetings?.[te]||Me.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Ze={entryPrompt:Me.entryPrompt||`Do you want to explore in a new way?`,yesLabel:Me.yesLabel||`Yes`,laterLabel:Me.laterLabel||`Later`,connectionTitle:Me.connectionTitle||`How would you like to connect?`,voiceLabel:Me.voiceLabel||`Voice`,textLabel:Me.textLabel||`Text`,chatTitle:Me.headerName||`Chat with FlowEngage`,introGreeting:Xe,inputPlaceholder:Me.inputPlaceholder||`Type your message`,analysingLabel:Me.analysingLabel||`analysing...`},Qe=je.elevenLabsAgentId||t?.elevenLabsAgentId||null,$e=t?.siteId||n?.siteId||null,et=t?.apiBaseUrl||``,tt=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),nt=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,rt=r.some(e=>e.sender===`user`),it=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),at=!l&&rt&&it,ot=!!(je._dashboardLivePreview||Ae._dashboardLivePreview),[w,T]=(0,d.useState)(()=>ot?`text_chat`:`entry_prompt`),[st,ct]=(0,d.useState)(``),[E,lt]=(0,d.useState)(null),[ut,dt]=(0,d.useState)(l||``),[ft,pt]=(0,d.useState)(``),[mt,ht]=(0,d.useState)(!1),[gt,_t]=(0,d.useState)(0),[vt,yt]=(0,d.useState)(null),[bt,xt]=(0,d.useState)(null),[St,Ct]=(0,d.useState)(``),[wt,Tt]=(0,d.useState)(!1),[Et,Dt]=(0,d.useState)(!1),[Ot,kt]=(0,d.useState)(!1),At=(0,d.useRef)(null),jt=(0,d.useRef)(!1);(0,d.useLayoutEffect)(()=>{if(e!==`ready`||jt.current)return;if(jt.current=!0,!Fe){T(`minimized_orb`);return}let t=!1;try{t=gr().shouldResumeVoice}catch{}let n=Ee(),r=$e?Se($e):null,i=n||!!r?.transcript;if(t){ce?.({notifyChatInitiated:!0}),ue?.(!0),T(`voice_mode`);return}if(ke()){ce?.({notifyChatInitiated:!1}),T(`text_chat`);return}if($e)try{Ce($e)}catch{}if(i){T(`minimized_orb`);return}if(C($e)){T(`minimized_orb`);return}},[e,r]);let[Mt,Nt]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>Nt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{dt(l||``),l&&pt(``)},[l]);let Pt=(0,d.useCallback)(()=>{xt(null),Ct(``)},[]),Ft=(0,d.useCallback)(e=>{let t=PD(e);if(t){xt(null),Ct(t);return}xt(e),Ct(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){_t(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||_t(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]);let It=(0,d.useCallback)(()=>{T(`call_screen`),Dt(!1)},[]),Lt=(0,d.useCallback)(()=>{T(`text_chat`),Dt(!0)},[]);(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){At.current=null;return}if(v?.callId||b===`connecting`||b===`connected`){if(w===`minimized_orb`&&Et&&y&&!v?.callId){At.current=e;return}!(!i||w===`minimized_orb`||w===`voice_mode`)&&At.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:w,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),At.current=e,w===`voice_mode`&&ue?.(!1),ce?.(),It())}},[y,b,It,v?.callId,i,ce,ue,w]),(0,d.useEffect)(()=>{!v&&!y&&w===`call_screen`&&T(`text_chat`)},[v,y,w]),(0,d.useEffect)(()=>{!y&&Et&&Dt(!1)},[y,Et]),(0,d.useEffect)(()=>{if(!o||_){be?.(``),ye?.();return}if(!st.trim()||bt){be?.(``);let e=window.setTimeout(()=>ye?.(),100);return()=>window.clearTimeout(e)}ve?.();let e=window.setTimeout(()=>be?.(st),120),t=window.setTimeout(()=>ye?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[st,bt,o,_,ve,ye,be]);let Rt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,zt=async e=>{if(e.preventDefault(),_)return;if(at){let e=ut.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){pt(`Please enter a valid email so we can continue helping you.`);return}await le(e),pt(``),ht(!0),setTimeout(()=>ht(!1),3e3);return}let t=Rt(E);if(!st.trim()&&!bt)return;if(bt){try{Tt(!0),Ct(``);let e=await se(bt),n=e?.data||e,r=st.trim()||`Shared file: ${ID(bt)}`;ct(``),lt(null),Pt(),await oe(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||bt.name,fileType:n?.fileType||bt.type,fileSize:n?.fileSize||bt.size}})}catch(e){Ct(e?.message||`Failed to upload the selected file.`)}finally{Tt(!1)}return}let n=st.trim();ct(``),lt(null),await oe(n,``,t)},Bt=(0,d.useCallback)(()=>{r.length!==0&&fe?.()},[r.length,fe]),Vt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},Ht=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await oe(t.trim(),``)},[_,m,oe]),Ut=Mt&&w===`entry_prompt`?{inset:0}:Mt&&w===`text_chat`?{left:0,right:0,bottom:0}:Mt&&w===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:Mt&&w===`connection_modal`?{left:`12px`,right:`12px`,bottom:`12px`}:w===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Be===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`}}:Be===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Wt=(0,d.useCallback)(()=>{w!==`minimized_orb`&&(kt(!0),setTimeout(()=>{T(`minimized_orb`),kt(!1),y&&Dt(!0)},280))},[y,w]),Gt=()=>T(`connection_modal`),Kt=()=>{try{let e=window.AudioContext||window.webkitAudioContext;if(e){let t=new e;t.resume().catch(()=>{}),setTimeout(()=>t.close().catch(()=>{}),3e3)}}catch{}ce({notifyChatInitiated:!0}),ue?.(!0),T(`voice_mode`)},qt=()=>{ce({notifyChatInitiated:!0}),ue?.(!1),T(`text_chat`)},Jt=()=>{ue?.(!1),Wt()};return e!==`ready`||!Ye||Pe.chat===!1?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Ut},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[w===`entry_prompt`&&(0,f.jsx)(bk,{copy:Ze,orbColors:Ie,primaryColor:Le,onYes:()=>{ie($e),Kt()},onLater:()=>{ie($e),Wt()},isMobile:Mt,isClosing:Ot}),w===`minimized_orb`&&(0,f.jsxs)(_m.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Be===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[y&&(0,f.jsxs)(`button`,{type:`button`,onClick:It,style:{maxWidth:Mt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,f.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,f.jsxs)(`span`,{style:{minWidth:0},children:[(0,f.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:b===`connected`?`Call in progress`:`Call is active`}),(0,f.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:b===`connected`?`${Vt(gt)} with ${tt}`:`Tap to return to ${tt}`})]})]}),(0,f.jsx)(yk,{size:ze,orbColors:Ie,onClick:y?It:Fe?Gt:qt})]}),w===`connection_modal`&&(0,f.jsx)(xk,{copy:Ze,orbColors:Ie,primaryColor:Le,onVoice:Kt,onText:qt,onClose:Wt,isMobile:Mt,isClosing:Ot}),w===`voice_mode`&&(0,f.jsx)(Sk,{orbColors:Ie,onEnterChat:qt,onEndChat:Jt,agentId:Qe,siteId:$e,apiBaseUrl:et,chatId:ne,historyRef:re,onMessageSync:ae,voiceEndCounter:Oe},`voice`),w===`call_screen`&&(0,f.jsx)(rO,{incomingCall:v,activeCallId:y,callConnectionState:b,callDurationSeconds:gt,isCallMuted:S,agentName:tt,agentHeadshot:nt,fallbackAgentName:Ve,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,formatCallDuration:Vt,onMinimize:Lt,primaryColor:Le,orbColors:Ie,chatHistory:r}),w===`text_chat`&&(0,f.jsx)(Tk,{isClosing:Ot,copy:Ze,orbColors:Ie,primaryColor:Le,chatBgGradient:He,logo:Ue,quickChatOptions:qe,onQuickChatSelect:Ht,isMobile:Mt,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:tt,agentHeadshot:nt,fallbackAgentName:Ve,input:st,setInput:ct,onSubmit:zt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:bt,onFileSelect:Ft,onRemoveSelectedFile:Pt,attachmentError:St,isUploadingAttachment:wt,requiresEmail:at,emailInput:ut,setEmailInput:dt,emailError:ft,emailCaptureSuccess:mt,replyContext:E,setReplyContext:lt,webRTCError:ee,micError:vt,setMicError:yt,dismissCallError:_e,activeCallId:y,isCallMuted:S,toggleCallMute:ge,endWebRTCCall:he,formatCallDuration:Vt,callDurationSeconds:gt,onCollapse:Wt,onStartVoice:Kt,onNewChat:Bt,onMinimize:Lt,onExpand:It,isCallMinimized:!!y,showPoweredBy:Je,getVisitorChatHistory:xe,resumeChat:we,isSessionRestoring:Te}),(0,f.jsx)(`style`,{children:`
|
|
634
|
+
</svg>`,xO=null,SO=!1;function CO(){return(!xO||!xO.isConnected)&&(xO=document.createElement(`div`),xO.id=`${Q}-cursor`,xO.innerHTML=bO,document.body.appendChild(xO),SO=!1),xO}async function wO(e){if(typeof document>`u`||!e)return;oO();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=CO();SO||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await OO(360)}function TO(e=!1){xO&&(e?(xO.classList.remove(`${Q}-cursor-visible`),SO=!1):(xO.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{SO=!1},250)))}async function EO(e){xO&&(xO.classList.add(`${Q}-cursor-click`),await OO(280),xO.classList.remove(`${Q}-cursor-click`))}function DO(e){if(!e||typeof document>`u`)return;oO();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function OO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){An()&&console.log(`[FlowEngage:voice-tools]`,...e)}function kO(e){return new Promise(t=>setTimeout(t,e))}var AO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function jO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(AO)}catch{return!1}}function MO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function NO(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!jO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function PO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function FO(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return PO(r.join(` `))}if(e.labels&&e.labels.length)return PO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return PO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return PO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return PO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=PO(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return PO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return PO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?PO(o):null}function IO(){let e=[];return NO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(jO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=MO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function LO(){return IO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:FO(e),placeholder:e.placeholder||null}))}function RO(){let e=[];return NO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(jO(e)||e.disabled)return!1;try{let t=MO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function zO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function BO(e){let t=zO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function VO(e,t){let n=BO(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,FO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>zO(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var HO=28;function UO(e,t){let n=null,r=0;for(let i of e){let e=VO(i,t);e>r&&(r=e,n=i)}return!n||r<HO?null:n}function WO(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,FO(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function GO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function KO(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function qO(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function JO(e){if(!qO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,FO(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function YO(e,t,n){let r=String(t??``),i=String(n??``),a=QO(e,r)||UO(e,r)||WO(e,r,i);if(!a)return[];let o=new Set([a]);if(GO(i)&&KO(r))for(let t of e)t!==a&&JO(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function XO(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function ZO(e){if(!e||typeof e!=`string`)return null;let t=null;return NO(n=>{try{let r=n.getElementById(e);r&&!jO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function QO(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=ZO(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=ZO(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function $O(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=(e.innerText||e.textContent||``).replace(/\s+/g,` `).trim(),i=[r,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-text`),e.getAttribute(`data-label`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(i.includes(n)||r.toLowerCase()===n)return 100;let a=n.split(/\s+/).filter(e=>e.length>1);if(!a.length)return 0;let o=0;for(let e of a)i.includes(e)&&(o+=1);return o/a.length*92}function ek(e,t){let n=[];NO(e=>{let t=Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"], a[href]`));n.push(...t.filter(e=>{if(jO(e)||e.disabled)return!1;try{let t=MO(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:$O(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<28)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=XO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function tk(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function nk(e){let t=tk(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function rk(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function ik(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function ak(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function ok(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function sk(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function ck(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function lk(){let e=document.querySelector(`main, [role='main'], article`)||document.body;return Array.from(e.querySelectorAll(`h1, h2, h3`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, .flowengage-widget-root`)).map(e=>e.textContent.replace(/\s+/g,` `).trim()).filter(e=>e.length>2&&e.length<200).slice(0,12)}function uk(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let i=tk(n),a=ak(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($(`flowengage_navigate · 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 $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(a=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,a))}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 $(`flowengage_navigate ✖ 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{}}if(!await dr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${a}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{uO(`Navigating to ${a}...`,{spinner:!0}),hO(),lD();try{let e=r?r():``;if(e&&t){let n=aO([{sender:`user`,message:e}]);n&&xe(t,n)}}catch{}Te();let e=a;try{e=new URL(a,typeof window<`u`?window.location.href:``).href}catch{}t&&typeof window<`u`&&Me(t,window.location.href,e),mr(e),$(`flowengage_navigate → real navigation`,a);let n=typeof window<`u`&&!!Gn();if(typeof window<`u`&&window.__fe_triggerVoiceNavHooks&&window.__fe_triggerVoiceNavHooks(),n&&Rn(3e3),_r(a,{voiceActive:!0}).catch(()=>{}),n)try{let e=new URL(a,window.location.origin).pathname,t=Date.now()+2e3;for(;Date.now()<t&&!(typeof window<`u`&&window.location.pathname===e);)await new Promise(e=>setTimeout(e,80));let n=typeof window<`u`?window.location.pathname:e,r=typeof window<`u`?window.location.href:a,i=n===e,o=(n.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`;$(`flowengage_navigate → SPA nav complete. target:`,e,`actual:`,n);let s=[],c=Date.now()+12e3;for(;Date.now()<c&&(await new Promise(e=>setTimeout(e,300)),s=lk(),!(s.length>=1)););ck(),$(`flowengage_navigate → page headings collected:`,s);let l=s.length?s.join(` | `):`none`,u=s.length?`Use ONLY these exact heading strings for flowengage_highlight — never invent or abbreviate.`:`No headings collected yet — call flowengage_get_current_page immediately (no speech) to get the live headings before speaking or highlighting.`;return i?(hr(),`OK_NAVIGATE_SPA. Visitor is now on: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page, then ask: "Would you like me to walk you through the sections here?"`):(hr(),`OK_NAVIGATE_SPA. CURRENT PAGE IS: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page, then ask: "Would you like me to walk you through the sections here?"`)}catch{}return`OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, immediately introduce the new page and continue guiding the visitor — do not wait for the user to speak first.`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),uO(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{gO(),dO(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=tk(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;if(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 flowengage_highlight 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.`}ck();let i=or(n||null,r||null);if(!i&&r){let e=Date.now()+600;for(;!i&&Date.now()<e;)await new Promise(e=>setTimeout(e,50)),ck(),i=or(null,r)}if(!i){$(`flowengage_highlight ✖ no element for:`,r||n);let e=lk(),t=e.length?`Page headings: ${e.join(` | `)}. Use one of these exact strings for section_text.`:`No headings found — skip highlight and continue.`;return`HIGHLIGHT_NOT_FOUND: "${r||n}" on the current page. ${t}`}return cD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}". WALKTHROUGH: continue immediately to the next section — do NOT pause between sections.`},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=tk(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=or(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
|
|
635
|
+
`)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=ok(tk(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;uO(`Searching${r?` for "${r}"`:``}…`,{spinner:!0});try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),o.length?`SEARCH_RESULTS: ${JSON.stringify(o)}. MANDATORY: Do NOT call flowengage_navigate now. Speak the answer from these results in 2-3 sentences. Then ask the visitor if they want to go to a relevant page — e.g. "Would you like me to take you to that page?" Only navigate if they say yes.`:`SEARCH_RESULTS: No results found. Answer from your knowledge base.`}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}finally{dO(600)}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=tk(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),`${e} FALLBACK REQUIRED: This page is not in the search index. Call flowengage_read_content (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 $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_get_current_page:async()=>{if($(`flowengage_get_current_page ▶`),typeof window>`u`)return`Cannot determine current page (no browser context).`;let e=window.location.href,t=window.location.pathname,n=document.title||``,r=lk(),i=r.length?r.join(` | `):`none`;return $(`flowengage_get_current_page ✓`,{url:e,path:t,title:n}),$(`flowengage_get_current_page → page headings collected:`,r),`CURRENT_PAGE. URL: ${e} | Path: ${t} | Title: ${n} | Section headings: ${i}. Use these EXACT strings verbatim for every flowengage_highlight call — never paraphrase or invent headings.`},flowengage_list_forms:async()=>{let e=LO(),t=RO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),_O();let t=nk(e);if(!t.length&&r){let e=r(),n=rk(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=ik(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key,r=e?.value;if(t==null||r==null)continue;uO(`Filling ${String(t)}...`,{spinner:!0});let a=IO(),o=YO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())vO(t),await wO(t),sk(t,r,{skipScroll:e>0}),yO(t),await kO(120);i=o,n.push(String(t));continue}let s=QO(a,String(t));s||=UO(a,String(t)),s||=WO(a,String(t),r),s&&(vO(s),await wO(s),sk(s,r),yO(s),await kO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),uO(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),uO(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{TO(),_O(),dO(700)}},flowengage_click_button:async e=>{let t=tk(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=ek(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{uO(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await wO(r),r.focus?.(),await EO(r),DO(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),uO(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),uO(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{TO(),dO(700)}}};return{...a,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function dk(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=An();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var fk={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function pk(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 mk(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 hk(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 gk({logo:e,style:t}){let n=hk(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 _k({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 vk(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function yk({orbColors:e,...t}){return(0,f.jsx)(XD,{colors:e,...t})}function bk({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||fk.green,c=mk(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)(_m.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,f.jsxs)(_m.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)(_m.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)(yk,{size:l,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(_m.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 xk({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||fk.green,l=mk(c);return(0,f.jsxs)(_m.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)(yk,{size:72,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background: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 Sk({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,chatId:o,historyRef:s,onMessageSync:c,voiceEndCounter:l}){let[u,p]=(0,d.useState)(`idle`),[m,h]=(0,d.useState)(!1),[g,_]=(0,d.useState)(!1),v=(0,d.useRef)(null),y=(0,d.useRef)(``),b=(0,d.useRef)(async()=>{}),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(!1),te=(0,d.useRef)(!1),ne=(0,d.useRef)(`minimized`),re=(0,d.useRef)(null),C=(0,d.useRef)(null),ie=(0,d.useRef)(null),ae=(0,d.useRef)(0),oe=(0,d.useRef)(!1),se=(0,d.useRef)(`idle`),ce=(0,d.useRef)(!1),le=(0,d.useRef)(null),ue=(0,d.useRef)(null),de=(0,d.useRef)(!1),fe=(0,d.useCallback)((e=`minimized`)=>{ne.current=e,te.current=!0,queueMicrotask(()=>{x.current||(x.current=!0,b.current?.())})},[s]),pe=(0,d.useCallback)(async e=>{te.current=!0;try{lD()}catch{}if(i)try{Ne(i)}catch{}try{await v.current?.endSession?.()}catch{}let t=re.current,n=C.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,elevenLabsConversationId:t,duration:e,siteId:i})}).catch(e=>console.warn(`[FlowEngage] save-chat-recording failed:`,e.message))}if(re.current=null,C.current=null,v.current=null,p(`idle`),h(!1),x.current=!1,xr(),i)try{Ce(i)}catch{}typeof c==`function`&&await c(s.current),e?.()},[s,c,i,o,a]);return b.current=()=>pe(ne.current===`chat`?t:n),(0,d.useEffect)(()=>{S.current=m},[m]),(0,d.useEffect)(()=>{l&&fe(`chat`)},[l]),(0,d.useEffect)(()=>{let e=!1,l=null,u=null,d=null;return(async()=>{if(!r){p(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;s.current=[],y.current=``,x.current=!1,ee.current=!1,te.current=!1,ne.current=`minimized`,br({onBeforeNavigate:()=>{if(i&&s.current.length>0)try{let e=aO(s.current);e&&xe(i,e)}catch{}if(!Gn()){let e=re.current,t=C.current;if(e&&o&&a)try{let n=t?Math.round((Date.now()-t)/1e3):0,r=JSON.stringify({chatId:o,elevenLabsConversationId: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(()=>{}),re.current=null,C.current=null}catch{}}Te()}});let t=dk(uk({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>y.current,requestEndSession:()=>{oe.current=!0}})),n=i?Se(i):null,c=!!n?.transcript,f=!!(i&&Ne(i)),m=typeof window<`u`?window.location.pathname:`/`,g=typeof document<`u`?document.title:``,_=m===`/`||m===``,b=null;try{let e=await fetch(`${a}/api/voice/signed-url?siteId=${encodeURIComponent(i||``)}`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(e.ok)b=(await e.json()).signedUrl||null,b&&console.log(`[FlowEngage] ✅ Using signed ElevenLabs URL`);else if(e.status===429){let t=await e.json().catch(()=>({}));throw Error(t.message||`Too many voice sessions started. Please wait a minute before trying again.`)}else console.warn(`[FlowEngage] ⚠️ Signed URL fetch failed, falling back to agentId`)}catch(e){if(e.message&&e.message.includes(`Too many voice sessions`))throw e;console.warn(`[FlowEngage] ⚠️ Signed URL fetch error:`,e.message)}let ie={clientTools:t,connectionType:`websocket`,minSpeechDurationMs:50,...b?{signedUrl:b}:{agentId:r}},pe=(m.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase()),me=``;g&&g.includes(`|`)&&(me=g.split(`|`).map(e=>e.trim()).filter(Boolean).reduce((e,t)=>e.length<=t.length?e:t));let he=me||pe||`this page`;b?f?(ie.overrides={agent:{firstMessage:`I've navigated you to the ${he} page. Let me walk you through what's here.`}},console.log(`[FlowEngage] 🔄 Agent-nav resume: firstMessage set for "${he}" (${m})`)):c?ie.overrides={agent:{firstMessage:`I'm still here. Go ahead!`}}:_||(ie.overrides={agent:{firstMessage:`Hi! I see you are currently on the ${he} page. Are you looking for something specific here?`}},console.log(`[FlowEngage] 🏠 Page-context override: "${he}" for ${m}`)):c&&(ie.overrides={agent:{firstMessage:``}});let ge=!1,_e=f?`NAVIGATION RESUME — Your intro has been spoken. NOW — without waiting for the visitor to say anything — call flowengage_highlight for the first content section on this page, then speak one sentence about it. Continue section by section (highlight + one sentence each) until you have covered the key content. Prior conversation context:\n${(i?Se(i):null)?.transcript||``}\n\n`:null,ve=await aD.startSession({...ie,onConnect:({conversationId:e})=>{re.current=e,C.current=Date.now(),console.log(`[FlowEngage] 🎙️ AI chat session connected:`,e)},onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{if(!e){if(t===`speaking`){ue.current&&=(clearTimeout(ue.current),null),p(`speaking`),se.current=`speaking`,ce.current=!0,de.current=!1,le.current&&=(clearTimeout(le.current),null);return}if(se.current=`listening`,oe.current){oe.current=!1,fe();return}if(_e&&!ge){ge=!0;try{v.current?.sendUserMessage?.(`continue with the tour`)}catch{}}ue.current&&clearTimeout(ue.current),ue.current=setTimeout(()=>{e||se.current!==`speaking`&&(de.current||(ue.current=null,se.current=`listening`,p(`listening`)))},1200)}},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(r){if(n===`user`&&(y.current=r,de.current=!0,ue.current&&=(clearTimeout(ue.current),null),le.current&&=(clearTimeout(le.current),null)),s.current=[...s.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=aO(s.current);e&&xe(i,e)}catch{}if(vk(n,r)){fe(`minimized`);return}if(S.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(ae.current+=1,ae.current===2)try{v.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 flowengage_end_session tool to end the voice session. Do NOT ask again after that.`)}catch{}else ae.current>=5&&fe(`minimized`)}},onError:t=>{if(!e&&!te.current&&!ee.current&&!Ae()){ee.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),p(`error`),fe(`chat`)}},onDisconnect:t=>{if(e||te.current||ee.current||Ae())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:y.current||``,wasMuted:S.current}),ee.current=!0;try{v.current?.setMicMuted?.(!0)}catch{}h(!0),fe(`chat`)}});if(e){ve.endSession().catch(()=>{});return}l=ve,v.current=ve,p(`listening`);try{let e=typeof window<`u`?window.location.href:``,r=`[]`;try{r=await t.list_page_forms()}catch{}let a=c&&!f?`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(`${a}Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${r}. 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=()=>{if(e)return;let n=window.location.pathname;if(n===t)return;if(zn()){t=n;return}let r=t;t=n;let i=window.location.href,a=typeof document<`u`?document.title:``,o=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{lD()}catch{}let s=e=>(e.split(`/`).filter(Boolean).pop()||``).replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())||`Home`,c=s(r),l=s(n);typeof window<`u`&&(window.__fe_user_nav_during_speech={fromPath:r,toPath:n,fromPageName:c,toPageName:l,ts:Date.now()});try{v.current?.sendUserMessage?.(`[SYSTEM: I navigated away mid-walkthrough — I am now on the "${l}" page (${i}). Page title: "${a}". Sections: ${JSON.stringify(o)}. STOP everything. Do NOT describe the new page. Say EXACTLY: "I see you've navigated to the ${l} 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 flowengage_navigate, do NOT call flowengage_highlight, the visitor will navigate themselves if needed. IF I want to hear about this page: call flowengage_highlight for sections of "${l}" only.]`)}catch{}};u=window.history.pushState.bind(window.history),window.history.pushState=(...e)=>{u(...e),setTimeout(n,50)},d=()=>setTimeout(n,50),window.addEventListener(`popstate`,d)}}catch(r){e||(console.error(`[FlowEngage] startSession failed`,r),r.message&&r.message.includes(`Too many voice sessions`)?(alert(r.message),n&&n(`minimized`)):(p(`error`),ne.current=`chat`,window.setTimeout(()=>{e||t?.()},0)))}})(),()=>{e=!0,te.current=!0;try{lD()}catch{}if(i)try{Ne(i)}catch{}typeof window<`u`&&(window.__fe_user_nav_during_speech=null),xr(),le.current&&=(clearTimeout(le.current),null),ue.current&&=(clearTimeout(ue.current),null),ce.current=!1,de.current=!1,se.current=`idle`,u&&typeof window<`u`&&(window.history.pushState=u),d&&typeof window<`u`&&window.removeEventListener(`popstate`,d);let t=l||v.current,n=re.current,r=C.current;if(t?.endSession?.().catch(()=>{}),n&&o&&a){let e=r?Math.round((Date.now()-r)/1e3):0,t=JSON.stringify({chatId:o,elevenLabsConversationId:n,duration:e,siteId:i}),s=`${a}/api/voice/save-chat-recording`;typeof navigator<`u`&&navigator.sendBeacon&&navigator.sendBeacon(s,new Blob([t],{type:`application/json`}))||fetch(s,{method:`POST`,headers:{"Content-Type":`application/json`},body:t,keepalive:!0}).catch(()=>{}),re.current=null,C.current=null}typeof c==`function`&&s.current.length>0&&c(s.current).catch?.(()=>{})}},[r,i,a,fe]),(0,d.useEffect)(()=>{if(!g)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ie.current&&!ie.current.contains(t)&&_(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[g]),(0,f.jsxs)(`div`,{ref:ie,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&!m&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),m&&(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)(yk,{size:72,voiceState:u,isMuted:m,orbColors:e})]}),u===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:async()=>{if(v.current)try{if(m){ae.current=0,await v.current.setMicMuted?.(!1),h(!1);try{v.current.sendContextualUpdate?.(`The visitor has unmuted. Resume normal interaction and wait for them to speak.`)}catch{}}else{ae.current=0,await v.current.setMicMuted?.(!0),h(!0);try{v.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{}},title:m?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:m?`#7f1d1d`:`#1f2937`,border:m?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:m?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:m?(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsx)(uD,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>_(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,f.jsx)(vD,{size:16,color:`currentColor`})})]}),g&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`chat`,pe(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)(yD,{}),`Enter Chat Mode`]}),(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`minimized`,pe(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)(bD,{}),`End Conversation`]}),(0,f.jsx)(`button`,{onClick:()=>_(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function Ck({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(yk,{size:36,orbColors:e})})}var wk=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function Tk({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:ee,selectedFile:te,onFileSelect:ne,onRemoveSelectedFile:re,attachmentError:C,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,emailCaptureSuccess:le,replyContext:ue,setReplyContext:de,webRTCError:fe,micError:pe,setMicError:me,dismissCallError:he,activeCallId:ge,isCallMuted:_e,toggleCallMute:ve,endWebRTCCall:ye,formatCallDuration:be,callDurationSeconds:xe,isCallMinimized:Se,onExpand:Ce,onCollapse:we,onStartVoice:Te,onNewChat:Ee,showPoweredBy:De,getVisitorChatHistory:Oe,resumeChat:ke,isSessionRestoring:Ae,isClosing:je}){let Me=c.length>0,Ne=x||S||b,Pe=!!ge,[Fe,Ie]=(0,d.useState)(!1),[Le,Re]=(0,d.useState)(!1),[ze,Be]=(0,d.useState)([]),[Ve,He]=(0,d.useState)(!1),Ue=(0,d.useRef)(null),[We,Ge]=(0,d.useState)(()=>typeof window<`u`?window.visualViewport?.height??window.innerHeight:600),[Ke,qe]=(0,d.useState)(0);(0,d.useEffect)(()=>{if(!s)return;let e=window.visualViewport;if(!e)return;let t=()=>{Ge(e.height),qe(Math.max(0,window.innerHeight-e.offsetTop-e.height))};return e.addEventListener(`resize`,t),e.addEventListener(`scroll`,t),t(),()=>{e.removeEventListener(`resize`,t),e.removeEventListener(`scroll`,t)}},[s]);let Je=s&&window.innerHeight-We>150,Ye=async()=>{Ie(!1),Re(!0),He(!0);try{let e=await Oe();e?.data&&Be(e.data)}catch(e){console.error(e)}finally{He(!1)}},Xe=async e=>{Re(!1),ke?.(e.chatId)};return(0,d.useEffect)(()=>{if(!Fe)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Ue.current&&!Ue.current.contains(t)&&Ie(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Fe]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:`${Ke}px`,height:We>0?`${Math.round(We*.92)}px`:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:je?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:je?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0,position:`relative`,zIndex:30},children:[(0,f.jsx)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,f.jsx)(`button`,{onClick:we,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})})}),(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(gk,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(_k,{title:e.chatTitle})})}),(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Ue,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>Ie(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Fe&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Ie(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Ie(!1),Ee?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,f.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new chat`]}),Oe&&(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:Ye,style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`path`,{d:`M12 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{Ie(!1),we?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,f.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,f.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,f.jsx)(VD,{webRTCError:fe,micError:pe,setMicError:me,dismissCallError:he,isRateLimited:S,rateLimitMessage:ee}),Se&&(0,f.jsx)(iO,{agentName:m,agentHeadshot:h,fallbackAgentName:g,callDurationSeconds:xe,isCallMuted:_e,formatCallDuration:be,toggleCallMute:ve,endWebRTCCall:ye,onExpand:Ce,primaryColor:n}),(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Le?(0,f.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:(0,f.jsxs)(`button`,{onClick:()=>Re(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,f.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,f.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Ve?(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):ze.length>0?(0,f.jsx)(`div`,{children:ze.map(e=>(0,f.jsxs)(`div`,{onClick:()=>Xe(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,f.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,f.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,f.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,Me?(0,f.jsx)(zD,{chatHistory:c,isAiTyping:l,isLoading:x,isAgentTyping:u,setReplyContext:de,TypingDots:wk,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(Ck,{orbColors:t})}):Ae?(0,f.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,f.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,f.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,f.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(yk,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})]}),le&&(0,f.jsxs)(`div`,{style:{margin:`0 16px 8px`,padding:`9px 14px`,borderRadius:`12px`,background:`#ecfdf5`,border:`1px solid #6ee7b7`,display:`flex`,alignItems:`center`,gap:`8px`,animation:`fe-orb-fade-in 0.2s ease`,flexShrink:0},children:[(0,f.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`#10b981`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,style:{flexShrink:0},children:(0,f.jsx)(`polyline`,{points:`20 6 9 17 4 12`})}),(0,f.jsx)(`span`,{style:{fontSize:`13px`,fontWeight:500,color:`#065f46`},children:`Email saved — we'll be in touch!`})]}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:ae?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(BD,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Pe,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Ne,replyContext:ue,clearReplyContext:()=>de(null),onFileSelect:ne,selectedFile:te,onRemoveSelectedFile:re,attachmentError:C,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),!Je&&(0,f.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`8px 20px`,paddingBottom:`max(12px, env(safe-area-inset-bottom, 12px))`,pointerEvents:`none`},children:De&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function Ek(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:ee,language:te,chatId:ne,historyRef:re,onMessageSync:ae,sendMessage:oe,uploadChatFile:se,openWidget:ce,captureVisitorEmail:le,setVoiceMode:ue,endConversation:de,startNewChat:fe,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,dismissCallError:_e,startTyping:ve,stopTyping:ye,updateTypingDraft:be,getVisitorChatHistory:xe,resumeChat:we,isSessionRestoring:Te,openToChatCounter:De,voiceEndCounter:Oe}=kn();(0,d.useEffect)(()=>{try{ir()}catch{}},[]),(0,d.useEffect)(()=>{De&&w!==`text_chat`&&w!==`call_screen`&&(ue?.(!1),T(`text_chat`))},[De]);let Ae=t?.widgetSettings||{},je=n?.widgetSettings||{},Me={...Ae.branding||{},...je.branding||{}},Ne={...Ae.theme||{},...je.theme||{}},Pe={...Ae.features||{},...je.features||{}},Fe=Pe.voice!==!1,Ie=Array.isArray(Ne.orbColors)&&Ne.orbColors.length>0?Ne.orbColors:null,Le=Ne.buttonColor||Ne.primaryColor||Ie?.[0]||`#3B82F6`,Re={small:50,medium:64,large:80},ze=Re[Ne.orbSize]||Re.small,Be=Ne.position||`bottom-right`,Ve=Me.fallbackAgentName||`Agent`,He=pk(Ie??Ne.chatBgColors),Ue=Me.logo||Me.logoUrl||null,We=te||`en`,Ge=Ae.recommendations?.[We]||[],Ke=(je.recommendations?.[We]??Ge).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),qe=Array.isArray(Me.quickChatOptions)&&Me.quickChatOptions.length>0?Me.quickChatOptions:Ke,Je=Me.hideWatermark===!0?!1:Me.showPoweredBy!==!1,Ye=Me.chatbotEnabled!==!1&&Ne.chatbotEnabled!==!1,Xe=Ae.greetings?.[te]||je.greetings?.[te]||Me.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Ze={entryPrompt:Me.entryPrompt||`Do you want to explore in a new way?`,yesLabel:Me.yesLabel||`Yes`,laterLabel:Me.laterLabel||`Later`,connectionTitle:Me.connectionTitle||`How would you like to connect?`,voiceLabel:Me.voiceLabel||`Voice`,textLabel:Me.textLabel||`Text`,chatTitle:Me.headerName||`Chat with FlowEngage`,introGreeting:Xe,inputPlaceholder:Me.inputPlaceholder||`Type your message`,analysingLabel:Me.analysingLabel||`analysing...`},Qe=je.elevenLabsAgentId||t?.elevenLabsAgentId||null,$e=t?.siteId||n?.siteId||null,et=t?.apiBaseUrl||``,tt=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),nt=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,rt=r.some(e=>e.sender===`user`),it=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),at=!l&&rt&&it,ot=!!(je._dashboardLivePreview||Ae._dashboardLivePreview),[w,T]=(0,d.useState)(()=>ot?`text_chat`:`entry_prompt`),[st,ct]=(0,d.useState)(``),[E,lt]=(0,d.useState)(null),[ut,dt]=(0,d.useState)(l||``),[ft,pt]=(0,d.useState)(``),[mt,ht]=(0,d.useState)(!1),[gt,_t]=(0,d.useState)(0),[vt,yt]=(0,d.useState)(null),[bt,xt]=(0,d.useState)(null),[St,Ct]=(0,d.useState)(``),[wt,Tt]=(0,d.useState)(!1),[Et,Dt]=(0,d.useState)(!1),[Ot,kt]=(0,d.useState)(!1),At=(0,d.useRef)(null),jt=(0,d.useRef)(!1);(0,d.useLayoutEffect)(()=>{if(e!==`ready`||jt.current)return;if(jt.current=!0,!Fe){T(`minimized_orb`);return}let t=!1;try{t=gr().shouldResumeVoice}catch{}let n=Ee(),r=$e?Se($e):null,i=n||!!r?.transcript;if(t){ce?.({notifyChatInitiated:!0}),ue?.(!0),T(`voice_mode`);return}if(ke()){ce?.({notifyChatInitiated:!1}),T(`text_chat`);return}if($e)try{Ce($e)}catch{}if(i){T(`minimized_orb`);return}if(C($e)){T(`minimized_orb`);return}},[e,r]);let[Mt,Nt]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>Nt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{dt(l||``),l&&pt(``)},[l]);let Pt=(0,d.useCallback)(()=>{xt(null),Ct(``)},[]),Ft=(0,d.useCallback)(e=>{let t=PD(e);if(t){xt(null),Ct(t);return}xt(e),Ct(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){_t(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||_t(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]);let It=(0,d.useCallback)(()=>{T(`call_screen`),Dt(!1)},[]),Lt=(0,d.useCallback)(()=>{T(`text_chat`),Dt(!0)},[]);(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){At.current=null;return}if(v?.callId||b===`connecting`||b===`connected`){if(w===`minimized_orb`&&Et&&y&&!v?.callId){At.current=e;return}!(!i||w===`minimized_orb`||w===`voice_mode`)&&At.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:w,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),At.current=e,w===`voice_mode`&&ue?.(!1),ce?.(),It())}},[y,b,It,v?.callId,i,ce,ue,w]),(0,d.useEffect)(()=>{!v&&!y&&w===`call_screen`&&T(`text_chat`)},[v,y,w]),(0,d.useEffect)(()=>{!y&&Et&&Dt(!1)},[y,Et]),(0,d.useEffect)(()=>{if(!o||_){be?.(``),ye?.();return}if(!st.trim()||bt){be?.(``);let e=window.setTimeout(()=>ye?.(),100);return()=>window.clearTimeout(e)}ve?.();let e=window.setTimeout(()=>be?.(st),120),t=window.setTimeout(()=>ye?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[st,bt,o,_,ve,ye,be]);let Rt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,zt=async e=>{if(e.preventDefault(),_)return;if(at){let e=ut.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){pt(`Please enter a valid email so we can continue helping you.`);return}await le(e),pt(``),ht(!0),setTimeout(()=>ht(!1),3e3);return}let t=Rt(E);if(!st.trim()&&!bt)return;if(bt){try{Tt(!0),Ct(``);let e=await se(bt),n=e?.data||e,r=st.trim()||`Shared file: ${ID(bt)}`;ct(``),lt(null),Pt(),await oe(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||bt.name,fileType:n?.fileType||bt.type,fileSize:n?.fileSize||bt.size}})}catch(e){Ct(e?.message||`Failed to upload the selected file.`)}finally{Tt(!1)}return}let n=st.trim();ct(``),lt(null),await oe(n,``,t)},Bt=(0,d.useCallback)(()=>{r.length!==0&&fe?.()},[r.length,fe]),Vt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},Ht=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await oe(t.trim(),``)},[_,m,oe]),Ut=Mt&&w===`entry_prompt`?{inset:0}:Mt&&w===`text_chat`?{left:0,right:0,bottom:0}:Mt&&w===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:Mt&&w===`connection_modal`?{left:`12px`,right:`12px`,bottom:`12px`}:w===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Be===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`}}:Be===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Wt=(0,d.useCallback)(()=>{w!==`minimized_orb`&&(kt(!0),setTimeout(()=>{T(`minimized_orb`),kt(!1),y&&Dt(!0)},280))},[y,w]),Gt=()=>T(`connection_modal`),Kt=()=>{try{let e=window.AudioContext||window.webkitAudioContext;if(e){let t=new e;t.resume().catch(()=>{}),setTimeout(()=>t.close().catch(()=>{}),3e3)}}catch{}ce({notifyChatInitiated:!0}),ue?.(!0),T(`voice_mode`)},qt=()=>{ce({notifyChatInitiated:!0}),ue?.(!1),T(`text_chat`)},Jt=()=>{ue?.(!1),Wt()};return e!==`ready`||!Ye||Pe.chat===!1?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Ut},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[w===`entry_prompt`&&(0,f.jsx)(bk,{copy:Ze,orbColors:Ie,primaryColor:Le,onYes:()=>{ie($e),Kt()},onLater:()=>{ie($e),Wt()},isMobile:Mt,isClosing:Ot}),w===`minimized_orb`&&(0,f.jsxs)(_m.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Be===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[y&&(0,f.jsxs)(`button`,{type:`button`,onClick:It,style:{maxWidth:Mt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,f.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,f.jsxs)(`span`,{style:{minWidth:0},children:[(0,f.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:b===`connected`?`Call in progress`:`Call is active`}),(0,f.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:b===`connected`?`${Vt(gt)} with ${tt}`:`Tap to return to ${tt}`})]})]}),(0,f.jsx)(yk,{size:ze,orbColors:Ie,onClick:y?It:Fe?Gt:qt})]}),w===`connection_modal`&&(0,f.jsx)(xk,{copy:Ze,orbColors:Ie,primaryColor:Le,onVoice:Kt,onText:qt,onClose:Wt,isMobile:Mt,isClosing:Ot}),w===`voice_mode`&&(0,f.jsx)(Sk,{orbColors:Ie,onEnterChat:qt,onEndChat:Jt,agentId:Qe,siteId:$e,apiBaseUrl:et,chatId:ne,historyRef:re,onMessageSync:ae,voiceEndCounter:Oe},`voice`),w===`call_screen`&&(0,f.jsx)(rO,{incomingCall:v,activeCallId:y,callConnectionState:b,callDurationSeconds:gt,isCallMuted:S,agentName:tt,agentHeadshot:nt,fallbackAgentName:Ve,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,formatCallDuration:Vt,onMinimize:Lt,primaryColor:Le,orbColors:Ie,chatHistory:r}),w===`text_chat`&&(0,f.jsx)(Tk,{isClosing:Ot,copy:Ze,orbColors:Ie,primaryColor:Le,chatBgGradient:He,logo:Ue,quickChatOptions:qe,onQuickChatSelect:Ht,isMobile:Mt,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:tt,agentHeadshot:nt,fallbackAgentName:Ve,input:st,setInput:ct,onSubmit:zt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:bt,onFileSelect:Ft,onRemoveSelectedFile:Pt,attachmentError:St,isUploadingAttachment:wt,requiresEmail:at,emailInput:ut,setEmailInput:dt,emailError:ft,emailCaptureSuccess:mt,replyContext:E,setReplyContext:lt,webRTCError:ee,micError:vt,setMicError:yt,dismissCallError:_e,activeCallId:y,isCallMuted:S,toggleCallMute:ge,endWebRTCCall:he,formatCallDuration:Vt,callDurationSeconds:gt,onCollapse:Wt,onStartVoice:Kt,onNewChat:Bt,onMinimize:Lt,onExpand:It,isCallMinimized:!!y,showPoweredBy:Je,getVisitorChatHistory:xe,resumeChat:we,isSessionRestoring:Te}),(0,f.jsx)(`style`,{children:`
|
|
636
636
|
/* Force any SVG (or img) inside LogoSlot to fill the container height
|
|
637
637
|
regardless of whether the component forwards its style prop. */
|
|
638
638
|
.fe-logo-slot svg,
|
|
@@ -29409,7 +29409,7 @@ function Ck(e) {
|
|
|
29409
29409
|
for (; Date.now() < c && (await new Promise((e) => setTimeout(e, 300)), s = Sk(), !(s.length >= 1)););
|
|
29410
29410
|
xk(), $("flowengage_navigate → page headings collected:", s);
|
|
29411
29411
|
let l = s.length ? s.join(" | ") : "none", u = s.length ? "Use ONLY these exact heading strings for flowengage_highlight — never invent or abbreviate." : "No headings collected yet — call flowengage_get_current_page immediately (no speech) to get the live headings before speaking or highlighting.";
|
|
29412
|
-
return i ? (wr(), `OK_NAVIGATE_SPA. Visitor is now on: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page
|
|
29412
|
+
return i ? (wr(), `OK_NAVIGATE_SPA. Visitor is now on: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page, then ask: "Would you like me to walk you through the sections here?"`) : (wr(), `OK_NAVIGATE_SPA. CURRENT PAGE IS: ${r} (page: "${o}") | Section headings: ${l}. ${u} Speak 2-3 sentences about this page, then ask: "Would you like me to walk you through the sections here?"`);
|
|
29413
29413
|
} catch {}
|
|
29414
29414
|
return "OK_NAVIGATE_RELOADING. Navigating to the page now; the voice session will resume automatically on the new page. When the session resumes, immediately introduce the new page and continue guiding the visitor — do not wait for the user to speak first.";
|
|
29415
29415
|
} catch (e) {
|
|
@@ -29539,7 +29539,7 @@ function Ck(e) {
|
|
|
29539
29539
|
url: e,
|
|
29540
29540
|
path: t,
|
|
29541
29541
|
title: n
|
|
29542
|
-
}), $("flowengage_get_current_page → page headings collected:", r), `CURRENT_PAGE. URL: ${e} | Path: ${t} | Title: ${n} | Section headings: ${i}.
|
|
29542
|
+
}), $("flowengage_get_current_page → page headings collected:", r), `CURRENT_PAGE. URL: ${e} | Path: ${t} | Title: ${n} | Section headings: ${i}. Use these EXACT strings verbatim for every flowengage_highlight call — never paraphrase or invent headings.`;
|
|
29543
29543
|
},
|
|
29544
29544
|
flowengage_list_forms: async () => {
|
|
29545
29545
|
let e = XO(), t = ZO();
|