@flowengage/react-chatbot 3.0.8 → 3.0.9

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.
@@ -600,7 +600,7 @@ registerProcessor("audioConcatProcessor", AudioConcatProcessor);
600
600
  fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
601
601
  filter="url(#${Q}-csh)"/>
602
602
  </svg>`,dk=null,fk=!1;function pk(){return(!dk||!dk.isConnected)&&(dk=document.createElement(`div`),dk.id=`${Q}-cursor`,dk.innerHTML=uk,document.body.appendChild(dk),fk=!1),dk}async function mk(e){if(typeof document>`u`||!e)return;XO();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=pk();fk||=(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 vk(360)}function hk(e=!1){dk&&(e?(dk.classList.remove(`${Q}-cursor-visible`),fk=!1):(dk.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{fk=!1},250)))}async function gk(e){dk&&(dk.classList.add(`${Q}-cursor-click`),await vk(280),dk.classList.remove(`${Q}-cursor-click`))}function _k(e){if(!e||typeof document>`u`)return;XO();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 vk(e){return new Promise(t=>setTimeout(t,e))}Nn();function $(...e){Dn()&&console.log(`[FlowEngage:voice-tools]`,...e)}function yk(e){return new Promise(t=>setTimeout(t,e))}function bk(e=3e3){return new Promise(t=>{if(typeof document>`u`){t();return}let n=!1,r=()=>{n||(n=!0,t())},i=document.querySelector(`main`)||document.querySelector(`[role='main']`)||document.getElementById(`root`)||document.body,a=new MutationObserver(e=>{for(let t of e)if(t.addedNodes.length>0){a.disconnect(),requestAnimationFrame(()=>setTimeout(r,100));return}});a.observe(i,{childList:!0,subtree:!0}),setTimeout(()=>{a.disconnect(),r()},e)})}var xk=`.loader, .loading, .preloader, .page-loader, .spinner, [class*='Preloader'], [class*='PageLoader'], [class*='AppLoader'], [id*='loader' i], [id*='loading' i], [id*='preloader' i]`;function Sk(e){if(!e||typeof window>`u`)return!1;try{let t=window.getComputedStyle(e);if(!t||t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity||`1`)===0)return!1;let n=e.getBoundingClientRect();return!(n.width===0||n.height===0)}catch{return!1}}function Ck({expectedSelectors:e=[],minContentNodes:t=20,minTextLength:n=200,maxWait:r=4e3,pollInterval:i=300}={}){return new Promise(n=>{if(typeof document>`u`){n({hydrated:!1,reason:`no-document`});return}let a=document.querySelector(`main`)||document.querySelector(`[role='main']`)||document.getElementById(`root`)||document.body,o=!1,s=null,c=null,l=null,u=(e,t)=>{if(!o){o=!0;try{s?.disconnect?.()}catch{}l&&clearTimeout(l),c&&clearInterval(c),n({hydrated:e,reason:t})}},d=()=>{if(!Array.isArray(e)||e.length===0)return!1;for(let t of e)if(!(typeof t!=`string`||!t.trim()))try{if(!document.querySelector(t))return!1}catch{return!1}return!0},f=()=>{if(!a)return!1;try{return!(a.querySelectorAll(`*:not(#flowengage-root):not(.flowengage-shell):not(.flowengage-shell *)`).length<t||Array.from(a.querySelectorAll(xk)).find(e=>!e.closest(`#flowengage-root, .flowengage-shell`)&&Sk(e)))}catch{return!1}},p=()=>Array.isArray(e)&&e.length>0?d()?(u(!0,`selectors-satisfied`),!0):!1:f()?(u(!0,`content-threshold`),!0):!1;if(!p()){s=new MutationObserver(()=>{p()});try{s.observe(a||document.body,{childList:!0,subtree:!0})}catch{}c=setInterval(p,i),l=setTimeout(()=>u(!1,`timeout`),r)}})}var wk=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function Tk(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(wk)}catch{return!1}}function Ek(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Dk(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(!Tk(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function Ok(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function kk(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 Ok(r.join(` `))}if(e.labels&&e.labels.length)return Ok(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return Ok(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return Ok(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return Ok(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=Ok(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 Ok(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return Ok(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?Ok(o):null}function Ak(){let e=[];return Dk(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Tk(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=Ek(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function jk(){return Ak().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:kk(e),placeholder:e.placeholder||null}))}function Mk(){let e=[];return Dk(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Tk(e)||e.disabled)return!1;try{let t=Ek(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 Nk(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function Pk(e){let t=Nk(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Fk(e,t){let n=Pk(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,kk(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Nk(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 Ik=28;function Lk(e,t){let n=null,r=0;for(let i of e){let e=Fk(i,t);e>r&&(r=e,n=i)}return!n||r<Ik?null:n}function Rk(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,kk(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 zk(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function Bk(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 Vk(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 Hk(e){if(!Vk(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,kk(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 Uk(e,t,n){let r=String(t??``),i=String(n??``),a=Kk(e,r)||Lk(e,r)||Rk(e,r,i);if(!a)return[];let o=new Set([a]);if(zk(i)&&Bk(r))for(let t of e)t!==a&&Hk(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 Wk(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 Gk(e){if(!e||typeof e!=`string`)return null;let t=null;return Dk(n=>{try{let r=n.getElementById(e);r&&!Tk(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function Kk(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=Gk(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=Gk(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 qk(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 Jk(e,t){let n=[];Dk(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Tk(e)||e.disabled)return!1;try{let t=Ek(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:qk(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=Wk(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function Yk(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 Xk(e){let t=Yk(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 Zk(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 Qk(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 $k(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 eA(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 tA(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 nA(){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 rA(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let i=Yk(n),a=$k(i),o=i.section_text??i.sectionText??i.section,s=Array.isArray(i.expected_landmarks)?i.expected_landmarks:Array.isArray(i.expectedLandmarks)?i.expectedLandmarks:[];if($(`flowengage_navigate · coerced:`,{url:a,sectionText:o,expectedLandmarks:s}),!a){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(a=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,a))}catch{}if(!await hr(a,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${a}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{if(ek(`Navigating to ${a}...`,{spinner:!0}),ak(),GO(),YO(),$(`flowengage_navigate → shadowNavigate`,a),!await qr(a,{sectionText:typeof o==`string`?o:void 0,voiceActive:!0}))return $(`flowengage_navigate ✖ SPA body-swap failed — staying on current page`),ek(`Page swap failed`,{spinner:!1,icon:`⚠️`,duration:1500}),`Could not navigate to ${a} without breaking the voice session. Use flowengage_search to find information about this topic, then answer from the search results. Do NOT tell the user navigation failed — just answer their question.`;if(Jn())return ke(),$(`flowengage_navigate → reload strategy deferred, page reloads after speech`),ek(`Navigating…`,{spinner:!0,duration:4e3}),`OK_NAVIGATE_RELOADING. Page needs a full reload to finish loading; the session will resume automatically. Do not speak until the user speaks first.`;await bk();let e=await Ck({expectedSelectors:s,minContentNodes:20,maxWait:4e3});if($(`flowengage_navigate · hydration:`,e),!e.hydrated){try{let e=r?r():``;if(e&&t){let n=UO([{sender:`user`,message:e}]);n&&Te(t,n)}}catch{}return ke(),ek(`Reloading page…`,{spinner:!0,duration:1500}),$(`flowengage_navigate → hydration failed, forcing reload to`,a),setTimeout(()=>{try{window.location.assign(a)}catch{}},150),`OK_NAVIGATE_RELOADING. Page needs a full reload to finish loading; the session will resume automatically. Do not speak until the user speaks first.`}if(nA(),o&&typeof o==`string`){let e=null;for(let t=0;t<5&&!e;t++)e=Hn(null,o),e||await yk(300);e&&JO(e),$(`flowengage_navigate · highlight`,{sectionText:o,found:!!e,attempts:e?`ok`:5})}let n=Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, nav, footer, header`)).map(e=>e.textContent.trim()).filter(e=>e.length>0&&e.length<150).slice(0,20),i=`OK_NAVIGATION ${a}. Page sections: ${JSON.stringify(n)}. For each section: call flowengage_highlight, speak 2-3 sentences about ONLY that section, then highlight the next. One section per speech turn.`;return $(`flowengage_navigate ✓`,i),ek(`Navigation complete`,{spinner:!1,icon:`✅`,duration:1200}),i}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),ek(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{ok(),tk(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=Yk(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;nA();let i=Hn(n||null,r||null);return!i&&r&&(await new Promise(e=>setTimeout(e,500)),nA(),i=Hn(null,r)),i?(JO(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=Yk(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=Hn(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(`
603
- `)}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=eA(Yk(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=Yk(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=jk(),t=Mk();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),sk();let t=Xk(e);if(!t.length&&r){let e=r(),n=Zk(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=Qk(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;ek(`Filling ${String(t)}...`,{spinner:!0});let a=Ak(),o=Uk(a,String(t),r);if(o.length){for(let[e,t]of o.entries())ck(t),await mk(t),tA(t,r,{skipScroll:e>0}),lk(t),await yk(120);i=o,n.push(String(t));continue}let s=Kk(a,String(t));s||=Lk(a,String(t)),s||=Rk(a,String(t),r),s&&(ck(s),await mk(s),tA(s,r),lk(s),await yk(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),ek(`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),ek(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{hk(),sk(),tk(700)}},flowengage_click_button:async e=>{let t=Yk(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=Jk(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{ek(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await mk(r),r.focus?.(),await gk(r),_k(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),ek(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),ek(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{hk(),tk(700)}}};return{...a,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}Nn();function iA(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Dn();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var aA={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function oA(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 sA(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 cA({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 lA({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 uA(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 dA({orbColors:e,...t}){return(0,M.jsx)(PO,{colors:e,...t})}function fA({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||aA.green,c=sA(s),l=a?72:94,u=(0,M.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,M.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,M.jsx)(Lm.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)(Lm.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:s,color:c,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${s}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,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)(Lm.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)(dA,{size:l,orbColors:t})})]});return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(Lm.div,{initial:{opacity:0},animate:{opacity:+!o},transition:{duration:.28},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`,animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u}):(0,M.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function pA({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||aA.green,l=sA(c);return(0,M.jsxs)(Lm.div,{initial:{scale:50/350,borderRadius:`50%`},animate:s?{scale:50/350,opacity:0,borderRadius:`50%`}:{scale:1,borderRadius:`16px`,opacity:1},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,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)(dA,{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:c,color:l,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${c}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,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 mA({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s}){let[c,l]=(0,b.useState)(`idle`),[u,d]=(0,b.useState)(!1),[f,p]=(0,b.useState)(!1),m=(0,b.useRef)(null),h=(0,b.useRef)(``),g=(0,b.useRef)(async()=>{}),_=(0,b.useRef)(!1),v=(0,b.useRef)(!1),y=(0,b.useRef)(!1),x=(0,b.useRef)(!1),ee=(0,b.useRef)(`minimized`),S=(0,b.useRef)(null),C=(0,b.useCallback)((e=`minimized`)=>{ee.current=e,x.current=!0,queueMicrotask(()=>{_.current||(_.current=!0,g.current?.())})},[o]),te=(0,b.useCallback)(async e=>{x.current=!0;try{await m.current?.endSession?.()}catch{}if(m.current=null,l(`idle`),d(!1),_.current=!1,i)try{De(i)}catch{}typeof s==`function`&&await s(o.current),e?.()},[o,s,i]);return g.current=()=>te(ee.current===`chat`?t:n),(0,b.useEffect)(()=>{v.current=u},[u]),(0,b.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){l(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;o.current=[],h.current=``,_.current=!1,y.current=!1,x.current=!1,ee.current=`minimized`;let t=iA(rA({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>h.current,requestEndSession:()=>{C()}})),s=i?Ee(i):null,c=!!s?.transcript,u={agentId:r,clientTools:t};c&&(u.overrides={agent:{firstMessage:``}});let f=await ZD.startSession({...u,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||l(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){if(n===`user`&&(h.current=r),o.current=[...o.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=UO(o.current);e&&Te(i,e)}catch{}uA(n,r)&&C(`minimized`)}},onError:t=>{if(!e&&!x.current&&!y.current){y.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{m.current?.setMicMuted?.(!0)}catch{}d(!0),l(`error`),C(`chat`)}},onDisconnect:()=>{if(!e&&!x.current&&!y.current){y.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:h.current||``,wasMuted:v.current});try{m.current?.setMicMuted?.(!0)}catch{}d(!0),C(`chat`)}}});if(e){f.endSession().catch(()=>{});return}n=f,m.current=f,l(`listening`);try{let e=typeof window<`u`?window.location.href:``,n=`[]`;try{n=await t.list_page_forms()}catch{}let r=c?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${s.transcript}\n\n`:``;f.sendContextualUpdate(`${r}Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${n}. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),l(`error`),ee.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,x.current=!0,(n||m.current)?.endSession?.().catch(()=>{})}},[r,i,a,C]),(0,b.useEffect)(()=>{if(!f)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;S.current&&!S.current.contains(t)&&p(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[f]),(0,M.jsxs)(`div`,{ref:S,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:[c===`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)(dA,{size:72,voiceState:c,isMuted:u,orbColors:e})]}),c===`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(m.current)try{u?(await m.current.setMicMuted?.(!1),d(!1)):(await m.current.setMicMuted?.(!0),d(!0))}catch{}},title:u?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:u?`#7f1d1d`:`#1f2937`,border:u?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:u?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:u?(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)(QD,{size:16,color:`currentColor`})}),(0,M.jsx)(`button`,{onClick:()=>p(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)(oO,{size:16,color:`currentColor`})})]}),f&&(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:()=>{p(!1),ee.current=`chat`,te(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)(sO,{}),`Enter Chat Mode`]}),(0,M.jsxs)(`button`,{onClick:()=>{p(!1),ee.current=`minimized`,te(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)(cO,{}),`End Conversation`]}),(0,M.jsx)(`button`,{onClick:()=>p(!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 hA({orbColors:e}){return(0,M.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,M.jsx)(dA,{size:36,orbColors:e})})}var gA=()=>(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 _A({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,activeCallId:de,isCallMuted:fe,toggleCallMute:pe,endWebRTCCall:me,formatCallDuration:he,callDurationSeconds:ge,isCallMinimized:_e,onExpand:ve,onCollapse:ye,onStartVoice:be,onNewChat:xe,onEndConversation:Se,showPoweredBy:Ce,getVisitorChatHistory:we,getVisitorChatThread:Te,resumeChat:Ee,isSessionRestoring:De,isClosing:Oe}){let ke=c.length>0,Ae=y||x||v,je=!!de,[Me,Ne]=(0,b.useState)(!1),[Pe,Fe]=(0,b.useState)(!1),[Ie,D]=(0,b.useState)([]),[Le,Re]=(0,b.useState)(!1),[ze,Be]=(0,b.useState)(null),[Ve,He]=(0,b.useState)([]),Ue=(0,b.useRef)(null),We=async()=>{Ne(!1),Fe(!0),Re(!0),Be(null);try{let e=await we();e?.data&&D(e.data)}catch(e){console.error(e)}finally{Re(!1)}},Ge=async e=>{Fe(!1),Ee?.(e.chatId)};return(0,b.useEffect)(()=>{if(!Me)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Ue.current&&!Ue.current.contains(t)&&Ne(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Me]),(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:Oe?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:Oe?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,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)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,M.jsx)(`button`,{onClick:ye,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,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)(cA,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,M.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,M.jsx)(lA,{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:Ue,children:[(0,M.jsx)(`button`,{type:`button`,onClick:()=>Ne(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`})]})}),Me&&(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:()=>{Ne(!1),be?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,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:()=>{Ne(!1),xe?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,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 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,M.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new conversation`]}),we&&(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,M.jsxs)(`button`,{type:`button`,onClick:We,style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,M.jsx)(`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 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,M.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>{Ne(!1),ye?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,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)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,M.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,M.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,M.jsx)(TO,{webRTCError:le,micError:ue,setMicError:T,dismissCallError:E,isRateLimited:x,rateLimitMessage:ee}),_e&&(0,M.jsx)(HO,{agentName:f,agentHeadshot:p,fallbackAgentName:m,callDurationSeconds:ge,isCallMuted:fe,formatCallDuration:he,toggleCallMute:pe,endWebRTCCall:me,onExpand:ve,primaryColor:n}),(0,M.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Pe?(0,M.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,M.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:ze?(0,M.jsxs)(`button`,{onClick:()=>Be(null),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,M.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Back to List`})]}):(0,M.jsxs)(`button`,{onClick:()=>Fe(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,M.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,M.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Le&&!ze?(0,M.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):ze?(0,M.jsxs)(`div`,{style:{padding:`20px 16px`},children:[Ve.length===0?(0,M.jsx)(`div`,{style:{color:`#9ca3af`,textAlign:`center`,marginTop:`20px`,fontSize:`14px`},children:`No messages`}):null,Ve.map((e,t)=>(0,M.jsx)(`div`,{style:{marginBottom:`16px`,display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,M.jsx)(`div`,{style:{maxWidth:`85%`,background:e.sender===`user`?n:`#f3f4f6`,color:e.sender===`user`?`white`:`#111827`,padding:`10px 14px`,borderRadius:`14px`,fontSize:`15px`,lineHeight:1.4,wordBreak:`break-word`},children:e.content})},e._id||t))]}):Ie.length>0?(0,M.jsx)(`div`,{children:Ie.map(e=>(0,M.jsxs)(`div`,{onClick:()=>Ge(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,M.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,M.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,M.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,ke?(0,M.jsx)(CO,{chatHistory:c,isAiTyping:l,isLoading:y,isAgentTyping:u,setReplyContext:ce,TypingDots:gA,primaryColor:n,agentHeadshot:p,agentDisplayName:f||m,botAvatarNode:(0,M.jsx)(hA,{orbColors:t})}):De?(0,M.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,M.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,M.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,M.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(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)(dA,{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)(wO,{input:h,setInput:g,onSubmit:_,isConversationEnded:v,callUiActive:je,handleToggleVoice:be,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Ae,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 vA(){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,startNewChat:se,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,dismissCallError:fe,startTyping:pe,stopTyping:me,updateTypingDraft:he,getVisitorChatHistory:ge,getVisitorChatThread:_e,resumeChat:ve,isSessionRestoring:ye}=En();(0,b.useEffect)(()=>{try{Ar()}catch{}},[]);let be=t?.widgetSettings||{},xe=n?.widgetSettings||{},Se={...be.branding||{},...xe.branding||{}},Ce={...be.theme||{},...xe.theme||{}},we={...be.features||{},...xe.features||{}},Te=we.voice!==!1,Ee=Array.isArray(Ce.orbColors)&&Ce.orbColors.length>0?Ce.orbColors:null,De=Ce.buttonColor||Ce.primaryColor||Ee?.[0]||`#3B82F6`,Oe=Ce.position||`bottom-right`,ke=Se.fallbackAgentName||`Agent`,je=oA(Ee??Ce.chatBgColors),Me=Se.logo||Se.logoUrl||null,Ne=S||`en`,Pe=be.recommendations?.[Ne]||[],Fe=(xe.recommendations?.[Ne]??Pe).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Ie=Array.isArray(Se.quickChatOptions)&&Se.quickChatOptions.length>0?Se.quickChatOptions:Fe,D=Se.hideWatermark===!0?!1:Se.showPoweredBy!==!1,Le=Se.chatbotEnabled!==!1&&Ce.chatbotEnabled!==!1,Re=be.greetings?.[S]||xe.greetings?.[S]||Se.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,ze={entryPrompt:Se.entryPrompt||`Do you want to explore in a new way?`,yesLabel:Se.yesLabel||`Yes`,laterLabel:Se.laterLabel||`Later`,connectionTitle:Se.connectionTitle||`How would you like to connect?`,voiceLabel:Se.voiceLabel||`Voice`,textLabel:Se.textLabel||`Text`,chatTitle:Se.headerName||`Chat with FlowEngage`,introGreeting:Re,inputPlaceholder:Se.inputPlaceholder||`Type your message`,analysingLabel:Se.analysingLabel||`analysing...`},Be=xe.elevenLabsAgentId||t?.elevenLabsAgentId||null,Ve=t?.siteId||n?.siteId||null,He=t?.apiBaseUrl||``,Ue=(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]),We=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Ge=r.some(e=>e.sender===`user`),Ke=(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]),qe=!l&&Ge&&Ke,Je=!!(xe._dashboardLivePreview||be._dashboardLivePreview),[Ye,Xe]=(0,b.useState)(()=>Je?`text_chat`:`entry_prompt`),[O,Ze]=(0,b.useState)(``),[Qe,$e]=(0,b.useState)(null),[et,tt]=(0,b.useState)(l||``),[nt,rt]=(0,b.useState)(``),[it,at]=(0,b.useState)(0),[k,ot]=(0,b.useState)(null),[st,ct]=(0,b.useState)(null),[lt,ut]=(0,b.useState)(``),[dt,ft]=(0,b.useState)(!1),[pt,mt]=(0,b.useState)(!1),[ht,gt]=(0,b.useState)(!1),_t=(0,b.useRef)(null),vt=(0,b.useRef)(!1);(0,b.useLayoutEffect)(()=>{if(!(e!==`ready`||vt.current)){if(vt.current=!0,Te&&Ae()){re?.({notifyChatInitiated:!0}),ae?.(!0),Xe(`voice_mode`);return}try{let{shouldResumeVoice:e}=qn();if(e&&Te){re?.({notifyChatInitiated:!0}),ae?.(!0),Xe(`voice_mode`);return}}catch{}if(T(Ve)||!Te){Xe(`minimized_orb`);return}}},[e,r]);let[yt,bt]=(0,b.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,b.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>bt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,b.useEffect)(()=>{tt(l||``),l&&rt(``)},[l]);let xt=(0,b.useCallback)(()=>{ct(null),ut(``)},[]),St=(0,b.useCallback)(e=>{let t=vO(e);if(t){ct(null),ut(t);return}ct(e),ut(``)},[]);(0,b.useEffect)(()=>{if(!y||v!==`connected`){at(0);return}let e=()=>{let e=new Date(y).getTime();isNaN(e)||at(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[y,v]);let Ct=(0,b.useCallback)(()=>{Xe(`call_screen`),mt(!1)},[]),wt=(0,b.useCallback)(()=>{Xe(`text_chat`),mt(!0)},[]);(0,b.useEffect)(()=>{let e=g?.callId||_||null;if(!e){_t.current=null;return}if(g?.callId||v===`connecting`||v===`connected`){if(Ye===`minimized_orb`&&pt&&_&&!g?.callId){_t.current=e;return}!(!i||Ye===`minimized_orb`||Ye===`voice_mode`)&&_t.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:Ye,hasIncomingCall:!!g?.callId,activeCallId:_,callConnectionState:v}),_t.current=e,Ye===`voice_mode`&&ae?.(!1),re?.(),Ct())}},[_,v,Ct,g?.callId,i,re,ae,Ye]),(0,b.useEffect)(()=>{!g&&!_&&Ye===`call_screen`&&Xe(`text_chat`)},[g,_,Ye]),(0,b.useEffect)(()=>{!_&&pt&&mt(!1)},[_,pt]),(0,b.useEffect)(()=>{if(!o||h){he?.(``),me?.();return}if(!O.trim()||st){he?.(``);let e=window.setTimeout(()=>me?.(),100);return()=>window.clearTimeout(e)}pe?.();let e=window.setTimeout(()=>he?.(O),120),t=window.setTimeout(()=>me?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[O,st,o,h,pe,me,he]);let Tt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,Et=async e=>{if(e.preventDefault(),h)return;if(qe){let e=et.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){rt(`Please enter a valid email so we can continue helping you.`);return}await ie(e),rt(``);return}let t=Tt(Qe);if(!O.trim()&&!st)return;if(st){try{ft(!0),ut(``);let e=await ne(st),n=e?.data||e,r=O.trim()||`Shared file: ${bO(st)}`;Ze(``),$e(null),xt(),await w(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||st.name,fileType:n?.fileType||st.type,fileSize:n?.fileSize||st.size}})}catch(e){ut(e?.message||`Failed to upload the selected file.`)}finally{ft(!1)}return}let n=O.trim();Ze(``),$e(null),await w(n,``,t)},Dt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},Ot=(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]),kt=yt&&Ye===`entry_prompt`?{inset:0}:yt&&Ye===`text_chat`?{left:0,right:0,bottom:0}:yt&&Ye===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:yt&&Ye===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:Ye===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Oe===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`}}:Oe===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},At=(0,b.useCallback)(()=>{Ye!==`minimized_orb`&&(gt(!0),setTimeout(()=>{Xe(`minimized_orb`),gt(!1)},280))},[Ye]),jt=()=>Xe(`connection_modal`),Mt=()=>{re({notifyChatInitiated:!0}),ae?.(!0),Xe(`voice_mode`)},Nt=()=>{re({notifyChatInitiated:!0}),ae?.(!1),Xe(`text_chat`)},Pt=()=>{ae?.(!1),At()};return e!==`ready`||!Le||we.chat===!1?null:(0,M.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...kt},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[Ye===`entry_prompt`&&(0,M.jsx)(fA,{copy:ze,orbColors:Ee,primaryColor:De,onYes:()=>{E(Ve),Mt()},onLater:()=>{E(Ve),At()},isMobile:yt,isClosing:ht}),Ye===`minimized_orb`&&(0,M.jsxs)(Lm.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Oe===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[_&&pt&&(0,M.jsxs)(`button`,{type:`button`,onClick:Ct,style:{maxWidth:yt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,M.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,M.jsxs)(`span`,{style:{minWidth:0},children:[(0,M.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:v===`connected`?`Call in progress`:`Call is active`}),(0,M.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:v===`connected`?`${Dt(it)} with ${Ue}`:`Tap to return to ${Ue}`})]})]}),(0,M.jsx)(dA,{size:50,orbColors:Ee,onClick:_&&pt?Ct:Te?jt:Nt})]}),Ye===`connection_modal`&&(0,M.jsx)(pA,{copy:ze,orbColors:Ee,primaryColor:De,onVoice:Mt,onText:Nt,onClose:At,isMobile:yt,isClosing:ht}),Ye===`voice_mode`&&(0,M.jsx)(mA,{orbColors:Ee,onEnterChat:Nt,onEndChat:Pt,agentId:Be,siteId:Ve,apiBaseUrl:He,historyRef:C,onMessageSync:te},`voice`),Ye===`call_screen`&&(0,M.jsx)(VO,{incomingCall:g,activeCallId:_,callConnectionState:v,callDurationSeconds:it,isCallMuted:x,agentName:Ue,agentHeadshot:We,fallbackAgentName:ke,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,formatCallDuration:Dt,onMinimize:wt,primaryColor:De,orbColors:Ee,chatHistory:r}),Ye===`text_chat`&&(0,M.jsx)(_A,{isClosing:ht,copy:ze,orbColors:Ee,primaryColor:De,chatBgGradient:je,logo:Me,quickChatOptions:Ie,onQuickChatSelect:Ot,isMobile:yt,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Ue,agentHeadshot:We,fallbackAgentName:ke,input:O,setInput:Ze,onSubmit:Et,isConversationEnded:h,isLoading:f,isRateLimited:p,rateLimitMessage:m,selectedFile:st,onFileSelect:St,onRemoveSelectedFile:xt,attachmentError:lt,isUploadingAttachment:dt,requiresEmail:qe,emailInput:et,setEmailInput:tt,emailError:nt,replyContext:Qe,setReplyContext:$e,webRTCError:ee,micError:k,setMicError:ot,dismissCallError:fe,activeCallId:_,isCallMuted:x,toggleCallMute:de,endWebRTCCall:ue,formatCallDuration:Dt,callDurationSeconds:it,onCollapse:At,onStartVoice:Mt,onNewChat:se,onEndConversation:oe,onMinimize:wt,onExpand:Ct,isCallMinimized:pt&&!!_,showPoweredBy:D,getVisitorChatHistory:ge,getVisitorChatThread:_e,resumeChat:ve,isSessionRestoring:ye}),(0,M.jsx)(`style`,{children:`
603
+ `)}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=eA(Yk(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=Yk(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=jk(),t=Mk();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),sk();let t=Xk(e);if(!t.length&&r){let e=r(),n=Zk(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=Qk(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;ek(`Filling ${String(t)}...`,{spinner:!0});let a=Ak(),o=Uk(a,String(t),r);if(o.length){for(let[e,t]of o.entries())ck(t),await mk(t),tA(t,r,{skipScroll:e>0}),lk(t),await yk(120);i=o,n.push(String(t));continue}let s=Kk(a,String(t));s||=Lk(a,String(t)),s||=Rk(a,String(t),r),s&&(ck(s),await mk(s),tA(s,r),lk(s),await yk(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),ek(`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),ek(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{hk(),sk(),tk(700)}},flowengage_click_button:async e=>{let t=Yk(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=Jk(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{ek(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await mk(r),r.focus?.(),await gk(r),_k(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),ek(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),ek(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{hk(),tk(700)}}};return{...a,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}Nn();function iA(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=Dn();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i;try{i=await t(n)}catch(t){let n=`Tool error: ${t?.message||String(t)}`;return console.error(`[FlowEngage] voice tool ${e} threw:`,t),n}let a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var aA={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function oA(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 sA(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 cA({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 lA({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 uA(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 dA({orbColors:e,...t}){return(0,M.jsx)(PO,{colors:e,...t})}function fA({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||aA.green,c=sA(s),l=a?72:94,u=(0,M.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,M.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,M.jsx)(Lm.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)(Lm.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:s,color:c,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${s}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,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)(Lm.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)(dA,{size:l,orbColors:t})})]});return(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(Lm.div,{initial:{opacity:0},animate:{opacity:+!o},transition:{duration:.28},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`,animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u}):(0,M.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function pA({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||aA.green,l=sA(c);return(0,M.jsxs)(Lm.div,{initial:{scale:50/350,borderRadius:`50%`},animate:s?{scale:50/350,opacity:0,borderRadius:`50%`}:{scale:1,borderRadius:`16px`,opacity:1},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,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)(dA,{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:c,color:l,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${c}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,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 mA({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s}){let[c,l]=(0,b.useState)(`idle`),[u,d]=(0,b.useState)(!1),[f,p]=(0,b.useState)(!1),m=(0,b.useRef)(null),h=(0,b.useRef)(``),g=(0,b.useRef)(async()=>{}),_=(0,b.useRef)(!1),v=(0,b.useRef)(!1),y=(0,b.useRef)(!1),x=(0,b.useRef)(!1),ee=(0,b.useRef)(`minimized`),S=(0,b.useRef)(null),C=(0,b.useCallback)((e=`minimized`)=>{ee.current=e,x.current=!0,queueMicrotask(()=>{_.current||(_.current=!0,g.current?.())})},[o]),te=(0,b.useCallback)(async e=>{x.current=!0;try{await m.current?.endSession?.()}catch{}if(m.current=null,l(`idle`),d(!1),_.current=!1,i)try{De(i)}catch{}typeof s==`function`&&await s(o.current),e?.()},[o,s,i]);return g.current=()=>te(ee.current===`chat`?t:n),(0,b.useEffect)(()=>{v.current=u},[u]),(0,b.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){l(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;o.current=[],h.current=``,_.current=!1,y.current=!1,x.current=!1,ee.current=`minimized`;let t=iA(rA({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>h.current,requestEndSession:()=>{C()}})),s=i?Ee(i):null,c=!!s?.transcript,u={agentId:r,clientTools:t,connectionType:`websocket`};c&&(u.overrides={agent:{firstMessage:``}});let f=await ZD.startSession({...u,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||l(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){if(n===`user`&&(h.current=r),o.current=[...o.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=UO(o.current);e&&Te(i,e)}catch{}uA(n,r)&&C(`minimized`)}},onError:t=>{if(!e&&!x.current&&!y.current){y.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{m.current?.setMicMuted?.(!0)}catch{}d(!0),l(`error`),C(`chat`)}},onDisconnect:()=>{if(!e&&!x.current&&!y.current){y.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:h.current||``,wasMuted:v.current});try{m.current?.setMicMuted?.(!0)}catch{}d(!0),C(`chat`)}}});if(e){f.endSession().catch(()=>{});return}n=f,m.current=f,l(`listening`);try{let e=typeof window<`u`?window.location.href:``,n=`[]`;try{n=await t.list_page_forms()}catch{}let r=c?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${s.transcript}\n\n`:``;f.sendContextualUpdate(`${r}Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${n}. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),l(`error`),ee.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,x.current=!0,(n||m.current)?.endSession?.().catch(()=>{})}},[r,i,a,C]),(0,b.useEffect)(()=>{if(!f)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;S.current&&!S.current.contains(t)&&p(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[f]),(0,M.jsxs)(`div`,{ref:S,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:[c===`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)(dA,{size:72,voiceState:c,isMuted:u,orbColors:e})]}),c===`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(m.current)try{u?(await m.current.setMicMuted?.(!1),d(!1)):(await m.current.setMicMuted?.(!0),d(!0))}catch{}},title:u?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:u?`#7f1d1d`:`#1f2937`,border:u?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:u?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:u?(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)(QD,{size:16,color:`currentColor`})}),(0,M.jsx)(`button`,{onClick:()=>p(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)(oO,{size:16,color:`currentColor`})})]}),f&&(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:()=>{p(!1),ee.current=`chat`,te(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)(sO,{}),`Enter Chat Mode`]}),(0,M.jsxs)(`button`,{onClick:()=>{p(!1),ee.current=`minimized`,te(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)(cO,{}),`End Conversation`]}),(0,M.jsx)(`button`,{onClick:()=>p(!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 hA({orbColors:e}){return(0,M.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,M.jsx)(dA,{size:36,orbColors:e})})}var gA=()=>(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 _A({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,activeCallId:de,isCallMuted:fe,toggleCallMute:pe,endWebRTCCall:me,formatCallDuration:he,callDurationSeconds:ge,isCallMinimized:_e,onExpand:ve,onCollapse:ye,onStartVoice:be,onNewChat:xe,onEndConversation:Se,showPoweredBy:Ce,getVisitorChatHistory:we,getVisitorChatThread:Te,resumeChat:Ee,isSessionRestoring:De,isClosing:Oe}){let ke=c.length>0,Ae=y||x||v,je=!!de,[Me,Ne]=(0,b.useState)(!1),[Pe,Fe]=(0,b.useState)(!1),[Ie,D]=(0,b.useState)([]),[Le,Re]=(0,b.useState)(!1),[ze,Be]=(0,b.useState)(null),[Ve,He]=(0,b.useState)([]),Ue=(0,b.useRef)(null),We=async()=>{Ne(!1),Fe(!0),Re(!0),Be(null);try{let e=await we();e?.data&&D(e.data)}catch(e){console.error(e)}finally{Re(!1)}},Ge=async e=>{Fe(!1),Ee?.(e.chatId)};return(0,b.useEffect)(()=>{if(!Me)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;Ue.current&&!Ue.current.contains(t)&&Ne(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Me]),(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:Oe?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:Oe?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,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)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,M.jsx)(`button`,{onClick:ye,style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`,flexShrink:0},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},children:(0,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)(cA,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,M.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,M.jsx)(lA,{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:Ue,children:[(0,M.jsx)(`button`,{type:`button`,onClick:()=>Ne(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`})]})}),Me&&(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:()=>{Ne(!1),be?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,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:()=>{Ne(!1),xe?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,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 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,M.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new conversation`]}),we&&(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,M.jsxs)(`button`,{type:`button`,onClick:We,style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,M.jsx)(`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 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,M.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,M.jsxs)(`button`,{type:`button`,onClick:()=>{Ne(!1),ye?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`#f87171`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(248,113,113,0.1)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,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)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,M.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,M.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,M.jsx)(TO,{webRTCError:le,micError:ue,setMicError:T,dismissCallError:E,isRateLimited:x,rateLimitMessage:ee}),_e&&(0,M.jsx)(HO,{agentName:f,agentHeadshot:p,fallbackAgentName:m,callDurationSeconds:ge,isCallMuted:fe,formatCallDuration:he,toggleCallMute:pe,endWebRTCCall:me,onExpand:ve,primaryColor:n}),(0,M.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Pe?(0,M.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,M.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:ze?(0,M.jsxs)(`button`,{onClick:()=>Be(null),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,M.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Back to List`})]}):(0,M.jsxs)(`button`,{onClick:()=>Fe(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,M.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,M.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,M.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,M.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Le&&!ze?(0,M.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):ze?(0,M.jsxs)(`div`,{style:{padding:`20px 16px`},children:[Ve.length===0?(0,M.jsx)(`div`,{style:{color:`#9ca3af`,textAlign:`center`,marginTop:`20px`,fontSize:`14px`},children:`No messages`}):null,Ve.map((e,t)=>(0,M.jsx)(`div`,{style:{marginBottom:`16px`,display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,M.jsx)(`div`,{style:{maxWidth:`85%`,background:e.sender===`user`?n:`#f3f4f6`,color:e.sender===`user`?`white`:`#111827`,padding:`10px 14px`,borderRadius:`14px`,fontSize:`15px`,lineHeight:1.4,wordBreak:`break-word`},children:e.content})},e._id||t))]}):Ie.length>0?(0,M.jsx)(`div`,{children:Ie.map(e=>(0,M.jsxs)(`div`,{onClick:()=>Ge(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,M.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,M.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,M.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,ke?(0,M.jsx)(CO,{chatHistory:c,isAiTyping:l,isLoading:y,isAgentTyping:u,setReplyContext:ce,TypingDots:gA,primaryColor:n,agentHeadshot:p,agentDisplayName:f||m,botAvatarNode:(0,M.jsx)(hA,{orbColors:t})}):De?(0,M.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,M.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,M.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,M.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(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)(dA,{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)(wO,{input:h,setInput:g,onSubmit:_,isConversationEnded:v,callUiActive:je,handleToggleVoice:be,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Ae,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 vA(){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,startNewChat:se,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,dismissCallError:fe,startTyping:pe,stopTyping:me,updateTypingDraft:he,getVisitorChatHistory:ge,getVisitorChatThread:_e,resumeChat:ve,isSessionRestoring:ye}=En();(0,b.useEffect)(()=>{try{Ar()}catch{}},[]);let be=t?.widgetSettings||{},xe=n?.widgetSettings||{},Se={...be.branding||{},...xe.branding||{}},Ce={...be.theme||{},...xe.theme||{}},we={...be.features||{},...xe.features||{}},Te=we.voice!==!1,Ee=Array.isArray(Ce.orbColors)&&Ce.orbColors.length>0?Ce.orbColors:null,De=Ce.buttonColor||Ce.primaryColor||Ee?.[0]||`#3B82F6`,Oe=Ce.position||`bottom-right`,ke=Se.fallbackAgentName||`Agent`,je=oA(Ee??Ce.chatBgColors),Me=Se.logo||Se.logoUrl||null,Ne=S||`en`,Pe=be.recommendations?.[Ne]||[],Fe=(xe.recommendations?.[Ne]??Pe).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Ie=Array.isArray(Se.quickChatOptions)&&Se.quickChatOptions.length>0?Se.quickChatOptions:Fe,D=Se.hideWatermark===!0?!1:Se.showPoweredBy!==!1,Le=Se.chatbotEnabled!==!1&&Ce.chatbotEnabled!==!1,Re=be.greetings?.[S]||xe.greetings?.[S]||Se.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,ze={entryPrompt:Se.entryPrompt||`Do you want to explore in a new way?`,yesLabel:Se.yesLabel||`Yes`,laterLabel:Se.laterLabel||`Later`,connectionTitle:Se.connectionTitle||`How would you like to connect?`,voiceLabel:Se.voiceLabel||`Voice`,textLabel:Se.textLabel||`Text`,chatTitle:Se.headerName||`Chat with FlowEngage`,introGreeting:Re,inputPlaceholder:Se.inputPlaceholder||`Type your message`,analysingLabel:Se.analysingLabel||`analysing...`},Be=xe.elevenLabsAgentId||t?.elevenLabsAgentId||null,Ve=t?.siteId||n?.siteId||null,He=t?.apiBaseUrl||``,Ue=(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]),We=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Ge=r.some(e=>e.sender===`user`),Ke=(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]),qe=!l&&Ge&&Ke,Je=!!(xe._dashboardLivePreview||be._dashboardLivePreview),[Ye,Xe]=(0,b.useState)(()=>Je?`text_chat`:`entry_prompt`),[O,Ze]=(0,b.useState)(``),[Qe,$e]=(0,b.useState)(null),[et,tt]=(0,b.useState)(l||``),[nt,rt]=(0,b.useState)(``),[it,at]=(0,b.useState)(0),[k,ot]=(0,b.useState)(null),[st,ct]=(0,b.useState)(null),[lt,ut]=(0,b.useState)(``),[dt,ft]=(0,b.useState)(!1),[pt,mt]=(0,b.useState)(!1),[ht,gt]=(0,b.useState)(!1),_t=(0,b.useRef)(null),vt=(0,b.useRef)(!1);(0,b.useLayoutEffect)(()=>{if(!(e!==`ready`||vt.current)){if(vt.current=!0,Te&&Ae()){re?.({notifyChatInitiated:!0}),ae?.(!0),Xe(`voice_mode`);return}try{let{shouldResumeVoice:e}=qn();if(e&&Te){re?.({notifyChatInitiated:!0}),ae?.(!0),Xe(`voice_mode`);return}}catch{}if(T(Ve)||!Te){Xe(`minimized_orb`);return}}},[e,r]);let[yt,bt]=(0,b.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,b.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>bt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,b.useEffect)(()=>{tt(l||``),l&&rt(``)},[l]);let xt=(0,b.useCallback)(()=>{ct(null),ut(``)},[]),St=(0,b.useCallback)(e=>{let t=vO(e);if(t){ct(null),ut(t);return}ct(e),ut(``)},[]);(0,b.useEffect)(()=>{if(!y||v!==`connected`){at(0);return}let e=()=>{let e=new Date(y).getTime();isNaN(e)||at(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[y,v]);let Ct=(0,b.useCallback)(()=>{Xe(`call_screen`),mt(!1)},[]),wt=(0,b.useCallback)(()=>{Xe(`text_chat`),mt(!0)},[]);(0,b.useEffect)(()=>{let e=g?.callId||_||null;if(!e){_t.current=null;return}if(g?.callId||v===`connecting`||v===`connected`){if(Ye===`minimized_orb`&&pt&&_&&!g?.callId){_t.current=e;return}!(!i||Ye===`minimized_orb`||Ye===`voice_mode`)&&_t.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:Ye,hasIncomingCall:!!g?.callId,activeCallId:_,callConnectionState:v}),_t.current=e,Ye===`voice_mode`&&ae?.(!1),re?.(),Ct())}},[_,v,Ct,g?.callId,i,re,ae,Ye]),(0,b.useEffect)(()=>{!g&&!_&&Ye===`call_screen`&&Xe(`text_chat`)},[g,_,Ye]),(0,b.useEffect)(()=>{!_&&pt&&mt(!1)},[_,pt]),(0,b.useEffect)(()=>{if(!o||h){he?.(``),me?.();return}if(!O.trim()||st){he?.(``);let e=window.setTimeout(()=>me?.(),100);return()=>window.clearTimeout(e)}pe?.();let e=window.setTimeout(()=>he?.(O),120),t=window.setTimeout(()=>me?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[O,st,o,h,pe,me,he]);let Tt=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,Et=async e=>{if(e.preventDefault(),h)return;if(qe){let e=et.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){rt(`Please enter a valid email so we can continue helping you.`);return}await ie(e),rt(``);return}let t=Tt(Qe);if(!O.trim()&&!st)return;if(st){try{ft(!0),ut(``);let e=await ne(st),n=e?.data||e,r=O.trim()||`Shared file: ${bO(st)}`;Ze(``),$e(null),xt(),await w(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||st.name,fileType:n?.fileType||st.type,fileSize:n?.fileSize||st.size}})}catch(e){ut(e?.message||`Failed to upload the selected file.`)}finally{ft(!1)}return}let n=O.trim();Ze(``),$e(null),await w(n,``,t)},Dt=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},Ot=(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]),kt=yt&&Ye===`entry_prompt`?{inset:0}:yt&&Ye===`text_chat`?{left:0,right:0,bottom:0}:yt&&Ye===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:yt&&Ye===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:Ye===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Oe===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`}}:Oe===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},At=(0,b.useCallback)(()=>{Ye!==`minimized_orb`&&(gt(!0),setTimeout(()=>{Xe(`minimized_orb`),gt(!1)},280))},[Ye]),jt=()=>Xe(`connection_modal`),Mt=()=>{re({notifyChatInitiated:!0}),ae?.(!0),Xe(`voice_mode`)},Nt=()=>{re({notifyChatInitiated:!0}),ae?.(!1),Xe(`text_chat`)},Pt=()=>{ae?.(!1),At()};return e!==`ready`||!Le||we.chat===!1?null:(0,M.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...kt},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[Ye===`entry_prompt`&&(0,M.jsx)(fA,{copy:ze,orbColors:Ee,primaryColor:De,onYes:()=>{E(Ve),Mt()},onLater:()=>{E(Ve),At()},isMobile:yt,isClosing:ht}),Ye===`minimized_orb`&&(0,M.jsxs)(Lm.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Oe===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[_&&pt&&(0,M.jsxs)(`button`,{type:`button`,onClick:Ct,style:{maxWidth:yt?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,M.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,M.jsxs)(`span`,{style:{minWidth:0},children:[(0,M.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:v===`connected`?`Call in progress`:`Call is active`}),(0,M.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:v===`connected`?`${Dt(it)} with ${Ue}`:`Tap to return to ${Ue}`})]})]}),(0,M.jsx)(dA,{size:50,orbColors:Ee,onClick:_&&pt?Ct:Te?jt:Nt})]}),Ye===`connection_modal`&&(0,M.jsx)(pA,{copy:ze,orbColors:Ee,primaryColor:De,onVoice:Mt,onText:Nt,onClose:At,isMobile:yt,isClosing:ht}),Ye===`voice_mode`&&(0,M.jsx)(mA,{orbColors:Ee,onEnterChat:Nt,onEndChat:Pt,agentId:Be,siteId:Ve,apiBaseUrl:He,historyRef:C,onMessageSync:te},`voice`),Ye===`call_screen`&&(0,M.jsx)(VO,{incomingCall:g,activeCallId:_,callConnectionState:v,callDurationSeconds:it,isCallMuted:x,agentName:Ue,agentHeadshot:We,fallbackAgentName:ke,acceptCall:ce,rejectCall:le,endWebRTCCall:ue,toggleCallMute:de,formatCallDuration:Dt,onMinimize:wt,primaryColor:De,orbColors:Ee,chatHistory:r}),Ye===`text_chat`&&(0,M.jsx)(_A,{isClosing:ht,copy:ze,orbColors:Ee,primaryColor:De,chatBgGradient:je,logo:Me,quickChatOptions:Ie,onQuickChatSelect:Ot,isMobile:yt,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Ue,agentHeadshot:We,fallbackAgentName:ke,input:O,setInput:Ze,onSubmit:Et,isConversationEnded:h,isLoading:f,isRateLimited:p,rateLimitMessage:m,selectedFile:st,onFileSelect:St,onRemoveSelectedFile:xt,attachmentError:lt,isUploadingAttachment:dt,requiresEmail:qe,emailInput:et,setEmailInput:tt,emailError:nt,replyContext:Qe,setReplyContext:$e,webRTCError:ee,micError:k,setMicError:ot,dismissCallError:fe,activeCallId:_,isCallMuted:x,toggleCallMute:de,endWebRTCCall:ue,formatCallDuration:Dt,callDurationSeconds:it,onCollapse:At,onStartVoice:Mt,onNewChat:se,onEndConversation:oe,onMinimize:wt,onExpand:Ct,isCallMinimized:pt&&!!_,showPoweredBy:D,getVisitorChatHistory:ge,getVisitorChatThread:_e,resumeChat:ve,isSessionRestoring:ye}),(0,M.jsx)(`style`,{children:`
604
604
  /* Force any SVG (or img) inside LogoSlot to fill the container height
605
605
  regardless of whether the component forwards its style prop. */
606
606
  .fe-logo-slot svg,
@@ -592,7 +592,7 @@ registerProcessor("audioConcatProcessor", AudioConcatProcessor);
592
592
  fill="white" stroke="#1e1b4b" stroke-width="1.6" stroke-linejoin="round"
593
593
  filter="url(#${Q}-csh)"/>
594
594
  </svg>`,TO=null,EO=!1;function DO(){return(!TO||!TO.isConnected)&&(TO=document.createElement(`div`),TO.id=`${Q}-cursor`,TO.innerHTML=wO,document.body.appendChild(TO),EO=!1),TO}async function OO(e){if(typeof document>`u`||!e)return;uO();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=DO();EO||=(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 MO(360)}function kO(e=!1){TO&&(e?(TO.classList.remove(`${Q}-cursor-visible`),EO=!1):(TO.classList.remove(`${Q}-cursor-visible`),setTimeout(()=>{EO=!1},250)))}async function AO(e){TO&&(TO.classList.add(`${Q}-cursor-click`),await MO(280),TO.classList.remove(`${Q}-cursor-click`))}function jO(e){if(!e||typeof document>`u`)return;uO();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 MO(e){return new Promise(t=>setTimeout(t,e))}function $(...e){d.i()&&console.log(`[FlowEngage:voice-tools]`,...e)}function NO(e){return new Promise(t=>setTimeout(t,e))}function PO(e=3e3){return new Promise(t=>{if(typeof document>`u`){t();return}let n=!1,r=()=>{n||(n=!0,t())},i=document.querySelector(`main`)||document.querySelector(`[role='main']`)||document.getElementById(`root`)||document.body,a=new MutationObserver(e=>{for(let t of e)if(t.addedNodes.length>0){a.disconnect(),requestAnimationFrame(()=>setTimeout(r,100));return}});a.observe(i,{childList:!0,subtree:!0}),setTimeout(()=>{a.disconnect(),r()},e)})}var FO=`.loader, .loading, .preloader, .page-loader, .spinner, [class*='Preloader'], [class*='PageLoader'], [class*='AppLoader'], [id*='loader' i], [id*='loading' i], [id*='preloader' i]`;function IO(e){if(!e||typeof window>`u`)return!1;try{let t=window.getComputedStyle(e);if(!t||t.display===`none`||t.visibility===`hidden`||parseFloat(t.opacity||`1`)===0)return!1;let n=e.getBoundingClientRect();return!(n.width===0||n.height===0)}catch{return!1}}function LO({expectedSelectors:e=[],minContentNodes:t=20,minTextLength:n=200,maxWait:r=4e3,pollInterval:i=300}={}){return new Promise(n=>{if(typeof document>`u`){n({hydrated:!1,reason:`no-document`});return}let a=document.querySelector(`main`)||document.querySelector(`[role='main']`)||document.getElementById(`root`)||document.body,o=!1,s=null,c=null,l=null,u=(e,t)=>{if(!o){o=!0;try{s?.disconnect?.()}catch{}l&&clearTimeout(l),c&&clearInterval(c),n({hydrated:e,reason:t})}},d=()=>{if(!Array.isArray(e)||e.length===0)return!1;for(let t of e)if(!(typeof t!=`string`||!t.trim()))try{if(!document.querySelector(t))return!1}catch{return!1}return!0},f=()=>{if(!a)return!1;try{return!(a.querySelectorAll(`*:not(#flowengage-root):not(.flowengage-shell):not(.flowengage-shell *)`).length<t||Array.from(a.querySelectorAll(FO)).find(e=>!e.closest(`#flowengage-root, .flowengage-shell`)&&IO(e)))}catch{return!1}},p=()=>Array.isArray(e)&&e.length>0?d()?(u(!0,`selectors-satisfied`),!0):!1:f()?(u(!0,`content-threshold`),!0):!1;if(!p()){s=new MutationObserver(()=>{p()});try{s.observe(a||document.body,{childList:!0,subtree:!0})}catch{}c=setInterval(p,i),l=setTimeout(()=>u(!1,`timeout`),r)}})}var RO=`#flowengage-root, .flowengage-shell, .flowengage-widget-root`;function zO(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(RO)}catch{return!1}}function BO(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function VO(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(!zO(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function HO(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function UO(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 HO(r.join(` `))}if(e.labels&&e.labels.length)return HO(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return HO(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return HO(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return HO(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=HO(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 HO(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return HO(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?HO(o):null}function WO(){let e=[];return VO(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(zO(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=BO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function GO(){return WO().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:UO(e),placeholder:e.placeholder||null}))}function KO(){let e=[];return VO(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(zO(e)||e.disabled)return!1;try{let t=BO(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 qO(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function JO(e){let t=qO(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function YO(e,t){let n=JO(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,UO(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>qO(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 XO=28;function ZO(e,t){let n=null,r=0;for(let i of e){let e=YO(i,t);e>r&&(r=e,n=i)}return!n||r<XO?null:n}function QO(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,UO(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 $O(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function ek(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 tk(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 nk(e){if(!tk(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,UO(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 rk(e,t,n){let r=String(t??``),i=String(n??``),a=ok(e,r)||ZO(e,r)||QO(e,r,i);if(!a)return[];let o=new Set([a]);if($O(i)&&ek(r))for(let t of e)t!==a&&nk(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 ik(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 ak(e){if(!e||typeof e!=`string`)return null;let t=null;return VO(n=>{try{let r=n.getElementById(e);r&&!zO(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function ok(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=ak(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=ak(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 sk(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 ck(e,t){let n=[];VO(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(zO(e)||e.disabled)return!1;try{let t=BO(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:sk(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=ik(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function lk(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 uk(e){let t=lk(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 dk(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 fk(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 pk(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 mk(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 hk(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 gk(){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 _k(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={flowengage_navigate:async n=>{$(`flowengage_navigate ▶ raw parameters:`,n);let i=lk(n),a=pk(i),o=i.section_text??i.sectionText??i.section,s=Array.isArray(i.expected_landmarks)?i.expected_landmarks:Array.isArray(i.expectedLandmarks)?i.expectedLandmarks:[];if($(`flowengage_navigate · coerced:`,{url:a,sectionText:o,expectedLandmarks:s}),!a){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`flowengage_navigate ✖`,e),e}if(typeof window<`u`)try{let e=new URL(a,window.location.href);e.origin!==window.location.origin&&/^https?:$/i.test(e.protocol)&&(a=e.pathname+e.search+e.hash,$(`flowengage_navigate · normalized cross-origin URL to path:`,a))}catch{}if(!await f.n(a,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`Page "${a}" could not be verified. Call flowengage_search with keywords from the topic to find the correct URL, then navigate to the URL from the search results.`;return $(`flowengage_navigate ✖ blocked`,e),e}try{if(mO(`Navigating to ${a}...`,{spinner:!0}),yO(),aO(),lO(),$(`flowengage_navigate → shadowNavigate`,a),!await ar(a,{sectionText:typeof o==`string`?o:void 0,voiceActive:!0}))return $(`flowengage_navigate ✖ SPA body-swap failed — staying on current page`),mO(`Page swap failed`,{spinner:!1,icon:`⚠️`,duration:1500}),`Could not navigate to ${a} without breaking the voice session. Use flowengage_search to find information about this topic, then answer from the search results. Do NOT tell the user navigation failed — just answer their question.`;if(f.s())return Te(),$(`flowengage_navigate → reload strategy deferred, page reloads after speech`),mO(`Navigating…`,{spinner:!0,duration:4e3}),`OK_NAVIGATE_RELOADING. Page needs a full reload to finish loading; the session will resume automatically. Do not speak until the user speaks first.`;await PO();let e=await LO({expectedSelectors:s,minContentNodes:20,maxWait:4e3});if($(`flowengage_navigate · hydration:`,e),!e.hydrated){try{let e=r?r():``;if(e&&t){let n=rO([{sender:`user`,message:e}]);n&&xe(t,n)}}catch{}return Te(),mO(`Reloading page…`,{spinner:!0,duration:1500}),$(`flowengage_navigate → hydration failed, forcing reload to`,a),setTimeout(()=>{try{window.location.assign(a)}catch{}},150),`OK_NAVIGATE_RELOADING. Page needs a full reload to finish loading; the session will resume automatically. Do not speak until the user speaks first.`}if(gk(),o&&typeof o==`string`){let e=null;for(let t=0;t<5&&!e;t++)e=On(null,o),e||await NO(300);e&&cO(e),$(`flowengage_navigate · highlight`,{sectionText:o,found:!!e,attempts:e?`ok`:5})}let n=Array.from(document.querySelectorAll(`h1, h2, h3, h4`)).filter(e=>!e.closest(`#flowengage-root, .flowengage-shell, nav, footer, header`)).map(e=>e.textContent.trim()).filter(e=>e.length>0&&e.length<150).slice(0,20),i=`OK_NAVIGATION ${a}. Page sections: ${JSON.stringify(n)}. For each section: call flowengage_highlight, speak 2-3 sentences about ONLY that section, then highlight the next. One section per speech turn.`;return $(`flowengage_navigate ✓`,i),mO(`Navigation complete`,{spinner:!1,icon:`✅`,duration:1200}),i}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`flowengage_navigate ✖`,t),mO(`Navigation failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{bO(),hO(900)}},flowengage_highlight:async e=>{$(`flowengage_highlight ▶`,e);let t=lk(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText;gk();let i=On(n||null,r||null);return!i&&r&&(await new Promise(e=>setTimeout(e,500)),gk(),i=On(null,r)),i?(cO(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=lk(e),n=t?.section_text||t?.sectionText||``;try{let e=``;if(n){let t=On(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(`
595
- `)}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=mk(lk(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=lk(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=GO(),t=KO();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),xO();let t=uk(e);if(!t.length&&r){let e=r(),n=dk(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=fk(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;mO(`Filling ${String(t)}...`,{spinner:!0});let a=WO(),o=rk(a,String(t),r);if(o.length){for(let[e,t]of o.entries())SO(t),await OO(t),hk(t,r,{skipScroll:e>0}),CO(t),await NO(120);i=o,n.push(String(t));continue}let s=ok(a,String(t));s||=ZO(a,String(t)),s||=QO(a,String(t),r),s&&(SO(s),await OO(s),hk(s,r),CO(s),await NO(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),mO(`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),mO(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{kO(),xO(),hO(700)}},flowengage_click_button:async e=>{let t=lk(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=ck(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{mO(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await OO(r),r.focus?.(),await AO(r),jO(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),mO(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),mO(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{kO(),hO(700)}}};return{...a,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function vk(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=d.i();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 yk={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function bk(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 xk(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 Sk({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`?p.default.createElement(e):p.default.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 Ck({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 wk(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 Tk({orbColors:e,...t}){return(0,m.jsx)(JD,{colors:e,...t})}function Ek({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||yk.green,c=xk(s),l=a?72:94,u=(0,m.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,m.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,m.jsx)(rm.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)(rm.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:s,color:c,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${s}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,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)(rm.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)(Tk,{size:l,orbColors:t})})]});return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(rm.div,{initial:{opacity:0},animate:{opacity:+!o},transition:{duration:.28},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`,animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u}):(0,m.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function Dk({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||yk.green,l=xk(c);return(0,m.jsxs)(rm.div,{initial:{scale:50/350,borderRadius:`50%`},animate:s?{scale:50/350,opacity:0,borderRadius:`50%`}:{scale:1,borderRadius:`16px`,opacity:1},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,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)(Tk,{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:c,color:l,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${c}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,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 Ok({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s}){let[c,l]=(0,p.useState)(`idle`),[u,d]=(0,p.useState)(!1),[f,h]=(0,p.useState)(!1),g=(0,p.useRef)(null),_=(0,p.useRef)(``),v=(0,p.useRef)(async()=>{}),y=(0,p.useRef)(!1),b=(0,p.useRef)(!1),x=(0,p.useRef)(!1),S=(0,p.useRef)(!1),C=(0,p.useRef)(`minimized`),ee=(0,p.useRef)(null),te=(0,p.useCallback)((e=`minimized`)=>{C.current=e,S.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),ne=(0,p.useCallback)(async e=>{S.current=!0;try{await g.current?.endSession?.()}catch{}if(g.current=null,l(`idle`),d(!1),y.current=!1,i)try{Ce(i)}catch{}typeof s==`function`&&await s(o.current),e?.()},[o,s,i]);return v.current=()=>ne(C.current===`chat`?t:n),(0,p.useEffect)(()=>{b.current=u},[u]),(0,p.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){l(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;o.current=[],_.current=``,y.current=!1,x.current=!1,S.current=!1,C.current=`minimized`;let t=vk(_k({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,requestEndSession:()=>{te()}})),s=i?Se(i):null,c=!!s?.transcript,u={agentId:r,clientTools:t};c&&(u.overrides={agent:{firstMessage:``}});let f=await dD.startSession({...u,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||l(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){if(n===`user`&&(_.current=r),o.current=[...o.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=rO(o.current);e&&xe(i,e)}catch{}wk(n,r)&&te(`minimized`)}},onError:t=>{if(!e&&!S.current&&!x.current){x.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}d(!0),l(`error`),te(`chat`)}},onDisconnect:()=>{if(!e&&!S.current&&!x.current){x.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:_.current||``,wasMuted:b.current});try{g.current?.setMicMuted?.(!0)}catch{}d(!0),te(`chat`)}}});if(e){f.endSession().catch(()=>{});return}n=f,g.current=f,l(`listening`);try{let e=typeof window<`u`?window.location.href:``,n=`[]`;try{n=await t.list_page_forms()}catch{}let r=c?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${s.transcript}\n\n`:``;f.sendContextualUpdate(`${r}Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${n}. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),l(`error`),C.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,S.current=!0,(n||g.current)?.endSession?.().catch(()=>{})}},[r,i,a,te]),(0,p.useEffect)(()=>{if(!f)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ee.current&&!ee.current.contains(t)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[f]),(0,m.jsxs)(`div`,{ref:ee,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:[c===`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)(Tk,{size:72,voiceState:c,isMuted:u,orbColors:e})]}),c===`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{u?(await g.current.setMicMuted?.(!1),d(!1)):(await g.current.setMicMuted?.(!0),d(!0))}catch{}},title:u?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:u?`#7f1d1d`:`#1f2937`,border:u?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:u?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:u?(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)(fD,{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)(bD,{size:16,color:`currentColor`})})]}),f&&(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),C.current=`chat`,ne(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)(xD,{}),`Enter Chat Mode`]}),(0,m.jsxs)(`button`,{onClick:()=>{h(!1),C.current=`minimized`,ne(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)(SD,{}),`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 kk({orbColors:e}){return(0,m.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,m.jsx)(Tk,{size:36,orbColors:e})})}var Ak=()=>(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 jk({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:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:C,selectedFile:ee,onFileSelect:te,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,activeCallId:he,isCallMuted:ge,toggleCallMute:_e,endWebRTCCall:ve,formatCallDuration:ye,callDurationSeconds:be,isCallMinimized:xe,onExpand:Se,onCollapse:Ce,onStartVoice:we,onNewChat:Te,onEndConversation:Ee,showPoweredBy:De,getVisitorChatHistory:w,getVisitorChatThread:Oe,resumeChat:ke,isSessionRestoring:Ae,isClosing:je}){let Me=c.length>0,Ne=x||S||b,Pe=!!he,[Fe,Ie]=(0,p.useState)(!1),[Le,Re]=(0,p.useState)(!1),[ze,Be]=(0,p.useState)([]),[Ve,He]=(0,p.useState)(!1),[Ue,We]=(0,p.useState)(null),[Ge,Ke]=(0,p.useState)([]),qe=(0,p.useRef)(null),Je=async()=>{Ie(!1),Re(!0),He(!0),We(null);try{let e=await w();e?.data&&Be(e.data)}catch(e){console.error(e)}finally{He(!1)}},Ye=async e=>{Re(!1),ke?.(e.chatId)};return(0,p.useEffect)(()=>{if(!Fe)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;qe.current&&!qe.current.contains(t)&&Ie(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Fe]),(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:je?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:je?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,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)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,m.jsx)(`button`,{onClick:Ce,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)(Sk,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,m.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,m.jsx)(Ck,{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:qe,children:[(0,m.jsx)(`button`,{type:`button`,onClick:()=>Ie(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,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`})]})}),Fe&&(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:()=>{Ie(!1),we?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,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:()=>{Ie(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,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 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,m.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new conversation`]}),w&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,m.jsxs)(`button`,{type:`button`,onClick:Je,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.jsx)(`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 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,m.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,m.jsxs)(`button`,{type:`button`,onClick:()=>{Ie(!1),Ce?.()},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)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,m.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,m.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,m.jsx)(zD,{webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,isRateLimited:S,rateLimitMessage:C}),xe&&(0,m.jsx)(nO,{agentName:f,agentHeadshot:h,fallbackAgentName:g,callDurationSeconds:be,isCallMuted:ge,formatCallDuration:ye,toggleCallMute:_e,endWebRTCCall:ve,onExpand:Se,primaryColor:n}),(0,m.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Le?(0,m.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,m.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:Ue?(0,m.jsxs)(`button`,{onClick:()=>We(null),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,m.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,m.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,m.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Back to List`})]}):(0,m.jsxs)(`button`,{onClick:()=>Re(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,m.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,m.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,m.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,m.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Ve&&!Ue?(0,m.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):Ue?(0,m.jsxs)(`div`,{style:{padding:`20px 16px`},children:[Ge.length===0?(0,m.jsx)(`div`,{style:{color:`#9ca3af`,textAlign:`center`,marginTop:`20px`,fontSize:`14px`},children:`No messages`}):null,Ge.map((e,t)=>(0,m.jsx)(`div`,{style:{marginBottom:`16px`,display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,m.jsx)(`div`,{style:{maxWidth:`85%`,background:e.sender===`user`?n:`#f3f4f6`,color:e.sender===`user`?`white`:`#111827`,padding:`10px 14px`,borderRadius:`14px`,fontSize:`15px`,lineHeight:1.4,wordBreak:`break-word`},children:e.content})},e._id||t))]}):ze.length>0?(0,m.jsx)(`div`,{children:ze.map(e=>(0,m.jsxs)(`div`,{onClick:()=>Ye(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,m.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,m.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,m.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,Me?(0,m.jsx)(LD,{chatHistory:c,isAiTyping:l,isLoading:x,isAgentTyping:u,setReplyContext:ue,TypingDots:Ak,primaryColor:n,agentHeadshot:h,agentDisplayName:f||g,botAvatarNode:(0,m.jsx)(kk,{orbColors:t})}):Ae?(0,m.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,m.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,m.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,m.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(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)(Tk,{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:ae?`6px 0 0`:`12px 0 0`},children:(0,m.jsx)(RD,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Pe,handleToggleVoice:we,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Ne,replyContext:le,clearReplyContext:()=>ue(null),onFileSelect:te,selectedFile:ee,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),(0,m.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:De&&(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 Mk(){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:h,isRateLimited:g,rateLimitMessage:_,isConversationEnded:v,incomingCall:y,activeCallId:b,callConnectionState:x,callConnectedAt:S,isCallMuted:C,webRTCError:ee,language:te,historyRef:ne,onMessageSync:re,sendMessage:ie,uploadChatFile:se,openWidget:ce,captureVisitorEmail:le,setVoiceMode:ue,endConversation:de,startNewChat:fe,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,dismissCallError:_e,startTyping:ve,stopTyping:ye,updateTypingDraft:be,getVisitorChatHistory:xe,getVisitorChatThread:Se,resumeChat:Ce,isSessionRestoring:we}=bn();(0,p.useEffect)(()=>{try{Qn()}catch{}},[]);let Te=t?.widgetSettings||{},De=n?.widgetSettings||{},w={...Te.branding||{},...De.branding||{}},Oe={...Te.theme||{},...De.theme||{}},ke={...Te.features||{},...De.features||{}},Ae=ke.voice!==!1,je=Array.isArray(Oe.orbColors)&&Oe.orbColors.length>0?Oe.orbColors:null,Me=Oe.buttonColor||Oe.primaryColor||je?.[0]||`#3B82F6`,Ne=Oe.position||`bottom-right`,Pe=w.fallbackAgentName||`Agent`,Fe=bk(je??Oe.chatBgColors),Ie=w.logo||w.logoUrl||null,Le=te||`en`,Re=Te.recommendations?.[Le]||[],ze=(De.recommendations?.[Le]??Re).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Be=Array.isArray(w.quickChatOptions)&&w.quickChatOptions.length>0?w.quickChatOptions:ze,Ve=w.hideWatermark===!0?!1:w.showPoweredBy!==!1,He=w.chatbotEnabled!==!1&&Oe.chatbotEnabled!==!1,Ue=Te.greetings?.[te]||De.greetings?.[te]||w.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,We={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:Ue,inputPlaceholder:w.inputPlaceholder||`Type your message`,analysingLabel:w.analysingLabel||`analysing...`},Ge=De.elevenLabsAgentId||t?.elevenLabsAgentId||null,Ke=t?.siteId||n?.siteId||null,qe=t?.apiBaseUrl||``,Je=(0,p.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Ye=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Xe=r.some(e=>e.sender===`user`),Ze=(0,p.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]),Qe=!l&&Xe&&Ze,$e=!!(De._dashboardLivePreview||Te._dashboardLivePreview),[T,E]=(0,p.useState)(()=>$e?`text_chat`:`entry_prompt`),[D,O]=(0,p.useState)(``),[et,tt]=(0,p.useState)(null),[nt,rt]=(0,p.useState)(l||``),[it,at]=(0,p.useState)(``),[ot,st]=(0,p.useState)(0),[ct,lt]=(0,p.useState)(null),[ut,dt]=(0,p.useState)(null),[ft,pt]=(0,p.useState)(``),[mt,ht]=(0,p.useState)(!1),[gt,_t]=(0,p.useState)(!1),[vt,yt]=(0,p.useState)(!1),bt=(0,p.useRef)(null),xt=(0,p.useRef)(!1);(0,p.useLayoutEffect)(()=>{if(!(e!==`ready`||xt.current)){if(xt.current=!0,Ae&&Ee()){ce?.({notifyChatInitiated:!0}),ue?.(!0),E(`voice_mode`);return}try{let{shouldResumeVoice:e}=f.c();if(e&&Ae){ce?.({notifyChatInitiated:!0}),ue?.(!0),E(`voice_mode`);return}}catch{}if(ae(Ke)||!Ae){E(`minimized_orb`);return}}},[e,r]);let[St,Ct]=(0,p.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,p.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>Ct(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,p.useEffect)(()=>{rt(l||``),l&&at(``)},[l]);let wt=(0,p.useCallback)(()=>{dt(null),pt(``)},[]),Tt=(0,p.useCallback)(e=>{let t=MD(e);if(t){dt(null),pt(t);return}dt(e),pt(``)},[]);(0,p.useEffect)(()=>{if(!S||x!==`connected`){st(0);return}let e=()=>{let e=new Date(S).getTime();isNaN(e)||st(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[S,x]);let Et=(0,p.useCallback)(()=>{E(`call_screen`),_t(!1)},[]),Dt=(0,p.useCallback)(()=>{E(`text_chat`),_t(!0)},[]);(0,p.useEffect)(()=>{let e=y?.callId||b||null;if(!e){bt.current=null;return}if(y?.callId||x===`connecting`||x===`connected`){if(T===`minimized_orb`&&gt&&b&&!y?.callId){bt.current=e;return}!(!i||T===`minimized_orb`||T===`voice_mode`)&&bt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:T,hasIncomingCall:!!y?.callId,activeCallId:b,callConnectionState:x}),bt.current=e,T===`voice_mode`&&ue?.(!1),ce?.(),Et())}},[b,x,Et,y?.callId,i,ce,ue,T]),(0,p.useEffect)(()=>{!y&&!b&&T===`call_screen`&&E(`text_chat`)},[y,b,T]),(0,p.useEffect)(()=>{!b&&gt&&_t(!1)},[b,gt]),(0,p.useEffect)(()=>{if(!o||v){be?.(``),ye?.();return}if(!D.trim()||ut){be?.(``);let e=window.setTimeout(()=>ye?.(),100);return()=>window.clearTimeout(e)}ve?.();let e=window.setTimeout(()=>be?.(D),120),t=window.setTimeout(()=>ye?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[D,ut,o,v,ve,ye,be]);let Ot=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,kt=async e=>{if(e.preventDefault(),v)return;if(Qe){let e=nt.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){at(`Please enter a valid email so we can continue helping you.`);return}await le(e),at(``);return}let t=Ot(et);if(!D.trim()&&!ut)return;if(ut){try{ht(!0),pt(``);let e=await se(ut),n=e?.data||e,r=D.trim()||`Shared file: ${PD(ut)}`;O(``),tt(null),wt(),await ie(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||ut.name,fileType:n?.fileType||ut.type,fileSize:n?.fileSize||ut.size}})}catch(e){pt(e?.message||`Failed to upload the selected file.`)}finally{ht(!1)}return}let n=D.trim();O(``),tt(null),await ie(n,``,t)},At=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},jt=(0,p.useCallback)(async e=>{if(v||h)return;let t=e.message||e.label||e.text||``;t.trim()&&await ie(t.trim(),``)},[v,h,ie]),Mt=St&&T===`entry_prompt`?{inset:0}:St&&T===`text_chat`?{left:0,right:0,bottom:0}:St&&T===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:St&&T===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:T===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Ne===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`}}:Ne===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Nt=(0,p.useCallback)(()=>{T!==`minimized_orb`&&(yt(!0),setTimeout(()=>{E(`minimized_orb`),yt(!1)},280))},[T]),Pt=()=>E(`connection_modal`),Ft=()=>{ce({notifyChatInitiated:!0}),ue?.(!0),E(`voice_mode`)},It=()=>{ce({notifyChatInitiated:!0}),ue?.(!1),E(`text_chat`)},Lt=()=>{ue?.(!1),Nt()};return e!==`ready`||!He||ke.chat===!1?null:(0,m.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Mt},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[T===`entry_prompt`&&(0,m.jsx)(Ek,{copy:We,orbColors:je,primaryColor:Me,onYes:()=>{oe(Ke),Ft()},onLater:()=>{oe(Ke),Nt()},isMobile:St,isClosing:vt}),T===`minimized_orb`&&(0,m.jsxs)(rm.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Ne===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[b&&gt&&(0,m.jsxs)(`button`,{type:`button`,onClick:Et,style:{maxWidth:St?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,m.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,m.jsxs)(`span`,{style:{minWidth:0},children:[(0,m.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:x===`connected`?`Call in progress`:`Call is active`}),(0,m.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:x===`connected`?`${At(ot)} with ${Je}`:`Tap to return to ${Je}`})]})]}),(0,m.jsx)(Tk,{size:50,orbColors:je,onClick:b&&gt?Et:Ae?Pt:It})]}),T===`connection_modal`&&(0,m.jsx)(Dk,{copy:We,orbColors:je,primaryColor:Me,onVoice:Ft,onText:It,onClose:Nt,isMobile:St,isClosing:vt}),T===`voice_mode`&&(0,m.jsx)(Ok,{orbColors:je,onEnterChat:It,onEndChat:Lt,agentId:Ge,siteId:Ke,apiBaseUrl:qe,historyRef:ne,onMessageSync:re},`voice`),T===`call_screen`&&(0,m.jsx)(tO,{incomingCall:y,activeCallId:b,callConnectionState:x,callDurationSeconds:ot,isCallMuted:C,agentName:Je,agentHeadshot:Ye,fallbackAgentName:Pe,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,formatCallDuration:At,onMinimize:Dt,primaryColor:Me,orbColors:je,chatHistory:r}),T===`text_chat`&&(0,m.jsx)(jk,{isClosing:vt,copy:We,orbColors:je,primaryColor:Me,chatBgGradient:Fe,logo:Ie,quickChatOptions:Be,onQuickChatSelect:jt,isMobile:St,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Je,agentHeadshot:Ye,fallbackAgentName:Pe,input:D,setInput:O,onSubmit:kt,isConversationEnded:v,isLoading:h,isRateLimited:g,rateLimitMessage:_,selectedFile:ut,onFileSelect:Tt,onRemoveSelectedFile:wt,attachmentError:ft,isUploadingAttachment:mt,requiresEmail:Qe,emailInput:nt,setEmailInput:rt,emailError:it,replyContext:et,setReplyContext:tt,webRTCError:ee,micError:ct,setMicError:lt,dismissCallError:_e,activeCallId:b,isCallMuted:C,toggleCallMute:ge,endWebRTCCall:he,formatCallDuration:At,callDurationSeconds:ot,onCollapse:Nt,onStartVoice:Ft,onNewChat:fe,onEndConversation:de,onMinimize:Dt,onExpand:Et,isCallMinimized:gt&&!!b,showPoweredBy:Ve,getVisitorChatHistory:xe,getVisitorChatThread:Se,resumeChat:Ce,isSessionRestoring:we}),(0,m.jsx)(`style`,{children:`
595
+ `)}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=mk(lk(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=lk(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=GO(),t=KO();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),xO();let t=uk(e);if(!t.length&&r){let e=r(),n=dk(e);n.length?$(`flowengage_fill_form · inferred URL from last user utterance (model omitted usable fields):`,n):(n=fk(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;mO(`Filling ${String(t)}...`,{spinner:!0});let a=WO(),o=rk(a,String(t),r);if(o.length){for(let[e,t]of o.entries())SO(t),await OO(t),hk(t,r,{skipScroll:e>0}),CO(t),await NO(120);i=o,n.push(String(t));continue}let s=ok(a,String(t));s||=ZO(a,String(t)),s||=QO(a,String(t),r),s&&(SO(s),await OO(s),hk(s,r),CO(s),await NO(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),mO(`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),mO(`Failed to fill form`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{kO(),xO(),hO(700)}},flowengage_click_button:async e=>{let t=lk(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=ck(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{mO(`Clicking ${n}...`,{spinner:!0});try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}await OO(r),r.focus?.(),await AO(r),jO(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),mO(`Clicked ${e}`,{spinner:!1,icon:`✅`,duration:1200}),t}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`flowengage_click_button ✖`,t),mO(`Click failed`,{spinner:!1,icon:`⚠️`,duration:1800}),t}finally{kO(),hO(700)}}};return{...a,highlightOnPage:a.flowengage_highlight,searchSiteContent:a.flowengage_search,getPageContent:a.flowengage_page_content,endVoiceSession:a.flowengage_end_session,listPageForms:a.flowengage_list_forms,fillFormFields:a.flowengage_fill_form,clickPageButton:a.flowengage_click_button}}function vk(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=d.i();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 yk={blue:`#135bd8`,red:`#ef334b`,yellow:`#ffbd2e`,dark:`#0d1b2a`,highlight:`rgba(255,255,255,0.9)`,green:`#10b981`};function bk(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 xk(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 Sk({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`?p.default.createElement(e):p.default.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 Ck({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 wk(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 Tk({orbColors:e,...t}){return(0,m.jsx)(JD,{colors:e,...t})}function Ek({copy:e,orbColors:t,primaryColor:n,onYes:r,onLater:i,isMobile:a,isClosing:o}){let s=n||yk.green,c=xk(s),l=a?72:94,u=(0,m.jsxs)(`div`,{style:{display:`flex`,alignItems:a?`flex-end`:`center`,gap:a?`7px`:`9px`},children:[(0,m.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,m.jsx)(rm.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)(rm.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:s,color:c,fontWeight:400,fontSize:`14px`,border:`none`,cursor:`pointer`,whiteSpace:`nowrap`,boxShadow:`0 4px 16px ${s}66`,transition:`transform 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.04)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.yesLabel}),(0,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)(rm.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)(Tk,{size:l,orbColors:t})})]});return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(rm.div,{initial:{opacity:0},animate:{opacity:+!o},transition:{duration:.28},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`,animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u}):(0,m.jsx)(`div`,{style:{animation:o?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:``},children:u})]})}function Dk({copy:e,orbColors:t,primaryColor:n,onVoice:r,onText:i,onClose:a,isMobile:o,isClosing:s}){let c=n||yk.green,l=xk(c);return(0,m.jsxs)(rm.div,{initial:{scale:50/350,borderRadius:`50%`},animate:s?{scale:50/350,opacity:0,borderRadius:`50%`}:{scale:1,borderRadius:`16px`,opacity:1},transition:{type:`spring`,stiffness:260,damping:26},style:{transformOrigin:o?`bottom center`:`bottom right`,background:`white`,width:o?`100%`:`350px`,height:`245px`,padding:`24px 40px 32px`,boxSizing:`border-box`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`space-between`,boxShadow:`0 20px 60px rgba(0,0,0,0.2)`,position:`relative`,overflow:`hidden`},children:[(0,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)(Tk,{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:c,color:l,fontWeight:400,fontSize:`16px`,border:`none`,cursor:`pointer`,transition:`transform 0.15s ease`,boxShadow:`0 4px 12px ${c}55`},onMouseEnter:e=>{e.currentTarget.style.transform=`scale(1.03)`},onMouseLeave:e=>{e.currentTarget.style.transform=`scale(1)`},children:e.voiceLabel}),(0,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 Ok({orbColors:e,onEnterChat:t,onEndChat:n,agentId:r,siteId:i,apiBaseUrl:a,historyRef:o,onMessageSync:s}){let[c,l]=(0,p.useState)(`idle`),[u,d]=(0,p.useState)(!1),[f,h]=(0,p.useState)(!1),g=(0,p.useRef)(null),_=(0,p.useRef)(``),v=(0,p.useRef)(async()=>{}),y=(0,p.useRef)(!1),b=(0,p.useRef)(!1),x=(0,p.useRef)(!1),S=(0,p.useRef)(!1),C=(0,p.useRef)(`minimized`),ee=(0,p.useRef)(null),te=(0,p.useCallback)((e=`minimized`)=>{C.current=e,S.current=!0,queueMicrotask(()=>{y.current||(y.current=!0,v.current?.())})},[o]),ne=(0,p.useCallback)(async e=>{S.current=!0;try{await g.current?.endSession?.()}catch{}if(g.current=null,l(`idle`),d(!1),y.current=!1,i)try{Ce(i)}catch{}typeof s==`function`&&await s(o.current),e?.()},[o,s,i]);return v.current=()=>ne(C.current===`chat`?t:n),(0,p.useEffect)(()=>{b.current=u},[u]),(0,p.useEffect)(()=>{let e=!1,n=null;return(async()=>{if(!r){l(`error`);return}try{if((await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e)return;o.current=[],_.current=``,y.current=!1,x.current=!1,S.current=!1,C.current=`minimized`;let t=vk(_k({siteId:i||null,apiBaseUrl:a||null,getLastUserVoiceText:()=>_.current,requestEndSession:()=>{te()}})),s=i?Se(i):null,c=!!s?.transcript,u={agentId:r,clientTools:t,connectionType:`websocket`};c&&(u.overrides={agent:{firstMessage:``}});let f=await dD.startSession({...u,onUnhandledClientToolCall:e=>console.error(`[FlowEngage] Unhandled tool:`,e?.tool_name),onModeChange:({mode:t})=>{e||l(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){if(n===`user`&&(_.current=r),o.current=[...o.current,{sender:n,message:r,timestamp:new Date().toISOString()}],i)try{let e=rO(o.current);e&&xe(i,e)}catch{}wk(n,r)&&te(`minimized`)}},onError:t=>{if(!e&&!S.current&&!x.current){x.current=!0,console.error(`[FlowEngageVoiceCall] session:error`,{message:t?.message,name:t?.name,raw:t});try{g.current?.setMicMuted?.(!0)}catch{}d(!0),l(`error`),te(`chat`)}},onDisconnect:()=>{if(!e&&!S.current&&!x.current){x.current=!0,console.warn(`[FlowEngageVoiceCall] session:disconnected`,{historyCount:o.current?.length||0,lastUserText:_.current||``,wasMuted:b.current});try{g.current?.setMicMuted?.(!0)}catch{}d(!0),te(`chat`)}}});if(e){f.endSession().catch(()=>{});return}n=f,g.current=f,l(`listening`);try{let e=typeof window<`u`?window.location.href:``,n=`[]`;try{n=await t.list_page_forms()}catch{}let r=c?`RESUMING PRIOR SESSION — DO NOT GREET. The visitor is continuing the same conversation after a page reload. Do not introduce yourself or re-state your capabilities. Wait silently until the visitor speaks; if you must speak first, briefly acknowledge where you left off in one short sentence.\nPrior transcript:\n${s.transcript}\n\n`:``;f.sendContextualUpdate(`${r}Page: ${e}. SiteId: ${i||`unknown`}. Forms: ${n}. Voice: call end_voice_session or say you are ending the session to stop.`)}catch{}}catch(n){e||(console.error(`[FlowEngage] startSession failed`,n),l(`error`),C.current=`chat`,window.setTimeout(()=>{e||t?.()},0))}})(),()=>{e=!0,S.current=!0,(n||g.current)?.endSession?.().catch(()=>{})}},[r,i,a,te]),(0,p.useEffect)(()=>{if(!f)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;ee.current&&!ee.current.contains(t)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[f]),(0,m.jsxs)(`div`,{ref:ee,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:[c===`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)(Tk,{size:72,voiceState:c,isMuted:u,orbColors:e})]}),c===`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{u?(await g.current.setMicMuted?.(!1),d(!1)):(await g.current.setMicMuted?.(!0),d(!0))}catch{}},title:u?`Unmute`:`Mute`,style:{width:`24px`,height:`24px`,borderRadius:`50%`,background:u?`#7f1d1d`:`#1f2937`,border:u?`1.5px solid #ef4444`:`1.5px solid #4b5563`,display:`flex`,alignItems:`center`,justifyContent:`center`,cursor:`pointer`,color:u?`#f87171`:`white`,transition:`all 0.2s ease`,boxShadow:`0 2px 8px rgba(0,0,0,0.4)`,padding:0,flexShrink:0},children:u?(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)(fD,{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)(bD,{size:16,color:`currentColor`})})]}),f&&(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),C.current=`chat`,ne(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)(xD,{}),`Enter Chat Mode`]}),(0,m.jsxs)(`button`,{onClick:()=>{h(!1),C.current=`minimized`,ne(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)(SD,{}),`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 kk({orbColors:e}){return(0,m.jsx)(`div`,{style:{flexShrink:0,width:`36px`,height:`36px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,m.jsx)(Tk,{size:36,orbColors:e})})}var Ak=()=>(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 jk({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:h,fallbackAgentName:g,input:_,setInput:v,onSubmit:y,isConversationEnded:b,isLoading:x,isRateLimited:S,rateLimitMessage:C,selectedFile:ee,onFileSelect:te,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,activeCallId:he,isCallMuted:ge,toggleCallMute:_e,endWebRTCCall:ve,formatCallDuration:ye,callDurationSeconds:be,isCallMinimized:xe,onExpand:Se,onCollapse:Ce,onStartVoice:we,onNewChat:Te,onEndConversation:Ee,showPoweredBy:De,getVisitorChatHistory:w,getVisitorChatThread:Oe,resumeChat:ke,isSessionRestoring:Ae,isClosing:je}){let Me=c.length>0,Ne=x||S||b,Pe=!!he,[Fe,Ie]=(0,p.useState)(!1),[Le,Re]=(0,p.useState)(!1),[ze,Be]=(0,p.useState)([]),[Ve,He]=(0,p.useState)(!1),[Ue,We]=(0,p.useState)(null),[Ge,Ke]=(0,p.useState)([]),qe=(0,p.useRef)(null),Je=async()=>{Ie(!1),Re(!0),He(!0),We(null);try{let e=await w();e?.data&&Be(e.data)}catch(e){console.error(e)}finally{He(!1)}},Ye=async e=>{Re(!1),ke?.(e.chatId)};return(0,p.useEffect)(()=>{if(!Fe)return;let e=e=>{let t=e.composedPath?.()?.[0]||e.target;qe.current&&!qe.current.contains(t)&&Ie(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[Fe]),(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:je?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.28s cubic-bezier(0.16,1,0.3,1)`}:{"--flowengage-primary":n,"--flowengage-accent":n,width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,background:r,borderRadius:`22px`,boxShadow:`0 24px 64px rgba(0,0,0,0.18), 0 4px 16px rgba(0,0,0,0.08)`,display:`flex`,flexDirection:`column`,overflow:`hidden`,position:`relative`,animation:je?`fe-orb-slide-down 0.28s cubic-bezier(0.16,1,0.3,1) forwards`:`fe-orb-slide-up 0.36s cubic-bezier(0.16,1,0.3,1)`},children:[(0,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)(`div`,{style:{display:`flex`,gap:`8px`,alignItems:`center`},children:(0,m.jsx)(`button`,{onClick:Ce,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)(Sk,{logo:i,style:{height:`34px`,width:`100%`,maxWidth:`96px`}}):(0,m.jsx)(`div`,{style:{width:`40px`,height:`40px`,flexShrink:0},children:(0,m.jsx)(Ck,{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:qe,children:[(0,m.jsx)(`button`,{type:`button`,onClick:()=>Ie(e=>!e),style:{width:`40px`,height:`40px`,background:`none`,border:`none`,cursor:`pointer`,color:`#6b7280`,display:`flex`,alignItems:`center`,justifyContent:`center`,padding:`4px`,borderRadius:`10px`,transition:`color 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.color=`#111827`},onMouseLeave:e=>{e.currentTarget.style.color=`#6b7280`},"aria-label":`Chat options`,children:(0,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`})]})}),Fe&&(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:()=>{Ie(!1),we?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,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:()=>{Ie(!1),Te?.()},style:{display:`flex`,alignItems:`center`,gap:`12px`,width:`100%`,padding:`14px 18px`,background:`none`,border:`none`,color:`white`,fontSize:`14px`,fontWeight:500,cursor:`pointer`,textAlign:`left`,transition:`background 0.15s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`rgba(255,255,255,0.08)`},onMouseLeave:e=>{e.currentTarget.style.background=`none`},children:[(0,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 5H5a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-7`}),(0,m.jsx)(`path`,{d:`M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z`})]}),`Start new conversation`]}),w&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,m.jsxs)(`button`,{type:`button`,onClick:Je,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.jsx)(`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 8v4l3 3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z`})}),`Chat history`]})]}),(0,m.jsx)(`div`,{style:{height:`1px`,background:`rgba(255,255,255,0.07)`,margin:`0 14px`}}),(0,m.jsxs)(`button`,{type:`button`,onClick:()=>{Ie(!1),Ce?.()},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)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,m.jsx)(`line`,{x1:`15`,y1:`9`,x2:`9`,y2:`15`}),(0,m.jsx)(`line`,{x1:`9`,y1:`9`,x2:`15`,y2:`15`})]}),`Close conversation`]})]})]})]}),(0,m.jsx)(zD,{webRTCError:de,micError:fe,setMicError:pe,dismissCallError:me,isRateLimited:S,rateLimitMessage:C}),xe&&(0,m.jsx)(nO,{agentName:f,agentHeadshot:h,fallbackAgentName:g,callDurationSeconds:be,isCallMuted:ge,formatCallDuration:ye,toggleCallMute:_e,endWebRTCCall:ve,onExpand:Se,primaryColor:n}),(0,m.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,minHeight:0,background:`transparent`,position:`relative`},children:[Le?(0,m.jsxs)(`div`,{style:{position:`absolute`,inset:0,background:`white`,zIndex:20,display:`flex`,flexDirection:`column`,animation:`fe-orb-fade-in 0.2s ease`},children:[(0,m.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,padding:`16px`,borderBottom:`1px solid #f3f4f6`,flexShrink:0},children:Ue?(0,m.jsxs)(`button`,{onClick:()=>We(null),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,m.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,m.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,m.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Back to List`})]}):(0,m.jsxs)(`button`,{onClick:()=>Re(!1),style:{background:`none`,border:`none`,cursor:`pointer`,display:`flex`,alignItems:`center`,color:`#6b7280`},children:[(0,m.jsx)(`svg`,{width:`20`,height:`20`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,m.jsx)(`polyline`,{points:`15 18 9 12 15 6`})}),(0,m.jsx)(`span`,{style:{marginLeft:`8px`,fontWeight:500,fontSize:`15px`},children:`Return to Chat`})]})}),(0,m.jsx)(`div`,{style:{flex:1,overflowY:`auto`,position:`relative`},children:Ve&&!Ue?(0,m.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#6b7280`,fontSize:`14px`},children:`Loading past conversations...`}):Ue?(0,m.jsxs)(`div`,{style:{padding:`20px 16px`},children:[Ge.length===0?(0,m.jsx)(`div`,{style:{color:`#9ca3af`,textAlign:`center`,marginTop:`20px`,fontSize:`14px`},children:`No messages`}):null,Ge.map((e,t)=>(0,m.jsx)(`div`,{style:{marginBottom:`16px`,display:`flex`,justifyContent:e.sender===`user`?`flex-end`:`flex-start`},children:(0,m.jsx)(`div`,{style:{maxWidth:`85%`,background:e.sender===`user`?n:`#f3f4f6`,color:e.sender===`user`?`white`:`#111827`,padding:`10px 14px`,borderRadius:`14px`,fontSize:`15px`,lineHeight:1.4,wordBreak:`break-word`},children:e.content})},e._id||t))]}):ze.length>0?(0,m.jsx)(`div`,{children:ze.map(e=>(0,m.jsxs)(`div`,{onClick:()=>Ye(e),style:{padding:`16px 20px`,borderBottom:`1px solid #f3f4f6`,cursor:`pointer`,transition:`background 0.15s ease`},onMouseEnter:e=>e.currentTarget.style.background=`#f9fafb`,onMouseLeave:e=>e.currentTarget.style.background=`white`,children:[(0,m.jsxs)(`div`,{style:{fontSize:`12px`,color:`#6b7280`,marginBottom:`6px`,fontWeight:500},children:[new Date(e.createdAt).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),` at `,new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})]}),(0,m.jsx)(`div`,{style:{fontSize:`14.5px`,color:`#111827`,opacity:.9,overflow:`hidden`,textOverflow:`ellipsis`,display:`-webkit-box`,WebkitLineClamp:2,WebkitBoxOrient:`vertical`,lineHeight:1.4},children:e.message||`Conversation`})]},e.chatId))}):(0,m.jsx)(`div`,{style:{padding:`40px 20px`,textAlign:`center`,color:`#9ca3af`,fontSize:`14px`},children:`No previous chats found.`})})]}):null,Me?(0,m.jsx)(LD,{chatHistory:c,isAiTyping:l,isLoading:x,isAgentTyping:u,setReplyContext:ue,TypingDots:Ak,primaryColor:n,agentHeadshot:h,agentDisplayName:f||g,botAvatarNode:(0,m.jsx)(kk,{orbColors:t})}):Ae?(0,m.jsxs)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,gap:`16px`},children:[(0,m.jsx)(`div`,{style:{width:`28px`,height:`28px`,border:`3px solid #f3f4f6`,borderTop:`3px solid ${n}`,borderRadius:`50%`,animation:`spin 1s linear infinite`},children:(0,m.jsx)(`style`,{children:`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`})}),(0,m.jsx)(`div`,{style:{color:`#6b7280`,fontSize:`14px`,fontWeight:500,animation:`fe-orb-fade-in 1s infinite alternate`},children:`Loading chat...`})]}):(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)(Tk,{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:ae?`6px 0 0`:`12px 0 0`},children:(0,m.jsx)(RD,{input:_,setInput:v,onSubmit:y,isConversationEnded:b,callUiActive:Pe,handleToggleVoice:we,showVoiceToggle:d===`agent`,activeScreen:d,inputDisabled:Ne,replyContext:le,clearReplyContext:()=>ue(null),onFileSelect:te,selectedFile:ee,onRemoveSelectedFile:ne,attachmentError:re,isUploadingAttachment:ie,requiresEmail:ae,emailInput:oe,setEmailInput:se,emailError:ce,inputPlaceholder:e.inputPlaceholder})}),(0,m.jsx)(`div`,{style:{flexShrink:0,textAlign:`center`,padding:`12px 20px 18px`,pointerEvents:`none`},children:De&&(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 Mk(){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:h,isRateLimited:g,rateLimitMessage:_,isConversationEnded:v,incomingCall:y,activeCallId:b,callConnectionState:x,callConnectedAt:S,isCallMuted:C,webRTCError:ee,language:te,historyRef:ne,onMessageSync:re,sendMessage:ie,uploadChatFile:se,openWidget:ce,captureVisitorEmail:le,setVoiceMode:ue,endConversation:de,startNewChat:fe,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,dismissCallError:_e,startTyping:ve,stopTyping:ye,updateTypingDraft:be,getVisitorChatHistory:xe,getVisitorChatThread:Se,resumeChat:Ce,isSessionRestoring:we}=bn();(0,p.useEffect)(()=>{try{Qn()}catch{}},[]);let Te=t?.widgetSettings||{},De=n?.widgetSettings||{},w={...Te.branding||{},...De.branding||{}},Oe={...Te.theme||{},...De.theme||{}},ke={...Te.features||{},...De.features||{}},Ae=ke.voice!==!1,je=Array.isArray(Oe.orbColors)&&Oe.orbColors.length>0?Oe.orbColors:null,Me=Oe.buttonColor||Oe.primaryColor||je?.[0]||`#3B82F6`,Ne=Oe.position||`bottom-right`,Pe=w.fallbackAgentName||`Agent`,Fe=bk(je??Oe.chatBgColors),Ie=w.logo||w.logoUrl||null,Le=te||`en`,Re=Te.recommendations?.[Le]||[],ze=(De.recommendations?.[Le]??Re).filter(e=>String(e?.label??``).trim()).map((e,t)=>({id:e.key||`qr-${t}`,label:e.label,message:e.label,text:e.label})),Be=Array.isArray(w.quickChatOptions)&&w.quickChatOptions.length>0?w.quickChatOptions:ze,Ve=w.hideWatermark===!0?!1:w.showPoweredBy!==!1,He=w.chatbotEnabled!==!1&&Oe.chatbotEnabled!==!1,Ue=Te.greetings?.[te]||De.greetings?.[te]||w.introGreeting||`Hello, I'm here to help you know more about OpenSense Labs.`,We={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:Ue,inputPlaceholder:w.inputPlaceholder||`Type your message`,analysingLabel:w.analysingLabel||`analysing...`},Ge=De.elevenLabsAgentId||t?.elevenLabsAgentId||null,Ke=t?.siteId||n?.siteId||null,qe=t?.apiBaseUrl||``,Je=(0,p.useMemo)(()=>s&&String(s).trim()||t?.ownerName&&String(t.ownerName).trim()||t?.websiteName&&String(t.websiteName).trim()||`Agent`,[s,t?.ownerName,t?.websiteName]),Ye=c&&String(c).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Xe=r.some(e=>e.sender===`user`),Ze=(0,p.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]),Qe=!l&&Xe&&Ze,$e=!!(De._dashboardLivePreview||Te._dashboardLivePreview),[T,E]=(0,p.useState)(()=>$e?`text_chat`:`entry_prompt`),[D,O]=(0,p.useState)(``),[et,tt]=(0,p.useState)(null),[nt,rt]=(0,p.useState)(l||``),[it,at]=(0,p.useState)(``),[ot,st]=(0,p.useState)(0),[ct,lt]=(0,p.useState)(null),[ut,dt]=(0,p.useState)(null),[ft,pt]=(0,p.useState)(``),[mt,ht]=(0,p.useState)(!1),[gt,_t]=(0,p.useState)(!1),[vt,yt]=(0,p.useState)(!1),bt=(0,p.useRef)(null),xt=(0,p.useRef)(!1);(0,p.useLayoutEffect)(()=>{if(!(e!==`ready`||xt.current)){if(xt.current=!0,Ae&&Ee()){ce?.({notifyChatInitiated:!0}),ue?.(!0),E(`voice_mode`);return}try{let{shouldResumeVoice:e}=f.c();if(e&&Ae){ce?.({notifyChatInitiated:!0}),ue?.(!0),E(`voice_mode`);return}}catch{}if(ae(Ke)||!Ae){E(`minimized_orb`);return}}},[e,r]);let[St,Ct]=(0,p.useState)(()=>typeof window<`u`&&window.matchMedia(`(max-width: 640px)`).matches);(0,p.useEffect)(()=>{let e=window.matchMedia(`(max-width: 640px)`),t=e=>Ct(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,p.useEffect)(()=>{rt(l||``),l&&at(``)},[l]);let wt=(0,p.useCallback)(()=>{dt(null),pt(``)},[]),Tt=(0,p.useCallback)(e=>{let t=MD(e);if(t){dt(null),pt(t);return}dt(e),pt(``)},[]);(0,p.useEffect)(()=>{if(!S||x!==`connected`){st(0);return}let e=()=>{let e=new Date(S).getTime();isNaN(e)||st(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[S,x]);let Et=(0,p.useCallback)(()=>{E(`call_screen`),_t(!1)},[]),Dt=(0,p.useCallback)(()=>{E(`text_chat`),_t(!0)},[]);(0,p.useEffect)(()=>{let e=y?.callId||b||null;if(!e){bt.current=null;return}if(y?.callId||x===`connecting`||x===`connected`){if(T===`minimized_orb`&&gt&&b&&!y?.callId){bt.current=e;return}!(!i||T===`minimized_orb`||T===`voice_mode`)&&bt.current===e||(console.log(`[FlowEngageWidget] forcing call UI to front`,{forcedKey:e,isOpen:i,surface:T,hasIncomingCall:!!y?.callId,activeCallId:b,callConnectionState:x}),bt.current=e,T===`voice_mode`&&ue?.(!1),ce?.(),Et())}},[b,x,Et,y?.callId,i,ce,ue,T]),(0,p.useEffect)(()=>{!y&&!b&&T===`call_screen`&&E(`text_chat`)},[y,b,T]),(0,p.useEffect)(()=>{!b&&gt&&_t(!1)},[b,gt]),(0,p.useEffect)(()=>{if(!o||v){be?.(``),ye?.();return}if(!D.trim()||ut){be?.(``);let e=window.setTimeout(()=>ye?.(),100);return()=>window.clearTimeout(e)}ve?.();let e=window.setTimeout(()=>be?.(D),120),t=window.setTimeout(()=>ye?.(),1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[D,ut,o,v,ve,ye,be]);let Ot=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,kt=async e=>{if(e.preventDefault(),v)return;if(Qe){let e=nt.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){at(`Please enter a valid email so we can continue helping you.`);return}await le(e),at(``);return}let t=Ot(et);if(!D.trim()&&!ut)return;if(ut){try{ht(!0),pt(``);let e=await se(ut),n=e?.data||e,r=D.trim()||`Shared file: ${PD(ut)}`;O(``),tt(null),wt(),await ie(r,``,t,{type:`file`,metadata:{fileUrl:n?.fileUrl,fileName:n?.fileName||ut.name,fileType:n?.fileType||ut.type,fileSize:n?.fileSize||ut.size}})}catch(e){pt(e?.message||`Failed to upload the selected file.`)}finally{ht(!1)}return}let n=D.trim();O(``),tt(null),await ie(n,``,t)},At=e=>{let t=Math.floor(e/60);return`${String(t).padStart(2,`0`)}:${String(e%60).padStart(2,`0`)}`},jt=(0,p.useCallback)(async e=>{if(v||h)return;let t=e.message||e.label||e.text||``;t.trim()&&await ie(t.trim(),``)},[v,h,ie]),Mt=St&&T===`entry_prompt`?{inset:0}:St&&T===`text_chat`?{left:0,right:0,bottom:0}:St&&T===`call_screen`?{left:0,right:0,bottom:0,height:`90dvh`,overflow:`hidden`,borderRadius:`16px 16px 0 0`}:St&&T===`connection_modal`?{left:`28px`,right:`12px`,bottom:`12px`}:T===`call_screen`?{width:`min(350px, calc(100vw - 40px))`,height:`min(640px, calc(100vh - 120px))`,borderRadius:`22px`,overflow:`hidden`,...Ne===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`}}:Ne===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Nt=(0,p.useCallback)(()=>{T!==`minimized_orb`&&(yt(!0),setTimeout(()=>{E(`minimized_orb`),yt(!1)},280))},[T]),Pt=()=>E(`connection_modal`),Ft=()=>{ce({notifyChatInitiated:!0}),ue?.(!0),E(`voice_mode`)},It=()=>{ce({notifyChatInitiated:!0}),ue?.(!1),E(`text_chat`)},Lt=()=>{ue?.(!1),Nt()};return e!==`ready`||!He||ke.chat===!1?null:(0,m.jsxs)(`div`,{className:`flowengage-widget-root`,style:{position:`fixed`,zIndex:999999,...Mt},onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),children:[T===`entry_prompt`&&(0,m.jsx)(Ek,{copy:We,orbColors:je,primaryColor:Me,onYes:()=>{oe(Ke),Ft()},onLater:()=>{oe(Ke),Nt()},isMobile:St,isClosing:vt}),T===`minimized_orb`&&(0,m.jsxs)(rm.div,{layoutId:`fe-main-orb`,initial:{scale:.4,opacity:0},animate:{scale:1,opacity:1},transition:{type:`spring`,stiffness:280,damping:18},style:{transformOrigin:`bottom right`,display:`inline-flex`,flexDirection:`column`,alignItems:Ne===`bottom-left`?`flex-start`:`flex-end`,gap:`10px`},children:[b&&gt&&(0,m.jsxs)(`button`,{type:`button`,onClick:Et,style:{maxWidth:St?`220px`:`240px`,padding:`10px 14px`,borderRadius:`18px`,border:`1px solid rgba(255,255,255,0.7)`,background:`rgba(255,255,255,0.94)`,backdropFilter:`blur(18px)`,WebkitBackdropFilter:`blur(18px)`,boxShadow:`0 10px 26px rgba(15,23,42,0.14)`,display:`flex`,alignItems:`center`,gap:`10px`,cursor:`pointer`,textAlign:`left`},children:[(0,m.jsx)(`span`,{style:{width:`9px`,height:`9px`,borderRadius:`50%`,background:`#22c55e`,boxShadow:`0 0 0 4px rgba(34,197,94,0.16)`,flexShrink:0}}),(0,m.jsxs)(`span`,{style:{minWidth:0},children:[(0,m.jsx)(`span`,{style:{display:`block`,fontSize:`12px`,fontWeight:700,color:`#111827`,lineHeight:1.2},children:x===`connected`?`Call in progress`:`Call is active`}),(0,m.jsx)(`span`,{style:{display:`block`,fontSize:`11px`,color:`#6b7280`,lineHeight:1.3,marginTop:`2px`,whiteSpace:`nowrap`},children:x===`connected`?`${At(ot)} with ${Je}`:`Tap to return to ${Je}`})]})]}),(0,m.jsx)(Tk,{size:50,orbColors:je,onClick:b&&gt?Et:Ae?Pt:It})]}),T===`connection_modal`&&(0,m.jsx)(Dk,{copy:We,orbColors:je,primaryColor:Me,onVoice:Ft,onText:It,onClose:Nt,isMobile:St,isClosing:vt}),T===`voice_mode`&&(0,m.jsx)(Ok,{orbColors:je,onEnterChat:It,onEndChat:Lt,agentId:Ge,siteId:Ke,apiBaseUrl:qe,historyRef:ne,onMessageSync:re},`voice`),T===`call_screen`&&(0,m.jsx)(tO,{incomingCall:y,activeCallId:b,callConnectionState:x,callDurationSeconds:ot,isCallMuted:C,agentName:Je,agentHeadshot:Ye,fallbackAgentName:Pe,acceptCall:pe,rejectCall:me,endWebRTCCall:he,toggleCallMute:ge,formatCallDuration:At,onMinimize:Dt,primaryColor:Me,orbColors:je,chatHistory:r}),T===`text_chat`&&(0,m.jsx)(jk,{isClosing:vt,copy:We,orbColors:je,primaryColor:Me,chatBgGradient:Fe,logo:Ie,quickChatOptions:Be,onQuickChatSelect:jt,isMobile:St,chatHistory:r,isAiTyping:d,isAgentTyping:u,activeScreen:a,agentName:Je,agentHeadshot:Ye,fallbackAgentName:Pe,input:D,setInput:O,onSubmit:kt,isConversationEnded:v,isLoading:h,isRateLimited:g,rateLimitMessage:_,selectedFile:ut,onFileSelect:Tt,onRemoveSelectedFile:wt,attachmentError:ft,isUploadingAttachment:mt,requiresEmail:Qe,emailInput:nt,setEmailInput:rt,emailError:it,replyContext:et,setReplyContext:tt,webRTCError:ee,micError:ct,setMicError:lt,dismissCallError:_e,activeCallId:b,isCallMuted:C,toggleCallMute:ge,endWebRTCCall:he,formatCallDuration:At,callDurationSeconds:ot,onCollapse:Nt,onStartVoice:Ft,onNewChat:fe,onEndConversation:de,onMinimize:Dt,onExpand:Et,isCallMinimized:gt&&!!b,showPoweredBy:Ve,getVisitorChatHistory:xe,getVisitorChatThread:Se,resumeChat:Ce,isSessionRestoring:we}),(0,m.jsx)(`style`,{children:`
596
596
  /* Force any SVG (or img) inside LogoSlot to fill the container height
597
597
  regardless of whether the component forwards its style prop. */
598
598
  .fe-logo-slot svg,
@@ -30187,7 +30187,8 @@ function Qk({ orbColors: e, onEnterChat: t, onEndChat: n, agentId: r, siteId: i,
30187
30187
  }
30188
30188
  })), s = i ? Be(i) : null, c = !!s?.transcript, u = {
30189
30189
  agentId: r,
30190
- clientTools: t
30190
+ clientTools: t,
30191
+ connectionType: "websocket"
30191
30192
  };
30192
30193
  c && (u.overrides = { agent: { firstMessage: "" } });
30193
30194
  let f = await FD.startSession({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowengage/react-chatbot",
3
- "version": "3.0.8",
3
+ "version": "3.0.9",
4
4
  "description": "Embeddable AI chat widget for React — powered by FlowEngage. Drop it in with a single siteId.",
5
5
  "keywords": [
6
6
  "chatbot",