@flowengage/react-chatbot 1.2.5 → 1.2.6

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.
@@ -30,7 +30,7 @@ Error generating stack: `+e.message+`
30
30
  box-shadow: none !important;
31
31
  transition: outline-color 0.25s ease, box-shadow 0.25s ease !important;
32
32
  }
33
- `,document.head.appendChild(e)};function ln(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`)).filter(e=>!nn(e));for(let e of i)if(e.textContent.replace(/\s+/g,` `).toLowerCase().trim()===n)return e;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=n.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!nn(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(nn(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(nn(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(nn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!nn(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(nn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function un(){return document.querySelector(`[itemprop='articleBody'], .article-body, .post-content, .entry-content, .field--name-body, .field--body, .node__content, article .content, .prose, article .prose`)||document.querySelector(`main article, main, [role='main'], article`)||document.body}var dn=new Set(`the.and.for.are.but.not.you.all.can.her.was.one.our.out.day.get.has.him.his.how.its.may.new.now.old.see.two.way.who.did.let.put.say.she.too.use.has.have.this.that.with.from.they.will.your.about.into.than.then.some.very.when.come.here.just.like.also.back.after.over.such.take.only.know.think.each.made.look.more.most.other.well`.split(`.`));function fn(e){return String(e||``).toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>0)}function pn(e,t){let n=fn(e).slice(-Math.min(t,28)),r=n.filter(e=>e.length>2&&!dn.has(e));return r.length>=2?r:n.filter(e=>e.length>2).slice(-12)}function mn(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`h1, h2, h3, h4, h5, h6, p, li, blockquote`,`main h2, main h3, main h4, article h2, article h3, article h4`,`section h2, section h3, section h4`].join(`, `)),i=null,a=0;for(let e of r){if(nn(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<3||n.length>6e3)continue;let r=0;for(let e of t)n.includes(e)&&r++;let o=r/t.length;if(o<.2)continue;let s=o,c=e.tagName;(c===`H2`||c===`H3`||c===`H4`)&&(s*=1.35),(c===`P`||c===`BLOCKQUOTE`)&&(s*=1.15),c?.startsWith(`H`)&&n.length<80&&(s*=1.2),n.length>400&&(s*=.65),s>a&&(a=s,i=e)}let o=n?t.length<=1?.62:.5:t.length<=1?.55:.35;return a>=o?i:null}function hn(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`main [role='group']`,`[class*='card']`,`[class*='Card']`,`[class*='column']`,`[class*='grid'] > div`,`[class*='grid'] > article`,`[data-section]`].join(`, `)),i=null,a=0;for(let e of r){if(nn(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<10||n.length>9e3)continue;let r=0;for(let e of t)e.length>1&&n.includes(e)&&r++;let o=r/t.length;if(o<.12)continue;let s=o,c=e.tagName;(c===`ARTICLE`||c===`SECTION`)&&(s*=1.05),n.length<900&&(s*=1.18),n.length<420&&(s*=1.12),n.length>2600?s*=.28:n.length>1400&&(s*=.45);try{e.querySelectorAll(`:scope > [role='group'], :scope > article, :scope > section`).length>=3&&n.length>1200&&(s*=.3)}catch{}s>a&&(a=s,i=e)}let o=n?t.length<=1?.48:.34:t.length<=1?.38:.2;return a>=o?i:null}function gn(e){return/^H[1-6]$/i.test(e?.tagName||``)}function _n(e,t,n=!1){if(!e||!t)return null;let r=t.replace(/\s+/g,` `).trim();if(r.length<14)return null;let i=n?.34:.24,a=r.toLowerCase(),o=pn(r,24);if(o.length<3&&(o=a.replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2).slice(-18)),o.length<3)return null;let s=e.querySelectorAll(`p, blockquote`),c=null,l=0;for(let e of s){if(nn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase();if(t.length<24)continue;let n=0;for(let e of o)t.includes(e)&&n++;let r=n/o.length,s=0;for(let e=Math.min(90,a.length);e>=22;e-=6){let n=a.slice(-e).trim();if(n.length>=22&&t.includes(n)){s=.28;break}}let u=r+s;u>l&&r>=i&&(l=u,c=e)}return c}function vn(e,t={}){if(typeof document>`u`||!e||!String(e).trim())return null;let n=t.strict===!0,r=String(e).trim(),i=r.length>450?r.slice(-450).trim():r,a=un(),o=pn(r,26);if(o.length>=1&&(o.length>=2||o.length===1&&o[0].length>=3)){let e=hn(a,o,{strict:n});if(e)return e}if(r.length>=(n?55:42)){let e=_n(a,i,n);if(e)return e}if((!n||o.length>=3||o.length===2&&o.every(e=>e.length>=5))&&(o.length>=2||o.length===1&&o[0].length>=5)){let e=mn(a,o,{strict:n});if(e)return e}let s=i.split(/(?<=[.!?])\s+/).filter(e=>e.trim().length>0),c=s[s.length-1]||i,l=c.toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2),u=[];c.length>=10&&(u.push(c.slice(-220).trim()),c.length>220&&u.push(c.slice(0,120).trim()));for(let e=4;e<=Math.min(10,l.length);e++)u.push(l.slice(-e).join(` `));for(let e=Math.min(14,l.length);e>=11;e--)u.push(l.slice(-e).join(` `));for(let e=Math.min(8,l.length);e>=3;e--)u.push(l.slice(-e).join(` `));let d=n?14:6,f=new Set;for(let e of u){let t=e.trim();if(t.length<d||f.has(t))continue;f.add(t);let n=ln(null,t);if(n&&!nn(n)){if(gn(n)&&r.length>140){let e=(a.querySelector?.(`[itemprop='articleBody'], .article-body, .post-content, .entry-content`)||a).querySelectorAll?.(`p, blockquote`)||[];for(let n of e)if(!nn(n)&&n.textContent.toLowerCase().includes(t.toLowerCase().slice(0,Math.min(48,t.length))))return n}return n}}let p=o.length>=3?o:l.slice(-22);if(p.length===0)return null;let m=null,h=-1,g=a.querySelectorAll(`h1, h2, h3, h4, h5, h6, p, li, blockquote, article`);for(let e of g){if(nn(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], footer`))continue}catch{}let t=e.textContent.toLowerCase();if(t.length<12)continue;let i=0;for(let e of p)e.length>2&&t.includes(e)&&i++;let a=i/p.length,o=e.tagName;(o===`P`||o===`BLOCKQUOTE`||o===`LI`)&&(a*=1.22),gn(e)&&(r.length>110?a*=.48:a*=.92),o===`ARTICLE`&&r.length>80&&(a*=.55),a>h&&a>=(n?.42:.28)&&(h=a,m=e)}return m}function yn(e){if(!e||typeof document>`u`)return null;try{if(nn(e))return e;let t=e.closest?.([`[role='group']`,`[class*='card']`,`[class*='Card']`,`[data-section]`,`[class*='grid'] > div`,`[class*='grid'] > article`].join(`, `)),n=t?.textContent?.replace(/\s+/g,` `)||``;if(t&&!nn(t)&&n.length>20&&n.length<=5200)return t;let r=e.closest?.(`p, li, blockquote, td, th, dd, figcaption, pre`);if(r&&!nn(r))return r;let i=e.closest?.(`section`),a=i?.textContent?.replace(/\s+/g,` `)||``;return i&&a.length>48&&a.length<=4e3&&!nn(i)?i:e}catch{return e}}function bn(e){if(!e||typeof e.getBoundingClientRect!=`function`)return!0;try{let t=e.getBoundingClientRect(),n=window.innerHeight||800;if(t.bottom<=72||t.top>=n-72)return!0;let r=Math.max(0,t.top),i=Math.min(n,t.bottom),a=Math.max(0,i-r),o=Math.min(120,Math.max(40,t.height*.28));return t.height>24&&a<o}catch{return!0}}function xn(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;cn();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function Sn(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`))}function Cn(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function wn(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function Tn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?wn(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}function En(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(an,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function Dn(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n}=t;try{let t=Cn(e),r=new URL(t,window.location.origin);if(rn(`input:`,e,`→ normalized:`,t,`href:`,r.href),r.hash&&r.pathname===window.location.pathname){let e=r.hash.slice(1),t=document.getElementById(e);if(t)return rn(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)return rn(`branch: already on page (no nav)`),!1;let i=r.pathname+r.search+r.hash,a=window.next?.router;if(a?.push)return rn(`branch: Next.js Pages router.push`,i),new Promise(e=>{let t=()=>{a.events?.off(`routeChangeComplete`,t),e(!0)};a.events?.on(`routeChangeComplete`,t),a.push(i),setTimeout(t,5e3)});let o=window.__NEXT_ROUTER__;return o?.push?(rn(`branch: __NEXT_ROUTER__.push`,i),o.push(i),!0):(n?(En(n),rn(`branch: location.assign (full navigation, section stored):`,n)):rn(`branch: location.assign (full navigation)`,r.href),window.location.assign(r.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&En(n);try{window.location.href=Cn(e)}catch{window.location.href=e}return!0}}var On=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),A=o(((e,t)=>{t.exports=On()}))(),kn=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request>[\s\S]*?<\/human_assistance_request>/gi,``).replace(/<human_assistance_request>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),An=(e=[])=>e.map(e=>({...e,message:kn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),jn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,Mn=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},Nn=e=>{if(!e)return null;let t=typeof e==`object`?e:{candidate:e};return{hasCandidate:!!t.candidate,sdpMid:t.sdpMid??null,sdpMLineIndex:t.sdpMLineIndex??null,candidatePreview:typeof t.candidate==`string`?t.candidate.slice(0,80):null}},Pn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function Fn({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,v.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,v.useMemo)(()=>Pn([i?.widgetSettings?.branding?.fallbackAgentName,i?.widgetSettings?.branding?.headerName],`Agent`),[i]),[o,s]=(0,v.useState)(`booting`),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(null),[f,p]=(0,v.useState)(``),[m,h]=(0,v.useState)([]),[g,_]=(0,v.useState)(ae().isOpen),[y,x]=(0,v.useState)(ae().activeScreen),[ee,C]=(0,v.useState)(ae().isHumanHandled),[re,le]=(0,v.useState)(ae().agentName),[ue,T]=(0,v.useState)(ae().agentHeadshot),[fe,pe]=(0,v.useState)(()=>se(i?.siteId)),[me,he]=(0,v.useState)(!1),[ge,E]=(0,v.useState)(!1),[_e,ve]=(0,v.useState)(`idle`),[ye,be]=(0,v.useState)(!1),[xe,Se]=(0,v.useState)(!1),[Ce,we]=(0,v.useState)(``),[Te,Ee]=(0,v.useState)(!1),[De,Oe]=(0,v.useState)(!1),[D,ke]=(0,v.useState)(null),[Ae,je]=(0,v.useState)(null),[Me,Ne]=(0,v.useState)(`idle`),[Pe,Fe]=(0,v.useState)(null),[Ie,Le]=(0,v.useState)(!1),[Re,ze]=(0,v.useState)(``),Be=(0,v.useRef)(null),Ve=(0,v.useRef)(null),O=(0,v.useRef)(``),He=(0,v.useRef)(null),Ue=(0,v.useRef)(null),We=(0,v.useRef)(null),Ge=(0,v.useRef)(null),Ke=(0,v.useRef)(null),qe=(0,v.useRef)([]),Je=(0,v.useRef)(null),Ye=(0,v.useRef)(null),Xe=(0,v.useRef)(!1),Ze=(0,v.useRef)(!1),Qe=(0,v.useRef)(``),$e=(0,v.useRef)(re),et=(0,v.useRef)([]),tt=(0,v.useRef)(!1),nt=(0,v.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),rt=(0,v.useMemo)(()=>{let e=u?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:S},[i,u]);(0,v.useEffect)(()=>{He.current=D},[D]),(0,v.useEffect)(()=>{$e.current=re},[re]);let it=()=>{ze(``)},at=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return pe(t),ce(t,i?.siteId),t};(0,v.useEffect)(()=>{let e=i?.siteId;e&&pe(se(e))},[i?.siteId]);let ot=()=>{Ue.current&&=(Ue.current.close(),null),We.current&&=(We.current.getTracks().forEach(e=>e.stop()),null),Ge.current&&=(Ge.current.srcObject=null,Ge.current.remove(),null),Ke.current=null,qe.current=[],Je.current=null,Ye.current=null,Xe.current=!1,Le(!1),ke(null),je(null),Ne(`idle`),Fe(null)},st=(e=new Date().toISOString())=>{let t=Be.current,n=Je.current||Ke.current?.callId;if(!t?.connected||!n||Xe.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:O.current,socketConnected:!!t?.connected,alreadyReported:Xe.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:O.current,connectedAt:e}),Xe.current=!0,t.emit(`call:connected`,{callId:n,chatId:O.current,connectedAt:e})},ct=(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=He.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),ke(null),t||n){Je.current=e.callId,je(e.callId),Ne(e=>e===`connected`?e:`connecting`),_(!0);return}Ne(`idle`)}},lt=(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=He.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){ot();return}Ye.current=null,Ke.current=null,qe.current=[],ke(null),Ne(`idle`)}},ut=async(e={})=>{let t=Ue.current,n=Be.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:O.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ke.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:O.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),qe.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:O.current,queuedCount:qe.current.length});for(let e of qe.current)await t.addIceCandidate(new RTCIceCandidate(e));qe.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:O.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:O.current})};(0,v.useEffect)(()=>{oe({isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:re,agentHeadshot:ue})},[g,y,ee,re,ue]),(0,v.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=b(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await de(t);if(!e)return;let o=ie();O.current=o;let c=w({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});Ve.current=c,d({...n,apiBaseUrl:t.apiBaseUrl}),p(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Zt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});Be.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),ve(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),ve(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:O.current}),E(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:O.current}),E(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:kn(t.message)};E(!1),he(!1),h(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),l.on(`conversationStarted`,e=>{console.log(`[FlowEngageProvider] conversationStarted`,e),e?.message&&h(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`message:new`,e=>{let t=e.message||e,n={...t,message:kn(t.message)};E(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&he(!1),h(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(C(!0),x(`agent`),le(Pn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&T(n.sender_headshot),_(!0))}),l.on(`agent:joined`,e=>{let t=Pn([e.agent?.name,e.agentName],a);C(!0),x(`agent`),le(t),T(e.agent?.headshot||null),_(!0),h(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentJoined`,e=>{let t=Pn([e.agent?.name,e.agentName],a);C(!0),x(`agent`),le(t),T(e.agent?.headshot||null),_(!0),h(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agent:left`,(e={})=>{let t=Pn([e.agent?.name,e.agentName,$e.current],a);C(!1),x(`ai`),h(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,(e={})=>{let t=Pn([e.agent?.name,e.agentName,$e.current],a);C(!1),x(`ai`),h(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{Oe(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;h(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{h(An(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&he(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&he(!1)}),l.on(`call:incoming`,(e={})=>{let t=Pn([e.agentName,e.ownerName,e.agent?.name,re],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:O.current,agentName:t}),it(),Xe.current=!1,ke({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),le(e=>Pn([t,e],a)),Ne(`incoming`),Fe(null),_(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||O.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ke.current=e;try{await ut(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),l.on(`call:ice-candidate-from-agent`,async(e={})=>{if(!e.candidate){console.log(`[FlowEngageProvider] skipping agent ICE candidate`,{callId:e.callId,chatId:e.chatId||O.current,hasPeerConnection:!!Ue.current,hasCandidate:!!e.candidate});return}try{let t=Mn(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||O.current,candidate:Nn(t),hasRemoteDescription:!!Ue.current?.remoteDescription}),!Ue.current||!Ue.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||O.current,queueSize:qe.current.length+1}),qe.current.push(t);return}await Ue.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{it(),ot()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||O.current}),ct(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||O.current}),ct(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),lt(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),lt(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),lt(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=He.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||O.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(ke(null),Ne(`idle`));return}Xe.current=!0,Ye.current=null,Je.current=e.callId,je(e.callId),ke(null),Ne(`connected`),Fe(e.connectedAt||new Date().toISOString()),_(!0)}),l.on(`call:unavailable`,(e={})=>{ot(),ze(jn(e,`This visitor is not available for a call right now.`)),_(!0)}),l.on(`call:error`,(e={})=>{ot(),ze(jn(e,`We couldn't connect the call right now.`)),_(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await Tn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}Dn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=ln(null,t);e&&xn(e)},e?300:150)})}}),l.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;console.log(`[FlowEngageProvider] visitor:highlight`,{sectionId:e,sectionText:t});let n=ln(e||null,t||null);n&&xn(n)}),l.on(`visitor:clear_highlight`,()=>{Sn()}),nt.current=Qt({socket:l,chatId:o}),console.log(`[FlowEngageProvider] tracking started`,{chatId:o});let u=await c.loadHistory(o,r);if(console.log(`[FlowEngageProvider] history loaded`,u),!e||(h(An(u.chat_history||[])),C(!!u.is_human_handled),x(u.is_human_handled?`agent`:y),await new Promise(e=>setTimeout(e,500)),!e))return;s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),l(t),s(`error`)}})(),()=>{e=!1,nt.current?.cleanup?.(),ot(),Be.current?.disconnect()}},[i,r]),(0,v.useEffect)(()=>()=>{if(Te&&!tt.current&&et.current.length>0){let e=O.current,t=et.current,n=Ve.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),tt.current=!0)}},[Te,u]),(0,v.useEffect)(()=>{if(!Ve.current||!f||o!==`ready`||ee)return;let e=window.setInterval(async()=>{try{let e=await Ve.current.checkHumanHandled(f);C(!!e.is_human_handled),e.is_human_handled&&(x(`agent`),e.agent_info?.name&&le(e.agent_info.name),e.agent_info?.headshot&&T(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[f,o,ee]);let dt=async()=>{if(!(!D?.callId||!Ve.current||!Be.current||!f)){it(),Ye.current=D.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:D?.callId,chatId:f,socketConnected:!!Be.current?.connected,hasPendingOffer:!!Ke.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:D.callId,chatId:f,trackCount:e.getTracks().length}),We.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Ue.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:D.callId,chatId:f,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Ne(`connected`),Fe(t=>t||e),st(e);return}e===`connecting`&&Ne(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:D.callId,chatId:f,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Ne(`connected`),Fe(t=>t||e),st(e);return}(e===`checking`||e===`new`)&&Ne(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!Be.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:D.callId,chatId:f,hasCandidate:!!e.candidate,socketConnected:!!Be.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:D.callId,chatId:f,candidate:Nn(e.candidate)}),Be.current.emit(`call:ice-candidate`,{callId:D.callId,candidate:e.candidate,chatId:f,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:D.callId,chatId:f,streamCount:e.streams?.length||0}),!Ge.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Ge.current=e,document.body.appendChild(e)}Ge.current.srcObject=e.streams[0]};let n=Ke.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||D.callId,chatId:f}),await ut({...n,callId:n.callId||D.callId})),await Ve.current.acceptCall(D.callId,f),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:D.callId,chatId:f}),Je.current=D.callId,je(D.callId),Ne(`connecting`),ke(null),_(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),Ye.current=null,ot(),e?.status===404||e?.status===409||e?.status===422){ze(jn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await Ve.current.rejectCall(D.callId,f)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}ze(`Microphone access was denied. Please allow microphone access to accept the call.`);return}ze(`We couldn't connect the call right now. Please try again.`)}}},ft=async()=>{if(!D?.callId||!Ve.current||!f){ot();return}it();try{await Ve.current.rejectCall(D.callId,f)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),ze(jn(e,`We couldn't decline the call cleanly.`))}finally{ot()}},pt=(0,v.useRef)(ft);pt.current=ft,(0,v.useEffect)(()=>{if(!D?.callId||Ae)return;let e=D.callId,t=window.setTimeout(()=>{He.current?.callId===e&&pt.current()},ne);return()=>window.clearTimeout(t)},[D?.callId,Ae]);let mt=async()=>{if(!Ae||!Ve.current||!f){ot();return}it();try{await Ve.current.endWebRTCCall(Ae,f)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),ze(jn(e,`The call ended locally, but the server could not be updated.`))}finally{ot()}},ht=()=>{let e=We.current?.getAudioTracks?.()||[],t=Ue.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0){console.warn(`[FlowEngageProvider] no local audio tracks available for mute`);return}let r=!Ie;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),Le(r)},gt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(_(!0),!(!t||!Ve.current||!f||typeof window>`u`)){try{await Ve.current.trackVisitor({chatId:f,currentPagePath:window.location.pathname||`/`})}catch{}try{await Ve.current.updateChatStatus(f,`open`)}catch{}}},_t=async e=>{let t=at(e);if(!t||!Ve.current||!O.current)return t;try{await Ve.current.trackVisitor({chatId:O.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},vt=()=>{if(!f||!Be.current?.connected||Ze.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:f,socketConnected:!!Be.current?.connected,alreadyTyping:Ze.current});return}Ze.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:f,sender:`user`}),Be.current.emit(`typing:start`,{chatId:f,sender:`user`})},yt=()=>{if(!f||!Be.current?.connected||!Ze.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:f,socketConnected:!!Be.current?.connected,wasTyping:Ze.current});return}Ze.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:f,sender:`user`}),Be.current.emit(`typing:stop`,{chatId:f,sender:`user`})},bt=(e=``)=>{let t=typeof e==`string`?e:``;if(!f||!Be.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:f,socketConnected:!!Be.current?.connected,textLength:t.length});return}Qe.current!==t&&(Qe.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:f,sender:`user`,textLength:t.length}),Be.current.emit(`typing:update`,{chatId:f,sender:`user`,text:t}))},xt=async(e,t=``,n=null)=>{if(!e.trim()||!Ve.current||!f||o!==`ready`||De)return;yt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(h(e=>[...e,a]),ee&&Be.current?.connected){Be.current.emit(`customer:message`,{chatId:f,content:e,sender:`user`,email:fe||void 0,...n||{}});return}be(!0);try{let i=await Ve.current.sendAiMessage(f,e,r,t,{...n||{},...fe?{email:fe}:{}});h(An(i.chat_history||[])),C(!!i.is_human_handled),x(i.is_human_handled?`agent`:`ai`),E(!1),await Ve.current.updateChatStatus(f,`messageSent`)}catch(e){h(e=>e.filter(e=>e.id!==i)),E(!1),e.status===429?(Se(!0),we(e.message),window.setTimeout(()=>{Se(!1),we(``)},te)):l(e)}finally{be(!1)}},St=async e=>{if(!(!Ve.current||!f)){try{let t=e?`voice`:`text`;await Ve.current.setChatMode(f,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}Ee(e),e&&(tt.current=!1)}},Ct=async e=>{if(!tt.current){if(tt.current=!0,!Ve.current||!f||!e?.length){Ee(!1);return}try{let t=await Ve.current.syncVoice(f,e);if(t?.chat_history?.length)h(An(t.chat_history));else if(t?.success)try{let e=await Ve.current.loadHistory(f,r);e?.chat_history?.length&&h(An(e.chat_history))}catch{}}catch{}finally{Ee(!1)}}},wt=async()=>{if(!(!Ve.current||!f)){Te&&!tt.current&&et.current.length>0&&await Ct(et.current);try{await Ve.current.endConversation(f)}catch{try{await Ve.current.updateChatStatus(f,`ended`)}catch{}}Oe(!0),h(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,v.useEffect)(()=>{if(Me!==`connected`||!Ae||!f||!Pe||!rt)return;let e=new Date(Pe).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,rt*1e3-t),r=window.setTimeout(()=>{ze(`The call ended because it reached the time limit.`),mt()},n);return()=>window.clearTimeout(r)},[Ae,Pe,Me,f,mt,rt]),(0,v.useEffect)(()=>{let e=()=>{let e=O.current,t=Ve.current;if(!t||!e)return;if(Je.current){t.beaconEndWebRTCCall(Je.current,e);return}let n=Ye.current||He.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let Tt=(0,v.useMemo)(()=>({status:o,error:c,runtimeConfig:u,resolvedConfig:i,chatId:f,chatHistory:m,isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:re,agentHeadshot:ue,visitorEmail:fe,isAgentTyping:me,isAiTyping:ge,connectionStatus:_e,isLoading:ye,isVoiceMode:Te,isRateLimited:xe,rateLimitMessage:Ce,isConversationEnded:De,incomingCall:D,activeCallId:Ae,callConnectionState:Me,callConnectedAt:Pe,isCallMuted:Ie,webRTCError:Re,language:r,historyRef:et,hasSyncedRef:tt,dismissCallError:it,captureVisitorEmail:_t,startTyping:vt,stopTyping:yt,updateTypingDraft:bt,notifyRouteChange:()=>nt.current?.notifyRouteChange?.(),openWidget:gt,closeWidget:()=>_(!1),toggleWidget:()=>{if(g){_(!1);return}gt({notifyChatInitiated:!0})},sendMessage:xt,setVoiceMode:St,onMessageSync:Ct,endConversation:wt,acceptCall:dt,rejectCall:ft,endWebRTCCall:mt,toggleCallMute:ht,startTyping:vt,stopTyping:yt,updateTypingDraft:bt}),[o,c,u,i,f,m,g,y,ee,re,ue,fe,me,ge,_e,ye,Te,xe,Ce,De,D,Ae,Me,Pe,Ie,Re,r,_t,vt,yt,bt,dt,ft,mt,ht,gt,xt,St,Ct,wt,it]);return(0,A.jsx)($t.Provider,{value:Tt,children:n})}var In=({color:e=`#3888FF`})=>(0,A.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,A.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,A.jsx)(`path`,{d:`M26 8H14C12.3431 8 11 9.34315 11 11V23C11 24.6569 12.3431 26 14 26H26C27.6569 26 29 24.6569 29 23V11C29 9.34315 27.6569 8 26 8Z`,fill:`#ECF0F0`}),(0,A.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,A.jsx)(`path`,{d:`M16.4067 20.5924C16.182 20.3674 16.1822 20.003 16.407 19.7783L22.7805 13.4068C23.0051 13.1821 23.3694 13.1823 23.5939 13.4071V13.4071C23.8182 13.6317 23.8181 13.9956 23.5936 14.2201L17.2212 20.5926C16.9962 20.8176 16.6315 20.8174 16.4067 20.5924V20.5924Z`,fill:`#3E87C8`})]}),Ln=()=>(0,A.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,A.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),Rn=({size:e=18,color:t=`currentColor`})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,A.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,A.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),zn=({size:e=20})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,A.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Bn=()=>(0,A.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,A.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),Vn=()=>(0,A.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,A.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),Hn=()=>(0,A.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),Un=({className:e=``})=>(0,A.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,A.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,A.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),Wn=({size:e=18,strokeWidth:t=2.5})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,A.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),Gn=({size:e=14})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 8V4H8`}),(0,A.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,A.jsx)(`path`,{d:`M2 14h2`}),(0,A.jsx)(`path`,{d:`M20 14h2`}),(0,A.jsx)(`path`,{d:`M15 13v2`}),(0,A.jsx)(`path`,{d:`M9 13v2`})]});function Kn({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){let[a,o]=(0,v.useState)(!1);return(0,v.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 640px)`),t=e=>{o(e.matches)};return o(e.matches),typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):(e.addListener(t),()=>e.removeListener(t))},[]),e?null:(0,A.jsxs)(`button`,{type:`button`,onClick:()=>t({notifyChatInitiated:!0}),"aria-label":n,style:{position:`fixed`,...i,zIndex:999999,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:a?`0`:`14px`,width:a?`60px`:`auto`,minWidth:a?`60px`:`unset`,height:a?`60px`:`auto`,padding:a?`0`:`14px 24px`,border:`none`,borderRadius:`9999px`,background:r,color:`#fff`,fontSize:`16px`,fontWeight:`600`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,cursor:`pointer`,boxShadow:`0 8px 24px rgba(0,0,0,0.18)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,outline:`none`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 12px 28px rgba(0,0,0,0.22)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 8px 24px rgba(0,0,0,0.18)`},children:[a?null:(0,A.jsx)(`span`,{children:n}),a?(0,A.jsx)(In,{color:`#fff`}):(0,A.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,A.jsx)(Ln,{})})]})}function qn(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function Jn({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,v.useState)(!1),o=typeof e==`string`?e.trim():``;return(0,v.useEffect)(()=>{a(!1)},[o]),o&&!i?(0,A.jsx)(`img`,{src:o,alt:``,onError:()=>a(!0),style:n}):(0,A.jsx)(`span`,{style:r,children:qn(t)})}function Yn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function Xn(e){let[t,n]=(0,v.useState)(`loading`),r=Yn(e);return(0,v.useEffect)(()=>{if(v.isValidElement(e)||typeof e==`function`){n(`square`);return}if(!r){n(`error`);return}n(`loading`);let t=new Image,i=!1;return t.onload=()=>{i||n(t.naturalWidth/t.naturalHeight>1.3?`wide`:`square`)},t.onerror=()=>{i||n(`error`)},t.src=r,()=>{i=!0}},[e,r]),{state:t,resolvedLogoUrl:r}}function Zn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c,botLabel:l=`AI`,agentAvatarUrl:u=null,primaryColor:d=`#3B82F6`}){let{state:f,resolvedLogoUrl:p}=Xn(e),m=i===`agent`,h=n||r||a?.fallbackAgentName||`Agent`;return(0,A.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,padding:`16px 20px`,borderTopLeftRadius:`inherit`,borderTopRightRadius:`inherit`,border:`none`,transition:`all 0.3s ease`,background:c?`transparent`:`#fff`,color:c?`#fff`:`#111827`,boxShadow:c?`none`:`0 1px 0 rgba(0,0,0,0.05), 0 10px 24px rgba(0,0,0,0.04)`,borderBottom:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:[(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[m?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:c?`rgba(255,255,255,0.2)`:`#f3f4f6`,color:c?`#fff`:d,fontWeight:800,fontSize:`15px`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},children:(0,A.jsx)(Jn,{src:typeof u==`string`?u:``,name:h,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}):(0,A.jsxs)(A.Fragment,{children:[f!==`loading`&&(f===`error`||!p&&!e?(0,A.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0}}):v.isValidElement(e)?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:e}):typeof e==`function`?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,A.jsx)(e,{})}):f===`wide`?(0,A.jsx)(`div`,{style:{height:`36px`,maxWidth:`88px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`12px`,padding:`4px 8px`,background:c?`rgba(255,255,255,0.15)`:`#f9fafb`,backdropFilter:c?`blur(12px)`:`none`,border:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:(0,A.jsx)(`img`,{src:p,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,A.jsx)(`img`,{src:p,alt:`Logo`,style:{width:`100%`,height:`100%`,objectFit:`contain`,padding:p.toLowerCase().includes(`.svg`)||p.startsWith(`data:image/svg`)?0:`2px`}})})),f===`loading`&&(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,A.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,borderRadius:`6px`,background:`rgba(255,255,255,0.95)`,padding:`3px 6px`,fontSize:`10px`,fontWeight:800,letterSpacing:`0.5px`,color:`var(--flowengage-primary)`},children:[(0,A.jsx)(Gn,{size:11}),(0,A.jsx)(`span`,{children:l})]})]}),(0,A.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,A.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,A.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,A.jsx)(`button`,{style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`transparent`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,border:0,cursor:`pointer`,color:c?`#fff`:`#000`},onClick:s,"aria-label":`Close chat`,onMouseEnter:e=>{e.currentTarget.style.background=c?`rgba(255,255,255,0.1)`:`rgba(0,0,0,0.05)`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,A.jsx)(Wn,{})})})]})}var Qn=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),$n=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`);function er(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var tr=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return er(t);let n=t.replace(/\r\n/g,`
33
+ `,document.head.appendChild(e)};function ln(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`)).filter(e=>!nn(e));for(let e of i)if(e.textContent.replace(/\s+/g,` `).toLowerCase().trim()===n)return e;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=n.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!nn(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(nn(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(nn(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(nn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!nn(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(nn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function un(){return document.querySelector(`[itemprop='articleBody'], .article-body, .post-content, .entry-content, .field--name-body, .field--body, .node__content, article .content, .prose, article .prose`)||document.querySelector(`main article, main, [role='main'], article`)||document.body}var dn=new Set(`the.and.for.are.but.not.you.all.can.her.was.one.our.out.day.get.has.him.his.how.its.may.new.now.old.see.two.way.who.did.let.put.say.she.too.use.has.have.this.that.with.from.they.will.your.about.into.than.then.some.very.when.come.here.just.like.also.back.after.over.such.take.only.know.think.each.made.look.more.most.other.well`.split(`.`));function fn(e){return String(e||``).toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>0)}function pn(e,t){let n=fn(e).slice(-Math.min(t,28)),r=n.filter(e=>e.length>2&&!dn.has(e));return r.length>=2?r:n.filter(e=>e.length>2).slice(-12)}function mn(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`h1, h2, h3, h4, h5, h6, p, li, blockquote`,`main h2, main h3, main h4, article h2, article h3, article h4`,`section h2, section h3, section h4`].join(`, `)),i=null,a=0;for(let e of r){if(nn(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<3||n.length>6e3)continue;let r=0;for(let e of t)n.includes(e)&&r++;let o=r/t.length;if(o<.2)continue;let s=o,c=e.tagName;(c===`H2`||c===`H3`||c===`H4`)&&(s*=1.35),(c===`P`||c===`BLOCKQUOTE`)&&(s*=1.15),c?.startsWith(`H`)&&n.length<80&&(s*=1.2),n.length>400&&(s*=.65),s>a&&(a=s,i=e)}let o=n?t.length<=1?.62:.5:t.length<=1?.55:.35;return a>=o?i:null}function hn(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`main [role='group']`,`[class*='card']`,`[class*='Card']`,`[class*='column']`,`[class*='grid'] > div`,`[class*='grid'] > article`,`[data-section]`].join(`, `)),i=null,a=0;for(let e of r){if(nn(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<10||n.length>9e3)continue;let r=0;for(let e of t)e.length>1&&n.includes(e)&&r++;let o=r/t.length;if(o<.12)continue;let s=o,c=e.tagName;(c===`ARTICLE`||c===`SECTION`)&&(s*=1.05),n.length<900&&(s*=1.18),n.length<420&&(s*=1.12),n.length>2600?s*=.28:n.length>1400&&(s*=.45);try{e.querySelectorAll(`:scope > [role='group'], :scope > article, :scope > section`).length>=3&&n.length>1200&&(s*=.3)}catch{}s>a&&(a=s,i=e)}let o=n?t.length<=1?.48:.34:t.length<=1?.38:.2;return a>=o?i:null}function gn(e){return/^H[1-6]$/i.test(e?.tagName||``)}function _n(e,t,n=!1){if(!e||!t)return null;let r=t.replace(/\s+/g,` `).trim();if(r.length<14)return null;let i=n?.34:.24,a=r.toLowerCase(),o=pn(r,24);if(o.length<3&&(o=a.replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2).slice(-18)),o.length<3)return null;let s=e.querySelectorAll(`p, blockquote`),c=null,l=0;for(let e of s){if(nn(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase();if(t.length<24)continue;let n=0;for(let e of o)t.includes(e)&&n++;let r=n/o.length,s=0;for(let e=Math.min(90,a.length);e>=22;e-=6){let n=a.slice(-e).trim();if(n.length>=22&&t.includes(n)){s=.28;break}}let u=r+s;u>l&&r>=i&&(l=u,c=e)}return c}function vn(e,t={}){if(typeof document>`u`||!e||!String(e).trim())return null;let n=t.strict===!0,r=String(e).trim(),i=r.length>450?r.slice(-450).trim():r,a=un(),o=pn(r,26);if(o.length>=1&&(o.length>=2||o.length===1&&o[0].length>=3)){let e=hn(a,o,{strict:n});if(e)return e}if(r.length>=(n?55:42)){let e=_n(a,i,n);if(e)return e}if((!n||o.length>=3||o.length===2&&o.every(e=>e.length>=5))&&(o.length>=2||o.length===1&&o[0].length>=5)){let e=mn(a,o,{strict:n});if(e)return e}let s=i.split(/(?<=[.!?])\s+/).filter(e=>e.trim().length>0),c=s[s.length-1]||i,l=c.toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2),u=[];c.length>=10&&(u.push(c.slice(-220).trim()),c.length>220&&u.push(c.slice(0,120).trim()));for(let e=4;e<=Math.min(10,l.length);e++)u.push(l.slice(-e).join(` `));for(let e=Math.min(14,l.length);e>=11;e--)u.push(l.slice(-e).join(` `));for(let e=Math.min(8,l.length);e>=3;e--)u.push(l.slice(-e).join(` `));let d=n?14:6,f=new Set;for(let e of u){let t=e.trim();if(t.length<d||f.has(t))continue;f.add(t);let n=ln(null,t);if(n&&!nn(n)){if(gn(n)&&r.length>140){let e=(a.querySelector?.(`[itemprop='articleBody'], .article-body, .post-content, .entry-content`)||a).querySelectorAll?.(`p, blockquote`)||[];for(let n of e)if(!nn(n)&&n.textContent.toLowerCase().includes(t.toLowerCase().slice(0,Math.min(48,t.length))))return n}return n}}let p=o.length>=3?o:l.slice(-22);if(p.length===0)return null;let m=null,h=-1,g=a.querySelectorAll(`h1, h2, h3, h4, h5, h6, p, li, blockquote, article`);for(let e of g){if(nn(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], footer`))continue}catch{}let t=e.textContent.toLowerCase();if(t.length<12)continue;let i=0;for(let e of p)e.length>2&&t.includes(e)&&i++;let a=i/p.length,o=e.tagName;(o===`P`||o===`BLOCKQUOTE`||o===`LI`)&&(a*=1.22),gn(e)&&(r.length>110?a*=.48:a*=.92),o===`ARTICLE`&&r.length>80&&(a*=.55),a>h&&a>=(n?.42:.28)&&(h=a,m=e)}return m}function yn(e){if(!e||typeof document>`u`)return null;try{if(nn(e))return e;let t=e.closest?.([`[role='group']`,`[class*='card']`,`[class*='Card']`,`[data-section]`,`[class*='grid'] > div`,`[class*='grid'] > article`].join(`, `)),n=t?.textContent?.replace(/\s+/g,` `)||``;if(t&&!nn(t)&&n.length>20&&n.length<=5200)return t;let r=e.closest?.(`p, li, blockquote, td, th, dd, figcaption, pre`);if(r&&!nn(r))return r;let i=e.closest?.(`section`),a=i?.textContent?.replace(/\s+/g,` `)||``;return i&&a.length>48&&a.length<=4e3&&!nn(i)?i:e}catch{return e}}function bn(e){if(!e||typeof e.getBoundingClientRect!=`function`)return!0;try{let t=e.getBoundingClientRect(),n=window.innerHeight||800;if(t.bottom<=72||t.top>=n-72)return!0;let r=Math.max(0,t.top),i=Math.min(n,t.bottom),a=Math.max(0,i-r),o=Math.min(120,Math.max(40,t.height*.28));return t.height>24&&a<o}catch{return!0}}function xn(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;cn();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function Sn(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`))}function Cn(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function wn(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function Tn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?wn(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}function En(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem(an,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function Dn(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n}=t;try{let t=Cn(e),r=new URL(t,window.location.origin);if(rn(`input:`,e,`→ normalized:`,t,`href:`,r.href),r.hash&&r.pathname===window.location.pathname){let e=r.hash.slice(1),t=document.getElementById(e);if(t)return rn(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)return rn(`branch: already on page (no nav)`),!1;let i=r.pathname+r.search+r.hash,a=window.next?.router;if(a?.push)return rn(`branch: Next.js Pages router.push`,i),new Promise(e=>{let t=()=>{a.events?.off(`routeChangeComplete`,t),e(!0)};a.events?.on(`routeChangeComplete`,t),a.push(i),setTimeout(t,5e3)});let o=window.__NEXT_ROUTER__;return o?.push?(rn(`branch: __NEXT_ROUTER__.push`,i),o.push(i),!0):(n?(En(n),rn(`branch: location.assign (full navigation, section stored):`,n)):rn(`branch: location.assign (full navigation)`,r.href),window.location.assign(r.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&En(n);try{window.location.href=Cn(e)}catch{window.location.href=e}return!0}}var On=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),A=o(((e,t)=>{t.exports=On()}))(),kn=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request>[\s\S]*?<\/human_assistance_request>/gi,``).replace(/<human_assistance_request>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),An=(e=[])=>e.map(e=>({...e,message:kn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),jn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,Mn=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},Nn=e=>{if(!e)return null;let t=typeof e==`object`?e:{candidate:e};return{hasCandidate:!!t.candidate,sdpMid:t.sdpMid??null,sdpMLineIndex:t.sdpMLineIndex??null,candidatePreview:typeof t.candidate==`string`?t.candidate.slice(0,80):null}},Pn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function Fn({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,v.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,v.useMemo)(()=>Pn([i?.widgetSettings?.branding?.fallbackAgentName,i?.widgetSettings?.branding?.headerName],`Agent`),[i]),[o,s]=(0,v.useState)(`booting`),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(null),[f,p]=(0,v.useState)(``),[m,h]=(0,v.useState)([]),[g,_]=(0,v.useState)(ae().isOpen),[y,x]=(0,v.useState)(ae().activeScreen),[ee,C]=(0,v.useState)(ae().isHumanHandled),[re,le]=(0,v.useState)(ae().agentName),[ue,T]=(0,v.useState)(ae().agentHeadshot),[fe,pe]=(0,v.useState)(()=>se(i?.siteId)),[me,he]=(0,v.useState)(!1),[ge,E]=(0,v.useState)(!1),[_e,ve]=(0,v.useState)(`idle`),[ye,be]=(0,v.useState)(!1),[xe,Se]=(0,v.useState)(!1),[Ce,we]=(0,v.useState)(``),[Te,Ee]=(0,v.useState)(!1),[De,Oe]=(0,v.useState)(!1),[D,ke]=(0,v.useState)(null),[Ae,je]=(0,v.useState)(null),[Me,Ne]=(0,v.useState)(`idle`),[Pe,Fe]=(0,v.useState)(null),[Ie,Le]=(0,v.useState)(!1),[Re,ze]=(0,v.useState)(``),Be=(0,v.useRef)(null),Ve=(0,v.useRef)(null),O=(0,v.useRef)(``),He=(0,v.useRef)(null),Ue=(0,v.useRef)(null),We=(0,v.useRef)(null),Ge=(0,v.useRef)(null),Ke=(0,v.useRef)(null),qe=(0,v.useRef)([]),Je=(0,v.useRef)(null),Ye=(0,v.useRef)(null),Xe=(0,v.useRef)(!1),Ze=(0,v.useRef)(!1),Qe=(0,v.useRef)(``),$e=(0,v.useRef)(re),et=(0,v.useRef)([]),tt=(0,v.useRef)(!1),nt=(0,v.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),rt=(0,v.useMemo)(()=>{let e=u?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:S},[i,u]);(0,v.useEffect)(()=>{He.current=D},[D]),(0,v.useEffect)(()=>{$e.current=re},[re]);let it=()=>{ze(``)},at=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return pe(t),ce(t,i?.siteId),t};(0,v.useEffect)(()=>{let e=i?.siteId;e&&pe(se(e))},[i?.siteId]);let ot=()=>{Ue.current&&=(Ue.current.close(),null),We.current&&=(We.current.getTracks().forEach(e=>e.stop()),null),Ge.current&&=(Ge.current.srcObject=null,Ge.current.remove(),null),Ke.current=null,qe.current=[],Je.current=null,Ye.current=null,Xe.current=!1,Le(!1),ke(null),je(null),Ne(`idle`),Fe(null)},st=(e=new Date().toISOString())=>{let t=Be.current,n=Je.current||Ke.current?.callId;if(!t?.connected||!n||Xe.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:O.current,socketConnected:!!t?.connected,alreadyReported:Xe.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:O.current,connectedAt:e}),Xe.current=!0,t.emit(`call:connected`,{callId:n,chatId:O.current,connectedAt:e})},ct=(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=He.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),ke(null),t||n){Je.current=e.callId,je(e.callId),Ne(e=>e===`connected`?e:`connecting`),_(!0);return}Ne(`idle`)}},lt=(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=He.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||O.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){ot();return}Ye.current=null,Ke.current=null,qe.current=[],ke(null),Ne(`idle`)}},ut=async(e={})=>{let t=Ue.current,n=Be.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:O.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ke.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:O.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),qe.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:O.current,queuedCount:qe.current.length});for(let e of qe.current)await t.addIceCandidate(new RTCIceCandidate(e));qe.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:O.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:O.current})};(0,v.useEffect)(()=>{oe({isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:re,agentHeadshot:ue})},[g,y,ee,re,ue]),(0,v.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=b(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await de(t);if(!e)return;let o=ie();O.current=o;let c=w({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});Ve.current=c,d({...n,apiBaseUrl:t.apiBaseUrl}),p(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Zt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});Be.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),ve(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),ve(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:O.current}),E(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:O.current}),E(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:kn(t.message)};E(!1),he(!1),h(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),l.on(`conversationStarted`,e=>{console.log(`[FlowEngageProvider] conversationStarted`,e),e?.message&&h(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`message:new`,e=>{let t=e.message||e,n={...t,message:kn(t.message)};E(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&he(!1),h(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(C(!0),x(`agent`),le(Pn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&T(n.sender_headshot),_(!0))}),l.on(`agent:joined`,e=>{let t=Pn([e.agent?.name,e.agentName],a);C(!0),x(`agent`),le(t),T(e.agent?.headshot||null),_(!0),h(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentJoined`,e=>{let t=Pn([e.agent?.name,e.agentName],a);C(!0),x(`agent`),le(t),T(e.agent?.headshot||null),_(!0),h(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agent:left`,(e={})=>{let t=Pn([e.agent?.name,e.agentName,$e.current],a);C(!1),x(`ai`),h(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,(e={})=>{let t=Pn([e.agent?.name,e.agentName,$e.current],a);C(!1),x(`ai`),h(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{Oe(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;h(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{h(An(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&he(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||O.current,sender:e?.sender}),e.sender===`agent`&&he(!1)}),l.on(`call:incoming`,(e={})=>{let t=Pn([e.agentName,e.ownerName,e.agent?.name,re],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:O.current,agentName:t}),it(),Xe.current=!1,ke({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),le(e=>Pn([t,e],a)),Ne(`incoming`),Fe(null),_(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||O.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ke.current=e;try{await ut(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),l.on(`call:ice-candidate-from-agent`,async(e={})=>{if(!e.candidate){console.log(`[FlowEngageProvider] skipping agent ICE candidate`,{callId:e.callId,chatId:e.chatId||O.current,hasPeerConnection:!!Ue.current,hasCandidate:!!e.candidate});return}try{let t=Mn(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||O.current,candidate:Nn(t),hasRemoteDescription:!!Ue.current?.remoteDescription}),!Ue.current||!Ue.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||O.current,queueSize:qe.current.length+1}),qe.current.push(t);return}await Ue.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{it(),ot()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||O.current}),ct(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||O.current}),ct(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),lt(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),lt(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||O.current,reason:e.reason}),lt(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=Ye.current===e.callId,n=Je.current===e.callId,r=Ke.current?.callId===e.callId,i=He.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||O.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isPendingOfferHere:r,isIncomingHere:i}),!t&&!n&&!r){i&&(ke(null),Ne(`idle`));return}Xe.current=!0,Ye.current=null,Je.current=e.callId,je(e.callId),ke(null),Ne(`connected`),Fe(e.connectedAt||new Date().toISOString()),_(!0)}),l.on(`call:unavailable`,(e={})=>{ot(),ze(jn(e,`This visitor is not available for a call right now.`)),_(!0)}),l.on(`call:error`,(e={})=>{ot(),ze(jn(e,`We couldn't connect the call right now.`)),_(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await Tn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}Dn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=ln(null,t);e&&xn(e)},e?300:150)})}}),l.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;console.log(`[FlowEngageProvider] visitor:highlight`,{sectionId:e,sectionText:t});let n=ln(e||null,t||null);n&&xn(n)}),l.on(`visitor:clear_highlight`,()=>{Sn()}),nt.current=Qt({socket:l,chatId:o}),console.log(`[FlowEngageProvider] tracking started`,{chatId:o});let u=await c.loadHistory(o,r);if(console.log(`[FlowEngageProvider] history loaded`,u),!e||(h(An(u.chat_history||[])),C(!!u.is_human_handled),x(u.is_human_handled?`agent`:y),await new Promise(e=>setTimeout(e,500)),!e))return;s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),l(t),s(`error`)}})(),()=>{e=!1,nt.current?.cleanup?.(),ot(),Be.current?.disconnect()}},[i,r]),(0,v.useEffect)(()=>()=>{if(Te&&!tt.current&&et.current.length>0){let e=O.current,t=et.current,n=Ve.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),tt.current=!0)}},[Te,u]),(0,v.useEffect)(()=>{if(!Ve.current||!f||o!==`ready`||ee)return;let e=window.setInterval(async()=>{try{let e=await Ve.current.checkHumanHandled(f);C(!!e.is_human_handled),e.is_human_handled&&(x(`agent`),e.agent_info?.name&&le(e.agent_info.name),e.agent_info?.headshot&&T(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[f,o,ee]);let dt=async()=>{if(!(!D?.callId||!Ve.current||!Be.current||!f)){it(),Ye.current=D.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:D?.callId,chatId:f,socketConnected:!!Be.current?.connected,hasPendingOffer:!!Ke.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:D.callId,chatId:f,trackCount:e.getTracks().length}),We.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Ue.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:D.callId,chatId:f,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Ne(`connected`),Fe(t=>t||e),st(e);return}e===`connecting`&&Ne(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:D.callId,chatId:f,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Ne(`connected`),Fe(t=>t||e),st(e);return}(e===`checking`||e===`new`)&&Ne(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!Be.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:D.callId,chatId:f,hasCandidate:!!e.candidate,socketConnected:!!Be.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:D.callId,chatId:f,candidate:Nn(e.candidate)}),Be.current.emit(`call:ice-candidate`,{callId:D.callId,candidate:e.candidate,chatId:f,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:D.callId,chatId:f,streamCount:e.streams?.length||0}),!Ge.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Ge.current=e,document.body.appendChild(e)}Ge.current.srcObject=e.streams[0];let t=D?.callId,n=t&&(Ye.current===t||Je.current===t);if(!Xe.current&&n){let e=new Date().toISOString();Ne(`connected`),Fe(t=>t||e),Je.current=t,je(t),st(e)}};let n=Ke.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||D.callId,chatId:f}),await ut({...n,callId:n.callId||D.callId})),await Ve.current.acceptCall(D.callId,f),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:D.callId,chatId:f}),Je.current=D.callId,je(D.callId),Ne(`connecting`),ke(null),_(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),Ye.current=null,ot(),e?.status===404||e?.status===409||e?.status===422){ze(jn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await Ve.current.rejectCall(D.callId,f)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}ze(`Microphone access was denied. Please allow microphone access to accept the call.`);return}ze(`We couldn't connect the call right now. Please try again.`)}}},ft=async()=>{if(!D?.callId||!Ve.current||!f){ot();return}it();try{await Ve.current.rejectCall(D.callId,f)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),ze(jn(e,`We couldn't decline the call cleanly.`))}finally{ot()}},pt=(0,v.useRef)(ft);pt.current=ft,(0,v.useEffect)(()=>{if(!D?.callId||Ae)return;let e=D.callId,t=window.setTimeout(()=>{He.current?.callId===e&&pt.current()},ne);return()=>window.clearTimeout(t)},[D?.callId,Ae]);let mt=async()=>{if(!Ae||!Ve.current||!f){ot();return}it();try{await Ve.current.endWebRTCCall(Ae,f)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),ze(jn(e,`The call ended locally, but the server could not be updated.`))}finally{ot()}},ht=()=>{let e=We.current?.getAudioTracks?.()||[],t=Ue.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0){console.warn(`[FlowEngageProvider] no local audio tracks available for mute`);return}let r=!Ie;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),Le(r)},gt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(_(!0),!(!t||!Ve.current||!f||typeof window>`u`)){try{await Ve.current.trackVisitor({chatId:f,currentPagePath:window.location.pathname||`/`})}catch{}try{await Ve.current.updateChatStatus(f,`open`)}catch{}}},_t=async e=>{let t=at(e);if(!t||!Ve.current||!O.current)return t;try{await Ve.current.trackVisitor({chatId:O.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},vt=()=>{if(!f||!Be.current?.connected||Ze.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:f,socketConnected:!!Be.current?.connected,alreadyTyping:Ze.current});return}Ze.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:f,sender:`user`}),Be.current.emit(`typing:start`,{chatId:f,sender:`user`})},yt=()=>{if(!f||!Be.current?.connected||!Ze.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:f,socketConnected:!!Be.current?.connected,wasTyping:Ze.current});return}Ze.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:f,sender:`user`}),Be.current.emit(`typing:stop`,{chatId:f,sender:`user`})},bt=(e=``)=>{let t=typeof e==`string`?e:``;if(!f||!Be.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:f,socketConnected:!!Be.current?.connected,textLength:t.length});return}Qe.current!==t&&(Qe.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:f,sender:`user`,textLength:t.length}),Be.current.emit(`typing:update`,{chatId:f,sender:`user`,text:t}))},xt=async(e,t=``,n=null)=>{if(!e.trim()||!Ve.current||!f||o!==`ready`||De)return;yt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(h(e=>[...e,a]),ee&&Be.current?.connected){Be.current.emit(`customer:message`,{chatId:f,content:e,sender:`user`,email:fe||void 0,...n||{}});return}be(!0);try{let i=await Ve.current.sendAiMessage(f,e,r,t,{...n||{},...fe?{email:fe}:{}});h(An(i.chat_history||[])),C(!!i.is_human_handled),x(i.is_human_handled?`agent`:`ai`),E(!1),await Ve.current.updateChatStatus(f,`messageSent`)}catch(e){h(e=>e.filter(e=>e.id!==i)),E(!1),e.status===429?(Se(!0),we(e.message),window.setTimeout(()=>{Se(!1),we(``)},te)):l(e)}finally{be(!1)}},St=async e=>{if(!(!Ve.current||!f)){try{let t=e?`voice`:`text`;await Ve.current.setChatMode(f,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}Ee(e),e&&(tt.current=!1)}},Ct=async e=>{if(!tt.current){if(tt.current=!0,!Ve.current||!f||!e?.length){Ee(!1);return}try{let t=await Ve.current.syncVoice(f,e);if(t?.chat_history?.length)h(An(t.chat_history));else if(t?.success)try{let e=await Ve.current.loadHistory(f,r);e?.chat_history?.length&&h(An(e.chat_history))}catch{}}catch{}finally{Ee(!1)}}},wt=async()=>{if(!(!Ve.current||!f)){Te&&!tt.current&&et.current.length>0&&await Ct(et.current);try{await Ve.current.endConversation(f)}catch{try{await Ve.current.updateChatStatus(f,`ended`)}catch{}}Oe(!0),h(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,v.useEffect)(()=>{if(Me!==`connected`||!Ae||!f||!Pe||!rt)return;let e=new Date(Pe).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,rt*1e3-t),r=window.setTimeout(()=>{ze(`The call ended because it reached the time limit.`),mt()},n);return()=>window.clearTimeout(r)},[Ae,Pe,Me,f,mt,rt]),(0,v.useEffect)(()=>{let e=()=>{let e=O.current,t=Ve.current;if(!t||!e)return;if(Je.current){t.beaconEndWebRTCCall(Je.current,e);return}let n=Ye.current||He.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let Tt=(0,v.useMemo)(()=>({status:o,error:c,runtimeConfig:u,resolvedConfig:i,chatId:f,chatHistory:m,isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:re,agentHeadshot:ue,visitorEmail:fe,isAgentTyping:me,isAiTyping:ge,connectionStatus:_e,isLoading:ye,isVoiceMode:Te,isRateLimited:xe,rateLimitMessage:Ce,isConversationEnded:De,incomingCall:D,activeCallId:Ae,callConnectionState:Me,callConnectedAt:Pe,isCallMuted:Ie,webRTCError:Re,language:r,historyRef:et,hasSyncedRef:tt,dismissCallError:it,captureVisitorEmail:_t,startTyping:vt,stopTyping:yt,updateTypingDraft:bt,notifyRouteChange:()=>nt.current?.notifyRouteChange?.(),openWidget:gt,closeWidget:()=>_(!1),toggleWidget:()=>{if(g){_(!1);return}gt({notifyChatInitiated:!0})},sendMessage:xt,setVoiceMode:St,onMessageSync:Ct,endConversation:wt,acceptCall:dt,rejectCall:ft,endWebRTCCall:mt,toggleCallMute:ht,startTyping:vt,stopTyping:yt,updateTypingDraft:bt}),[o,c,u,i,f,m,g,y,ee,re,ue,fe,me,ge,_e,ye,Te,xe,Ce,De,D,Ae,Me,Pe,Ie,Re,r,_t,vt,yt,bt,dt,ft,mt,ht,gt,xt,St,Ct,wt,it]);return(0,A.jsx)($t.Provider,{value:Tt,children:n})}var In=({color:e=`#3888FF`})=>(0,A.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,A.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,A.jsx)(`path`,{d:`M26 8H14C12.3431 8 11 9.34315 11 11V23C11 24.6569 12.3431 26 14 26H26C27.6569 26 29 24.6569 29 23V11C29 9.34315 27.6569 8 26 8Z`,fill:`#ECF0F0`}),(0,A.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,A.jsx)(`path`,{d:`M16.4067 20.5924C16.182 20.3674 16.1822 20.003 16.407 19.7783L22.7805 13.4068C23.0051 13.1821 23.3694 13.1823 23.5939 13.4071V13.4071C23.8182 13.6317 23.8181 13.9956 23.5936 14.2201L17.2212 20.5926C16.9962 20.8176 16.6315 20.8174 16.4067 20.5924V20.5924Z`,fill:`#3E87C8`})]}),Ln=()=>(0,A.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,A.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),Rn=({size:e=18,color:t=`currentColor`})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,A.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,A.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),zn=({size:e=20})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,A.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Bn=()=>(0,A.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,A.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),Vn=()=>(0,A.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,A.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),Hn=()=>(0,A.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),Un=({className:e=``})=>(0,A.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,A.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,A.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),Wn=({size:e=18,strokeWidth:t=2.5})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,A.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),Gn=({size:e=14})=>(0,A.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,A.jsx)(`path`,{d:`M12 8V4H8`}),(0,A.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,A.jsx)(`path`,{d:`M2 14h2`}),(0,A.jsx)(`path`,{d:`M20 14h2`}),(0,A.jsx)(`path`,{d:`M15 13v2`}),(0,A.jsx)(`path`,{d:`M9 13v2`})]});function Kn({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){let[a,o]=(0,v.useState)(!1);return(0,v.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 640px)`),t=e=>{o(e.matches)};return o(e.matches),typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):(e.addListener(t),()=>e.removeListener(t))},[]),e?null:(0,A.jsxs)(`button`,{type:`button`,onClick:()=>t({notifyChatInitiated:!0}),"aria-label":n,style:{position:`fixed`,...i,zIndex:999999,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:a?`0`:`14px`,width:a?`60px`:`auto`,minWidth:a?`60px`:`unset`,height:a?`60px`:`auto`,padding:a?`0`:`14px 24px`,border:`none`,borderRadius:`9999px`,background:r,color:`#fff`,fontSize:`16px`,fontWeight:`600`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,cursor:`pointer`,boxShadow:`0 8px 24px rgba(0,0,0,0.18)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,outline:`none`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 12px 28px rgba(0,0,0,0.22)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 8px 24px rgba(0,0,0,0.18)`},children:[a?null:(0,A.jsx)(`span`,{children:n}),a?(0,A.jsx)(In,{color:`#fff`}):(0,A.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,A.jsx)(Ln,{})})]})}function qn(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function Jn({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,v.useState)(!1),o=typeof e==`string`?e.trim():``;return(0,v.useEffect)(()=>{a(!1)},[o]),o&&!i?(0,A.jsx)(`img`,{src:o,alt:``,onError:()=>a(!0),style:n}):(0,A.jsx)(`span`,{style:r,children:qn(t)})}function Yn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function Xn(e){let[t,n]=(0,v.useState)(`loading`),r=Yn(e);return(0,v.useEffect)(()=>{if(v.isValidElement(e)||typeof e==`function`){n(`square`);return}if(!r){n(`error`);return}n(`loading`);let t=new Image,i=!1;return t.onload=()=>{i||n(t.naturalWidth/t.naturalHeight>1.3?`wide`:`square`)},t.onerror=()=>{i||n(`error`)},t.src=r,()=>{i=!0}},[e,r]),{state:t,resolvedLogoUrl:r}}function Zn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c,botLabel:l=`AI`,agentAvatarUrl:u=null,primaryColor:d=`#3B82F6`}){let{state:f,resolvedLogoUrl:p}=Xn(e),m=i===`agent`,h=n||r||a?.fallbackAgentName||`Agent`;return(0,A.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,padding:`16px 20px`,borderTopLeftRadius:`inherit`,borderTopRightRadius:`inherit`,border:`none`,transition:`all 0.3s ease`,background:c?`transparent`:`#fff`,color:c?`#fff`:`#111827`,boxShadow:c?`none`:`0 1px 0 rgba(0,0,0,0.05), 0 10px 24px rgba(0,0,0,0.04)`,borderBottom:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:[(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[m?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:c?`rgba(255,255,255,0.2)`:`#f3f4f6`,color:c?`#fff`:d,fontWeight:800,fontSize:`15px`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},children:(0,A.jsx)(Jn,{src:typeof u==`string`?u:``,name:h,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}):(0,A.jsxs)(A.Fragment,{children:[f!==`loading`&&(f===`error`||!p&&!e?(0,A.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0}}):v.isValidElement(e)?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:e}):typeof e==`function`?(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,A.jsx)(e,{})}):f===`wide`?(0,A.jsx)(`div`,{style:{height:`36px`,maxWidth:`88px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`12px`,padding:`4px 8px`,background:c?`rgba(255,255,255,0.15)`:`#f9fafb`,backdropFilter:c?`blur(12px)`:`none`,border:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:(0,A.jsx)(`img`,{src:p,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,A.jsx)(`img`,{src:p,alt:`Logo`,style:{width:`100%`,height:`100%`,objectFit:`contain`,padding:p.toLowerCase().includes(`.svg`)||p.startsWith(`data:image/svg`)?0:`2px`}})})),f===`loading`&&(0,A.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,A.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,A.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,borderRadius:`6px`,background:`rgba(255,255,255,0.95)`,padding:`3px 6px`,fontSize:`10px`,fontWeight:800,letterSpacing:`0.5px`,color:`var(--flowengage-primary)`},children:[(0,A.jsx)(Gn,{size:11}),(0,A.jsx)(`span`,{children:l})]})]}),(0,A.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,A.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,A.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,A.jsx)(`button`,{style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`transparent`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,border:0,cursor:`pointer`,color:c?`#fff`:`#000`},onClick:s,"aria-label":`Close chat`,onMouseEnter:e=>{e.currentTarget.style.background=c?`rgba(255,255,255,0.1)`:`rgba(0,0,0,0.05)`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,A.jsx)(Wn,{})})})]})}var Qn=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),$n=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`);function er(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var tr=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return er(t);let n=t.replace(/\r\n/g,`
34
34
  `).replace(/\n{3,}/g,`
35
35
 
36
36
  `).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>$n(e).replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*\n]+)\*/g,`<em>$1</em>`);return er(n.map(e=>{let t=e.split(`
@@ -22,7 +22,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
22
22
  box-shadow: none !important;
23
23
  transition: outline-color 0.25s ease, box-shadow 0.25s ease !important;
24
24
  }
25
- `,document.head.appendChild(e)};function rn(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`)).filter(e=>!Zt(e));for(let e of i)if(e.textContent.replace(/\s+/g,` `).toLowerCase().trim()===n)return e;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=n.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!Zt(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(Zt(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(Zt(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(Zt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!Zt(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(Zt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function an(){return document.querySelector(`[itemprop='articleBody'], .article-body, .post-content, .entry-content, .field--name-body, .field--body, .node__content, article .content, .prose, article .prose`)||document.querySelector(`main article, main, [role='main'], article`)||document.body}var on=new Set(`the.and.for.are.but.not.you.all.can.her.was.one.our.out.day.get.has.him.his.how.its.may.new.now.old.see.two.way.who.did.let.put.say.she.too.use.has.have.this.that.with.from.they.will.your.about.into.than.then.some.very.when.come.here.just.like.also.back.after.over.such.take.only.know.think.each.made.look.more.most.other.well`.split(`.`));function sn(e){return String(e||``).toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>0)}function cn(e,t){let n=sn(e).slice(-Math.min(t,28)),r=n.filter(e=>e.length>2&&!on.has(e));return r.length>=2?r:n.filter(e=>e.length>2).slice(-12)}function ln(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`h1, h2, h3, h4, h5, h6, p, li, blockquote`,`main h2, main h3, main h4, article h2, article h3, article h4`,`section h2, section h3, section h4`].join(`, `)),i=null,a=0;for(let e of r){if(Zt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<3||n.length>6e3)continue;let r=0;for(let e of t)n.includes(e)&&r++;let o=r/t.length;if(o<.2)continue;let s=o,c=e.tagName;(c===`H2`||c===`H3`||c===`H4`)&&(s*=1.35),(c===`P`||c===`BLOCKQUOTE`)&&(s*=1.15),c?.startsWith(`H`)&&n.length<80&&(s*=1.2),n.length>400&&(s*=.65),s>a&&(a=s,i=e)}let o=n?t.length<=1?.62:.5:t.length<=1?.55:.35;return a>=o?i:null}function un(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`main [role='group']`,`[class*='card']`,`[class*='Card']`,`[class*='column']`,`[class*='grid'] > div`,`[class*='grid'] > article`,`[data-section]`].join(`, `)),i=null,a=0;for(let e of r){if(Zt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<10||n.length>9e3)continue;let r=0;for(let e of t)e.length>1&&n.includes(e)&&r++;let o=r/t.length;if(o<.12)continue;let s=o,c=e.tagName;(c===`ARTICLE`||c===`SECTION`)&&(s*=1.05),n.length<900&&(s*=1.18),n.length<420&&(s*=1.12),n.length>2600?s*=.28:n.length>1400&&(s*=.45);try{e.querySelectorAll(`:scope > [role='group'], :scope > article, :scope > section`).length>=3&&n.length>1200&&(s*=.3)}catch{}s>a&&(a=s,i=e)}let o=n?t.length<=1?.48:.34:t.length<=1?.38:.2;return a>=o?i:null}function dn(e){return/^H[1-6]$/i.test(e?.tagName||``)}function fn(e,t,n=!1){if(!e||!t)return null;let r=t.replace(/\s+/g,` `).trim();if(r.length<14)return null;let i=n?.34:.24,a=r.toLowerCase(),o=cn(r,24);if(o.length<3&&(o=a.replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2).slice(-18)),o.length<3)return null;let s=e.querySelectorAll(`p, blockquote`),c=null,l=0;for(let e of s){if(Zt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase();if(t.length<24)continue;let n=0;for(let e of o)t.includes(e)&&n++;let r=n/o.length,s=0;for(let e=Math.min(90,a.length);e>=22;e-=6){let n=a.slice(-e).trim();if(n.length>=22&&t.includes(n)){s=.28;break}}let u=r+s;u>l&&r>=i&&(l=u,c=e)}return c}function pn(e,t={}){if(typeof document>`u`||!e||!String(e).trim())return null;let n=t.strict===!0,r=String(e).trim(),i=r.length>450?r.slice(-450).trim():r,a=an(),o=cn(r,26);if(o.length>=1&&(o.length>=2||o.length===1&&o[0].length>=3)){let e=un(a,o,{strict:n});if(e)return e}if(r.length>=(n?55:42)){let e=fn(a,i,n);if(e)return e}if((!n||o.length>=3||o.length===2&&o.every(e=>e.length>=5))&&(o.length>=2||o.length===1&&o[0].length>=5)){let e=ln(a,o,{strict:n});if(e)return e}let s=i.split(/(?<=[.!?])\s+/).filter(e=>e.trim().length>0),c=s[s.length-1]||i,l=c.toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2),u=[];c.length>=10&&(u.push(c.slice(-220).trim()),c.length>220&&u.push(c.slice(0,120).trim()));for(let e=4;e<=Math.min(10,l.length);e++)u.push(l.slice(-e).join(` `));for(let e=Math.min(14,l.length);e>=11;e--)u.push(l.slice(-e).join(` `));for(let e=Math.min(8,l.length);e>=3;e--)u.push(l.slice(-e).join(` `));let d=n?14:6,f=new Set;for(let e of u){let t=e.trim();if(t.length<d||f.has(t))continue;f.add(t);let n=rn(null,t);if(n&&!Zt(n)){if(dn(n)&&r.length>140){let e=(a.querySelector?.(`[itemprop='articleBody'], .article-body, .post-content, .entry-content`)||a).querySelectorAll?.(`p, blockquote`)||[];for(let n of e)if(!Zt(n)&&n.textContent.toLowerCase().includes(t.toLowerCase().slice(0,Math.min(48,t.length))))return n}return n}}let p=o.length>=3?o:l.slice(-22);if(p.length===0)return null;let m=null,ee=-1,h=a.querySelectorAll(`h1, h2, h3, h4, h5, h6, p, li, blockquote, article`);for(let e of h){if(Zt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], footer`))continue}catch{}let t=e.textContent.toLowerCase();if(t.length<12)continue;let i=0;for(let e of p)e.length>2&&t.includes(e)&&i++;let a=i/p.length,o=e.tagName;(o===`P`||o===`BLOCKQUOTE`||o===`LI`)&&(a*=1.22),dn(e)&&(r.length>110?a*=.48:a*=.92),o===`ARTICLE`&&r.length>80&&(a*=.55),a>ee&&a>=(n?.42:.28)&&(ee=a,m=e)}return m}function mn(e){if(!e||typeof document>`u`)return null;try{if(Zt(e))return e;let t=e.closest?.([`[role='group']`,`[class*='card']`,`[class*='Card']`,`[data-section]`,`[class*='grid'] > div`,`[class*='grid'] > article`].join(`, `)),n=t?.textContent?.replace(/\s+/g,` `)||``;if(t&&!Zt(t)&&n.length>20&&n.length<=5200)return t;let r=e.closest?.(`p, li, blockquote, td, th, dd, figcaption, pre`);if(r&&!Zt(r))return r;let i=e.closest?.(`section`),a=i?.textContent?.replace(/\s+/g,` `)||``;return i&&a.length>48&&a.length<=4e3&&!Zt(i)?i:e}catch{return e}}function hn(e){if(!e||typeof e.getBoundingClientRect!=`function`)return!0;try{let t=e.getBoundingClientRect(),n=window.innerHeight||800;if(t.bottom<=72||t.top>=n-72)return!0;let r=Math.max(0,t.top),i=Math.min(n,t.bottom),a=Math.max(0,i-r),o=Math.min(120,Math.max(40,t.height*.28));return t.height>24&&a<o}catch{return!0}}function gn(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;nn();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function _n(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`))}function vn(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function yn(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function bn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?yn(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}function xn(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem($t,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function Sn(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n}=t;try{let t=vn(e),r=new URL(t,window.location.origin);if(Qt(`input:`,e,`→ normalized:`,t,`href:`,r.href),r.hash&&r.pathname===window.location.pathname){let e=r.hash.slice(1),t=document.getElementById(e);if(t)return Qt(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)return Qt(`branch: already on page (no nav)`),!1;let i=r.pathname+r.search+r.hash,a=window.next?.router;if(a?.push)return Qt(`branch: Next.js Pages router.push`,i),new Promise(e=>{let t=()=>{a.events?.off(`routeChangeComplete`,t),e(!0)};a.events?.on(`routeChangeComplete`,t),a.push(i),setTimeout(t,5e3)});let o=window.__NEXT_ROUTER__;return o?.push?(Qt(`branch: __NEXT_ROUTER__.push`,i),o.push(i),!0):(n?(xn(n),Qt(`branch: location.assign (full navigation, section stored):`,n)):Qt(`branch: location.assign (full navigation)`,r.href),window.location.assign(r.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&xn(n);try{window.location.href=vn(e)}catch{window.location.href=e}return!0}}var Cn=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request>[\s\S]*?<\/human_assistance_request>/gi,``).replace(/<human_assistance_request>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),wn=(e=[])=>e.map(e=>({...e,message:Cn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),Tn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,En=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},Dn=e=>{if(!e)return null;let t=typeof e==`object`?e:{candidate:e};return{hasCandidate:!!t.candidate,sdpMid:t.sdpMid??null,sdpMLineIndex:t.sdpMLineIndex??null,candidatePreview:typeof t.candidate==`string`?t.candidate.slice(0,80):null}},On=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function kn({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,l.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,l.useMemo)(()=>On([i?.widgetSettings?.branding?.fallbackAgentName,i?.widgetSettings?.branding?.headerName],`Agent`),[i]),[o,s]=(0,l.useState)(`booting`),[c,f]=(0,l.useState)(null),[p,g]=(0,l.useState)(null),[_,oe]=(0,l.useState)(``),[v,y]=(0,l.useState)([]),[le,ue]=(0,l.useState)(ne().isOpen),[de,fe]=(0,l.useState)(ne().activeScreen),[pe,me]=(0,l.useState)(ne().isHumanHandled),[he,ge]=(0,l.useState)(ne().agentName),[_e,ve]=(0,l.useState)(ne().agentHeadshot),[ye,be]=(0,l.useState)(()=>ie(i?.siteId)),[xe,Se]=(0,l.useState)(!1),[Ce,we]=(0,l.useState)(!1),[Te,Ee]=(0,l.useState)(`idle`),[De,Oe]=(0,l.useState)(!1),[ke,Ae]=(0,l.useState)(!1),[je,Me]=(0,l.useState)(``),[Ne,b]=(0,l.useState)(!1),[Pe,Fe]=(0,l.useState)(!1),[x,Ie]=(0,l.useState)(null),[Le,Re]=(0,l.useState)(null),[ze,Be]=(0,l.useState)(`idle`),[Ve,He]=(0,l.useState)(null),[Ue,We]=(0,l.useState)(!1),[Ge,Ke]=(0,l.useState)(``),S=(0,l.useRef)(null),C=(0,l.useRef)(null),w=(0,l.useRef)(``),qe=(0,l.useRef)(null),Je=(0,l.useRef)(null),Ye=(0,l.useRef)(null),Xe=(0,l.useRef)(null),Ze=(0,l.useRef)(null),Qe=(0,l.useRef)([]),$e=(0,l.useRef)(null),et=(0,l.useRef)(null),tt=(0,l.useRef)(!1),nt=(0,l.useRef)(!1),rt=(0,l.useRef)(``),it=(0,l.useRef)(he),at=(0,l.useRef)([]),ot=(0,l.useRef)(!1),st=(0,l.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),ct=(0,l.useMemo)(()=>{let e=p?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:ee},[i,p]);(0,l.useEffect)(()=>{qe.current=x},[x]),(0,l.useEffect)(()=>{it.current=he},[he]);let lt=()=>{Ke(``)},ut=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return be(t),ae(t,i?.siteId),t};(0,l.useEffect)(()=>{let e=i?.siteId;e&&be(ie(e))},[i?.siteId]);let dt=()=>{Je.current&&=(Je.current.close(),null),Ye.current&&=(Ye.current.getTracks().forEach(e=>e.stop()),null),Xe.current&&=(Xe.current.srcObject=null,Xe.current.remove(),null),Ze.current=null,Qe.current=[],$e.current=null,et.current=null,tt.current=!1,We(!1),Ie(null),Re(null),Be(`idle`),He(null)},ft=(e=new Date().toISOString())=>{let t=S.current,n=$e.current||Ze.current?.callId;if(!t?.connected||!n||tt.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:w.current,socketConnected:!!t?.connected,alreadyReported:tt.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:w.current,connectedAt:e}),tt.current=!0,t.emit(`call:connected`,{callId:n,chatId:w.current,connectedAt:e})},pt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||w.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Ie(null),t||n){$e.current=e.callId,Re(e.callId),Be(e=>e===`connected`?e:`connecting`),ue(!0);return}Be(`idle`)}},mt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||w.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){dt();return}et.current=null,Ze.current=null,Qe.current=[],Ie(null),Be(`idle`)}},ht=async(e={})=>{let t=Je.current,n=S.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:w.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ze.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:w.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Qe.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:w.current,queuedCount:Qe.current.length});for(let e of Qe.current)await t.addIceCandidate(new RTCIceCandidate(e));Qe.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:w.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:w.current})};(0,l.useEffect)(()=>{re({isOpen:le,activeScreen:de,isHumanHandled:pe,agentName:he,agentHeadshot:_e})},[le,de,pe,he,_e]),(0,l.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=d(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await se(t);if(!e)return;let o=te();w.current=o;let c=ce({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});C.current=c,g({...n,apiBaseUrl:t.apiBaseUrl}),oe(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Kt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});S.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),Ee(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),Ee(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:w.current}),we(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:w.current}),we(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:Cn(t.message)};we(!1),Se(!1),y(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),l.on(`conversationStarted`,e=>{console.log(`[FlowEngageProvider] conversationStarted`,e),e?.message&&y(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`message:new`,e=>{let t=e.message||e,n={...t,message:Cn(t.message)};we(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&Se(!1),y(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(me(!0),fe(`agent`),ge(On([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&ve(n.sender_headshot),ue(!0))}),l.on(`agent:joined`,e=>{let t=On([e.agent?.name,e.agentName],a);me(!0),fe(`agent`),ge(t),ve(e.agent?.headshot||null),ue(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentJoined`,e=>{let t=On([e.agent?.name,e.agentName],a);me(!0),fe(`agent`),ge(t),ve(e.agent?.headshot||null),ue(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agent:left`,(e={})=>{let t=On([e.agent?.name,e.agentName,it.current],a);me(!1),fe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,(e={})=>{let t=On([e.agent?.name,e.agentName,it.current],a);me(!1),fe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{Fe(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{y(wn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||w.current,sender:e?.sender}),e.sender===`agent`&&Se(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||w.current,sender:e?.sender}),e.sender===`agent`&&Se(!1)}),l.on(`call:incoming`,(e={})=>{let t=On([e.agentName,e.ownerName,e.agent?.name,he],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:w.current,agentName:t}),lt(),tt.current=!1,Ie({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ge(e=>On([t,e],a)),Be(`incoming`),He(null),ue(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||w.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ze.current=e;try{await ht(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),l.on(`call:ice-candidate-from-agent`,async(e={})=>{if(!e.candidate){console.log(`[FlowEngageProvider] skipping agent ICE candidate`,{callId:e.callId,chatId:e.chatId||w.current,hasPeerConnection:!!Je.current,hasCandidate:!!e.candidate});return}try{let t=En(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||w.current,candidate:Dn(t),hasRemoteDescription:!!Je.current?.remoteDescription}),!Je.current||!Je.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||w.current,queueSize:Qe.current.length+1}),Qe.current.push(t);return}await Je.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{lt(),dt()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||w.current}),pt(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||w.current}),pt(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||w.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(Ie(null),Be(`idle`));return}tt.current=!0,et.current=null,$e.current=e.callId,Re(e.callId),Ie(null),Be(`connected`),He(e.connectedAt||new Date().toISOString()),ue(!0)}),l.on(`call:unavailable`,(e={})=>{dt(),Ke(Tn(e,`This visitor is not available for a call right now.`)),ue(!0)}),l.on(`call:error`,(e={})=>{dt(),Ke(Tn(e,`We couldn't connect the call right now.`)),ue(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await bn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}Sn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=rn(null,t);e&&gn(e)},e?300:150)})}}),l.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;console.log(`[FlowEngageProvider] visitor:highlight`,{sectionId:e,sectionText:t});let n=rn(e||null,t||null);n&&gn(n)}),l.on(`visitor:clear_highlight`,()=>{_n()}),st.current=qt({socket:l,chatId:o}),console.log(`[FlowEngageProvider] tracking started`,{chatId:o});let u=await c.loadHistory(o,r);if(console.log(`[FlowEngageProvider] history loaded`,u),!e||(y(wn(u.chat_history||[])),me(!!u.is_human_handled),fe(u.is_human_handled?`agent`:de),await new Promise(e=>setTimeout(e,500)),!e))return;s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),f(t),s(`error`)}})(),()=>{e=!1,st.current?.cleanup?.(),dt(),S.current?.disconnect()}},[i,r]),(0,l.useEffect)(()=>()=>{if(Ne&&!ot.current&&at.current.length>0){let e=w.current,t=at.current,n=C.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),ot.current=!0)}},[Ne,p]),(0,l.useEffect)(()=>{if(!C.current||!_||o!==`ready`||pe)return;let e=window.setInterval(async()=>{try{let e=await C.current.checkHumanHandled(_);me(!!e.is_human_handled),e.is_human_handled&&(fe(`agent`),e.agent_info?.name&&ge(e.agent_info.name),e.agent_info?.headshot&&ve(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[_,o,pe]);let gt=async()=>{if(!(!x?.callId||!C.current||!S.current||!_)){lt(),et.current=x.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:x?.callId,chatId:_,socketConnected:!!S.current?.connected,hasPendingOffer:!!Ze.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:x.callId,chatId:_,trackCount:e.getTracks().length}),Ye.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Je.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:x.callId,chatId:_,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),ft(e);return}e===`connecting`&&Be(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:x.callId,chatId:_,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),ft(e);return}(e===`checking`||e===`new`)&&Be(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!S.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:x.callId,chatId:_,hasCandidate:!!e.candidate,socketConnected:!!S.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:x.callId,chatId:_,candidate:Dn(e.candidate)}),S.current.emit(`call:ice-candidate`,{callId:x.callId,candidate:e.candidate,chatId:_,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:x.callId,chatId:_,streamCount:e.streams?.length||0}),!Xe.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Xe.current=e,document.body.appendChild(e)}Xe.current.srcObject=e.streams[0]};let n=Ze.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||x.callId,chatId:_}),await ht({...n,callId:n.callId||x.callId})),await C.current.acceptCall(x.callId,_),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:x.callId,chatId:_}),$e.current=x.callId,Re(x.callId),Be(`connecting`),Ie(null),ue(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),et.current=null,dt(),e?.status===404||e?.status===409||e?.status===422){Ke(Tn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await C.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Ke(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Ke(`We couldn't connect the call right now. Please try again.`)}}},_t=async()=>{if(!x?.callId||!C.current||!_){dt();return}lt();try{await C.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Ke(Tn(e,`We couldn't decline the call cleanly.`))}finally{dt()}},vt=(0,l.useRef)(_t);vt.current=_t,(0,l.useEffect)(()=>{if(!x?.callId||Le)return;let e=x.callId,t=window.setTimeout(()=>{qe.current?.callId===e&&vt.current()},h);return()=>window.clearTimeout(t)},[x?.callId,Le]);let yt=async()=>{if(!Le||!C.current||!_){dt();return}lt();try{await C.current.endWebRTCCall(Le,_)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Ke(Tn(e,`The call ended locally, but the server could not be updated.`))}finally{dt()}},bt=()=>{let e=Ye.current?.getAudioTracks?.()||[],t=Je.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0){console.warn(`[FlowEngageProvider] no local audio tracks available for mute`);return}let r=!Ue;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),We(r)},xt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(ue(!0),!(!t||!C.current||!_||typeof window>`u`)){try{await C.current.trackVisitor({chatId:_,currentPagePath:window.location.pathname||`/`})}catch{}try{await C.current.updateChatStatus(_,`open`)}catch{}}},St=async e=>{let t=ut(e);if(!t||!C.current||!w.current)return t;try{await C.current.trackVisitor({chatId:w.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Ct=()=>{if(!_||!S.current?.connected||nt.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:_,socketConnected:!!S.current?.connected,alreadyTyping:nt.current});return}nt.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:_,sender:`user`}),S.current.emit(`typing:start`,{chatId:_,sender:`user`})},wt=()=>{if(!_||!S.current?.connected||!nt.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:_,socketConnected:!!S.current?.connected,wasTyping:nt.current});return}nt.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:_,sender:`user`}),S.current.emit(`typing:stop`,{chatId:_,sender:`user`})},Tt=(e=``)=>{let t=typeof e==`string`?e:``;if(!_||!S.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:_,socketConnected:!!S.current?.connected,textLength:t.length});return}rt.current!==t&&(rt.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:_,sender:`user`,textLength:t.length}),S.current.emit(`typing:update`,{chatId:_,sender:`user`,text:t}))},Et=async(e,t=``,n=null)=>{if(!e.trim()||!C.current||!_||o!==`ready`||Pe)return;wt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(y(e=>[...e,a]),pe&&S.current?.connected){S.current.emit(`customer:message`,{chatId:_,content:e,sender:`user`,email:ye||void 0,...n||{}});return}Oe(!0);try{let i=await C.current.sendAiMessage(_,e,r,t,{...n||{},...ye?{email:ye}:{}});y(wn(i.chat_history||[])),me(!!i.is_human_handled),fe(i.is_human_handled?`agent`:`ai`),we(!1),await C.current.updateChatStatus(_,`messageSent`)}catch(e){y(e=>e.filter(e=>e.id!==i)),we(!1),e.status===429?(Ae(!0),Me(e.message),window.setTimeout(()=>{Ae(!1),Me(``)},m)):f(e)}finally{Oe(!1)}},Dt=async e=>{if(!(!C.current||!_)){try{let t=e?`voice`:`text`;await C.current.setChatMode(_,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}b(e),e&&(ot.current=!1)}},Ot=async e=>{if(!ot.current){if(ot.current=!0,!C.current||!_||!e?.length){b(!1);return}try{let t=await C.current.syncVoice(_,e);if(t?.chat_history?.length)y(wn(t.chat_history));else if(t?.success)try{let e=await C.current.loadHistory(_,r);e?.chat_history?.length&&y(wn(e.chat_history))}catch{}}catch{}finally{b(!1)}}},kt=async()=>{if(!(!C.current||!_)){Ne&&!ot.current&&at.current.length>0&&await Ot(at.current);try{await C.current.endConversation(_)}catch{try{await C.current.updateChatStatus(_,`ended`)}catch{}}Fe(!0),y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,l.useEffect)(()=>{if(ze!==`connected`||!Le||!_||!Ve||!ct)return;let e=new Date(Ve).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,ct*1e3-t),r=window.setTimeout(()=>{Ke(`The call ended because it reached the time limit.`),yt()},n);return()=>window.clearTimeout(r)},[Le,Ve,ze,_,yt,ct]),(0,l.useEffect)(()=>{let e=()=>{let e=w.current,t=C.current;if(!t||!e)return;if($e.current){t.beaconEndWebRTCCall($e.current,e);return}let n=et.current||qe.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let T=(0,l.useMemo)(()=>({status:o,error:c,runtimeConfig:p,resolvedConfig:i,chatId:_,chatHistory:v,isOpen:le,activeScreen:de,isHumanHandled:pe,agentName:he,agentHeadshot:_e,visitorEmail:ye,isAgentTyping:xe,isAiTyping:Ce,connectionStatus:Te,isLoading:De,isVoiceMode:Ne,isRateLimited:ke,rateLimitMessage:je,isConversationEnded:Pe,incomingCall:x,activeCallId:Le,callConnectionState:ze,callConnectedAt:Ve,isCallMuted:Ue,webRTCError:Ge,language:r,historyRef:at,hasSyncedRef:ot,dismissCallError:lt,captureVisitorEmail:St,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt,notifyRouteChange:()=>st.current?.notifyRouteChange?.(),openWidget:xt,closeWidget:()=>ue(!1),toggleWidget:()=>{if(le){ue(!1);return}xt({notifyChatInitiated:!0})},sendMessage:Et,setVoiceMode:Dt,onMessageSync:Ot,endConversation:kt,acceptCall:gt,rejectCall:_t,endWebRTCCall:yt,toggleCallMute:bt,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt}),[o,c,p,i,_,v,le,de,pe,he,_e,ye,xe,Ce,Te,De,Ne,ke,je,Pe,x,Le,ze,Ve,Ue,Ge,r,St,Ct,wt,Tt,gt,_t,yt,bt,xt,Et,Dt,Ot,kt,lt]);return(0,u.jsx)(Jt.Provider,{value:T,children:n})}var An=({color:e=`#3888FF`})=>(0,u.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,u.jsx)(`path`,{d:`M26 8H14C12.3431 8 11 9.34315 11 11V23C11 24.6569 12.3431 26 14 26H26C27.6569 26 29 24.6569 29 23V11C29 9.34315 27.6569 8 26 8Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M16.4067 20.5924C16.182 20.3674 16.1822 20.003 16.407 19.7783L22.7805 13.4068C23.0051 13.1821 23.3694 13.1823 23.5939 13.4071V13.4071C23.8182 13.6317 23.8181 13.9956 23.5936 14.2201L17.2212 20.5926C16.9962 20.8176 16.6315 20.8174 16.4067 20.5924V20.5924Z`,fill:`#3E87C8`})]}),jn=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,u.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),Mn=({size:e=18,color:t=`currentColor`})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),Nn=({size:e=20})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,u.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Pn=()=>(0,u.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,u.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),Fn=()=>(0,u.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,u.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),In=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,u.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),Ln=({className:e=``})=>(0,u.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,u.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,u.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),Rn=({size:e=18,strokeWidth:t=2.5})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,u.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),zn=({size:e=14})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M12 8V4H8`}),(0,u.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,u.jsx)(`path`,{d:`M2 14h2`}),(0,u.jsx)(`path`,{d:`M20 14h2`}),(0,u.jsx)(`path`,{d:`M15 13v2`}),(0,u.jsx)(`path`,{d:`M9 13v2`})]});function Bn({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){let[a,o]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 640px)`),t=e=>{o(e.matches)};return o(e.matches),typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):(e.addListener(t),()=>e.removeListener(t))},[]),e?null:(0,u.jsxs)(`button`,{type:`button`,onClick:()=>t({notifyChatInitiated:!0}),"aria-label":n,style:{position:`fixed`,...i,zIndex:999999,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:a?`0`:`14px`,width:a?`60px`:`auto`,minWidth:a?`60px`:`unset`,height:a?`60px`:`auto`,padding:a?`0`:`14px 24px`,border:`none`,borderRadius:`9999px`,background:r,color:`#fff`,fontSize:`16px`,fontWeight:`600`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,cursor:`pointer`,boxShadow:`0 8px 24px rgba(0,0,0,0.18)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,outline:`none`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 12px 28px rgba(0,0,0,0.22)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 8px 24px rgba(0,0,0,0.18)`},children:[a?null:(0,u.jsx)(`span`,{children:n}),a?(0,u.jsx)(An,{color:`#fff`}):(0,u.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,u.jsx)(jn,{})})]})}function Vn(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function Hn({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,l.useState)(!1),o=typeof e==`string`?e.trim():``;return(0,l.useEffect)(()=>{a(!1)},[o]),o&&!i?(0,u.jsx)(`img`,{src:o,alt:``,onError:()=>a(!0),style:n}):(0,u.jsx)(`span`,{style:r,children:Vn(t)})}function Un(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function Wn(e){let[t,n]=(0,l.useState)(`loading`),r=Un(e);return(0,l.useEffect)(()=>{if(l.default.isValidElement(e)||typeof e==`function`){n(`square`);return}if(!r){n(`error`);return}n(`loading`);let t=new Image,i=!1;return t.onload=()=>{i||n(t.naturalWidth/t.naturalHeight>1.3?`wide`:`square`)},t.onerror=()=>{i||n(`error`)},t.src=r,()=>{i=!0}},[e,r]),{state:t,resolvedLogoUrl:r}}function Gn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c,botLabel:d=`AI`,agentAvatarUrl:f=null,primaryColor:p=`#3B82F6`}){let{state:m,resolvedLogoUrl:ee}=Wn(e),h=i===`agent`,g=n||r||a?.fallbackAgentName||`Agent`;return(0,u.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,padding:`16px 20px`,borderTopLeftRadius:`inherit`,borderTopRightRadius:`inherit`,border:`none`,transition:`all 0.3s ease`,background:c?`transparent`:`#fff`,color:c?`#fff`:`#111827`,boxShadow:c?`none`:`0 1px 0 rgba(0,0,0,0.05), 0 10px 24px rgba(0,0,0,0.04)`,borderBottom:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[h?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:c?`rgba(255,255,255,0.2)`:`#f3f4f6`,color:c?`#fff`:p,fontWeight:800,fontSize:`15px`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},children:(0,u.jsx)(Hn,{src:typeof f==`string`?f:``,name:g,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}):(0,u.jsxs)(u.Fragment,{children:[m!==`loading`&&(m===`error`||!ee&&!e?(0,u.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0}}):l.default.isValidElement(e)?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:e}):typeof e==`function`?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(e,{})}):m===`wide`?(0,u.jsx)(`div`,{style:{height:`36px`,maxWidth:`88px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`12px`,padding:`4px 8px`,background:c?`rgba(255,255,255,0.15)`:`#f9fafb`,backdropFilter:c?`blur(12px)`:`none`,border:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{width:`100%`,height:`100%`,objectFit:`contain`,padding:ee.toLowerCase().includes(`.svg`)||ee.startsWith(`data:image/svg`)?0:`2px`}})})),m===`loading`&&(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,u.jsxs)(`div`,{children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,u.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,borderRadius:`6px`,background:`rgba(255,255,255,0.95)`,padding:`3px 6px`,fontSize:`10px`,fontWeight:800,letterSpacing:`0.5px`,color:`var(--flowengage-primary)`},children:[(0,u.jsx)(zn,{size:11}),(0,u.jsx)(`span`,{children:d})]})]}),(0,u.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,u.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,u.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,u.jsx)(`button`,{style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`transparent`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,border:0,cursor:`pointer`,color:c?`#fff`:`#000`},onClick:s,"aria-label":`Close chat`,onMouseEnter:e=>{e.currentTarget.style.background=c?`rgba(255,255,255,0.1)`:`rgba(0,0,0,0.05)`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,u.jsx)(Rn,{})})})]})}var Kn=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),qn=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`);function Jn(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var Yn=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return Jn(t);let n=t.replace(/\r\n/g,`
25
+ `,document.head.appendChild(e)};function rn(e,t){if(typeof document>`u`)return null;if(e){let n=document.getElementById(e)||document.querySelector(`[data-section="${e}"]`);if(n)return n;t||=e.replace(/[-_]+/g,` `).trim()}if(!t)return null;let n=t.toLowerCase().trim(),r=n.split(/\s+/).filter(e=>e.length>2),i=Array.from(document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`)).filter(e=>!Zt(e));for(let e of i)if(e.textContent.replace(/\s+/g,` `).toLowerCase().trim()===n)return e;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.startsWith(n)||t.endsWith(n))return e}let a=[];for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.includes(n)&&a.push({el:e,len:t.length})}if(a.length)return a.sort((e,t)=>e.len-t.len),a[0].el;for(let e of i){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.length>3&&n.includes(t))return e}if(r.length>0){let e=null,t=0;for(let n of i){let i=n.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let e of r)i.includes(e)&&a++;let o=a/r.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let o=Array.from(document.querySelectorAll(`main [role='group']`)).filter(e=>!Zt(e)),s=[];for(let e of o){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();t.length<15||t.length>8e3||t.includes(n)&&s.push({el:e,len:t.length})}if(s.length)return s.sort((e,t)=>e.len-t.len),s[0].el;if(r.length>0){let e=Array.from(document.querySelectorAll(`main a[href], article a[href], .views-row a[href], h2 a[href], h3 a[href], .card a[href], [class*='teaser'] a[href]`)).filter(e=>{if(Zt(e))return!1;try{let t=e.getAttribute(`href`)||``;if(!t||t===`#`||t.startsWith(`javascript:`))return!1}catch{return!1}let t=e.textContent.replace(/\s+/g,` `).trim();return t.length>=3&&t.length<=220}),t=null,n=0;for(let i of e){let e=i.textContent.replace(/\s+/g,` `).toLowerCase(),a=0;for(let t of r)e.includes(t)&&a++;let o=a/r.length;o>n&&o>=.5&&(n=o,t=i)}if(t)return t.closest(`article`)||t.closest(`.views-row`)||t}let c=document.querySelectorAll(`section, article, .card, [class*='feature'], [class*='service']`);for(let e of c){if(Zt(e))continue;let t=e.querySelector(`h1, h2, h3, h4, h5, h6`);if(t){let r=t.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(r.includes(n)||n.includes(r))return e}}let l=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of l){if(Zt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let u=Array.from(document.querySelectorAll(`a[href]`)).filter(e=>!Zt(e));u.sort((e,t)=>(e.textContent||``).trim().length-(t.textContent||``).trim().length);for(let e of u){let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<500)return e}let d=document.querySelectorAll(`p`);for(let e of d){if(Zt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase().trim();if(t.includes(n)&&t.length<800)return e}return null}function an(){return document.querySelector(`[itemprop='articleBody'], .article-body, .post-content, .entry-content, .field--name-body, .field--body, .node__content, article .content, .prose, article .prose`)||document.querySelector(`main article, main, [role='main'], article`)||document.body}var on=new Set(`the.and.for.are.but.not.you.all.can.her.was.one.our.out.day.get.has.him.his.how.its.may.new.now.old.see.two.way.who.did.let.put.say.she.too.use.has.have.this.that.with.from.they.will.your.about.into.than.then.some.very.when.come.here.just.like.also.back.after.over.such.take.only.know.think.each.made.look.more.most.other.well`.split(`.`));function sn(e){return String(e||``).toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>0)}function cn(e,t){let n=sn(e).slice(-Math.min(t,28)),r=n.filter(e=>e.length>2&&!on.has(e));return r.length>=2?r:n.filter(e=>e.length>2).slice(-12)}function ln(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`h1, h2, h3, h4, h5, h6, p, li, blockquote`,`main h2, main h3, main h4, article h2, article h3, article h4`,`section h2, section h3, section h4`].join(`, `)),i=null,a=0;for(let e of r){if(Zt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<3||n.length>6e3)continue;let r=0;for(let e of t)n.includes(e)&&r++;let o=r/t.length;if(o<.2)continue;let s=o,c=e.tagName;(c===`H2`||c===`H3`||c===`H4`)&&(s*=1.35),(c===`P`||c===`BLOCKQUOTE`)&&(s*=1.15),c?.startsWith(`H`)&&n.length<80&&(s*=1.2),n.length>400&&(s*=.65),s>a&&(a=s,i=e)}let o=n?t.length<=1?.62:.5:t.length<=1?.55:.35;return a>=o?i:null}function un(e,t,{strict:n=!1}={}){if(!e||!t?.length)return null;let r=e.querySelectorAll([`main [role='group']`,`[class*='card']`,`[class*='Card']`,`[class*='column']`,`[class*='grid'] > div`,`[class*='grid'] > article`,`[data-section]`].join(`, `)),i=null,a=0;for(let e of r){if(Zt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], [role='banner'], footer`))continue}catch{}let n=e.textContent.replace(/\s+/g,` `).toLowerCase();if(n.length<10||n.length>9e3)continue;let r=0;for(let e of t)e.length>1&&n.includes(e)&&r++;let o=r/t.length;if(o<.12)continue;let s=o,c=e.tagName;(c===`ARTICLE`||c===`SECTION`)&&(s*=1.05),n.length<900&&(s*=1.18),n.length<420&&(s*=1.12),n.length>2600?s*=.28:n.length>1400&&(s*=.45);try{e.querySelectorAll(`:scope > [role='group'], :scope > article, :scope > section`).length>=3&&n.length>1200&&(s*=.3)}catch{}s>a&&(a=s,i=e)}let o=n?t.length<=1?.48:.34:t.length<=1?.38:.2;return a>=o?i:null}function dn(e){return/^H[1-6]$/i.test(e?.tagName||``)}function fn(e,t,n=!1){if(!e||!t)return null;let r=t.replace(/\s+/g,` `).trim();if(r.length<14)return null;let i=n?.34:.24,a=r.toLowerCase(),o=cn(r,24);if(o.length<3&&(o=a.replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2).slice(-18)),o.length<3)return null;let s=e.querySelectorAll(`p, blockquote`),c=null,l=0;for(let e of s){if(Zt(e))continue;let t=e.textContent.replace(/\s+/g,` `).toLowerCase();if(t.length<24)continue;let n=0;for(let e of o)t.includes(e)&&n++;let r=n/o.length,s=0;for(let e=Math.min(90,a.length);e>=22;e-=6){let n=a.slice(-e).trim();if(n.length>=22&&t.includes(n)){s=.28;break}}let u=r+s;u>l&&r>=i&&(l=u,c=e)}return c}function pn(e,t={}){if(typeof document>`u`||!e||!String(e).trim())return null;let n=t.strict===!0,r=String(e).trim(),i=r.length>450?r.slice(-450).trim():r,a=an(),o=cn(r,26);if(o.length>=1&&(o.length>=2||o.length===1&&o[0].length>=3)){let e=un(a,o,{strict:n});if(e)return e}if(r.length>=(n?55:42)){let e=fn(a,i,n);if(e)return e}if((!n||o.length>=3||o.length===2&&o.every(e=>e.length>=5))&&(o.length>=2||o.length===1&&o[0].length>=5)){let e=ln(a,o,{strict:n});if(e)return e}let s=i.split(/(?<=[.!?])\s+/).filter(e=>e.trim().length>0),c=s[s.length-1]||i,l=c.toLowerCase().replace(/[^\w\s'-]/g,` `).split(/\s+/).filter(e=>e.length>2),u=[];c.length>=10&&(u.push(c.slice(-220).trim()),c.length>220&&u.push(c.slice(0,120).trim()));for(let e=4;e<=Math.min(10,l.length);e++)u.push(l.slice(-e).join(` `));for(let e=Math.min(14,l.length);e>=11;e--)u.push(l.slice(-e).join(` `));for(let e=Math.min(8,l.length);e>=3;e--)u.push(l.slice(-e).join(` `));let d=n?14:6,f=new Set;for(let e of u){let t=e.trim();if(t.length<d||f.has(t))continue;f.add(t);let n=rn(null,t);if(n&&!Zt(n)){if(dn(n)&&r.length>140){let e=(a.querySelector?.(`[itemprop='articleBody'], .article-body, .post-content, .entry-content`)||a).querySelectorAll?.(`p, blockquote`)||[];for(let n of e)if(!Zt(n)&&n.textContent.toLowerCase().includes(t.toLowerCase().slice(0,Math.min(48,t.length))))return n}return n}}let p=o.length>=3?o:l.slice(-22);if(p.length===0)return null;let m=null,ee=-1,h=a.querySelectorAll(`h1, h2, h3, h4, h5, h6, p, li, blockquote, article`);for(let e of h){if(Zt(e))continue;try{if(e.closest(`aside, nav, [role='navigation'], footer`))continue}catch{}let t=e.textContent.toLowerCase();if(t.length<12)continue;let i=0;for(let e of p)e.length>2&&t.includes(e)&&i++;let a=i/p.length,o=e.tagName;(o===`P`||o===`BLOCKQUOTE`||o===`LI`)&&(a*=1.22),dn(e)&&(r.length>110?a*=.48:a*=.92),o===`ARTICLE`&&r.length>80&&(a*=.55),a>ee&&a>=(n?.42:.28)&&(ee=a,m=e)}return m}function mn(e){if(!e||typeof document>`u`)return null;try{if(Zt(e))return e;let t=e.closest?.([`[role='group']`,`[class*='card']`,`[class*='Card']`,`[data-section]`,`[class*='grid'] > div`,`[class*='grid'] > article`].join(`, `)),n=t?.textContent?.replace(/\s+/g,` `)||``;if(t&&!Zt(t)&&n.length>20&&n.length<=5200)return t;let r=e.closest?.(`p, li, blockquote, td, th, dd, figcaption, pre`);if(r&&!Zt(r))return r;let i=e.closest?.(`section`),a=i?.textContent?.replace(/\s+/g,` `)||``;return i&&a.length>48&&a.length<=4e3&&!Zt(i)?i:e}catch{return e}}function hn(e){if(!e||typeof e.getBoundingClientRect!=`function`)return!0;try{let t=e.getBoundingClientRect(),n=window.innerHeight||800;if(t.bottom<=72||t.top>=n-72)return!0;let r=Math.max(0,t.top),i=Math.min(n,t.bottom),a=Math.max(0,i-r),o=Math.min(120,Math.max(40,t.height*.28));return t.height>24&&a<o}catch{return!0}}function gn(e,{speaking:t=!1,scroll:n=!0}={}){if(!e||typeof document>`u`)return;nn();let r=document.querySelectorAll(`.fe-highlight-section`);for(let t of r)t!==e&&(t.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`),t.classList.add(`fe-highlight-exiting`),setTimeout(()=>t.classList.remove(`fe-highlight-exiting`),300));if(e.classList.remove(`fe-highlight-exiting`),e.classList.add(`fe-highlight-section`),t?e.classList.add(`fe-highlight-speaking`):e.classList.remove(`fe-highlight-speaking`),n)try{e.scrollIntoView({behavior:`smooth`,block:`center`})}catch{try{e.scrollIntoView(!0)}catch{}}}function _n(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section, .fe-highlight-exiting`).forEach(e=>e.classList.remove(`fe-highlight-section`,`fe-highlight-speaking`,`fe-highlight-exiting`))}function vn(e){if(typeof window>`u`)return e;try{let t=new URL(String(e).trim(),window.location.href);return!/^https?:$/i.test(t.protocol)||t.origin===window.location.origin?t.href:new URL(t.pathname+t.search+t.hash,window.location.origin).href}catch{return e}}async function yn(e){if(typeof window>`u`)return!1;try{let t=new URL(String(e).trim(),window.location.href);return t.origin===window.location.origin?(await fetch(t.href,{method:`HEAD`,mode:`same-origin`,cache:`no-store`})).ok:!1}catch{return!1}}async function bn(e,{siteId:t,apiBaseUrl:n}){if(!e)return!1;if(!t||!n)return console.warn(`[FlowEngage] shouldProceedWithNavigation: missing siteId or apiBaseUrl`),!1;let r=String(n).replace(/\/$/,``),i=new URLSearchParams({siteId:String(t),url:String(e).trim()});try{let t=await(await fetch(`${r}/api/widget/navigate-allowed?${i.toString()}`)).json().catch(()=>({}));return t.success?t.allowed?!0:t.hasIndex===!1?yn(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}function xn(e){if(!(!e||typeof sessionStorage>`u`))try{sessionStorage.setItem($t,JSON.stringify({sectionText:e,ts:Date.now()}))}catch{}}async function Sn(e,t={}){if(typeof window>`u`)return!1;let{sectionText:n}=t;try{let t=vn(e),r=new URL(t,window.location.origin);if(Qt(`input:`,e,`→ normalized:`,t,`href:`,r.href),r.hash&&r.pathname===window.location.pathname){let e=r.hash.slice(1),t=document.getElementById(e);if(t)return Qt(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(r.pathname===window.location.pathname&&r.search===window.location.search&&!r.hash)return Qt(`branch: already on page (no nav)`),!1;let i=r.pathname+r.search+r.hash,a=window.next?.router;if(a?.push)return Qt(`branch: Next.js Pages router.push`,i),new Promise(e=>{let t=()=>{a.events?.off(`routeChangeComplete`,t),e(!0)};a.events?.on(`routeChangeComplete`,t),a.push(i),setTimeout(t,5e3)});let o=window.__NEXT_ROUTER__;return o?.push?(Qt(`branch: __NEXT_ROUTER__.push`,i),o.push(i),!0):(n?(xn(n),Qt(`branch: location.assign (full navigation, section stored):`,n)):Qt(`branch: location.assign (full navigation)`,r.href),window.location.assign(r.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t),n&&xn(n);try{window.location.href=vn(e)}catch{window.location.href=e}return!0}}var Cn=e=>!e||typeof e!=`string`?e:e.replace(/<human_assistance_request>[\s\S]*?<\/human_assistance_request>/gi,``).replace(/<human_assistance_request>/gi,``).replace(/<\/human_assistance_request>/gi,``).replace(/<navigate[^>]*\/>/gi,``).replace(/<navigate[^>]*>[\s\S]*?<\/navigate>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*>[\s\S]*?<\/[a-z]+(?:_[a-z]+)+>/gi,``).replace(/<[a-z]+(?:_[a-z]+)+[^>]*\/>/gi,``).trim(),wn=(e=[])=>e.map(e=>({...e,message:Cn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),Tn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,En=(e={})=>{if(!e?.candidate)return null;if(typeof e.candidate==`object`)return e.candidate;let t=e.sdpMid!==void 0&&e.sdpMid!==null&&e.sdpMid!==``,n=e.sdpMLineIndex!==void 0&&e.sdpMLineIndex!==null;return!t&&!n?null:{candidate:e.candidate,...t?{sdpMid:e.sdpMid}:{},...n?{sdpMLineIndex:e.sdpMLineIndex}:{}}},Dn=e=>{if(!e)return null;let t=typeof e==`object`?e:{candidate:e};return{hasCandidate:!!t.candidate,sdpMid:t.sdpMid??null,sdpMLineIndex:t.sdpMLineIndex??null,candidatePreview:typeof t.candidate==`string`?t.candidate.slice(0,80):null}},On=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function kn({siteId:e,config:t,children:n,language:r=`en`}){let i=(0,l.useMemo)(()=>e?{...t||{},siteId:e}:t||null,[e,t]),a=(0,l.useMemo)(()=>On([i?.widgetSettings?.branding?.fallbackAgentName,i?.widgetSettings?.branding?.headerName],`Agent`),[i]),[o,s]=(0,l.useState)(`booting`),[c,f]=(0,l.useState)(null),[p,g]=(0,l.useState)(null),[_,oe]=(0,l.useState)(``),[v,y]=(0,l.useState)([]),[le,ue]=(0,l.useState)(ne().isOpen),[de,fe]=(0,l.useState)(ne().activeScreen),[pe,me]=(0,l.useState)(ne().isHumanHandled),[he,ge]=(0,l.useState)(ne().agentName),[_e,ve]=(0,l.useState)(ne().agentHeadshot),[ye,be]=(0,l.useState)(()=>ie(i?.siteId)),[xe,Se]=(0,l.useState)(!1),[Ce,we]=(0,l.useState)(!1),[Te,Ee]=(0,l.useState)(`idle`),[De,Oe]=(0,l.useState)(!1),[ke,Ae]=(0,l.useState)(!1),[je,Me]=(0,l.useState)(``),[Ne,b]=(0,l.useState)(!1),[Pe,Fe]=(0,l.useState)(!1),[x,Ie]=(0,l.useState)(null),[Le,Re]=(0,l.useState)(null),[ze,Be]=(0,l.useState)(`idle`),[Ve,He]=(0,l.useState)(null),[Ue,We]=(0,l.useState)(!1),[Ge,Ke]=(0,l.useState)(``),S=(0,l.useRef)(null),C=(0,l.useRef)(null),w=(0,l.useRef)(``),qe=(0,l.useRef)(null),Je=(0,l.useRef)(null),Ye=(0,l.useRef)(null),Xe=(0,l.useRef)(null),Ze=(0,l.useRef)(null),Qe=(0,l.useRef)([]),$e=(0,l.useRef)(null),et=(0,l.useRef)(null),tt=(0,l.useRef)(!1),nt=(0,l.useRef)(!1),rt=(0,l.useRef)(``),it=(0,l.useRef)(he),at=(0,l.useRef)([]),ot=(0,l.useRef)(!1),st=(0,l.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),ct=(0,l.useMemo)(()=>{let e=p?.widgetSettings?.call?.maxDurationSeconds??i?.widgetSettings?.call?.maxDurationSeconds??i?.callMaxDurationSeconds,t=Number(e);return Number.isFinite(t)&&t>0?t:ee},[i,p]);(0,l.useEffect)(()=>{qe.current=x},[x]),(0,l.useEffect)(()=>{it.current=he},[he]);let lt=()=>{Ke(``)},ut=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return be(t),ae(t,i?.siteId),t};(0,l.useEffect)(()=>{let e=i?.siteId;e&&be(ie(e))},[i?.siteId]);let dt=()=>{Je.current&&=(Je.current.close(),null),Ye.current&&=(Ye.current.getTracks().forEach(e=>e.stop()),null),Xe.current&&=(Xe.current.srcObject=null,Xe.current.remove(),null),Ze.current=null,Qe.current=[],$e.current=null,et.current=null,tt.current=!1,We(!1),Ie(null),Re(null),Be(`idle`),He(null)},ft=(e=new Date().toISOString())=>{let t=S.current,n=$e.current||Ze.current?.callId;if(!t?.connected||!n||tt.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:w.current,socketConnected:!!t?.connected,alreadyReported:tt.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:w.current,connectedAt:e}),tt.current=!0,t.emit(`call:connected`,{callId:n,chatId:w.current,connectedAt:e})},pt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||w.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Ie(null),t||n){$e.current=e.callId,Re(e.callId),Be(e=>e===`connected`?e:`connecting`),ue(!0);return}Be(`idle`)}},mt=(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=qe.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||w.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){dt();return}et.current=null,Ze.current=null,Qe.current=[],Ie(null),Be(`idle`)}},ht=async(e={})=>{let t=Je.current,n=S.current,r=e.sdpOffer||e.offer?.sdp;if(!t||!n?.connected||!r||!e.callId){console.log(`[FlowEngageProvider] deferring remote offer until peer/socket ready`,{callId:e.callId,chatId:w.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Ze.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:w.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Qe.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:w.current,queuedCount:Qe.current.length});for(let e of Qe.current)await t.addIceCandidate(new RTCIceCandidate(e));Qe.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:w.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:w.current})};(0,l.useEffect)(()=>{re({isOpen:le,activeScreen:de,isHumanHandled:pe,agentName:he,agentHeadshot:_e})},[le,de,pe,he,_e]),(0,l.useEffect)(()=>{let e=!0;return(async()=>{try{console.log(`[FlowEngageProvider] boot start`,{resolvedConfig:i,language:r});let t=d(i);console.log(`[FlowEngageProvider] config validated`,t);let n=await se(t);if(!e)return;let o=te();w.current=o;let c=ce({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});C.current=c,g({...n,apiBaseUrl:t.apiBaseUrl}),oe(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Kt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});S.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),Ee(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),Ee(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:w.current}),we(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:w.current}),we(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:Cn(t.message)};we(!1),Se(!1),y(e=>[...e.filter(e=>!e.isPending),{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}])}),l.on(`conversationStarted`,e=>{console.log(`[FlowEngageProvider] conversationStarted`,e),e?.message&&y(t=>[...t,{id:`system-start-${Date.now()}`,sender:`system`,message:e.message,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`message:new`,e=>{let t=e.message||e,n={...t,message:Cn(t.message)};we(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&Se(!1),y(e=>n.sender===`bot`||n.sender===`ai`?[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]:e.some(e=>e.id===n.messageId||e.sender===n.sender&&e.message===n.message&&e.isPending)?e.map(e=>e.sender===n.sender&&e.message===n.message&&e.isPending?{...n,isPending:!1,id:n.messageId||e.id}:e):[...e,{...n,isPending:!1,id:n.messageId||`${n.sender}-${Date.now()}-${Math.random()}`}]),(n.sender===`agent`||n.agent_name)&&(me(!0),fe(`agent`),ge(On([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&ve(n.sender_headshot),ue(!0))}),l.on(`agent:joined`,e=>{let t=On([e.agent?.name,e.agentName],a);me(!0),fe(`agent`),ge(t),ve(e.agent?.headshot||null),ue(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentJoined`,e=>{let t=On([e.agent?.name,e.agentName],a);me(!0),fe(`agent`),ge(t),ve(e.agent?.headshot||null),ue(!0),y(e=>[...e,{id:`agent-joined-${Date.now()}`,sender:`system`,message:`${t} has joined the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agent:left`,(e={})=>{let t=On([e.agent?.name,e.agentName,it.current],a);me(!1),fe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`agentLeft`,(e={})=>{let t=On([e.agent?.name,e.agentName,it.current],a);me(!1),fe(`ai`),y(e=>[...e,{id:`agent-left-${Date.now()}`,sender:`system`,message:`${t} has left the chat.`,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`conversationEnded`,e=>{Fe(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{y(wn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||w.current,sender:e?.sender}),e.sender===`agent`&&Se(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||w.current,sender:e?.sender}),e.sender===`agent`&&Se(!1)}),l.on(`call:incoming`,(e={})=>{let t=On([e.agentName,e.ownerName,e.agent?.name,he],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:w.current,agentName:t}),lt(),tt.current=!1,Ie({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ge(e=>On([t,e],a)),Be(`incoming`),He(null),ue(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||w.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Ze.current=e;try{await ht(e)}catch(e){console.error(`[FlowEngageProvider] failed to apply remote offer`,e)}}),l.on(`call:ice-candidate-from-agent`,async(e={})=>{if(!e.candidate){console.log(`[FlowEngageProvider] skipping agent ICE candidate`,{callId:e.callId,chatId:e.chatId||w.current,hasPeerConnection:!!Je.current,hasCandidate:!!e.candidate});return}try{let t=En(e);if(!t){console.warn(`[FlowEngageProvider] ignoring invalid ICE candidate payload`,e);return}if(console.log(`[FlowEngageProvider] adding agent ICE candidate`,{callId:e.callId,chatId:e.chatId||w.current,candidate:Dn(t),hasRemoteDescription:!!Je.current?.remoteDescription}),!Je.current||!Je.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||w.current,queueSize:Qe.current.length+1}),Qe.current.push(t);return}await Je.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{lt(),dt()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||w.current}),pt(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||w.current}),pt(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||w.current,reason:e.reason}),mt(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=et.current===e.callId,n=$e.current===e.callId,r=Ze.current?.callId===e.callId,i=qe.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||w.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isPendingOfferHere:r,isIncomingHere:i}),!t&&!n&&!r){i&&(Ie(null),Be(`idle`));return}tt.current=!0,et.current=null,$e.current=e.callId,Re(e.callId),Ie(null),Be(`connected`),He(e.connectedAt||new Date().toISOString()),ue(!0)}),l.on(`call:unavailable`,(e={})=>{dt(),Ke(Tn(e,`This visitor is not available for a call right now.`)),ue(!0)}),l.on(`call:error`,(e={})=>{dt(),Ke(Tn(e,`We couldn't connect the call right now.`)),ue(!0)}),l.on(`visitor:navigate`,async({url:e,section:n,highlight:r}={})=>{if(e){if(console.log(`[FlowEngageProvider] visitor:navigate`,{url:e,section:n,highlight:r}),!await bn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}Sn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=rn(null,t);e&&gn(e)},e?300:150)})}}),l.on(`visitor:highlight`,({sectionId:e,sectionText:t}={})=>{if(!e&&!t)return;console.log(`[FlowEngageProvider] visitor:highlight`,{sectionId:e,sectionText:t});let n=rn(e||null,t||null);n&&gn(n)}),l.on(`visitor:clear_highlight`,()=>{_n()}),st.current=qt({socket:l,chatId:o}),console.log(`[FlowEngageProvider] tracking started`,{chatId:o});let u=await c.loadHistory(o,r);if(console.log(`[FlowEngageProvider] history loaded`,u),!e||(y(wn(u.chat_history||[])),me(!!u.is_human_handled),fe(u.is_human_handled?`agent`:de),await new Promise(e=>setTimeout(e,500)),!e))return;s(`ready`),console.log(`[FlowEngageProvider] status ready`)}catch(t){if(!e)return;console.error(`[FlowEngageProvider] boot failed`,t),f(t),s(`error`)}})(),()=>{e=!1,st.current?.cleanup?.(),dt(),S.current?.disconnect()}},[i,r]),(0,l.useEffect)(()=>()=>{if(Ne&&!ot.current&&at.current.length>0){let e=w.current,t=at.current,n=C.current;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(e,t)||n.syncVoice(e,t).catch(()=>{}),ot.current=!0)}},[Ne,p]),(0,l.useEffect)(()=>{if(!C.current||!_||o!==`ready`||pe)return;let e=window.setInterval(async()=>{try{let e=await C.current.checkHumanHandled(_);me(!!e.is_human_handled),e.is_human_handled&&(fe(`agent`),e.agent_info?.name&&ge(e.agent_info.name),e.agent_info?.headshot&&ve(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[_,o,pe]);let gt=async()=>{if(!(!x?.callId||!C.current||!S.current||!_)){lt(),et.current=x.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:x?.callId,chatId:_,socketConnected:!!S.current?.connected,hasPendingOffer:!!Ze.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:x.callId,chatId:_,trackCount:e.getTracks().length}),Ye.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Je.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:x.callId,chatId:_,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),ft(e);return}e===`connecting`&&Be(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:x.callId,chatId:_,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),ft(e);return}(e===`checking`||e===`new`)&&Be(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!S.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:x.callId,chatId:_,hasCandidate:!!e.candidate,socketConnected:!!S.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:x.callId,chatId:_,candidate:Dn(e.candidate)}),S.current.emit(`call:ice-candidate`,{callId:x.callId,candidate:e.candidate,chatId:_,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:x.callId,chatId:_,streamCount:e.streams?.length||0}),!Xe.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Xe.current=e,document.body.appendChild(e)}Xe.current.srcObject=e.streams[0];let t=x?.callId,n=t&&(et.current===t||$e.current===t);if(!tt.current&&n){let e=new Date().toISOString();Be(`connected`),He(t=>t||e),$e.current=t,Re(t),ft(e)}};let n=Ze.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||x.callId,chatId:_}),await ht({...n,callId:n.callId||x.callId})),await C.current.acceptCall(x.callId,_),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:x.callId,chatId:_}),$e.current=x.callId,Re(x.callId),Be(`connecting`),Ie(null),ue(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),et.current=null,dt(),e?.status===404||e?.status===409||e?.status===422){Ke(Tn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await C.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Ke(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Ke(`We couldn't connect the call right now. Please try again.`)}}},_t=async()=>{if(!x?.callId||!C.current||!_){dt();return}lt();try{await C.current.rejectCall(x.callId,_)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Ke(Tn(e,`We couldn't decline the call cleanly.`))}finally{dt()}},vt=(0,l.useRef)(_t);vt.current=_t,(0,l.useEffect)(()=>{if(!x?.callId||Le)return;let e=x.callId,t=window.setTimeout(()=>{qe.current?.callId===e&&vt.current()},h);return()=>window.clearTimeout(t)},[x?.callId,Le]);let yt=async()=>{if(!Le||!C.current||!_){dt();return}lt();try{await C.current.endWebRTCCall(Le,_)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Ke(Tn(e,`The call ended locally, but the server could not be updated.`))}finally{dt()}},bt=()=>{let e=Ye.current?.getAudioTracks?.()||[],t=Je.current?.getSenders?.().map(e=>e.track).filter(e=>e?.kind===`audio`)||[],n=[...e,...t].filter(Boolean);if(n.length===0){console.warn(`[FlowEngageProvider] no local audio tracks available for mute`);return}let r=!Ue;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),We(r)},xt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(ue(!0),!(!t||!C.current||!_||typeof window>`u`)){try{await C.current.trackVisitor({chatId:_,currentPagePath:window.location.pathname||`/`})}catch{}try{await C.current.updateChatStatus(_,`open`)}catch{}}},St=async e=>{let t=ut(e);if(!t||!C.current||!w.current)return t;try{await C.current.trackVisitor({chatId:w.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},Ct=()=>{if(!_||!S.current?.connected||nt.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:_,socketConnected:!!S.current?.connected,alreadyTyping:nt.current});return}nt.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:_,sender:`user`}),S.current.emit(`typing:start`,{chatId:_,sender:`user`})},wt=()=>{if(!_||!S.current?.connected||!nt.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:_,socketConnected:!!S.current?.connected,wasTyping:nt.current});return}nt.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:_,sender:`user`}),S.current.emit(`typing:stop`,{chatId:_,sender:`user`})},Tt=(e=``)=>{let t=typeof e==`string`?e:``;if(!_||!S.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:_,socketConnected:!!S.current?.connected,textLength:t.length});return}rt.current!==t&&(rt.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:_,sender:`user`,textLength:t.length}),S.current.emit(`typing:update`,{chatId:_,sender:`user`,text:t}))},Et=async(e,t=``,n=null)=>{if(!e.trim()||!C.current||!_||o!==`ready`||Pe)return;wt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(y(e=>[...e,a]),pe&&S.current?.connected){S.current.emit(`customer:message`,{chatId:_,content:e,sender:`user`,email:ye||void 0,...n||{}});return}Oe(!0);try{let i=await C.current.sendAiMessage(_,e,r,t,{...n||{},...ye?{email:ye}:{}});y(wn(i.chat_history||[])),me(!!i.is_human_handled),fe(i.is_human_handled?`agent`:`ai`),we(!1),await C.current.updateChatStatus(_,`messageSent`)}catch(e){y(e=>e.filter(e=>e.id!==i)),we(!1),e.status===429?(Ae(!0),Me(e.message),window.setTimeout(()=>{Ae(!1),Me(``)},m)):f(e)}finally{Oe(!1)}},Dt=async e=>{if(!(!C.current||!_)){try{let t=e?`voice`:`text`;await C.current.setChatMode(_,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}b(e),e&&(ot.current=!1)}},Ot=async e=>{if(!ot.current){if(ot.current=!0,!C.current||!_||!e?.length){b(!1);return}try{let t=await C.current.syncVoice(_,e);if(t?.chat_history?.length)y(wn(t.chat_history));else if(t?.success)try{let e=await C.current.loadHistory(_,r);e?.chat_history?.length&&y(wn(e.chat_history))}catch{}}catch{}finally{b(!1)}}},kt=async()=>{if(!(!C.current||!_)){Ne&&!ot.current&&at.current.length>0&&await Ot(at.current);try{await C.current.endConversation(_)}catch{try{await C.current.updateChatStatus(_,`ended`)}catch{}}Fe(!0),y(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:`This conversation has ended. Thank you for reaching out!`,timestamp:new Date().toISOString(),isPending:!1}])}};(0,l.useEffect)(()=>{if(ze!==`connected`||!Le||!_||!Ve||!ct)return;let e=new Date(Ve).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,ct*1e3-t),r=window.setTimeout(()=>{Ke(`The call ended because it reached the time limit.`),yt()},n);return()=>window.clearTimeout(r)},[Le,Ve,ze,_,yt,ct]),(0,l.useEffect)(()=>{let e=()=>{let e=w.current,t=C.current;if(!t||!e)return;if($e.current){t.beaconEndWebRTCCall($e.current,e);return}let n=et.current||qe.current?.callId;n&&t.beaconCustomerUnavailable(n,e)};return window.addEventListener(`pagehide`,e),window.addEventListener(`beforeunload`,e),()=>{window.removeEventListener(`pagehide`,e),window.removeEventListener(`beforeunload`,e)}},[]);let T=(0,l.useMemo)(()=>({status:o,error:c,runtimeConfig:p,resolvedConfig:i,chatId:_,chatHistory:v,isOpen:le,activeScreen:de,isHumanHandled:pe,agentName:he,agentHeadshot:_e,visitorEmail:ye,isAgentTyping:xe,isAiTyping:Ce,connectionStatus:Te,isLoading:De,isVoiceMode:Ne,isRateLimited:ke,rateLimitMessage:je,isConversationEnded:Pe,incomingCall:x,activeCallId:Le,callConnectionState:ze,callConnectedAt:Ve,isCallMuted:Ue,webRTCError:Ge,language:r,historyRef:at,hasSyncedRef:ot,dismissCallError:lt,captureVisitorEmail:St,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt,notifyRouteChange:()=>st.current?.notifyRouteChange?.(),openWidget:xt,closeWidget:()=>ue(!1),toggleWidget:()=>{if(le){ue(!1);return}xt({notifyChatInitiated:!0})},sendMessage:Et,setVoiceMode:Dt,onMessageSync:Ot,endConversation:kt,acceptCall:gt,rejectCall:_t,endWebRTCCall:yt,toggleCallMute:bt,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt}),[o,c,p,i,_,v,le,de,pe,he,_e,ye,xe,Ce,Te,De,Ne,ke,je,Pe,x,Le,ze,Ve,Ue,Ge,r,St,Ct,wt,Tt,gt,_t,yt,bt,xt,Et,Dt,Ot,kt,lt]);return(0,u.jsx)(Jt.Provider,{value:T,children:n})}var An=({color:e=`#3888FF`})=>(0,u.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,u.jsx)(`path`,{d:`M26 8H14C12.3431 8 11 9.34315 11 11V23C11 24.6569 12.3431 26 14 26H26C27.6569 26 29 24.6569 29 23V11C29 9.34315 27.6569 8 26 8Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,u.jsx)(`path`,{d:`M16.4067 20.5924C16.182 20.3674 16.1822 20.003 16.407 19.7783L22.7805 13.4068C23.0051 13.1821 23.3694 13.1823 23.5939 13.4071V13.4071C23.8182 13.6317 23.8181 13.9956 23.5936 14.2201L17.2212 20.5926C16.9962 20.8176 16.6315 20.8174 16.4067 20.5924V20.5924Z`,fill:`#3E87C8`})]}),jn=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,u.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),Mn=({size:e=18,color:t=`currentColor`})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,u.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,u.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),Nn=({size:e=20})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M10.68 13.31a16 16 0 003.41 2.6l1.27-1.27a2 2 0 012.11-.45 12.84 12.84 0 002.81.7 2 2 0 011.72 2v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.42 19.42 0 013.07 8.62 19.79 19.79 0 01.1 2 2 2 0 012.11 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.18 7.84`}),(0,u.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Pn=()=>(0,u.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,u.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),Fn=()=>(0,u.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,u.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),In=()=>(0,u.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,u.jsx)(`path`,{d:`M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.42 19.42 0 01-6.12-6.11A19.79 19.79 0 012 4.11 2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.91.71 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.9.34 1.85.58 2.81.71A2 2 0 0122 16.92z`})}),Ln=({className:e=``})=>(0,u.jsxs)(`svg`,{className:e,width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,u.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,u.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),Rn=({size:e=18,strokeWidth:t=2.5})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,u.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),zn=({size:e=14})=>(0,u.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,u.jsx)(`path`,{d:`M12 8V4H8`}),(0,u.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,u.jsx)(`path`,{d:`M2 14h2`}),(0,u.jsx)(`path`,{d:`M20 14h2`}),(0,u.jsx)(`path`,{d:`M15 13v2`}),(0,u.jsx)(`path`,{d:`M9 13v2`})]});function Bn({isOpen:e,openWidget:t,launcherText:n,primaryColor:r,posInline:i}){let[a,o]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 640px)`),t=e=>{o(e.matches)};return o(e.matches),typeof e.addEventListener==`function`?(e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)):(e.addListener(t),()=>e.removeListener(t))},[]),e?null:(0,u.jsxs)(`button`,{type:`button`,onClick:()=>t({notifyChatInitiated:!0}),"aria-label":n,style:{position:`fixed`,...i,zIndex:999999,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:a?`0`:`14px`,width:a?`60px`:`auto`,minWidth:a?`60px`:`unset`,height:a?`60px`:`auto`,padding:a?`0`:`14px 24px`,border:`none`,borderRadius:`9999px`,background:r,color:`#fff`,fontSize:`16px`,fontWeight:`600`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,cursor:`pointer`,boxShadow:`0 8px 24px rgba(0,0,0,0.18)`,transition:`transform 0.2s ease, box-shadow 0.2s ease`,outline:`none`,whiteSpace:`nowrap`},onMouseEnter:e=>{e.currentTarget.style.transform=`translateY(-2px)`,e.currentTarget.style.boxShadow=`0 12px 28px rgba(0,0,0,0.22)`},onMouseLeave:e=>{e.currentTarget.style.transform=`translateY(0)`,e.currentTarget.style.boxShadow=`0 8px 24px rgba(0,0,0,0.18)`},children:[a?null:(0,u.jsx)(`span`,{children:n}),a?(0,u.jsx)(An,{color:`#fff`}):(0,u.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,u.jsx)(jn,{})})]})}function Vn(e){if(!e||typeof e!=`string`)return`?`;let t=e.trim();if(!t)return`?`;let n=t.split(/\s+/).filter(Boolean);return n.length>=2?`${n[0][0]}${n[n.length-1][0]}`.toUpperCase():t.slice(0,2).toUpperCase()}function Hn({src:e,name:t,imgStyle:n,initialsSpanStyle:r}){let[i,a]=(0,l.useState)(!1),o=typeof e==`string`?e.trim():``;return(0,l.useEffect)(()=>{a(!1)},[o]),o&&!i?(0,u.jsx)(`img`,{src:o,alt:``,onError:()=>a(!0),style:n}):(0,u.jsx)(`span`,{style:r,children:Vn(t)})}function Un(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function Wn(e){let[t,n]=(0,l.useState)(`loading`),r=Un(e);return(0,l.useEffect)(()=>{if(l.default.isValidElement(e)||typeof e==`function`){n(`square`);return}if(!r){n(`error`);return}n(`loading`);let t=new Image,i=!1;return t.onload=()=>{i||n(t.naturalWidth/t.naturalHeight>1.3?`wide`:`square`)},t.onerror=()=>{i||n(`error`)},t.src=r,()=>{i=!0}},[e,r]),{state:t,resolvedLogoUrl:r}}function Gn({logoUrl:e,brandName:t,agentName:n,fallbackAgentName:r,activeScreen:i,branding:a,isConversationEnded:o,closeWidget:s,isInitial:c,botLabel:d=`AI`,agentAvatarUrl:f=null,primaryColor:p=`#3B82F6`}){let{state:m,resolvedLogoUrl:ee}=Wn(e),h=i===`agent`,g=n||r||a?.fallbackAgentName||`Agent`;return(0,u.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,padding:`16px 20px`,borderTopLeftRadius:`inherit`,borderTopRightRadius:`inherit`,border:`none`,transition:`all 0.3s ease`,background:c?`transparent`:`#fff`,color:c?`#fff`:`#111827`,boxShadow:c?`none`:`0 1px 0 rgba(0,0,0,0.05), 0 10px 24px rgba(0,0,0,0.04)`,borderBottom:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[h?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:c?`rgba(255,255,255,0.2)`:`#f3f4f6`,color:c?`#fff`:p,fontWeight:800,fontSize:`15px`,border:c?`2px solid rgba(255,255,255,0.35)`:`1px solid rgba(0,0,0,0.06)`},children:(0,u.jsx)(Hn,{src:typeof f==`string`?f:``,name:g,imgStyle:{width:`100%`,height:`100%`,objectFit:`cover`},initialsSpanStyle:{lineHeight:1}})}):(0,u.jsxs)(u.Fragment,{children:[m!==`loading`&&(m===`error`||!ee&&!e?(0,u.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0}}):l.default.isValidElement(e)?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:e}):typeof e==`function`?(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(e,{})}):m===`wide`?(0,u.jsx)(`div`,{style:{height:`36px`,maxWidth:`88px`,flexShrink:0,display:`flex`,alignItems:`center`,justifyContent:`center`,borderRadius:`12px`,padding:`4px 8px`,background:c?`rgba(255,255,255,0.15)`:`#f9fafb`,backdropFilter:c?`blur(12px)`:`none`,border:c?`none`:`1px solid rgba(0,0,0,0.05)`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,u.jsx)(`img`,{src:ee,alt:`Logo`,style:{width:`100%`,height:`100%`,objectFit:`contain`,padding:ee.toLowerCase().includes(`.svg`)||ee.startsWith(`data:image/svg`)?0:`2px`}})})),m===`loading`&&(0,u.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,u.jsxs)(`div`,{children:[(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,u.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,u.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`,borderRadius:`6px`,background:`rgba(255,255,255,0.95)`,padding:`3px 6px`,fontSize:`10px`,fontWeight:800,letterSpacing:`0.5px`,color:`var(--flowengage-primary)`},children:[(0,u.jsx)(zn,{size:11}),(0,u.jsx)(`span`,{children:d})]})]}),(0,u.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,u.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,u.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,u.jsx)(`button`,{style:{width:`36px`,height:`36px`,borderRadius:`9999px`,background:`transparent`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.2s ease`,border:0,cursor:`pointer`,color:c?`#fff`:`#000`},onClick:s,"aria-label":`Close chat`,onMouseEnter:e=>{e.currentTarget.style.background=c?`rgba(255,255,255,0.1)`:`rgba(0,0,0,0.05)`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`},children:(0,u.jsx)(Rn,{})})})]})}var Kn=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),qn=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`);function Jn(e){let t=String(e||``).trim();if(!t)return t;let n=/^<p>\s*<strong>([\s\S]*?)<\/strong>\s*<\/p>$/i.exec(t);if(n&&!/<\/?strong\b/i.test(n[1]))return`<p>${n[1]}</p>`;let r=/^<strong>([\s\S]*?)<\/strong>$/i.exec(t);if(r&&!/<\/?strong\b/i.test(r[1])){let e=r[1].trim();return/^<(?:p|ul|ol)\b/i.test(e)?e:`<p>${e}</p>`}return e}var Yn=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return Jn(t);let n=t.replace(/\r\n/g,`
26
26
  `).replace(/\n{3,}/g,`
27
27
 
28
28
  `).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>qn(e).replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,`<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>`).replace(/\*\*([^*]+)\*\*/g,`<strong>$1</strong>`).replace(/\*([^*\n]+)\*/g,`<em>$1</em>`);return Jn(n.map(e=>{let t=e.split(`
@@ -2621,7 +2621,7 @@ function An({ siteId: e, config: t, children: n, language: r = "en" }) {
2621
2621
  }), gt(e);
2622
2622
  }), o.on("call:connected", (e = {}) => {
2623
2623
  if (!e.callId) return;
2624
- let t = nt.current === e.callId, n = tt.current === e.callId, r = Ye.current?.callId === e.callId;
2624
+ let t = nt.current === e.callId, n = tt.current === e.callId, r = $e.current?.callId === e.callId, i = Ye.current?.callId === e.callId;
2625
2625
  if (console.log("[FlowEngageProvider] received call:connected", {
2626
2626
  callId: e.callId,
2627
2627
  chatId: e.chatId || T.current,
@@ -2629,9 +2629,10 @@ function An({ siteId: e, config: t, children: n, language: r = "en" }) {
2629
2629
  status: e.status,
2630
2630
  isAcceptingHere: t,
2631
2631
  isAlreadyActive: n,
2632
- isIncomingHere: r
2633
- }), !t && !n) {
2634
- r && (Re(null), He("idle"));
2632
+ isPendingOfferHere: r,
2633
+ isIncomingHere: i
2634
+ }), !t && !n && !r) {
2635
+ i && (Re(null), He("idle"));
2635
2636
  return;
2636
2637
  }
2637
2638
  rt.current = !0, nt.current = null, tt.current = e.callId, Be(e.callId), Re(null), He("connected"), We(e.connectedAt || (/* @__PURE__ */ new Date()).toISOString()), fe(!0);
@@ -2779,6 +2780,11 @@ function An({ siteId: e, config: t, children: n, language: r = "en" }) {
2779
2780
  e.id = "flowengage-remote-audio", e.autoplay = !0, Qe.current = e, document.body.appendChild(e);
2780
2781
  }
2781
2782
  Qe.current.srcObject = e.streams[0];
2783
+ let t = S?.callId, n = t && (nt.current === t || tt.current === t);
2784
+ if (!rt.current && n) {
2785
+ let e = (/* @__PURE__ */ new Date()).toISOString();
2786
+ He("connected"), We((t) => t || e), tt.current = t, Be(t), mt(e);
2787
+ }
2782
2788
  };
2783
2789
  let n = $e.current;
2784
2790
  n && (console.log("[FlowEngageProvider] found pending remote offer during accept", {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowengage/react-chatbot",
3
- "version": "1.2.5",
3
+ "version": "1.2.6",
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",