@flowengage/react-chatbot 1.8.21 → 1.8.22
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
|
@@ -613,7 +613,7 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
613
613
|
fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
|
|
614
614
|
filter="url(#${Q}-csh)"/>
|
|
615
615
|
</svg>`,ZD=null,QD=!1;function $D(){return(!ZD||!ZD.isConnected)&&(ZD=document.createElement(`div`),ZD.id=`${Q}-cursor`,ZD.innerHTML=XD,document.body.appendChild(ZD),QD=!1),ZD}async function eO(e){if(typeof document>`u`||!e)return;ID();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=$D();QD||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await iO(360)}function tO(e=!1){ZD&&(e?(ZD.classList.remove(`${Q}-cursor-visible`),QD=!1):(ZD.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{QD=!1},250)))}async function nO(e){ZD&&(ZD.classList.add(`${Q}-cursor-click`),await iO(280),ZD.classList.remove(`${Q}-cursor-click`))}function rO(e){if(!e||typeof document>`u`)return;ID();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function iO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){pn()&&console.log(`[FlowEngage:voice-tools]`,...e)}function aO(e){return new Promise(t=>setTimeout(t,e))}var oO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function sO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(oO)}catch{return!1}}function cO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function lO(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!sO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function uO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function dO(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return uO(r.join(` `))}if(e.labels&&e.labels.length)return uO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return uO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return uO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return uO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=uO(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return uO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return uO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?uO(o):null}function fO(){let e=[];return lO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(sO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=cO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function pO(){return fO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:dO(e),placeholder:e.placeholder||null}))}function mO(){let e=[];return lO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(sO(e)||e.disabled)return!1;try{let t=cO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function hO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function gO(e){let t=hO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function _O(e,t){let n=gO(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,dO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>hO(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var vO=28;function yO(e,t){let n=null,r=0;for(let i of e){let e=_O(i,t);e>r&&(r=e,n=i)}return!n||r<vO?null:n}function bO(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,dO(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function xO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function SO(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function CO(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function wO(e){if(!CO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,dO(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function TO(e,t,n){let r=String(t??``),i=String(n??``),a=OO(e,r)||yO(e,r)||bO(e,r,i);if(!a)return[];let o=new Set([a]);if(xO(i)&&SO(r))for(let t of e)t!==a&&wO(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function EO(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function DO(e){if(!e||typeof e!=`string`)return null;let t=null;return lO(n=>{try{let r=n.getElementById(e);r&&!sO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function OO(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=DO(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=DO(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function kO(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function AO(e,t){let n=[];lO(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(sO(e)||e.disabled)return!1;try{let t=cO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:kO(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=EO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function jO(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function MO(e){let t=jO(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function NO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function PO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function FO(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function IO(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function LO(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function RO(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function zO(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{if($(`flowengage_navigate ▶ raw parameters:`,n),typeof e.getPostResumeNavLocked==`function`&&e.getPostResumeNavLocked())return $(`flowengage_navigate · blocked (post-resume lock active)`,n),`Navigation is not needed — you just arrived at this page via the user's navigation request. Stay here and continue the conversation naturally.`;let r=jO(n),i=FO(r),a=r.section_text??r.sectionText??r.section;if($(`flowengage_navigate · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(i,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(i=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,i))}catch{}if(typeof window<`u`)try{let e=new URL(i,window.location.href),t=window.location;if(e.pathname===t.pathname&&e.search===t.search&&(e.hash===t.hash||!e.hash))return $(`flowengage_navigate · already on target page, skipping navigation`),`Already on that page. Continue the conversation naturally without calling flowengage_navigate again.`}catch{}if(!await Hn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${i}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{BD(`Navigating to ${i}...`,{spinner:!0}),GD();let t=typeof e.getSessionCaptureData==`function`?e.getSessionCaptureData():null,n=i;if(t){let{ok:e,sessionKey:r,compact:o}=DD.capture({siteId:t.siteId,chatId:t.chatId,agentId:t.agentId,trigger:`agent_navigate`,navigationConfidence:`high`,targetUrl:i,interruption:{state:`tool_calling`,toolName:`flowengage_navigate`,toolParams:{url:i,section_text:a||null},lastAgentText:t.lastAgentText,lastUserText:t.lastUserText,estimatedSpokenWords:t.estimatedSpokenWords,agentTextWordCount:t.agentTextWordCount,isMuted:t.isMuted||!1},history:t.history});e&&r?n=TD(i,r):o&&(n=TD(i,o)),$(`flowengage_navigate · session captured, resumeUrl:`,n)}return typeof e.markNavigationShutdown==`function`&&($(`flowengage_navigate · awaiting markNavigationShutdown (clean WS close)`),await e.markNavigationShutdown(),$(`flowengage_navigate · endSession complete — server session closed`)),jD(),await aO(300),$(`flowengage_navigate → location.assign`,n),window.location.assign(n),`Navigating...`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),BD(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{KD(),VD(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=jO(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;RO();let i=Rn(n||null,r||null);return!i&&r&&(await new Promise(e=>setTimeout(e,500)),RO(),i=Rn(null,r)),i?(PD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}"`):($(`flowengage_highlight ✖ no element for:`,r||n),`Could not find "${r||n}" on the current page. Try a shorter phrase matching a visible heading.`)},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=jO(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=Rn(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
|
|
616
|
-
`)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=IO(jO(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=jO(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=pO(),t=mO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),qD();let t=MO(e);if(!t.length&&r){let e=r(),n=NO(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=PO(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;BD(`Filling ${String(t)}...`,{spinner:!0});let a=fO(),o=TO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())JD(t),await eO(t),LO(t,r,{skipScroll:e>0}),YD(t),await aO(120);i=o,n.push(String(t));continue}let s=OO(a,String(t));s||=yO(a,String(t)),s||=bO(a,String(t),r),s&&(JD(s),await eO(s),LO(s,r),YD(s),await aO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),BD(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),BD(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{tO(),qD(),VD(700)}},flowengage_click_button:async e=>{let t=jO(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=AO(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{BD(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await eO(r),r.focus?.(),await nO(r),rO(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),BD(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),BD(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{tO(),VD(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function BO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=pn();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var VO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function HO(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function UO(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function WO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,M.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?b.createElement(e):b.isValidElement(e)?e:null;return n?(0,M.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function GO({title:e}){return(0,M.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function KO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function qO({orbColors:e,...t}){return(0,M.jsx)(uD,{colors:e,...t})}function JO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||VO.green,s=UO(o),c=a?72:94,l=(0,M.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,M.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,M.jsx)(jp.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,M.jsxs)(jp.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,M.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:o,color:s,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,M.jsx)(`button`,{onClick:i,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,M.jsx)(jp.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,M.jsx)(qO,{size:c,orbColors:t})})]});return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(jp.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,M.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function YO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o}){let s=n||VO.green,c=UO(s);return(0,M.jsxs)(jp.div,{initial:{scale:50/350,borderRadius:`50%`},animate:{scale:1,borderRadius:`16px`},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,M.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,M.jsx)(qO,{size:72,orbColors:t}),(0,M.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,M.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,M.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${s}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,M.jsx)(`button`,{onClick:i,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function XO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s,pendingResume:c,chatId:l}){let[u,d]=(0,b.useState)(`idle`),[f,p]=(0,b.useState)(!1),[m,h]=(0,b.useState)(!1),g=(0,b.useRef)(null),_=(0,b.useRef)(``),v=(0,b.useRef)(async()=>{}),y=(0,b.useRef)(!1),x=(0,b.useRef)(!1),ee=(0,b.useRef)(`idle`),S=(0,b.useRef)(!1),C=(0,b.useRef)(!1),te=(0,b.useRef)(`minimized`),w=(0,b.useRef)(0),ne=(0,b.useRef)(!1),re=(0,b.useRef)(null),ie=(0,b.useCallback)((e=`minimized`)=>{te.current=e,C.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),ae=(0,b.useCallback)(()=>(C.current=!0,y.current=!0,console.log(`[FlowEngage voice] markNavigationShutdown — calling endSession() for clean server close`),(g.current?.endSession?.()??Promise.resolve()).catch(()=>{})),[]),oe=(0,b.useCallback)(async e=>{C.current=!0;try{await g.current?.endSession?.()}catch{}if(g.current=null,d(`idle`),p(!1),y.current=!1,typeof s==`function`){let e=w.current;await s(e>0?o.current.slice(e):o.current)}e?.()},[o,s]);return v.current=()=>oe(te.current===`chat`?t:n),(0,b.useEffect)(()=>{x.current=f},[f]),(0,b.useEffect)(()=>{ee.current=u},[u]),(0,b.useEffect)(()=>{let e=()=>!!g.current,t=()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``},n=e=>{let n=t(),a=n.split(/\s+/).filter(Boolean).length;return{siteId:i,chatId:l||null,agentId:r,trigger:e,navigationConfidence:e===`agent_navigate`?`high`:`medium`,interruption:{state:ee.current,lastAgentText:n,lastUserText:_.current,estimatedSpokenWords:AD(),agentTextWordCount:a,isMuted:x.current},history:o.current||[]}},a=()=>{e()&&(OD()||DD.capture(n(`user_link_click`)))},s=t=>{e()&&(t.persisted||OD()||DD.capture(n(`pagehide`)))};return window.addEventListener(`beforeunload`,a),window.addEventListener(`pagehide`,s),()=>{window.removeEventListener(`beforeunload`,a),window.removeEventListener(`pagehide`,s)}},[i,l,r,o]),(0,b.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){d(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e||(c?(o.current=Array.isArray(c.history)?[...c.history]:[],w.current=o.current.length,c.interruption?.lastUserText&&(_.current=c.interruption.lastUserText),ne.current=!0,setTimeout(()=>{ne.current=!1},5e3)):(o.current=[],w.current=0,_.current=``,ne.current=!1),y.current=!1,S.current=!1,C.current=!1,te.current=`minimized`,c&&(console.log(`[FlowEngage voice] resume — waiting 800ms for server session cleanup`),await new Promise(e=>setTimeout(e,800)),e)))return;let t=BO(zO({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,getPostResumeNavLocked:()=>ne.current,requestEndSession:()=>{ie()},markNavigationShutdown:()=>{ae()},getSessionCaptureData:()=>{let e=(()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``})();return{siteId:i,chatId:l||null,agentId:r,history:o.current||[],lastAgentText:e,agentTextWordCount:e.split(/\s+/).filter(Boolean).length,lastUserText:_.current,estimatedSpokenWords:AD(),isMuted:x.current}}})),s=typeof window<`u`?window.location.href:``,u,f=null,m={prompt:null,sent:!1,conv:null,hasSeenSpeaking:!1};if(c&&!c.consumed){let e=typeof document<`u`?Array.from(document.querySelectorAll(`h1,h2,h3,h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.replace(/\s+/g,` `).trim().slice(0,80),id:e.id||null})).filter(e=>e.text.length>0).slice(0,25):[];f=DD.buildResumePrompt(c,e,s),m.prompt=f;let t=(()=>{if(typeof document<`u`&&document.title){let e=document.title.split(/\s*[|\-–—]\s*/)[0].replace(/\s+/g,` `).trim();if(e.length>0&&e.length<=60)return e}if(typeof window<`u`){let e=window.location.pathname.replace(/^\/|\/$/g,``).split(`/`).pop();if(e)return e.replace(/[-_]/g,` `)}return``})();u={agent:{firstMessage:t?`I've navigated you to the ${t} page as requested.`:`I've navigated to the page you requested.`}}}console.log(`[FlowEngage voice] startSession →`,{agentId:r,hasOverrides:!!u,firstMessage:u?.agent?.firstMessage??null,isResume:!!c});let h=await EE.startSession({agentId:r,...u?{overrides:u}:{},clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{if(!e&&(console.log(`[FlowEngage voice] onModeChange`,t,`hasSeenSpeaking:`,m.hasSeenSpeaking,`sent:`,m.sent),d(t===`speaking`?`speaking`:`listening`),t===`speaking`&&(m.hasSeenSpeaking=!0),t===`listening`&&m.hasSeenSpeaking&&!m.sent&&m.prompt&&m.conv)){console.log(`[FlowEngage voice] onModeChange → sending sendContextualUpdate (resume)`),m.sent=!0;let e=m.prompt;m.prompt=null;try{m.conv.sendContextualUpdate(e),DD.clear()}catch{}}},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(!r)return;let i=o.current,a=i.length>0?i[i.length-1]:null;a&&a.sender===n&&a.message===r||(n===`user`&&(_.current=r),o.current=[...i,{sender:n,message:r,timestamp:new Date().toISOString()}],KO(n,r)&&ie(`minimized`))},onError:t=>{if(!e&&!C.current&&!S.current){S.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),d(`error`),ie(`minimized`)}},onDisconnect:()=>{if(!e&&!C.current&&!S.current){S.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:_.current||``,wasMuted:x.current});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),ie(`minimized`)}}});if(e){y.current||h.endSession().catch(()=>{});return}n=h,g.current=h,m.conv=h,console.log(`[FlowEngage voice] startSession resolved OK`,{isResume:!!c}),d(`listening`);try{if(f){let t=setTimeout(()=>{if(!m.sent&&m.hasSeenSpeaking&&m.prompt&&m.conv&&!e){console.log(`[FlowEngage voice] fallbackTimerA firing sendContextualUpdate`),m.sent=!0;let e=m.prompt;m.prompt=null;try{m.conv.sendContextualUpdate(e),DD.clear()}catch{}}},6e3);setTimeout(()=>{if(!m.sent&&m.prompt&&m.conv&&!e){console.log(`[FlowEngage voice] fallbackTimerB firing sendContextualUpdate (no speaking seen)`),m.sent=!0;let e=m.prompt;m.prompt=null;try{m.conv.sendContextualUpdate(e),DD.clear()}catch{}}clearTimeout(t)},1e4)}else{let e=`[]`;try{e=await t.flowengage_list_forms()}catch{}let n=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, nav, footer, header`)).map(e=>({tag:e.tagName,text:e.textContent.trim(),id:e.id||null})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,25):[];h.sendContextualUpdate(`Page: ${s}. SiteId: ${i||`unknown`}. Sections on this page: ${JSON.stringify(n)}. IMPORTANT: Call flowengage_highlight with section_text from the list above as you explain each section. Forms: ${e}. Navigation: flowengage_navigate — use for cross-page navigation. End call: flowengage_end_session.`)}}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),d(`error`),te.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,C.current=!0,y.current||(n||g.current)?.endSession?.().catch(()=>{})}},[r,i,a,ie]),(0,b.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;re.current&&!re.current.contains(t)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,M.jsxs)(`div`,{ref:re,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,M.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&(0,M.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),(0,M.jsx)(qO,{size:72,voiceState:u,isMuted:f,orbColors:e})]}),u===`error`&&(0,M.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,M.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,M.jsx)(`button`,{onClick:async()=>{if(g.current)try{f?(await g.current.setMicMuted?.(!1),p(!1)):(await g.current.setMicMuted?.(!0),p(!0))}catch{}},title:f?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:f?`#7f1d1d`:`#1f2937`,border:f?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:f?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:f?(0,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,M.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,M.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,M.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,M.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,M.jsx)(DE,{size:16,color:`currentColor`})}),(0,M.jsx)(`button`,{onClick:()=>h(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,M.jsx)(FE,{size:16,color:`currentColor`})})]}),m&&(0,M.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,M.jsxs)(`button`,{onClick:()=>{h(!1),te.current=`chat`,oe(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,M.jsx)(IE,{}),`Enter Chat Mode`]}),(0,M.jsxs)(`button`,{onClick:()=>{h(!1),te.current=`minimized`,oe(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,M.jsx)(LE,{}),`End Conversation`]}),(0,M.jsx)(`button`,{onClick:()=>h(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,M.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,M.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function ZO({orbColors:e}){return(0,M.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,M.jsx)(qO,{size:36,orbColors:e})})}var QO=()=>(0,M.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,M.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,M.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function $O({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:d,agentName:f,agentHeadshot:p,fallbackAgentName:m,input:h,setInput:g,onSubmit:_,isConversationEnded:v,isLoading:y,isRateLimited:x,rateLimitMessage:ee,selectedFile:S,onFileSelect:C,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:ae,emailError:oe,replyContext:se,setReplyContext:ce,webRTCError:le,micError:ue,setMicError:T,dismissCallError:E,incomingCall:de,rejectCall:fe,acceptCall:pe,activeCallId:me,callConnectionState:he,isCallMuted:ge,toggleCallMute:_e,endWebRTCCall:ve,formatCallDuration:ye,callDurationSeconds:be,onCollapse:xe,onStartVoice:Se,showPoweredBy:Ce}){let we=c.length>0,Te=y||x||v,Ee=!!(de||me),[De,Oe]=(0,b.useState)(!1),ke=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(!De)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ke.current&&!ke.current.contains(t)&&Oe(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[De]),(0,M.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:0,width:`calc(100% - 16px)`,height:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,M.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0},children:[(0,M.jsx)(`button`,{onClick:xe,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,M.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,M.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,M.jsx)(WO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,M.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,M.jsx)(GO,{title:e.chatTitle})})}),(0,M.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,M.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,M.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:ke,children:[(0,M.jsx)(`button`,{type:`button`,onClick:()=>Oe(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,M.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,M.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,M.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,M.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),De&&(0,M.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,M.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),Se?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,M.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,M.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),xe?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,M.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,M.jsx)(tD,{webRTCError:le,micError:ue,setMicError:T,dismissCallError:E,incomingCall:de,rejectCall:fe,acceptCall:pe,activeCallId:me,callConnectionState:he,formatCallDuration:ye,callDurationSeconds:be,endWebRTCCall:ve,isCallMuted:ge,toggleCallMute:_e,isAIVoiceActive:!1,currentCallAgentName:f||m,isRateLimited:x,rateLimitMessage:ee}),(0,M.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:we?(0,M.jsx)(ZE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ce,TypingDots:QO,primaryColor:n,agentHeadshot:p,agentDisplayName:f||m,botAvatarNode:(0,M.jsx)(ZO,{orbColors:t})}):(0,M.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,M.jsx)(qO,{size:94,orbColors:t}),(0,M.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,M.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,M.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})}),(0,M.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:re?`6px 0 0`:`12px 0 0`},children:(0,M.jsx)(QE,{input:h,setInput:g,onSubmit:_,isConversationEnded:v,callUiActive:Ee,handleToggleVoice:Se,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Te,replyContext:se,clearReplyContext:()=>ce(null),onFileSelect:C,selectedFile:S,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:ae,emailError:oe,inputPlaceholder:e.inputPlaceholder})}),(0,M.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:Ce&&(0,M.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,M.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function ek(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:d,isLoading:f,isRateLimited:p,rateLimitMessage:m,isConversationEnded:h,incomingCall:g,activeCallId:_,callConnectionState:v,callConnectedAt:y,isCallMuted:x,webRTCError:ee,language:S,historyRef:C,onMessageSync:te,sendMessage:w,uploadChatFile:ne,openWidget:re,captureVisitorEmail:ie,setVoiceMode:ae,endConversation:oe,acceptCall:se,rejectCall:ce,endWebRTCCall:le,toggleCallMute:ue,dismissCallError:de,startTyping:pe,stopTyping:me,updateTypingDraft:he}=fn();(0,b.useEffect)(()=>{try{In()}catch{}},[]);let ge=t?.widgetSettings||{},_e=n?.widgetSettings||{},ve={...ge.branding||{},..._e.branding||{}},ye={...ge.theme||{},..._e.theme||{}},be={...ge.features||{},..._e.features||{}},xe=be.voice!==!1,Se=Array.isArray(ye.orbColors)&&ye.orbColors.length>0?ye.orbColors:null,Ce=Se?.[0]||ye.primaryColor||`#3B82F6`,we=ye.position||`bottom-right`,Te=ve.fallbackAgentName||`Agent`,Ee=HO(Se??ye.chatBgColors),De=ve.logo||ve.logoUrl||null,Oe=S||`en`,ke=ge.recommendations?.[Oe]||[],Ae=(_e.recommendations?.[Oe]??ke).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),je=Array.isArray(ve.quickChatOptions)&&ve.quickChatOptions.length>0?ve.quickChatOptions:Ae,Me=ve.hideWatermark===!0?!1:ve.showPoweredBy!==!1,D=ve.chatbotEnabled!==!1&&ye.chatbotEnabled!==!1,Ne=ge.greetings?.[S]||_e.greetings?.[S]||ve.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Pe={entryPrompt:ve.entryPrompt||`Do you want to explore in a new way?`,yesLabel:ve.yesLabel||`Yes`,laterLabel:ve.laterLabel||`Later`,connectionTitle:ve.connectionTitle||`How would you like to connect?`,voiceLabel:ve.voiceLabel||`Voice`,textLabel:ve.textLabel||`Text`,chatTitle:ve.headerName||`Chat with FlowEngage`,introGreeting:Ne,inputPlaceholder:ve.inputPlaceholder||`Type your message`,analysingLabel:ve.analysingLabel||`analysing...`},Fe=_e.elevenLabsAgentId||t?.elevenLabsAgentId||null,Ie=t?.siteId||n?.siteId||null,Le=t?.apiBaseUrl||``,Re=(0,b.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),ze=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Be=r.some(e=>e.sender===`user`),Ve=(0,b.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),He=!l&&Be&&Ve,Ue=!!(_e._dashboardLivePreview||ge._dashboardLivePreview),[We,O]=(0,b.useState)(()=>Ue?`text_chat`:`entry_prompt`),[k,Ge]=(0,b.useState)(``),[A,Ke]=(0,b.useState)(null),[qe,Je]=(0,b.useState)(l||``),[Ye,Xe]=(0,b.useState)(``),[Ze,Qe]=(0,b.useState)(0),[$e,et]=(0,b.useState)(null),[tt,nt]=(0,b.useState)(null),[rt,it]=(0,b.useState)(``),[at,ot]=(0,b.useState)(!1),st=(0,b.useRef)(null),ct=(0,b.useRef)(!1),lt=(0,b.useRef)(null),ut=(0,b.useMemo)(()=>fe(Ie),[Ie]);(0,b.useLayoutEffect)(()=>{if(!(e!==`ready`||ct.current)){ct.current=!0;try{let e=DD.read(Ie);if(e&&e._resumeMode===`auto`){lt.current=e,re({notifyChatInitiated:!0}),ae?.(!0),O(`voice_mode`);return}}catch{}if(T(Ie)||!xe){O(`minimized_orb`);return}}},[e,r]);let[dt,ft]=(0,b.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,b.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>ft(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,b.useEffect)(()=>{Je(l||``),l&&Xe(``)},[l]);let pt=(0,b.useCallback)(()=>{nt(null),it(``)},[]),mt=(0,b.useCallback)(e=>{let t=KE(e);if(t){nt(null),it(t);return}nt(e),it(``)},[]);(0,b.useEffect)(()=>{if(!y||v!==`connected`){Qe(0);return}let e=()=>{let e=new Date(y).getTime();isNaN(e)||Qe(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[y,v]),(0,b.useEffect)(()=>{let e=g?.callId||_||null;if(!e){st.current=null;return}(g?.callId||v===`connecting`||v===`connected`)&&(!(!i||We===`minimized_orb`||We===`voice_mode`)&&st.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:We,hasIncomingCall:!!g?.callId,activeCallId:_,callConnectionState:v}),st.current=e,We===`voice_mode`&&ae?.(!1),re?.(),O(`text_chat`)))},[_,v,g?.callId,i,re,ae,We]),(0,b.useEffect)(()=>{if(!o||h){he?.(``),me?.();return}if(!k.trim()||tt){he?.(``),me?.();return}pe?.();let e=window.setTimeout(()=>he?.(k),120),t=window.setTimeout(()=>me?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[k,tt,o,h,pe,me,he]);let ht=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,gt=async e=>{if(e.preventDefault(),h)return;if(He){let e=qe.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Xe(`Please enter a valid email so we can continue helping you.`);return}await ie(e),Xe(``);return}let t=ht(A);if(!k.trim()&&!tt)return;if(tt){try{ot(!0),it(``);let e=await ne(tt),n=e?.data||e,r=k.trim()||`Shared file: ${JE(tt)}`;Ge(``),Ke(null),pt(),await w(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||tt.name,fileType:n?.fileType||tt.type,fileSize:n?.fileSize||tt.size}})}catch(e){it(e?.message||`Failed to upload the selected file.`)}finally{ot(!1)}return}let n=k.trim();Ge(``),Ke(null),await w(n,``,t)},_t=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},vt=(0,b.useCallback)(async e=>{if(h||f)return;let t=e.message||e.label||e.text||``;t.trim()&&await w(t.trim(),``)},[h,f,w]),yt=dt&&We===`entry_prompt`?{inset:0}:dt&&We===`text_chat`?{left:0,right:0,bottom:0}:dt&&We===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:we===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},bt=()=>O(`minimized_orb`),xt=()=>O(`connection_modal`),St=()=>{re({notifyChatInitiated:!0}),ae?.(!0),O(`voice_mode`)},Ct=()=>{re({notifyChatInitiated:!0}),ae?.(!1),O(`text_chat`)},wt=()=>{ae?.(!1),bt()};return e!==`ready`||!D||be.chat===!1?null:(0,M.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...yt},children:[We===`entry_prompt`&&(0,M.jsx)(JO,{copy:Pe,orbColors:Se,primaryColor:Ce,onYes:()=>{E(Ie),St()},onLater:()=>{E(Ie),bt()},isMobile:dt}),We===`minimized_orb`&&(0,M.jsx)(jp.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,M.jsx)(qO,{size:50,orbColors:Se,onClick:xe?xt:Ct})}),We===`connection_modal`&&(0,M.jsx)(YO,{copy:Pe,orbColors:Se,primaryColor:Ce,onVoice:St,onText:Ct,onClose:bt,isMobile:dt}),We===`voice_mode`&&(0,M.jsx)(XO,{orbColors:Se,onEnterChat:Ct,onEndChat:wt,agentId:Fe,siteId:Ie,apiBaseUrl:Le,historyRef:C,onMessageSync:te,pendingResume:lt.current,chatId:ut},`voice`),We===`text_chat`&&(0,M.jsx)($O,{copy:Pe,orbColors:Se,primaryColor:Ce,chatBgGradient:Ee,logo:De,quickChatOptions:je,onQuickChatSelect:vt,isMobile:dt,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Re,agentHeadshot:ze,fallbackAgentName:Te,input:k,setInput:Ge,onSubmit:gt,isConversationEnded:h,isLoading:f,isRateLimited:p,rateLimitMessage:m,selectedFile:tt,onFileSelect:mt,onRemoveSelectedFile:pt,attachmentError:rt,isUploadingAttachment:at,requiresEmail:He,emailInput:qe,setEmailInput:Je,emailError:Ye,replyContext:A,setReplyContext:Ke,webRTCError:ee,micError:$e,setMicError:et,dismissCallError:de,incomingCall:g,rejectCall:ce,acceptCall:se,activeCallId:_,callConnectionState:v,isCallMuted:x,toggleCallMute:ue,endWebRTCCall:le,formatCallDuration:_t,callDurationSeconds:Ze,onCollapse:bt,onStartVoice:St,onEndConversation:oe,showPoweredBy:Me}),(0,M.jsx)(`style`,{children:`
|
|
616
|
+
`)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=IO(jO(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=jO(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=pO(),t=mO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),qD();let t=MO(e);if(!t.length&&r){let e=r(),n=NO(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=PO(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;BD(`Filling ${String(t)}...`,{spinner:!0});let a=fO(),o=TO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())JD(t),await eO(t),LO(t,r,{skipScroll:e>0}),YD(t),await aO(120);i=o,n.push(String(t));continue}let s=OO(a,String(t));s||=yO(a,String(t)),s||=bO(a,String(t),r),s&&(JD(s),await eO(s),LO(s,r),YD(s),await aO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),BD(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),BD(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{tO(),qD(),VD(700)}},flowengage_click_button:async e=>{let t=jO(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=AO(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{BD(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await eO(r),r.focus?.(),await nO(r),rO(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),BD(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),BD(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{tO(),VD(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function BO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=pn();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var VO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function HO(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function UO(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function WO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,M.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?b.createElement(e):b.isValidElement(e)?e:null;return n?(0,M.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function GO({title:e}){return(0,M.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function KO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function qO({orbColors:e,...t}){return(0,M.jsx)(uD,{colors:e,...t})}function JO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||VO.green,s=UO(o),c=a?72:94,l=(0,M.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,M.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,M.jsx)(jp.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,M.jsxs)(jp.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,M.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:o,color:s,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,M.jsx)(`button`,{onClick:i,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,M.jsx)(jp.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,M.jsx)(qO,{size:c,orbColors:t})})]});return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(jp.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,M.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function YO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o}){let s=n||VO.green,c=UO(s);return(0,M.jsxs)(jp.div,{initial:{scale:50/350,borderRadius:`50%`},animate:{scale:1,borderRadius:`16px`},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,M.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,M.jsx)(qO,{size:72,orbColors:t}),(0,M.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,M.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,M.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${s}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,M.jsx)(`button`,{onClick:i,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function XO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s,pendingResume:c,chatId:l}){let[u,d]=(0,b.useState)(`idle`),[f,p]=(0,b.useState)(!1),[m,h]=(0,b.useState)(!1),g=(0,b.useRef)(null),_=(0,b.useRef)(``),v=(0,b.useRef)(async()=>{}),y=(0,b.useRef)(!1),x=(0,b.useRef)(!1),ee=(0,b.useRef)(`idle`),S=(0,b.useRef)(!1),C=(0,b.useRef)(!1),te=(0,b.useRef)(`minimized`),w=(0,b.useRef)(0),ne=(0,b.useRef)(!1),re=(0,b.useRef)(null),ie=(0,b.useCallback)((e=`minimized`)=>{te.current=e,C.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),ae=(0,b.useCallback)(()=>(C.current=!0,y.current=!0,console.log(`[FlowEngage voice] markNavigationShutdown — calling endSession() for clean server close`),(g.current?.endSession?.()??Promise.resolve()).catch(()=>{})),[]),oe=(0,b.useCallback)(async e=>{C.current=!0;try{await g.current?.endSession?.()}catch{}if(g.current=null,d(`idle`),p(!1),y.current=!1,typeof s==`function`){let e=w.current;await s(e>0?o.current.slice(e):o.current)}e?.()},[o,s]);return v.current=()=>oe(te.current===`chat`?t:n),(0,b.useEffect)(()=>{x.current=f},[f]),(0,b.useEffect)(()=>{ee.current=u},[u]),(0,b.useEffect)(()=>{let e=()=>!!g.current,t=()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``},n=e=>{let n=t(),a=n.split(/\s+/).filter(Boolean).length;return{siteId:i,chatId:l||null,agentId:r,trigger:e,navigationConfidence:e===`agent_navigate`?`high`:`medium`,interruption:{state:ee.current,lastAgentText:n,lastUserText:_.current,estimatedSpokenWords:AD(),agentTextWordCount:a,isMuted:x.current},history:o.current||[]}},a=()=>{e()&&(OD()||DD.capture(n(`user_link_click`)))},s=t=>{e()&&(t.persisted||OD()||DD.capture(n(`pagehide`)))};return window.addEventListener(`beforeunload`,a),window.addEventListener(`pagehide`,s),()=>{window.removeEventListener(`beforeunload`,a),window.removeEventListener(`pagehide`,s)}},[i,l,r,o]),(0,b.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){d(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e||(c?(o.current=Array.isArray(c.history)?[...c.history]:[],w.current=o.current.length,c.interruption?.lastUserText&&(_.current=c.interruption.lastUserText),ne.current=!0,setTimeout(()=>{ne.current=!1},5e3)):(o.current=[],w.current=0,_.current=``,ne.current=!1),y.current=!1,S.current=!1,C.current=!1,te.current=`minimized`,c&&(console.log(`[FlowEngage voice] resume — waiting 800ms for server session cleanup`),await new Promise(e=>setTimeout(e,800)),e)))return;let t=BO(zO({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,getPostResumeNavLocked:()=>ne.current,requestEndSession:()=>{ie()},markNavigationShutdown:()=>{ae()},getSessionCaptureData:()=>{let e=(()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``})();return{siteId:i,chatId:l||null,agentId:r,history:o.current||[],lastAgentText:e,agentTextWordCount:e.split(/\s+/).filter(Boolean).length,lastUserText:_.current,estimatedSpokenWords:AD(),isMuted:x.current}}})),s=typeof window<`u`?window.location.href:``,u=null;if(c&&!c.consumed){let e=typeof document<`u`?Array.from(document.querySelectorAll(`h1,h2,h3,h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.replace(/\s+/g,` `).trim().slice(0,80),id:e.id||null})).filter(e=>e.text.length>0).slice(0,25):[];u=DD.buildResumePrompt(c,e,s)}console.log(`[FlowEngage voice] startSession →`,{agentId:r,isResume:!!c,hasImmediateResumePrompt:!!u});let f=await EE.startSession({agentId:r,clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||(console.log(`[FlowEngage voice] onModeChange`,t),d(t===`speaking`?`speaking`:`listening`))},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(!r)return;let i=o.current,a=i.length>0?i[i.length-1]:null;a&&a.sender===n&&a.message===r||(n===`user`&&(_.current=r),o.current=[...i,{sender:n,message:r,timestamp:new Date().toISOString()}],KO(n,r)&&ie(`minimized`))},onError:t=>{if(!e&&!C.current&&!S.current){S.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),d(`error`),ie(`minimized`)}},onDisconnect:()=>{if(!e&&!C.current&&!S.current){S.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:_.current||``,wasMuted:x.current});try{g.current?.setMicMuted?.(!0)}catch{}p(!0),ie(`minimized`)}}});if(e){y.current||f.endSession().catch(()=>{});return}n=f,g.current=f,console.log(`[FlowEngage voice] startSession resolved OK`,{isResume:!!c}),d(`listening`);try{if(u)console.log(`[FlowEngage voice] sending resume contextualUpdate immediately`),f.sendContextualUpdate(u),DD.clear();else{let e=`[]`;try{e=await t.flowengage_list_forms()}catch{}let n=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, nav, footer, header`)).map(e=>({tag:e.tagName,text:e.textContent.trim(),id:e.id||null})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,25):[];f.sendContextualUpdate(`Page: ${s}. SiteId: ${i||`unknown`}. Sections on this page: ${JSON.stringify(n)}. IMPORTANT: Call flowengage_highlight with section_text from the list above as you explain each section. Forms: ${e}. Navigation: flowengage_navigate — use for cross-page navigation. End call: flowengage_end_session.`)}}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),d(`error`),te.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,C.current=!0,y.current||(n||g.current)?.endSession?.().catch(()=>{})}},[r,i,a,ie]),(0,b.useEffect)(()=>{if(!m)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;re.current&&!re.current.contains(t)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m]),(0,M.jsxs)(`div`,{ref:re,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,M.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&(0,M.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),(0,M.jsx)(qO,{size:72,voiceState:u,isMuted:f,orbColors:e})]}),u===`error`&&(0,M.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,M.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,M.jsx)(`button`,{onClick:async()=>{if(g.current)try{f?(await g.current.setMicMuted?.(!1),p(!1)):(await g.current.setMicMuted?.(!0),p(!0))}catch{}},title:f?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:f?`#7f1d1d`:`#1f2937`,border:f?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:f?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:f?(0,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,M.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,M.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,M.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,M.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,M.jsx)(DE,{size:16,color:`currentColor`})}),(0,M.jsx)(`button`,{onClick:()=>h(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,M.jsx)(FE,{size:16,color:`currentColor`})})]}),m&&(0,M.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,M.jsxs)(`button`,{onClick:()=>{h(!1),te.current=`chat`,oe(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,M.jsx)(IE,{}),`Enter Chat Mode`]}),(0,M.jsxs)(`button`,{onClick:()=>{h(!1),te.current=`minimized`,oe(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,M.jsx)(LE,{}),`End Conversation`]}),(0,M.jsx)(`button`,{onClick:()=>h(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,M.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,M.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function ZO({orbColors:e}){return(0,M.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,M.jsx)(qO,{size:36,orbColors:e})})}var QO=()=>(0,M.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,M.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,M.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function $O({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:d,agentName:f,agentHeadshot:p,fallbackAgentName:m,input:h,setInput:g,onSubmit:_,isConversationEnded:v,isLoading:y,isRateLimited:x,rateLimitMessage:ee,selectedFile:S,onFileSelect:C,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:ae,emailError:oe,replyContext:se,setReplyContext:ce,webRTCError:le,micError:ue,setMicError:T,dismissCallError:E,incomingCall:de,rejectCall:fe,acceptCall:pe,activeCallId:me,callConnectionState:he,isCallMuted:ge,toggleCallMute:_e,endWebRTCCall:ve,formatCallDuration:ye,callDurationSeconds:be,onCollapse:xe,onStartVoice:Se,showPoweredBy:Ce}){let we=c.length>0,Te=y||x||v,Ee=!!(de||me),[De,Oe]=(0,b.useState)(!1),ke=(0,b.useRef)(null);return(0,b.useEffect)(()=>{if(!De)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ke.current&&!ke.current.contains(t)&&Oe(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[De]),(0,M.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:0,width:`calc(100% - 16px)`,height:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,M.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0},children:[(0,M.jsx)(`button`,{onClick:xe,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,M.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,M.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,M.jsx)(WO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,M.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,M.jsx)(GO,{title:e.chatTitle})})}),(0,M.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,M.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,M.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:ke,children:[(0,M.jsx)(`button`,{type:`button`,onClick:()=>Oe(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,M.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,M.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,M.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,M.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),De&&(0,M.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,M.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),Se?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,M.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,M.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>{Oe(!1),xe?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,M.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,M.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,M.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,M.jsx)(tD,{webRTCError:le,micError:ue,setMicError:T,dismissCallError:E,incomingCall:de,rejectCall:fe,acceptCall:pe,activeCallId:me,callConnectionState:he,formatCallDuration:ye,callDurationSeconds:be,endWebRTCCall:ve,isCallMuted:ge,toggleCallMute:_e,isAIVoiceActive:!1,currentCallAgentName:f||m,isRateLimited:x,rateLimitMessage:ee}),(0,M.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:we?(0,M.jsx)(ZE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ce,TypingDots:QO,primaryColor:n,agentHeadshot:p,agentDisplayName:f||m,botAvatarNode:(0,M.jsx)(ZO,{orbColors:t})}):(0,M.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,M.jsx)(qO,{size:94,orbColors:t}),(0,M.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,M.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,M.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})}),(0,M.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:re?`6px 0 0`:`12px 0 0`},children:(0,M.jsx)(QE,{input:h,setInput:g,onSubmit:_,isConversationEnded:v,callUiActive:Ee,handleToggleVoice:Se,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Te,replyContext:se,clearReplyContext:()=>ce(null),onFileSelect:C,selectedFile:S,onRemoveSelectedFile:te,attachmentError:w,isUploadingAttachment:ne,requiresEmail:re,emailInput:ie,setEmailInput:ae,emailError:oe,inputPlaceholder:e.inputPlaceholder})}),(0,M.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:Ce&&(0,M.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,M.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function ek(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:d,isLoading:f,isRateLimited:p,rateLimitMessage:m,isConversationEnded:h,incomingCall:g,activeCallId:_,callConnectionState:v,callConnectedAt:y,isCallMuted:x,webRTCError:ee,language:S,historyRef:C,onMessageSync:te,sendMessage:w,uploadChatFile:ne,openWidget:re,captureVisitorEmail:ie,setVoiceMode:ae,endConversation:oe,acceptCall:se,rejectCall:ce,endWebRTCCall:le,toggleCallMute:ue,dismissCallError:de,startTyping:pe,stopTyping:me,updateTypingDraft:he}=fn();(0,b.useEffect)(()=>{try{In()}catch{}},[]);let ge=t?.widgetSettings||{},_e=n?.widgetSettings||{},ve={...ge.branding||{},..._e.branding||{}},ye={...ge.theme||{},..._e.theme||{}},be={...ge.features||{},..._e.features||{}},xe=be.voice!==!1,Se=Array.isArray(ye.orbColors)&&ye.orbColors.length>0?ye.orbColors:null,Ce=Se?.[0]||ye.primaryColor||`#3B82F6`,we=ye.position||`bottom-right`,Te=ve.fallbackAgentName||`Agent`,Ee=HO(Se??ye.chatBgColors),De=ve.logo||ve.logoUrl||null,Oe=S||`en`,ke=ge.recommendations?.[Oe]||[],Ae=(_e.recommendations?.[Oe]??ke).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),je=Array.isArray(ve.quickChatOptions)&&ve.quickChatOptions.length>0?ve.quickChatOptions:Ae,Me=ve.hideWatermark===!0?!1:ve.showPoweredBy!==!1,D=ve.chatbotEnabled!==!1&&ye.chatbotEnabled!==!1,Ne=ge.greetings?.[S]||_e.greetings?.[S]||ve.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Pe={entryPrompt:ve.entryPrompt||`Do you want to explore in a new way?`,yesLabel:ve.yesLabel||`Yes`,laterLabel:ve.laterLabel||`Later`,connectionTitle:ve.connectionTitle||`How would you like to connect?`,voiceLabel:ve.voiceLabel||`Voice`,textLabel:ve.textLabel||`Text`,chatTitle:ve.headerName||`Chat with FlowEngage`,introGreeting:Ne,inputPlaceholder:ve.inputPlaceholder||`Type your message`,analysingLabel:ve.analysingLabel||`analysing...`},Fe=_e.elevenLabsAgentId||t?.elevenLabsAgentId||null,Ie=t?.siteId||n?.siteId||null,Le=t?.apiBaseUrl||``,Re=(0,b.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),ze=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Be=r.some(e=>e.sender===`user`),Ve=(0,b.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),He=!l&&Be&&Ve,Ue=!!(_e._dashboardLivePreview||ge._dashboardLivePreview),[We,O]=(0,b.useState)(()=>Ue?`text_chat`:`entry_prompt`),[k,Ge]=(0,b.useState)(``),[A,Ke]=(0,b.useState)(null),[qe,Je]=(0,b.useState)(l||``),[Ye,Xe]=(0,b.useState)(``),[Ze,Qe]=(0,b.useState)(0),[$e,et]=(0,b.useState)(null),[tt,nt]=(0,b.useState)(null),[rt,it]=(0,b.useState)(``),[at,ot]=(0,b.useState)(!1),st=(0,b.useRef)(null),ct=(0,b.useRef)(!1),lt=(0,b.useRef)(null),ut=(0,b.useMemo)(()=>fe(Ie),[Ie]);(0,b.useLayoutEffect)(()=>{if(!(e!==`ready`||ct.current)){ct.current=!0;try{let e=DD.read(Ie);if(e&&e._resumeMode===`auto`){lt.current=e,re({notifyChatInitiated:!0}),ae?.(!0),O(`voice_mode`);return}}catch{}if(T(Ie)||!xe){O(`minimized_orb`);return}}},[e,r]);let[dt,ft]=(0,b.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,b.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>ft(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,b.useEffect)(()=>{Je(l||``),l&&Xe(``)},[l]);let pt=(0,b.useCallback)(()=>{nt(null),it(``)},[]),mt=(0,b.useCallback)(e=>{let t=KE(e);if(t){nt(null),it(t);return}nt(e),it(``)},[]);(0,b.useEffect)(()=>{if(!y||v!==`connected`){Qe(0);return}let e=()=>{let e=new Date(y).getTime();isNaN(e)||Qe(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[y,v]),(0,b.useEffect)(()=>{let e=g?.callId||_||null;if(!e){st.current=null;return}(g?.callId||v===`connecting`||v===`connected`)&&(!(!i||We===`minimized_orb`||We===`voice_mode`)&&st.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:We,hasIncomingCall:!!g?.callId,activeCallId:_,callConnectionState:v}),st.current=e,We===`voice_mode`&&ae?.(!1),re?.(),O(`text_chat`)))},[_,v,g?.callId,i,re,ae,We]),(0,b.useEffect)(()=>{if(!o||h){he?.(``),me?.();return}if(!k.trim()||tt){he?.(``),me?.();return}pe?.();let e=window.setTimeout(()=>he?.(k),120),t=window.setTimeout(()=>me?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[k,tt,o,h,pe,me,he]);let ht=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,gt=async e=>{if(e.preventDefault(),h)return;if(He){let e=qe.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Xe(`Please enter a valid email so we can continue helping you.`);return}await ie(e),Xe(``);return}let t=ht(A);if(!k.trim()&&!tt)return;if(tt){try{ot(!0),it(``);let e=await ne(tt),n=e?.data||e,r=k.trim()||`Shared file: ${JE(tt)}`;Ge(``),Ke(null),pt(),await w(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||tt.name,fileType:n?.fileType||tt.type,fileSize:n?.fileSize||tt.size}})}catch(e){it(e?.message||`Failed to upload the selected file.`)}finally{ot(!1)}return}let n=k.trim();Ge(``),Ke(null),await w(n,``,t)},_t=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},vt=(0,b.useCallback)(async e=>{if(h||f)return;let t=e.message||e.label||e.text||``;t.trim()&&await w(t.trim(),``)},[h,f,w]),yt=dt&&We===`entry_prompt`?{inset:0}:dt&&We===`text_chat`?{left:0,right:0,bottom:0}:dt&&We===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:we===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},bt=()=>O(`minimized_orb`),xt=()=>O(`connection_modal`),St=()=>{re({notifyChatInitiated:!0}),ae?.(!0),O(`voice_mode`)},Ct=()=>{re({notifyChatInitiated:!0}),ae?.(!1),O(`text_chat`)},wt=()=>{ae?.(!1),bt()};return e!==`ready`||!D||be.chat===!1?null:(0,M.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...yt},children:[We===`entry_prompt`&&(0,M.jsx)(JO,{copy:Pe,orbColors:Se,primaryColor:Ce,onYes:()=>{E(Ie),St()},onLater:()=>{E(Ie),bt()},isMobile:dt}),We===`minimized_orb`&&(0,M.jsx)(jp.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,M.jsx)(qO,{size:50,orbColors:Se,onClick:xe?xt:Ct})}),We===`connection_modal`&&(0,M.jsx)(YO,{copy:Pe,orbColors:Se,primaryColor:Ce,onVoice:St,onText:Ct,onClose:bt,isMobile:dt}),We===`voice_mode`&&(0,M.jsx)(XO,{orbColors:Se,onEnterChat:Ct,onEndChat:wt,agentId:Fe,siteId:Ie,apiBaseUrl:Le,historyRef:C,onMessageSync:te,pendingResume:lt.current,chatId:ut},`voice`),We===`text_chat`&&(0,M.jsx)($O,{copy:Pe,orbColors:Se,primaryColor:Ce,chatBgGradient:Ee,logo:De,quickChatOptions:je,onQuickChatSelect:vt,isMobile:dt,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Re,agentHeadshot:ze,fallbackAgentName:Te,input:k,setInput:Ge,onSubmit:gt,isConversationEnded:h,isLoading:f,isRateLimited:p,rateLimitMessage:m,selectedFile:tt,onFileSelect:mt,onRemoveSelectedFile:pt,attachmentError:rt,isUploadingAttachment:at,requiresEmail:He,emailInput:qe,setEmailInput:Je,emailError:Ye,replyContext:A,setReplyContext:Ke,webRTCError:ee,micError:$e,setMicError:et,dismissCallError:de,incomingCall:g,rejectCall:ce,acceptCall:se,activeCallId:_,callConnectionState:v,isCallMuted:x,toggleCallMute:ue,endWebRTCCall:le,formatCallDuration:_t,callDurationSeconds:Ze,onCollapse:bt,onStartVoice:St,onEndConversation:oe,showPoweredBy:Me}),(0,M.jsx)(`style`,{children:`
|
|
617
617
|
/* Force any SVG (or img) inside LogoSlot to fill the container height
|
|
618
618
|
regardless of whether the component forwards its style prop. */
|
|
619
619
|
.fe-logo-slot svg,
|
|
@@ -605,7 +605,7 @@ registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
|
605
605
|
fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
|
|
606
606
|
filter="url(#${Q}-csh)"/>
|
|
607
607
|
</svg>`,KD=null,qD=!1;function JD(){return(!KD||!KD.isConnected)&&(KD=document.createElement(`div`),KD.id=`${Q}-cursor`,KD.innerHTML=GD,document.body.appendChild(KD),qD=!1),KD}async function YD(e){if(typeof document>`u`||!e)return;jD();let t;try{t=e.getBoundingClientRect()}catch{return}let n=t.left+Math.min(16,t.width*.2),r=t.top+Math.min(12,t.height*.25),i=JD();qD||=(i.style.transition=`none`,i.style.left=`${window.innerWidth/2}px`,i.style.top=`${window.innerHeight*.4}px`,i.classList.add(`${Q}-cursor-visible`),i.offsetHeight,i.style.transition=`left 0.32s cubic-bezier(0.25,0.46,0.45,0.94), top 0.32s cubic-bezier(0.25,0.46,0.45,0.94), opacity 0.2s ease`,!0),i.style.left=`${n}px`,i.style.top=`${r}px`,await $D(360)}function XD(e=!1){KD&&(e?(KD.classList.remove(`${Q}-cursor-visible`),qD=!1):(KD.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{qD=!1},250)))}async function ZD(e){KD&&(KD.classList.add(`${Q}-cursor-click`),await $D(280),KD.classList.remove(`${Q}-cursor-click`))}function QD(e){if(!e||typeof document>`u`)return;jD();let t;try{t=e.getBoundingClientRect()}catch{return}let n=e.style.position,r=e.style.overflow,i=window.getComputedStyle(e).position;[`relative`,`absolute`,`fixed`,`sticky`].includes(i)||(e.style.position=`relative`),e.style.overflow=`hidden`;let a=document.createElement(`span`);a.className=`${Q}-ripple`;let o=Math.max(t.width,t.height)*1.2;Object.assign(a.style,{width:`${o}px`,height:`${o}px`,left:`${t.width/2-o/2}px`,top:`${t.height/2-o/2}px`}),e.appendChild(a),setTimeout(()=>{a.remove(),e.style.position=n,e.style.overflow=r},650)}function $D(e){return new Promise(t=>setTimeout(t,e))}function $(...e){an()&&console.log(`[FlowEngage:voice-tools]`,...e)}function eO(e){return new Promise(t=>setTimeout(t,e))}var tO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function nO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(tO)}catch{return!1}}function rO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function iO(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!nO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function aO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function oO(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return aO(r.join(` `))}if(e.labels&&e.labels.length)return aO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return aO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return aO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return aO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=aO(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return aO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return aO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?aO(o):null}function sO(){let e=[];return iO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(nO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=rO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function cO(){return sO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:oO(e),placeholder:e.placeholder||null}))}function lO(){let e=[];return iO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(nO(e)||e.disabled)return!1;try{let t=rO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function uO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function dO(e){let t=uO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function fO(e,t){let n=dO(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,oO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>uO(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var pO=28;function mO(e,t){let n=null,r=0;for(let i of e){let e=fO(i,t);e>r&&(r=e,n=i)}return!n||r<pO?null:n}function hO(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,oO(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function gO(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function _O(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function vO(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function yO(e){if(!vO(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,oO(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function bO(e,t,n){let r=String(t??``),i=String(n??``),a=CO(e,r)||mO(e,r)||hO(e,r,i);if(!a)return[];let o=new Set([a]);if(gO(i)&&_O(r))for(let t of e)t!==a&&yO(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function xO(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function SO(e){if(!e||typeof e!=`string`)return null;let t=null;return iO(n=>{try{let r=n.getElementById(e);r&&!nO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function CO(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=SO(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=SO(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function wO(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function TO(e,t){let n=[];iO(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(nO(e)||e.disabled)return!1;try{let t=rO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:wO(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=xO(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function EO(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function DO(e){let t=EO(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function OO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function kO(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function AO(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function jO(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function MO(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function NO(){let e={};document.querySelectorAll(`h1, h2, h3, h4, h5, h6`).forEach(t=>{if(t.id)return;let n=t.textContent.trim();if(!n)return;let r=n.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).substring(0,60);if(e[r]){let t=2;for(;e[r+`-`+t];)t++;r=r+`-`+t}e[r]=!0,t.id=r})}function PO(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{if($(`flowengage_navigate ▶ raw parameters:`,n),typeof e.getPostResumeNavLocked==`function`&&e.getPostResumeNavLocked())return $(`flowengage_navigate · blocked (post-resume lock active)`,n),`Navigation is not needed — you just arrived at this page via the user's navigation request. Stay here and continue the conversation naturally.`;let r=EO(n),i=AO(r),a=r.section_text??r.sectionText??r.section;if($(`flowengage_navigate · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(i,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(i=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,i))}catch{}if(typeof window<`u`)try{let e=new URL(i,window.location.href),t=window.location;if(e.pathname===t.pathname&&e.search===t.search&&(e.hash===t.hash||!e.hash))return $(`flowengage_navigate · already on target page, skipping navigation`),`Already on that page. Continue the conversation naturally without calling flowengage_navigate again.`}catch{}if(!await Pn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${i}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{FD(`Navigating to ${i}...`,{spinner:!0}),BD();let t=typeof e.getSessionCaptureData==`function`?e.getSessionCaptureData():null,n=i;if(t){let{ok:e,sessionKey:r,compact:o}=SD.capture({siteId:t.siteId,chatId:t.chatId,agentId:t.agentId,trigger:`agent_navigate`,navigationConfidence:`high`,targetUrl:i,interruption:{state:`tool_calling`,toolName:`flowengage_navigate`,toolParams:{url:i,section_text:a||null},lastAgentText:t.lastAgentText,lastUserText:t.lastUserText,estimatedSpokenWords:t.estimatedSpokenWords,agentTextWordCount:t.agentTextWordCount,isMuted:t.isMuted||!1},history:t.history});e&&r?n=bD(i,r):o&&(n=bD(i,o)),$(`flowengage_navigate · session captured, resumeUrl:`,n)}return typeof e.markNavigationShutdown==`function`&&($(`flowengage_navigate · awaiting markNavigationShutdown (clean WS close)`),await e.markNavigationShutdown(),$(`flowengage_navigate · endSession complete — server session closed`)),ED(),await eO(300),$(`flowengage_navigate → location.assign`,n),window.location.assign(n),`Navigating...`}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),FD(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{VD(),ID(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=EO(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;NO();let i=An(n||null,r||null);return!i&&r&&(await new Promise(e=>setTimeout(e,500)),NO(),i=An(null,r)),i?(kD(i),$(`flowengage_highlight ✓`,r||n),`OK_HIGHLIGHT: "${r||n}"`):($(`flowengage_highlight ✖ no element for:`,r||n),`Could not find "${r||n}" on the current page. Try a shorter phrase matching a visible heading.`)},flowengage_read_content:async e=>{$(`flowengage_read_content ▶`,e);let t=EO(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=An(null,n);if(!t)return`Could not find section "${n}" on the page.`;let r=[t.textContent.trim()],i=t.nextElementSibling;for(;i&&!/^H[1-3]$/i.test(i.tagName);){let e=i.textContent.trim();e&&r.push(e),i=i.nextElementSibling}e=r.join(`
|
|
608
|
-
`)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=jO(EO(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=EO(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=cO(),t=lO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),HD();let t=DO(e);if(!t.length&&r){let e=r(),n=OO(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=kO(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;FD(`Filling ${String(t)}...`,{spinner:!0});let a=sO(),o=bO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())UD(t),await YD(t),MO(t,r,{skipScroll:e>0}),WD(t),await eO(120);i=o,n.push(String(t));continue}let s=CO(a,String(t));s||=mO(a,String(t)),s||=hO(a,String(t),r),s&&(UD(s),await YD(s),MO(s,r),WD(s),await eO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),FD(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),FD(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{XD(),HD(),ID(700)}},flowengage_click_button:async e=>{let t=EO(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=TO(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{FD(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await YD(r),r.focus?.(),await ZD(r),QD(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),FD(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),FD(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{XD(),ID(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function FO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=an();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var IO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function LO(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function RO(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function zO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,f.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return n?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function BO({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function VO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function HO({orbColors:e,...t}){return(0,f.jsx)(aD,{colors:e,...t})}function UO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||IO.green,s=RO(o),c=a?72:94,l=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(Mp.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,f.jsxs)(Mp.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:o,color:s,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(Mp.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,f.jsx)(HO,{size:c,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(Mp.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,f.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function WO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o}){let s=n||IO.green,c=RO(s);return(0,f.jsxs)(Mp.div,{initial:{scale:50/350,borderRadius:`50%`},animate:{scale:1,borderRadius:`16px`},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(HO,{size:72,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${s}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function GO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s,pendingResume:c,chatId:l}){let[u,p]=(0,d.useState)(`idle`),[m,h]=(0,d.useState)(!1),[g,_]=(0,d.useState)(!1),v=(0,d.useRef)(null),y=(0,d.useRef)(``),b=(0,d.useRef)(async()=>{}),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(`idle`),te=(0,d.useRef)(!1),C=(0,d.useRef)(!1),ne=(0,d.useRef)(`minimized`),re=(0,d.useRef)(0),ie=(0,d.useRef)(!1),ae=(0,d.useRef)(null),oe=(0,d.useCallback)((e=`minimized`)=>{ne.current=e,C.current=!0,queueMicrotask(()=>{x.current||(x.current=!0,b.current?.())})},[o]),se=(0,d.useCallback)(()=>(C.current=!0,x.current=!0,console.log(`[FlowEngage voice] markNavigationShutdown — calling endSession() for clean server close`),(v.current?.endSession?.()??Promise.resolve()).catch(()=>{})),[]),ce=(0,d.useCallback)(async e=>{C.current=!0;try{await v.current?.endSession?.()}catch{}if(v.current=null,p(`idle`),h(!1),x.current=!1,typeof s==`function`){let e=re.current;await s(e>0?o.current.slice(e):o.current)}e?.()},[o,s]);return b.current=()=>ce(ne.current===`chat`?t:n),(0,d.useEffect)(()=>{S.current=m},[m]),(0,d.useEffect)(()=>{ee.current=u},[u]),(0,d.useEffect)(()=>{let e=()=>!!v.current,t=()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``},n=e=>{let n=t(),a=n.split(/\s+/).filter(Boolean).length;return{siteId:i,chatId:l||null,agentId:r,trigger:e,navigationConfidence:e===`agent_navigate`?`high`:`medium`,interruption:{state:ee.current,lastAgentText:n,lastUserText:y.current,estimatedSpokenWords:TD(),agentTextWordCount:a,isMuted:S.current},history:o.current||[]}},a=()=>{e()&&(CD()||SD.capture(n(`user_link_click`)))},s=t=>{e()&&(t.persisted||CD()||SD.capture(n(`pagehide`)))};return window.addEventListener(`beforeunload`,a),window.addEventListener(`pagehide`,s),()=>{window.removeEventListener(`beforeunload`,a),window.removeEventListener(`pagehide`,s)}},[i,l,r,o]),(0,d.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){p(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e||(c?(o.current=Array.isArray(c.history)?[...c.history]:[],re.current=o.current.length,c.interruption?.lastUserText&&(y.current=c.interruption.lastUserText),ie.current=!0,setTimeout(()=>{ie.current=!1},5e3)):(o.current=[],re.current=0,y.current=``,ie.current=!1),x.current=!1,te.current=!1,C.current=!1,ne.current=`minimized`,c&&(console.log(`[FlowEngage voice] resume — waiting 800ms for server session cleanup`),await new Promise(e=>setTimeout(e,800)),e)))return;let t=FO(PO({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>y.current,getPostResumeNavLocked:()=>ie.current,requestEndSession:()=>{oe()},markNavigationShutdown:()=>{se()},getSessionCaptureData:()=>{let e=(()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``})();return{siteId:i,chatId:l||null,agentId:r,history:o.current||[],lastAgentText:e,agentTextWordCount:e.split(/\s+/).filter(Boolean).length,lastUserText:y.current,estimatedSpokenWords:TD(),isMuted:S.current}}})),s=typeof window<`u`?window.location.href:``,u,d=null,f={prompt:null,sent:!1,conv:null,hasSeenSpeaking:!1};if(c&&!c.consumed){let e=typeof document<`u`?Array.from(document.querySelectorAll(`h1,h2,h3,h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.replace(/\s+/g,` `).trim().slice(0,80),id:e.id||null})).filter(e=>e.text.length>0).slice(0,25):[];d=SD.buildResumePrompt(c,e,s),f.prompt=d;let t=(()=>{if(typeof document<`u`&&document.title){let e=document.title.split(/\s*[|\-–—]\s*/)[0].replace(/\s+/g,` `).trim();if(e.length>0&&e.length<=60)return e}if(typeof window<`u`){let e=window.location.pathname.replace(/^\/|\/$/g,``).split(`/`).pop();if(e)return e.replace(/[-_]/g,` `)}return``})();u={agent:{firstMessage:t?`I've navigated you to the ${t} page as requested.`:`I've navigated to the page you requested.`}}}console.log(`[FlowEngage voice] startSession →`,{agentId:r,hasOverrides:!!u,firstMessage:u?.agent?.firstMessage??null,isResume:!!c});let m=await xE.startSession({agentId:r,...u?{overrides:u}:{},clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{if(!e&&(console.log(`[FlowEngage voice] onModeChange`,t,`hasSeenSpeaking:`,f.hasSeenSpeaking,`sent:`,f.sent),p(t===`speaking`?`speaking`:`listening`),t===`speaking`&&(f.hasSeenSpeaking=!0),t===`listening`&&f.hasSeenSpeaking&&!f.sent&&f.prompt&&f.conv)){console.log(`[FlowEngage voice] onModeChange → sending sendContextualUpdate (resume)`),f.sent=!0;let e=f.prompt;f.prompt=null;try{f.conv.sendContextualUpdate(e),SD.clear()}catch{}}},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(!r)return;let i=o.current,a=i.length>0?i[i.length-1]:null;a&&a.sender===n&&a.message===r||(n===`user`&&(y.current=r),o.current=[...i,{sender:n,message:r,timestamp:new Date().toISOString()}],VO(n,r)&&oe(`minimized`))},onError:t=>{if(!e&&!C.current&&!te.current){te.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),p(`error`),oe(`minimized`)}},onDisconnect:()=>{if(!e&&!C.current&&!te.current){te.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:y.current||``,wasMuted:S.current});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),oe(`minimized`)}}});if(e){x.current||m.endSession().catch(()=>{});return}n=m,v.current=m,f.conv=m,console.log(`[FlowEngage voice] startSession resolved OK`,{isResume:!!c}),p(`listening`);try{if(d){let t=setTimeout(()=>{if(!f.sent&&f.hasSeenSpeaking&&f.prompt&&f.conv&&!e){console.log(`[FlowEngage voice] fallbackTimerA firing sendContextualUpdate`),f.sent=!0;let e=f.prompt;f.prompt=null;try{f.conv.sendContextualUpdate(e),SD.clear()}catch{}}},6e3);setTimeout(()=>{if(!f.sent&&f.prompt&&f.conv&&!e){console.log(`[FlowEngage voice] fallbackTimerB firing sendContextualUpdate (no speaking seen)`),f.sent=!0;let e=f.prompt;f.prompt=null;try{f.conv.sendContextualUpdate(e),SD.clear()}catch{}}clearTimeout(t)},1e4)}else{let e=`[]`;try{e=await t.flowengage_list_forms()}catch{}let n=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, nav, footer, header`)).map(e=>({tag:e.tagName,text:e.textContent.trim(),id:e.id||null})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,25):[];m.sendContextualUpdate(`Page: ${s}. SiteId: ${i||`unknown`}. Sections on this page: ${JSON.stringify(n)}. IMPORTANT: Call flowengage_highlight with section_text from the list above as you explain each section. Forms: ${e}. Navigation: flowengage_navigate — use for cross-page navigation. End call: flowengage_end_session.`)}}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),p(`error`),ne.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,C.current=!0,x.current||(n||v.current)?.endSession?.().catch(()=>{})}},[r,i,a,oe]),(0,d.useEffect)(()=>{if(!g)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ae.current&&!ae.current.contains(t)&&_(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[g]),(0,f.jsxs)(`div`,{ref:ae,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),(0,f.jsx)(HO,{size:72,voiceState:u,isMuted:m,orbColors:e})]}),u===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:async()=>{if(v.current)try{m?(await v.current.setMicMuted?.(!1),h(!1)):(await v.current.setMicMuted?.(!0),h(!0))}catch{}},title:m?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:m?`#7f1d1d`:`#1f2937`,border:m?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:m?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:m?(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsx)(SE,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>_(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,f.jsx)(AE,{size:16,color:`currentColor`})})]}),g&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`chat`,ce(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(jE,{}),`Enter Chat Mode`]}),(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`minimized`,ce(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(ME,{}),`End Conversation`]}),(0,f.jsx)(`button`,{onClick:()=>_(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function KO({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(HO,{size:36,orbColors:e})})}var qO=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function JO({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:ee,selectedFile:te,onFileSelect:C,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,replyContext:le,setReplyContext:ue,webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:ye,isCallMuted:be,toggleCallMute:xe,endWebRTCCall:w,formatCallDuration:Se,callDurationSeconds:Ce,onCollapse:we,onStartVoice:Te,showPoweredBy:Ee}){let De=c.length>0,Oe=x||S||b,ke=!!(he||ve),[Ae,je]=(0,d.useState)(!1),Me=(0,d.useRef)(null);return(0,d.useEffect)(()=>{if(!Ae)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Me.current&&!Me.current.contains(t)&&je(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Ae]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:0,width:`calc(100% - 16px)`,height:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0},children:[(0,f.jsx)(`button`,{onClick:we,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(zO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(BO,{title:e.chatTitle})})}),(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Me,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>je(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Ae&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),we?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,f.jsx)(XE,{webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:ye,formatCallDuration:Se,callDurationSeconds:Ce,endWebRTCCall:w,isCallMuted:be,toggleCallMute:xe,isAIVoiceActive:!1,currentCallAgentName:m||g,isRateLimited:S,rateLimitMessage:ee}),(0,f.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:De?(0,f.jsx)(KE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ue,TypingDots:qO,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(KO,{orbColors:t})}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(HO,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:ae?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(qE,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:ke,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Oe,replyContext:le,clearReplyContext:()=>ue(null),onFileSelect:C,selectedFile:te,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),(0,f.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:Ee&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function YO(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:ee,language:te,historyRef:C,onMessageSync:ne,sendMessage:ae,uploadChatFile:se,openWidget:ce,captureVisitorEmail:le,setVoiceMode:ue,endConversation:de,acceptCall:fe,rejectCall:pe,endWebRTCCall:me,toggleCallMute:he,dismissCallError:ge,startTyping:_e,stopTyping:ve,updateTypingDraft:ye}=rn();(0,d.useEffect)(()=>{try{On()}catch{}},[]);let be=t?.widgetSettings||{},xe=n?.widgetSettings||{},w={...be.branding||{},...xe.branding||{}},Se={...be.theme||{},...xe.theme||{}},Ce={...be.features||{},...xe.features||{}},we=Ce.voice!==!1,Te=Array.isArray(Se.orbColors)&&Se.orbColors.length>0?Se.orbColors:null,Ee=Te?.[0]||Se.primaryColor||`#3B82F6`,De=Se.position||`bottom-right`,Oe=w.fallbackAgentName||`Agent`,ke=LO(Te??Se.chatBgColors),Ae=w.logo||w.logoUrl||null,je=te||`en`,Me=be.recommendations?.[je]||[],Ne=(xe.recommendations?.[je]??Me).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Pe=Array.isArray(w.quickChatOptions)&&w.quickChatOptions.length>0?w.quickChatOptions:Ne,Fe=w.hideWatermark===!0?!1:w.showPoweredBy!==!1,T=w.chatbotEnabled!==!1&&Se.chatbotEnabled!==!1,Ie=be.greetings?.[te]||xe.greetings?.[te]||w.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Le={entryPrompt:w.entryPrompt||`Do you want to explore in a new way?`,yesLabel:w.yesLabel||`Yes`,laterLabel:w.laterLabel||`Later`,connectionTitle:w.connectionTitle||`How would you like to connect?`,voiceLabel:w.voiceLabel||`Voice`,textLabel:w.textLabel||`Text`,chatTitle:w.headerName||`Chat with FlowEngage`,introGreeting:Ie,inputPlaceholder:w.inputPlaceholder||`Type your message`,analysingLabel:w.analysingLabel||`analysing...`},Re=xe.elevenLabsAgentId||t?.elevenLabsAgentId||null,ze=t?.siteId||n?.siteId||null,Be=t?.apiBaseUrl||``,E=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Ve=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,He=r.some(e=>e.sender===`user`),Ue=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),We=!l&&He&&Ue,Ge=!!(xe._dashboardLivePreview||be._dashboardLivePreview),[D,O]=(0,d.useState)(()=>Ge?`text_chat`:`entry_prompt`),[k,Ke]=(0,d.useState)(``),[qe,Je]=(0,d.useState)(null),[Ye,Xe]=(0,d.useState)(l||``),[Ze,Qe]=(0,d.useState)(``),[$e,et]=(0,d.useState)(0),[tt,nt]=(0,d.useState)(null),[rt,it]=(0,d.useState)(null),[at,ot]=(0,d.useState)(``),[st,ct]=(0,d.useState)(!1),lt=(0,d.useRef)(null),ut=(0,d.useRef)(!1),dt=(0,d.useRef)(null),ft=(0,d.useMemo)(()=>oe(ze),[ze]);(0,d.useLayoutEffect)(()=>{if(!(e!==`ready`||ut.current)){ut.current=!0;try{let e=SD.read(ze);if(e&&e._resumeMode===`auto`){dt.current=e,ce({notifyChatInitiated:!0}),ue?.(!0),O(`voice_mode`);return}}catch{}if(re(ze)||!we){O(`minimized_orb`);return}}},[e,r]);let[pt,mt]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>mt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{Xe(l||``),l&&Qe(``)},[l]);let ht=(0,d.useCallback)(()=>{it(null),ot(``)},[]),gt=(0,d.useCallback)(e=>{let t=VE(e);if(t){it(null),ot(t);return}it(e),ot(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){et(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||et(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]),(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){lt.current=null;return}(v?.callId||b===`connecting`||b===`connected`)&&(!(!i||D===`minimized_orb`||D===`voice_mode`)&<.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:D,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),lt.current=e,D===`voice_mode`&&ue?.(!1),ce?.(),O(`text_chat`)))},[y,b,v?.callId,i,ce,ue,D]),(0,d.useEffect)(()=>{if(!o||_){ye?.(``),ve?.();return}if(!k.trim()||rt){ye?.(``),ve?.();return}_e?.();let e=window.setTimeout(()=>ye?.(k),120),t=window.setTimeout(()=>ve?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[k,rt,o,_,_e,ve,ye]);let _t=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,vt=async e=>{if(e.preventDefault(),_)return;if(We){let e=Ye.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Qe(`Please enter a valid email so we can continue helping you.`);return}await le(e),Qe(``);return}let t=_t(qe);if(!k.trim()&&!rt)return;if(rt){try{ct(!0),ot(``);let e=await se(rt),n=e?.data||e,r=k.trim()||`Shared file: ${UE(rt)}`;Ke(``),Je(null),ht(),await ae(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||rt.name,fileType:n?.fileType||rt.type,fileSize:n?.fileSize||rt.size}})}catch(e){ot(e?.message||`Failed to upload the selected file.`)}finally{ct(!1)}return}let n=k.trim();Ke(``),Je(null),await ae(n,``,t)},yt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},bt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await ae(t.trim(),``)},[_,m,ae]),xt=pt&&D===`entry_prompt`?{inset:0}:pt&&D===`text_chat`?{left:0,right:0,bottom:0}:pt&&D===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:De===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},St=()=>O(`minimized_orb`),Ct=()=>O(`connection_modal`),wt=()=>{ce({notifyChatInitiated:!0}),ue?.(!0),O(`voice_mode`)},Tt=()=>{ce({notifyChatInitiated:!0}),ue?.(!1),O(`text_chat`)},Et=()=>{ue?.(!1),St()};return e!==`ready`||!T||Ce.chat===!1?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...xt},children:[D===`entry_prompt`&&(0,f.jsx)(UO,{copy:Le,orbColors:Te,primaryColor:Ee,onYes:()=>{ie(ze),wt()},onLater:()=>{ie(ze),St()},isMobile:pt}),D===`minimized_orb`&&(0,f.jsx)(Mp.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,f.jsx)(HO,{size:50,orbColors:Te,onClick:we?Ct:Tt})}),D===`connection_modal`&&(0,f.jsx)(WO,{copy:Le,orbColors:Te,primaryColor:Ee,onVoice:wt,onText:Tt,onClose:St,isMobile:pt}),D===`voice_mode`&&(0,f.jsx)(GO,{orbColors:Te,onEnterChat:Tt,onEndChat:Et,agentId:Re,siteId:ze,apiBaseUrl:Be,historyRef:C,onMessageSync:ne,pendingResume:dt.current,chatId:ft},`voice`),D===`text_chat`&&(0,f.jsx)(JO,{copy:Le,orbColors:Te,primaryColor:Ee,chatBgGradient:ke,logo:Ae,quickChatOptions:Pe,onQuickChatSelect:bt,isMobile:pt,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:E,agentHeadshot:Ve,fallbackAgentName:Oe,input:k,setInput:Ke,onSubmit:vt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:rt,onFileSelect:gt,onRemoveSelectedFile:ht,attachmentError:at,isUploadingAttachment:st,requiresEmail:We,emailInput:Ye,setEmailInput:Xe,emailError:Ze,replyContext:qe,setReplyContext:Je,webRTCError:ee,micError:tt,setMicError:nt,dismissCallError:ge,incomingCall:v,rejectCall:pe,acceptCall:fe,activeCallId:y,callConnectionState:b,isCallMuted:S,toggleCallMute:he,endWebRTCCall:me,formatCallDuration:yt,callDurationSeconds:$e,onCollapse:St,onStartVoice:wt,onEndConversation:de,showPoweredBy:Fe}),(0,f.jsx)(`style`,{children:`
|
|
608
|
+
`)}else{let t=(document.querySelector(`main`)||document.querySelector(`article`)||document.querySelector(`[role="main"]`)||document.querySelector(`#content`)||document.querySelector(`.content`)||document.body).cloneNode(!0);t.querySelectorAll(`nav, footer, header, aside, script, style, noscript, .nav, .footer, .header, .sidebar`).forEach(e=>e.remove()),e=t.textContent.replace(/\s+/g,` `).trim()}return e.length>8e3&&(e=e.substring(0,8e3)+`... (truncated)`),$(`flowengage_read_content ✓`,`${e.length} chars`),e||`No readable content found on this page.`}catch(e){return $(`flowengage_read_content ✖`,e.message),`Could not read page content: ${e.message}`}},flowengage_search:async e=>{$(`flowengage_search ▶`,e);let r=jO(EO(e));if($(`flowengage_search · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`flowengage_search ✖ missing query`),`Missing query parameter.`;if(!t)return $(`flowengage_search ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`flowengage_search ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`flowengage_search → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`flowengage_search · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`flowengage_search ✖`,e),e}let o=a.results||[];return $(`flowengage_search ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`flowengage_search ✖`,t),t}},flowengage_page_content:async e=>{$(`flowengage_page_content ▶`,e);let r=EO(e),i=r?.url||r?.page_url||``;if($(`flowengage_page_content · url:`,i,`siteId:`,t,`apiBase:`,n||`(empty)`),!i)return $(`flowengage_page_content ✖ missing url`),`Missing url parameter.`;if(!t)return $(`flowengage_page_content ✖ no siteId`),`Site is not configured.`;if(!n)return $(`flowengage_page_content ✖ no api base`),`API base URL is missing; cannot fetch page content.`;try{let e=`${n}/api/site-tools/page-content`;$(`flowengage_page_content → POST`,e);let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,url:i})}),a=await r.json();if($(`flowengage_page_content · HTTP`,r.status,`success:`,a.success),!a.success){let e=a.error||`Failed to get page content.`;return $(`flowengage_page_content ✖`,e),e}return $(`flowengage_page_content ✓`,`title: ${a.title}`,`sections: ${(a.sections||[]).length}`,`content: ${(a.content||``).length} chars`),JSON.stringify({title:a.title,url:a.url,sections:a.sections,content:a.content})}catch(e){let t=`Page content error: ${e.message||`network`}`;return $(`flowengage_page_content ✖`,t),t}},flowengage_end_session:async()=>($(`flowengage_end_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),flowengage_list_forms:async()=>{let e=cO(),t=lO();return $(`flowengage_list_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, flowengage_fill_form sets all matching URL inputs. flowengage_click_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},flowengage_fill_form:async e=>{try{$(`flowengage_fill_form ▶ raw:`,e),HD();let t=DO(e);if(!t.length&&r){let e=r(),n=OO(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=kO(e),n.length&&$(`flowengage_fill_form · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`flowengage_fill_form · normalized fields:`,t),!t.length)return`No fields provided. Call flowengage_list_forms for field_key strings, then flowengage_fill_form with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;FD(`Filling ${String(t)}...`,{spinner:!0});let a=sO(),o=bO(a,String(t),r);if(o.length){for(let[e,t]of o.entries())UD(t),await YD(t),MO(t,r,{skipScroll:e>0}),WD(t),await eO(120);i=o,n.push(String(t));continue}let s=CO(a,String(t));s||=mO(a,String(t)),s||=hO(a,String(t),r),s&&(UD(s),await YD(s),MO(s,r),WD(s),await eO(120),i=[s],n.push(String(t)))}if(!n.length)return $(`flowengage_fill_form ✖ no matches`),`Could not match any fields. Call flowengage_list_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`flowengage_fill_form ✓`,a),FD(`Form filled`,{spinner:!1,icon:`✅`,duration:1100}),a}catch(e){let t=`flowengage_fill_form error: ${e?.message||String(e)}`;return $(`flowengage_fill_form ✖`,t),FD(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{XD(),HD(),ID(700)}},flowengage_click_button:async e=>{let t=EO(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`flowengage_click_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=TO(n,i);if(!r)return $(`flowengage_click_button ✖ no match`),`Could not find a button matching "${n}". Call flowengage_list_forms to see button texts.`;try{FD(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await YD(r),r.focus?.(),await ZD(r),QD(r),r.click();let e=(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`,t=`OK_CLICK ${e}`;return $(`flowengage_click_button ✓`,t),FD(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),FD(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{XD(),ID(700)}}};return{...a,navigateToPage:a.flowengage_navigate,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function FO(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=an();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var IO={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function LO(e){if(!Array.isArray(e)||e.length<2)return`linear-gradient(145deg, #dce8f022 0%, #e8dff522 45%, #f5e0e022 100%), #f7f8fa`;let[t,n,r]=e;return e.length>=3&&r?[`radial-gradient(ellipse 80% 70% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 70% 80% at 110% 30%, ${n}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 60% at 50% 110%, ${r}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `):[`radial-gradient(ellipse 80% 100% at -10% 50%, ${t}1a 0%, transparent 70%)`,`radial-gradient(ellipse 80% 100% at 110% 50%, ${n}1a 0%, transparent 70%)`,`#f7f8fa`].join(`, `)}function RO(e){if(!e||typeof e!=`string`)return`#1a1a1a`;let t=e.replace(`#`,``),n=t.length===3?t.split(``).map(e=>e+e).join(``):t,r=parseInt(n.slice(0,2),16)/255,i=parseInt(n.slice(2,4),16)/255,a=parseInt(n.slice(4,6),16)/255,o=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;return .2126*o(r)+.7152*o(i)+.0722*o(a)>.179?`#1a1a1a`:`#ffffff`}function zO({logo:e,style:t}){if(!e)return null;if(typeof e==`string`)return(0,f.jsx)(`img`,{src:e,alt:``,style:{objectFit:`contain`,flexShrink:0,display:`block`,...t}});let n=typeof e==`function`?d.default.createElement(e):d.default.isValidElement(e)?e:null;return n?(0,f.jsx)(`span`,{className:`fe-logo-slot`,style:{display:`inline-flex`,alignItems:`center`,flexShrink:0,overflow:`hidden`,...t},children:n}):null}function BO({title:e}){return(0,f.jsx)(`div`,{style:{width:`100%`,height:`100%`,borderRadius:`16px`,background:`linear-gradient(135deg, rgba(59,130,246,0.16) 0%, rgba(59,130,246,0.08) 100%)`,color:`#2563eb`,display:`flex`,alignItems:`center`,justifyContent:`center`,fontSize:`18px`,fontWeight:700,letterSpacing:`-0.03em`},children:String(e||`FE`).split(/\s+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()||``).join(``)||`FE`})}function VO(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function HO({orbColors:e,...t}){return(0,f.jsx)(aD,{colors:e,...t})}function UO({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a}){let o=n||IO.green,s=RO(o),c=a?72:94,l=(0,f.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:a?`14px`:`18px`},children:[(0,f.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,f.jsx)(Mp.p,{initial:{x:-16,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.36},style:{margin:`0 0 14px`,fontSize:`14px`,fontWeight:700,color:`white`,lineHeight:1.4,textShadow:`0 1px 4px rgba(0,0,0,0.35)`,maxWidth:a?void 0:`210px`},children:e.entryPrompt}),(0,f.jsxs)(Mp.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},transition:{type:`spring`,stiffness:260,damping:24,delay:.54},style:{display:`flex`,gap:`16px`,flexWrap:`nowrap`},children:[(0,f.jsx)(`button`,{onClick:r,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:o,color:s,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${o}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,f.jsx)(`button`,{onClick:i,style:{height:`31px`,boxSizing:`border-box`,padding:`0 16px`,borderRadius:`999px`,background:`transparent`,color:`white`,fontWeight:400,fontSize:`14px`,border:`2px solid rgba(255,255,255,0.55)`,cursor:`pointer`,whiteSpace:`nowrap`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.9)`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`rgba(255,255,255,0.55)`},children:e.laterLabel})]})]}),(0,f.jsx)(Mp.div,{initial:{x:120,opacity:0},animate:{x:0,opacity:1},transition:{type:`spring`,stiffness:220,damping:22,delay:0},style:{flexShrink:0},children:(0,f.jsx)(HO,{size:c,orbColors:t})})]});return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(Mp.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.4},style:{position:`fixed`,inset:0,background:`rgba(0,0,0,0.72)`,zIndex:-1}}),a?(0,f.jsx)(`div`,{style:{position:`absolute`,bottom:0,left:0,right:0,padding:`24px 20px 40px`,overflow:`hidden`},children:l}):l]})}function WO({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o}){let s=n||IO.green,c=RO(s);return(0,f.jsxs)(Mp.div,{initial:{scale:50/350,borderRadius:`50%`},animate:{scale:1,borderRadius:`16px`},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,f.jsx)(`button`,{onClick:a,style:{position:`absolute`,top:`14px`,right:`14px`,background:`none`,border:`none`,cursor:`pointer`,color:`#9ca3af`,padding:`4px`,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`50%`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#374151`},onMouseLeave:e=>{e.currentTarget.style.color=`#9ca3af`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsx)(HO,{size:72,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,fontSize:`16px`,fontWeight:400,color:`#111827`,textAlign:`center`,lineHeight:1.4},children:e.connectionTitle}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`16px`,width:`100%`},children:[(0,f.jsx)(`button`,{onClick:r,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:s,color:c,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${s}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,f.jsx)(`button`,{onClick:i,style:{width:`127px`,height:`43px`,borderRadius:`999px`,background:`transparent`,color:`#111827`,fontWeight:400,fontSize:`16px`,border:`1.5px solid #d1d5db`,cursor:`pointer`,transition:`border-color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.borderColor=`#6b7280`},onMouseLeave:e=>{e.currentTarget.style.borderColor=`#d1d5db`},children:e.textLabel})]})]})}function GO({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s,pendingResume:c,chatId:l}){let[u,p]=(0,d.useState)(`idle`),[m,h]=(0,d.useState)(!1),[g,_]=(0,d.useState)(!1),v=(0,d.useRef)(null),y=(0,d.useRef)(``),b=(0,d.useRef)(async()=>{}),x=(0,d.useRef)(!1),S=(0,d.useRef)(!1),ee=(0,d.useRef)(`idle`),te=(0,d.useRef)(!1),C=(0,d.useRef)(!1),ne=(0,d.useRef)(`minimized`),re=(0,d.useRef)(0),ie=(0,d.useRef)(!1),ae=(0,d.useRef)(null),oe=(0,d.useCallback)((e=`minimized`)=>{ne.current=e,C.current=!0,queueMicrotask(()=>{x.current||(x.current=!0,b.current?.())})},[o]),se=(0,d.useCallback)(()=>(C.current=!0,x.current=!0,console.log(`[FlowEngage voice] markNavigationShutdown — calling endSession() for clean server close`),(v.current?.endSession?.()??Promise.resolve()).catch(()=>{})),[]),ce=(0,d.useCallback)(async e=>{C.current=!0;try{await v.current?.endSession?.()}catch{}if(v.current=null,p(`idle`),h(!1),x.current=!1,typeof s==`function`){let e=re.current;await s(e>0?o.current.slice(e):o.current)}e?.()},[o,s]);return b.current=()=>ce(ne.current===`chat`?t:n),(0,d.useEffect)(()=>{S.current=m},[m]),(0,d.useEffect)(()=>{ee.current=u},[u]),(0,d.useEffect)(()=>{let e=()=>!!v.current,t=()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``},n=e=>{let n=t(),a=n.split(/\s+/).filter(Boolean).length;return{siteId:i,chatId:l||null,agentId:r,trigger:e,navigationConfidence:e===`agent_navigate`?`high`:`medium`,interruption:{state:ee.current,lastAgentText:n,lastUserText:y.current,estimatedSpokenWords:TD(),agentTextWordCount:a,isMuted:S.current},history:o.current||[]}},a=()=>{e()&&(CD()||SD.capture(n(`user_link_click`)))},s=t=>{e()&&(t.persisted||CD()||SD.capture(n(`pagehide`)))};return window.addEventListener(`beforeunload`,a),window.addEventListener(`pagehide`,s),()=>{window.removeEventListener(`beforeunload`,a),window.removeEventListener(`pagehide`,s)}},[i,l,r,o]),(0,d.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){p(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e||(c?(o.current=Array.isArray(c.history)?[...c.history]:[],re.current=o.current.length,c.interruption?.lastUserText&&(y.current=c.interruption.lastUserText),ie.current=!0,setTimeout(()=>{ie.current=!1},5e3)):(o.current=[],re.current=0,y.current=``,ie.current=!1),x.current=!1,te.current=!1,C.current=!1,ne.current=`minimized`,c&&(console.log(`[FlowEngage voice] resume — waiting 800ms for server session cleanup`),await new Promise(e=>setTimeout(e,800)),e)))return;let t=FO(PO({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>y.current,getPostResumeNavLocked:()=>ie.current,requestEndSession:()=>{oe()},markNavigationShutdown:()=>{se()},getSessionCaptureData:()=>{let e=(()=>{let e=o.current||[];for(let t=e.length-1;t>=0;t--)if(e[t].sender===`bot`)return e[t].message||``;return``})();return{siteId:i,chatId:l||null,agentId:r,history:o.current||[],lastAgentText:e,agentTextWordCount:e.split(/\s+/).filter(Boolean).length,lastUserText:y.current,estimatedSpokenWords:TD(),isMuted:S.current}}})),s=typeof window<`u`?window.location.href:``,u=null;if(c&&!c.consumed){let e=typeof document<`u`?Array.from(document.querySelectorAll(`h1,h2,h3,h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell`)).map(e=>({tag:e.tagName,text:e.textContent.replace(/\s+/g,` `).trim().slice(0,80),id:e.id||null})).filter(e=>e.text.length>0).slice(0,25):[];u=SD.buildResumePrompt(c,e,s)}console.log(`[FlowEngage voice] startSession →`,{agentId:r,isResume:!!c,hasImmediateResumePrompt:!!u});let d=await xE.startSession({agentId:r,clientTools:t,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||(console.log(`[FlowEngage voice] onModeChange`,t),p(t===`speaking`?`speaking`:`listening`))},onMessage:t=>{if(e)return;let n=t.role===`user`?`user`:`bot`,r=t.message||t.text||t.content||``;if(!r)return;let i=o.current,a=i.length>0?i[i.length-1]:null;a&&a.sender===n&&a.message===r||(n===`user`&&(y.current=r),o.current=[...i,{sender:n,message:r,timestamp:new Date().toISOString()}],VO(n,r)&&oe(`minimized`))},onError:t=>{if(!e&&!C.current&&!te.current){te.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),p(`error`),oe(`minimized`)}},onDisconnect:()=>{if(!e&&!C.current&&!te.current){te.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:y.current||``,wasMuted:S.current});try{v.current?.setMicMuted?.(!0)}catch{}h(!0),oe(`minimized`)}}});if(e){x.current||d.endSession().catch(()=>{});return}n=d,v.current=d,console.log(`[FlowEngage voice] startSession resolved OK`,{isResume:!!c}),p(`listening`);try{if(u)console.log(`[FlowEngage voice] sending resume contextualUpdate immediately`),d.sendContextualUpdate(u),SD.clear();else{let e=`[]`;try{e=await t.flowengage_list_forms()}catch{}let n=typeof document<`u`?Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, nav, footer, header`)).map(e=>({tag:e.tagName,text:e.textContent.trim(),id:e.id||null})).filter(e=>e.text.length>0&&e.text.length<200).slice(0,25):[];d.sendContextualUpdate(`Page: ${s}. SiteId: ${i||`unknown`}. Sections on this page: ${JSON.stringify(n)}. IMPORTANT: Call flowengage_highlight with section_text from the list above as you explain each section. Forms: ${e}. Navigation: flowengage_navigate — use for cross-page navigation. End call: flowengage_end_session.`)}}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),p(`error`),ne.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,C.current=!0,x.current||(n||v.current)?.endSession?.().catch(()=>{})}},[r,i,a,oe]),(0,d.useEffect)(()=>{if(!g)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ae.current&&!ae.current.contains(t)&&_(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[g]),(0,f.jsxs)(`div`,{ref:ae,style:{position:`relative`,display:`flex`,flexDirection:`column`,alignItems:`center`,gap:`14px`,animation:`fe-orb-slide-up 0.42s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{position:`relative`},children:[u===`listening`&&(0,f.jsx)(`span`,{style:{position:`absolute`,right:`100%`,marginRight:`18px`,top:`50%`,transform:`translateY(-50%)`,color:`white`,fontSize:`18px`,fontWeight:600,letterSpacing:`0.01em`,textShadow:`0 2px 4px rgba(0,0,0,0.4)`,whiteSpace:`nowrap`},children:`Listening...`}),(0,f.jsx)(HO,{size:72,voiceState:u,isMuted:m,orbColors:e})]}),u===`error`&&(0,f.jsx)(`span`,{style:{color:`#f87171`,fontSize:`13px`,fontWeight:500},children:`Could not start voice session.`}),(0,f.jsxs)(`div`,{style:{display:`flex`,gap:`12px`,alignItems:`center`},children:[(0,f.jsx)(`button`,{onClick:async()=>{if(v.current)try{m?(await v.current.setMicMuted?.(!1),h(!1)):(await v.current.setMicMuted?.(!0),h(!0))}catch{}},title:m?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:m?`#7f1d1d`:`#1f2937`,border:m?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:m?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:m?(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`1`,y1:`1`,x2:`23`,y2:`23`}),(0,f.jsx)(`path`,{d:`M9 9v3a3 3 0 005.12 2.12M15 9.34V4a3 3 0 00-5.94-.6`}),(0,f.jsx)(`path`,{d:`M17 16.95A7 7 0 015 12v-2m14 0v2a7 7 0 01-.11 1.23`}),(0,f.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),(0,f.jsx)(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]}):(0,f.jsx)(SE,{size:16,color:`currentColor`})}),(0,f.jsx)(`button`,{onClick:()=>_(e=>!e),style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:`#1f2937`,border:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`,transition:`background 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:(0,f.jsx)(AE,{size:16,color:`currentColor`})})]}),g&&(0,f.jsxs)(`div`,{style:{position:`absolute`,bottom:0,right:0,width:`230px`,zIndex:9999,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,animation:`fe-orb-fade-in 0.18s ease`,padding:`12px 12px 40px`},children:[(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`chat`,ce(t)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(jE,{}),`Enter Chat Mode`]}),(0,f.jsxs)(`button`,{onClick:()=>{_(!1),ne.current=`minimized`,ce(n)},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`12px 16px`,background:`none`,border:`none`,color:`#E30C12`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`,borderRadius:`8px`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(227,12,18,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsx)(ME,{}),`End Conversation`]}),(0,f.jsx)(`button`,{onClick:()=>_(!1),style:{position:`absolute`,bottom:`8px`,right:`8px`,width:`24px`,height:`24px`,borderRadius:`50%`,background:`rgba(255,255,255,0.15)`,border:`none`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:`white`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.25)`},onMouseLeave:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.15)`},children:(0,f.jsxs)(`svg`,{width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,f.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]})})]})]})}function KO({orbColors:e}){return(0,f.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,f.jsx)(HO,{size:36,orbColors:e})})}var qO=()=>(0,f.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,f.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[0,1,2].map(e=>(0,f.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e))})});function JO({copy:e,orbColors:t,primaryColor:n,chatBgGradient:r,logo:i,quickChatOptions:a,onQuickChatSelect:o,isMobile:s,chatHistory:c,isAiTyping:l,isAgentTyping:u,activeScreen:p,agentName:m,agentHeadshot:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:ee,selectedFile:te,onFileSelect:C,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,replyContext:le,setReplyContext:ue,webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:ye,isCallMuted:be,toggleCallMute:xe,endWebRTCCall:w,formatCallDuration:Se,callDurationSeconds:Ce,onCollapse:we,onStartVoice:Te,showPoweredBy:Ee}){let De=c.length>0,Oe=x||S||b,ke=!!(he||ve),[Ae,je]=(0,d.useState)(!1),Me=(0,d.useRef)(null);return(0,d.useEffect)(()=>{if(!Ae)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Me.current&&!Me.current.contains(t)&&je(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Ae]),(0,f.jsxs)(`div`,{style:s?{"--flowengage-primary":n,"--flowengage-accent":n,position:`fixed`,left:`8px`,right:`8px`,bottom:0,width:`calc(100% - 16px)`,height:`90dvh`,background:r,borderRadius:`16px 16px 0 0`,display:`flex`,flexDirection:`column`,overflow:`hidden`,animation:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,f.jsxs)(`div`,{style:{display:`grid`,gridTemplateColumns:`40px minmax(0, 1fr) 40px`,alignItems:`center`,columnGap:`14px`,padding:`16px 10px 14px`,background:`transparent`,flexShrink:0},children:[(0,f.jsx)(`button`,{onClick:we,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,f.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,f.jsx)(`polyline`,{points:`6 9 12 15 18 9`})})}),(0,f.jsxs)(`div`,{style:{minWidth:0,maxWidth:s?`100%`:`250px`,width:`100%`,justifySelf:`center`,display:`grid`,gridTemplateColumns:`minmax(72px, 40%) minmax(0, 60%)`,alignItems:`center`},children:[(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`,justifyContent:`center`,height:`40px`},children:i?(0,f.jsx)(zO,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,f.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,f.jsx)(BO,{title:e.chatTitle})})}),(0,f.jsx)(`div`,{style:{minWidth:0,display:`flex`,alignItems:`center`},children:(0,f.jsx)(`span`,{style:{fontSize:`15px`,fontWeight:600,color:`#111827`,letterSpacing:`-0.01em`,lineHeight:1.2,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},title:e.chatTitle,children:e.chatTitle})})]}),(0,f.jsxs)(`div`,{style:{position:`relative`,isolation:`isolate`,zIndex:10},ref:Me,children:[(0,f.jsx)(`button`,{type:`button`,onClick:()=>je(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,f.jsxs)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,f.jsx)(`circle`,{cx:`12`,cy:`5`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`12`,r:`1.5`}),(0,f.jsx)(`circle`,{cx:`12`,cy:`19`,r:`1.5`})]})}),Ae&&(0,f.jsxs)(`div`,{style:{position:`absolute`,top:`34px`,right:0,background:`rgba(15,22,36,0.96)`,backdropFilter:`blur(14px)`,WebkitBackdropFilter:`blur(14px)`,borderRadius:`16px`,overflow:`hidden`,boxShadow:`0 10px 40px rgba(0,0,0,0.45)`,minWidth:`210px`,border:`1px solid rgba(255,255,255,0.07)`,animation:`fe-orb-fade-in 0.18s ease`},children:[(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`}),(0,f.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`})]}),`Enter Voice Mode`]}),(0,f.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,f.jsxs)(`button`,{type:`button`,onClick:()=>{je(!1),we?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,f.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,f.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,f.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),`Close Conversation`]})]})]})]}),(0,f.jsx)(XE,{webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,incomingCall:he,rejectCall:ge,acceptCall:_e,activeCallId:ve,callConnectionState:ye,formatCallDuration:Se,callDurationSeconds:Ce,endWebRTCCall:w,isCallMuted:be,toggleCallMute:xe,isAIVoiceActive:!1,currentCallAgentName:m||g,isRateLimited:S,rateLimitMessage:ee}),(0,f.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`},children:De?(0,f.jsx)(KE,{chatHistory:c,isAiTyping:l,isAgentTyping:u,setReplyContext:ue,TypingDots:qO,primaryColor:n,agentHeadshot:h,agentDisplayName:m||g,botAvatarNode:(0,f.jsx)(KO,{orbColors:t})}):(0,f.jsxs)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`22px`,padding:`28px 24px`},children:[(0,f.jsx)(HO,{size:94,orbColors:t}),(0,f.jsx)(`p`,{style:{margin:0,textAlign:`center`,fontSize:`16px`,color:`#374151`,lineHeight:1.55,maxWidth:`270px`},children:e.introGreeting}),a.length>0&&(0,f.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:`8px`,justifyContent:`center`,width:`100%`,padding:`0 8px`},children:a.map(e=>(0,f.jsx)(`button`,{onClick:()=>o?.(e),style:{padding:`8px 16px`,borderRadius:`999px`,background:`white`,border:`1.5px solid ${n}33`,color:n||`#374151`,fontSize:`13px`,fontWeight:500,cursor:`pointer`,transition:`all 0.15s ease`,boxShadow:`0 1px 4px rgba(0,0,0,0.06)`},onMouseEnter:e=>{e.currentTarget.style.background=`${n}12`,e.currentTarget.style.borderColor=n},onMouseLeave:e=>{e.currentTarget.style.background=`white`,e.currentTarget.style.borderColor=`${n}33`},children:e.label||e.text},e.id))})]})}),(0,f.jsx)(`div`,{style:{background:`transparent`,flexShrink:0,position:`relative`,zIndex:1,padding:ae?`6px 0 0`:`12px 0 0`},children:(0,f.jsx)(qE,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:ke,handleToggleVoice:Te,showVoiceToggle:p===`agent`,activeScreen:p,inputDisabled:Oe,replyContext:le,clearReplyContext:()=>ue(null),onFileSelect:C,selectedFile:te,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),(0,f.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:Ee&&(0,f.jsxs)(`span`,{style:{fontSize:`11px`,color:`#9ca3af`,letterSpacing:`0.01em`,userSelect:`none`},children:[`Powered by `,(0,f.jsx)(`strong`,{style:{fontWeight:600,color:`#6b7280`},children:`FlowEngage`})]})})]})}function YO(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatHistory:r,isOpen:i,activeScreen:a,isHumanHandled:o,agentName:s,agentHeadshot:c,visitorEmail:l,isAgentTyping:u,isAiTyping:p,isLoading:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:v,activeCallId:y,callConnectionState:b,callConnectedAt:x,isCallMuted:S,webRTCError:ee,language:te,historyRef:C,onMessageSync:ne,sendMessage:ae,uploadChatFile:se,openWidget:ce,captureVisitorEmail:le,setVoiceMode:ue,endConversation:de,acceptCall:fe,rejectCall:pe,endWebRTCCall:me,toggleCallMute:he,dismissCallError:ge,startTyping:_e,stopTyping:ve,updateTypingDraft:ye}=rn();(0,d.useEffect)(()=>{try{On()}catch{}},[]);let be=t?.widgetSettings||{},xe=n?.widgetSettings||{},w={...be.branding||{},...xe.branding||{}},Se={...be.theme||{},...xe.theme||{}},Ce={...be.features||{},...xe.features||{}},we=Ce.voice!==!1,Te=Array.isArray(Se.orbColors)&&Se.orbColors.length>0?Se.orbColors:null,Ee=Te?.[0]||Se.primaryColor||`#3B82F6`,De=Se.position||`bottom-right`,Oe=w.fallbackAgentName||`Agent`,ke=LO(Te??Se.chatBgColors),Ae=w.logo||w.logoUrl||null,je=te||`en`,Me=be.recommendations?.[je]||[],Ne=(xe.recommendations?.[je]??Me).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Pe=Array.isArray(w.quickChatOptions)&&w.quickChatOptions.length>0?w.quickChatOptions:Ne,Fe=w.hideWatermark===!0?!1:w.showPoweredBy!==!1,T=w.chatbotEnabled!==!1&&Se.chatbotEnabled!==!1,Ie=be.greetings?.[te]||xe.greetings?.[te]||w.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,Le={entryPrompt:w.entryPrompt||`Do you want to explore in a new way?`,yesLabel:w.yesLabel||`Yes`,laterLabel:w.laterLabel||`Later`,connectionTitle:w.connectionTitle||`How would you like to connect?`,voiceLabel:w.voiceLabel||`Voice`,textLabel:w.textLabel||`Text`,chatTitle:w.headerName||`Chat with FlowEngage`,introGreeting:Ie,inputPlaceholder:w.inputPlaceholder||`Type your message`,analysingLabel:w.analysingLabel||`analysing...`},Re=xe.elevenLabsAgentId||t?.elevenLabsAgentId||null,ze=t?.siteId||n?.siteId||null,Be=t?.apiBaseUrl||``,E=(0,d.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Ve=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,He=r.some(e=>e.sender===`user`),Ue=(0,d.useMemo)(()=>{let e=r.findIndex(e=>e.sender===`user`);return e===-1?!1:r.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[r]),We=!l&&He&&Ue,Ge=!!(xe._dashboardLivePreview||be._dashboardLivePreview),[D,O]=(0,d.useState)(()=>Ge?`text_chat`:`entry_prompt`),[k,Ke]=(0,d.useState)(``),[qe,Je]=(0,d.useState)(null),[Ye,Xe]=(0,d.useState)(l||``),[Ze,Qe]=(0,d.useState)(``),[$e,et]=(0,d.useState)(0),[tt,nt]=(0,d.useState)(null),[rt,it]=(0,d.useState)(null),[at,ot]=(0,d.useState)(``),[st,ct]=(0,d.useState)(!1),lt=(0,d.useRef)(null),ut=(0,d.useRef)(!1),dt=(0,d.useRef)(null),ft=(0,d.useMemo)(()=>oe(ze),[ze]);(0,d.useLayoutEffect)(()=>{if(!(e!==`ready`||ut.current)){ut.current=!0;try{let e=SD.read(ze);if(e&&e._resumeMode===`auto`){dt.current=e,ce({notifyChatInitiated:!0}),ue?.(!0),O(`voice_mode`);return}}catch{}if(re(ze)||!we){O(`minimized_orb`);return}}},[e,r]);let[pt,mt]=(0,d.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,d.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>mt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,d.useEffect)(()=>{Xe(l||``),l&&Qe(``)},[l]);let ht=(0,d.useCallback)(()=>{it(null),ot(``)},[]),gt=(0,d.useCallback)(e=>{let t=VE(e);if(t){it(null),ot(t);return}it(e),ot(``)},[]);(0,d.useEffect)(()=>{if(!x||b!==`connected`){et(0);return}let e=()=>{let e=new Date(x).getTime();isNaN(e)||et(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[x,b]),(0,d.useEffect)(()=>{let e=v?.callId||y||null;if(!e){lt.current=null;return}(v?.callId||b===`connecting`||b===`connected`)&&(!(!i||D===`minimized_orb`||D===`voice_mode`)&<.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:D,hasIncomingCall:!!v?.callId,activeCallId:y,callConnectionState:b}),lt.current=e,D===`voice_mode`&&ue?.(!1),ce?.(),O(`text_chat`)))},[y,b,v?.callId,i,ce,ue,D]),(0,d.useEffect)(()=>{if(!o||_){ye?.(``),ve?.();return}if(!k.trim()||rt){ye?.(``),ve?.();return}_e?.();let e=window.setTimeout(()=>ye?.(k),120),t=window.setTimeout(()=>ve?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[k,rt,o,_,_e,ve,ye]);let _t=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,vt=async e=>{if(e.preventDefault(),_)return;if(We){let e=Ye.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){Qe(`Please enter a valid email so we can continue helping you.`);return}await le(e),Qe(``);return}let t=_t(qe);if(!k.trim()&&!rt)return;if(rt){try{ct(!0),ot(``);let e=await se(rt),n=e?.data||e,r=k.trim()||`Shared file: ${UE(rt)}`;Ke(``),Je(null),ht(),await ae(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||rt.name,fileType:n?.fileType||rt.type,fileSize:n?.fileSize||rt.size}})}catch(e){ot(e?.message||`Failed to upload the selected file.`)}finally{ct(!1)}return}let n=k.trim();Ke(``),Je(null),await ae(n,``,t)},yt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},bt=(0,d.useCallback)(async e=>{if(_||m)return;let t=e.message||e.label||e.text||``;t.trim()&&await ae(t.trim(),``)},[_,m,ae]),xt=pt&&D===`entry_prompt`?{inset:0}:pt&&D===`text_chat`?{left:0,right:0,bottom:0}:pt&&D===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:De===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},St=()=>O(`minimized_orb`),Ct=()=>O(`connection_modal`),wt=()=>{ce({notifyChatInitiated:!0}),ue?.(!0),O(`voice_mode`)},Tt=()=>{ce({notifyChatInitiated:!0}),ue?.(!1),O(`text_chat`)},Et=()=>{ue?.(!1),St()};return e!==`ready`||!T||Ce.chat===!1?null:(0,f.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...xt},children:[D===`entry_prompt`&&(0,f.jsx)(UO,{copy:Le,orbColors:Te,primaryColor:Ee,onYes:()=>{ie(ze),wt()},onLater:()=>{ie(ze),St()},isMobile:pt}),D===`minimized_orb`&&(0,f.jsx)(Mp.div,{layoutId:`fe-main-orb`,initial:{scale:94/50},animate:{scale:1},transition:{type:`spring`,stiffness:220,damping:26},style:{transformOrigin:`bottom right`,display:`inline-block`},children:(0,f.jsx)(HO,{size:50,orbColors:Te,onClick:we?Ct:Tt})}),D===`connection_modal`&&(0,f.jsx)(WO,{copy:Le,orbColors:Te,primaryColor:Ee,onVoice:wt,onText:Tt,onClose:St,isMobile:pt}),D===`voice_mode`&&(0,f.jsx)(GO,{orbColors:Te,onEnterChat:Tt,onEndChat:Et,agentId:Re,siteId:ze,apiBaseUrl:Be,historyRef:C,onMessageSync:ne,pendingResume:dt.current,chatId:ft},`voice`),D===`text_chat`&&(0,f.jsx)(JO,{copy:Le,orbColors:Te,primaryColor:Ee,chatBgGradient:ke,logo:Ae,quickChatOptions:Pe,onQuickChatSelect:bt,isMobile:pt,chatHistory:r,isAiTyping:p,isAgentTyping:u,activeScreen:a,agentName:E,agentHeadshot:Ve,fallbackAgentName:Oe,input:k,setInput:Ke,onSubmit:vt,isConversationEnded:_,isLoading:m,isRateLimited:h,rateLimitMessage:g,selectedFile:rt,onFileSelect:gt,onRemoveSelectedFile:ht,attachmentError:at,isUploadingAttachment:st,requiresEmail:We,emailInput:Ye,setEmailInput:Xe,emailError:Ze,replyContext:qe,setReplyContext:Je,webRTCError:ee,micError:tt,setMicError:nt,dismissCallError:ge,incomingCall:v,rejectCall:pe,acceptCall:fe,activeCallId:y,callConnectionState:b,isCallMuted:S,toggleCallMute:he,endWebRTCCall:me,formatCallDuration:yt,callDurationSeconds:$e,onCollapse:St,onStartVoice:wt,onEndConversation:de,showPoweredBy:Fe}),(0,f.jsx)(`style`,{children:`
|
|
609
609
|
/* Force any SVG (or img) inside LogoSlot to fill the container height
|
|
610
610
|
regardless of whether the component forwards its style prop. */
|
|
611
611
|
.fe-logo-slot svg,
|
|
@@ -29489,52 +29489,26 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
|
|
|
29489
29489
|
isMuted: te.current
|
|
29490
29490
|
};
|
|
29491
29491
|
}
|
|
29492
|
-
})), o = typeof window < "u" ? window.location.href : "", c
|
|
29493
|
-
prompt: null,
|
|
29494
|
-
sent: !1,
|
|
29495
|
-
conv: null,
|
|
29496
|
-
hasSeenSpeaking: !1
|
|
29497
|
-
};
|
|
29492
|
+
})), o = typeof window < "u" ? window.location.href : "", c = null;
|
|
29498
29493
|
if (u && !u.consumed) {
|
|
29499
29494
|
let e = typeof document < "u" ? Array.from(document.querySelectorAll("h1,h2,h3,h4")).filter((e) => !e.closest("#flowengage-root, .flowengage-shell")).map((e) => ({
|
|
29500
29495
|
tag: e.tagName,
|
|
29501
29496
|
text: e.textContent.replace(/\s+/g, " ").trim().slice(0, 80),
|
|
29502
29497
|
id: e.id || null
|
|
29503
29498
|
})).filter((e) => e.text.length > 0).slice(0, 25) : [];
|
|
29504
|
-
|
|
29505
|
-
let t = (() => {
|
|
29506
|
-
if (typeof document < "u" && document.title) {
|
|
29507
|
-
let e = document.title.split(/\s*[|\-–—]\s*/)[0].replace(/\s+/g, " ").trim();
|
|
29508
|
-
if (e.length > 0 && e.length <= 60) return e;
|
|
29509
|
-
}
|
|
29510
|
-
if (typeof window < "u") {
|
|
29511
|
-
let e = window.location.pathname.replace(/^\/|\/$/g, "").split("/").pop();
|
|
29512
|
-
if (e) return e.replace(/[-_]/g, " ");
|
|
29513
|
-
}
|
|
29514
|
-
return "";
|
|
29515
|
-
})();
|
|
29516
|
-
c = { agent: { firstMessage: t ? `I've navigated you to the ${t} page as requested.` : "I've navigated to the page you requested." } };
|
|
29499
|
+
c = FD.buildResumePrompt(u, e, o);
|
|
29517
29500
|
}
|
|
29518
29501
|
console.log("[FlowEngage voice] startSession →", {
|
|
29519
29502
|
agentId: r,
|
|
29520
|
-
|
|
29521
|
-
|
|
29522
|
-
isResume: !!u
|
|
29503
|
+
isResume: !!u,
|
|
29504
|
+
hasImmediateResumePrompt: !!c
|
|
29523
29505
|
});
|
|
29524
|
-
let
|
|
29506
|
+
let l = await PE.startSession({
|
|
29525
29507
|
agentId: r,
|
|
29526
|
-
...c ? { overrides: c } : {},
|
|
29527
29508
|
clientTools: t,
|
|
29528
29509
|
onUnhandledClientToolCall: (e) => console.error("[FlowEngage] Unhandled tool:", e?.tool_name),
|
|
29529
29510
|
onModeChange: ({ mode: t }) => {
|
|
29530
|
-
|
|
29531
|
-
console.log("[FlowEngage voice] onModeChange → sending sendContextualUpdate (resume)"), f.sent = !0;
|
|
29532
|
-
let e = f.prompt;
|
|
29533
|
-
f.prompt = null;
|
|
29534
|
-
try {
|
|
29535
|
-
f.conv.sendContextualUpdate(e), FD.clear();
|
|
29536
|
-
} catch {}
|
|
29537
|
-
}
|
|
29511
|
+
e || (console.log("[FlowEngage voice] onModeChange", t), h(t === "speaking" ? "speaking" : "listening"));
|
|
29538
29512
|
},
|
|
29539
29513
|
onMessage: (t) => {
|
|
29540
29514
|
if (e) return;
|
|
@@ -29575,34 +29549,13 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
|
|
|
29575
29549
|
}
|
|
29576
29550
|
});
|
|
29577
29551
|
if (e) {
|
|
29578
|
-
w.current ||
|
|
29552
|
+
w.current || l.endSession().catch(() => {});
|
|
29579
29553
|
return;
|
|
29580
29554
|
}
|
|
29581
|
-
n =
|
|
29555
|
+
n = l, S.current = l, console.log("[FlowEngage voice] startSession resolved OK", { isResume: !!u }), h("listening");
|
|
29582
29556
|
try {
|
|
29583
|
-
if (l)
|
|
29584
|
-
|
|
29585
|
-
if (!f.sent && f.hasSeenSpeaking && f.prompt && f.conv && !e) {
|
|
29586
|
-
console.log("[FlowEngage voice] fallbackTimerA firing sendContextualUpdate"), f.sent = !0;
|
|
29587
|
-
let e = f.prompt;
|
|
29588
|
-
f.prompt = null;
|
|
29589
|
-
try {
|
|
29590
|
-
f.conv.sendContextualUpdate(e), FD.clear();
|
|
29591
|
-
} catch {}
|
|
29592
|
-
}
|
|
29593
|
-
}, 6e3);
|
|
29594
|
-
setTimeout(() => {
|
|
29595
|
-
if (!f.sent && f.prompt && f.conv && !e) {
|
|
29596
|
-
console.log("[FlowEngage voice] fallbackTimerB firing sendContextualUpdate (no speaking seen)"), f.sent = !0;
|
|
29597
|
-
let e = f.prompt;
|
|
29598
|
-
f.prompt = null;
|
|
29599
|
-
try {
|
|
29600
|
-
f.conv.sendContextualUpdate(e), FD.clear();
|
|
29601
|
-
} catch {}
|
|
29602
|
-
}
|
|
29603
|
-
clearTimeout(t);
|
|
29604
|
-
}, 1e4);
|
|
29605
|
-
} else {
|
|
29557
|
+
if (c) console.log("[FlowEngage voice] sending resume contextualUpdate immediately"), l.sendContextualUpdate(c), FD.clear();
|
|
29558
|
+
else {
|
|
29606
29559
|
let e = "[]";
|
|
29607
29560
|
try {
|
|
29608
29561
|
e = await t.flowengage_list_forms();
|
|
@@ -29612,7 +29565,7 @@ function ik({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
|
|
|
29612
29565
|
text: e.textContent.trim(),
|
|
29613
29566
|
id: e.id || null
|
|
29614
29567
|
})).filter((e) => e.text.length > 0 && e.text.length < 200).slice(0, 25) : [];
|
|
29615
|
-
|
|
29568
|
+
l.sendContextualUpdate(`Page: ${o}. SiteId: ${i || "unknown"}. Sections on this page: ${JSON.stringify(n)}. IMPORTANT: Call flowengage_highlight with section_text from the list above as you explain each section. Forms: ${e}. Navigation: flowengage_navigate — use for cross-page navigation. End call: flowengage_end_session.`);
|
|
29616
29569
|
}
|
|
29617
29570
|
} catch {}
|
|
29618
29571
|
} catch (n) {
|