@flowengage/react-chatbot 1.0.2 → 1.0.3

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.
@@ -13,7 +13,7 @@ Error generating stack: `+e.message+`
13
13
  transition: all 0.3s ease !important;
14
14
  border-radius: 8px !important;
15
15
  }
16
- `,document.head.appendChild(e)};function on(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=document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`);for(let e of r)if(e.textContent.toLowerCase().includes(n))return e;let i=n.split(/\s+/).filter(e=>e.length>2);if(i.length>1){let e=null,t=0;for(let n of r){let r=n.textContent.toLowerCase(),a=0;for(let e of i)r.includes(e)&&a++;let o=a/i.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let a=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of a){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let o=document.querySelectorAll(`p`);for(let e of o){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<800)return e}return null}function sn(e){!e||typeof document>`u`||(an(),cn(),e.classList.add(`fe-highlight-section`),e.scrollIntoView({behavior:`smooth`,block:`center`}))}function cn(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section`).forEach(e=>e.classList.remove(`fe-highlight-section`))}function ln(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 un(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 dn(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?un(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}async function fn(e){if(typeof window>`u`)return!1;try{let t=ln(e),n=new URL(t,window.location.origin);if(rn(`input:`,e,`→ normalized:`,t,`href:`,n.href),n.hash&&n.pathname===window.location.pathname){let e=n.hash.slice(1),t=document.getElementById(e);if(t)return rn(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(n.pathname===window.location.pathname&&n.search===window.location.search&&!n.hash)return rn(`branch: already on page (no nav)`),!1;let r=n.pathname+n.search+n.hash,i=window.next?.router;if(i?.push)return rn(`branch: Next.js Pages router.push`,r),new Promise(e=>{let t=()=>{i.events?.off(`routeChangeComplete`,t),e(!0)};i.events?.on(`routeChangeComplete`,t),i.push(r),setTimeout(t,4e3)});let a=window.__NEXT_ROUTER__;return a?.push?(rn(`branch: __NEXT_ROUTER__.push`,r),a.push(r),!0):(rn(`branch: location.assign (full navigation)`,n.href),window.location.assign(n.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t);try{window.location.href=ln(e)}catch{window.location.href=e}return!0}}var pn=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})),k=o(((e,t)=>{t.exports=pn()}))(),mn=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(),hn=(e=[])=>e.map(e=>({...e,message:mn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),gn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,_n=(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}:{}}},vn=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}},yn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function bn({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)(()=>yn([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)(oe().isOpen),[y,x]=(0,v.useState)(oe().activeScreen),[ee,re]=(0,v.useState)(oe().isHumanHandled),[ie,ue]=(0,v.useState)(oe().agentName),[de,w]=(0,v.useState)(oe().agentHeadshot),[pe,me]=(0,v.useState)(()=>ce(i?.siteId)),[he,ge]=(0,v.useState)(!1),[_e,T]=(0,v.useState)(!1),[ve,ye]=(0,v.useState)(`idle`),[be,xe]=(0,v.useState)(!1),[Se,Ce]=(0,v.useState)(!1),[we,Te]=(0,v.useState)(``),[Ee,De]=(0,v.useState)(!1),[Oe,ke]=(0,v.useState)(!1),[E,Ae]=(0,v.useState)(null),[je,Me]=(0,v.useState)(null),[Ne,Pe]=(0,v.useState)(`idle`),[Fe,Ie]=(0,v.useState)(null),[Le,Re]=(0,v.useState)(!1),[ze,Be]=(0,v.useState)(``),Ve=(0,v.useRef)(null),He=(0,v.useRef)(null),D=(0,v.useRef)(``),Ue=(0,v.useRef)(null),We=(0,v.useRef)(null),Ge=(0,v.useRef)(null),Ke=(0,v.useRef)(null),qe=(0,v.useRef)(null),Je=(0,v.useRef)([]),Ye=(0,v.useRef)(null),Xe=(0,v.useRef)(null),Ze=(0,v.useRef)(!1),Qe=(0,v.useRef)(!1),$e=(0,v.useRef)(``),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)(()=>{Ue.current=E},[E]);let it=()=>{Be(``)},at=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return me(t),le(t,i?.siteId),t};(0,v.useEffect)(()=>{let e=i?.siteId;e&&me(ce(e))},[i?.siteId]);let ot=()=>{We.current&&=(We.current.close(),null),Ge.current&&=(Ge.current.getTracks().forEach(e=>e.stop()),null),Ke.current&&=(Ke.current.srcObject=null,Ke.current.remove(),null),qe.current=null,Je.current=[],Ye.current=null,Xe.current=null,Ze.current=!1,Re(!1),Ae(null),Me(null),Pe(`idle`),Ie(null)},st=(e=new Date().toISOString())=>{let t=Ve.current,n=Ye.current||qe.current?.callId;if(!t?.connected||!n||Ze.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:D.current,socketConnected:!!t?.connected,alreadyReported:Ze.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:D.current,connectedAt:e}),Ze.current=!0,t.emit(`call:connected`,{callId:n,chatId:D.current,connectedAt:e})},ct=(e={})=>{if(!e.callId)return;let t=Xe.current===e.callId,n=Ye.current===e.callId,r=Ue.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||D.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Ae(null),t||n){Ye.current=e.callId,Me(e.callId),Pe(e=>e===`connected`?e:`connecting`),_(!0);return}Pe(`idle`)}},lt=(e={})=>{if(!e.callId)return;let t=Xe.current===e.callId,n=Ye.current===e.callId,r=Ue.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||D.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){ot();return}Xe.current=null,qe.current=null,Je.current=[],Ae(null),Pe(`idle`)}},ut=async(e={})=>{let t=We.current,n=Ve.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:D.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),qe.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:D.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Je.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:D.current,queuedCount:Je.current.length});for(let e of Je.current)await t.addIceCandidate(new RTCIceCandidate(e));Je.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:D.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:D.current})};(0,v.useEffect)(()=>{se({isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:ie,agentHeadshot:de})},[g,y,ee,ie,de]),(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 fe(t);if(!e)return;let o=ae();D.current=o;let c=C({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});He.current=c,d({...n,apiBaseUrl:t.apiBaseUrl}),p(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Qt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});Ve.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),ye(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),ye(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:D.current}),T(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:D.current}),T(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:mn(t.message)};T(!1),ge(!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:mn(t.message)};T(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&ge(!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)&&(re(!0),x(`agent`),ue(yn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&w(n.sender_headshot),_(!0))}),l.on(`agent:joined`,e=>{let t=yn([e.agent?.name,e.agentName],a);re(!0),x(`agent`),ue(t),w(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=yn([e.agent?.name,e.agentName],a);re(!0),x(`agent`),ue(t),w(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=yn([e.agent?.name,e.agentName,ie],a);re(!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=yn([e.agent?.name,e.agentName,ie],a);re(!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=>{ke(!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(hn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||D.current,sender:e?.sender}),e.sender===`agent`&&ge(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||D.current,sender:e?.sender}),e.sender===`agent`&&ge(!1)}),l.on(`call:incoming`,(e={})=>{let t=yn([e.agentName,e.ownerName,e.agent?.name,ie],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:D.current,agentName:t}),it(),Ze.current=!1,Ae({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ue(e=>yn([t,e],a)),Pe(`incoming`),Ie(null),_(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||D.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),qe.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||D.current,hasPeerConnection:!!We.current,hasCandidate:!!e.candidate});return}try{let t=_n(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||D.current,candidate:vn(t),hasRemoteDescription:!!We.current?.remoteDescription}),!We.current||!We.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||D.current,queueSize:Je.current.length+1}),Je.current.push(t);return}await We.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||D.current}),ct(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||D.current}),ct(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||D.current,reason:e.reason}),lt(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||D.current,reason:e.reason}),lt(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||D.current,reason:e.reason}),lt(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=Xe.current===e.callId,n=Ye.current===e.callId,r=Ue.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||D.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(Ae(null),Pe(`idle`));return}Ze.current=!0,Xe.current=null,Ye.current=e.callId,Me(e.callId),Ae(null),Pe(`connected`),Ie(e.connectedAt||new Date().toISOString()),_(!0)}),l.on(`call:unavailable`,(e={})=>{ot(),Be(gn(e,`This visitor is not available for a call right now.`)),_(!0)}),l.on(`call:error`,(e={})=>{ot(),Be(gn(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 dn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}fn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=on(null,t);e&&sn(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=on(e||null,t||null);n&&sn(n)}),l.on(`visitor:clear_highlight`,()=>{cn()}),nt.current=$t({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(hn(u.chat_history||[])),re(!!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(),Ve.current?.disconnect()}},[i,r]),(0,v.useEffect)(()=>()=>{if(Ee&&!tt.current&&et.current.length>0){let e=D.current,t=et.current,n=He.current,r=u?.apiBaseUrl||``,i=u?.userId||``;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(r,i,e,t)||n.syncVoice(e,t).catch(()=>{}),tt.current=!0)}},[Ee,u]),(0,v.useEffect)(()=>{if(!He.current||!f||o!==`ready`||ee)return;let e=window.setInterval(async()=>{try{let e=await He.current.checkHumanHandled(f);re(!!e.is_human_handled),e.is_human_handled&&(x(`agent`),e.agent_info?.name&&ue(e.agent_info.name),e.agent_info?.headshot&&w(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[f,o,ee]);let dt=async()=>{if(!(!E?.callId||!He.current||!Ve.current||!f)){it(),Xe.current=E.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:E?.callId,chatId:f,socketConnected:!!Ve.current?.connected,hasPendingOffer:!!qe.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:E.callId,chatId:f,trackCount:e.getTracks().length}),Ge.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});We.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:E.callId,chatId:f,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Pe(`connected`),Ie(t=>t||e),st(e);return}e===`connecting`&&Pe(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:E.callId,chatId:f,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Pe(`connected`),Ie(t=>t||e),st(e);return}(e===`checking`||e===`new`)&&Pe(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!Ve.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:E.callId,chatId:f,hasCandidate:!!e.candidate,socketConnected:!!Ve.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:E.callId,chatId:f,candidate:vn(e.candidate)}),Ve.current.emit(`call:ice-candidate`,{callId:E.callId,candidate:e.candidate,chatId:f,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:E.callId,chatId:f,streamCount:e.streams?.length||0}),!Ke.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Ke.current=e,document.body.appendChild(e)}Ke.current.srcObject=e.streams[0]};let n=qe.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||E.callId,chatId:f}),await ut({...n,callId:n.callId||E.callId})),await He.current.acceptCall(E.callId,f),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:E.callId,chatId:f}),Ye.current=E.callId,Me(E.callId),Pe(`connecting`),Ae(null),_(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),Xe.current=null,ot(),e?.status===404||e?.status===409||e?.status===422){Be(gn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await He.current.rejectCall(E.callId,f)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Be(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Be(`We couldn't connect the call right now. Please try again.`)}}},ft=async()=>{if(!E?.callId||!He.current||!f){ot();return}it();try{await He.current.rejectCall(E.callId,f)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Be(gn(e,`We couldn't decline the call cleanly.`))}finally{ot()}},pt=(0,v.useRef)(ft);pt.current=ft,(0,v.useEffect)(()=>{if(!E?.callId||je)return;let e=E.callId,t=window.setTimeout(()=>{Ue.current?.callId===e&&pt.current()},ne);return()=>window.clearTimeout(t)},[E?.callId,je]);let mt=async()=>{if(!je||!He.current||!f){ot();return}it();try{await He.current.endWebRTCCall(je,f)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Be(gn(e,`The call ended locally, but the server could not be updated.`))}finally{ot()}},ht=()=>{let e=Ge.current?.getAudioTracks?.()||[],t=We.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=!Le;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),Re(r)},gt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(_(!0),!(!t||!He.current||!f||typeof window>`u`)){try{await He.current.trackVisitor({chatId:f,currentPagePath:window.location.pathname||`/`})}catch{}try{await He.current.updateChatStatus(f,`open`)}catch{}}},_t=async e=>{let t=at(e);if(!t||!He.current||!D.current)return t;try{await He.current.trackVisitor({chatId:D.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||!Ve.current?.connected||Qe.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:f,socketConnected:!!Ve.current?.connected,alreadyTyping:Qe.current});return}Qe.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:f,sender:`user`}),Ve.current.emit(`typing:start`,{chatId:f,sender:`user`})},yt=()=>{if(f&&Ve.current?.connected&&$e.current!==``&&(console.log(`[FlowEngageProvider] clearing typing draft`,{chatId:f,sender:`user`}),Ve.current.emit(`typing:update`,{chatId:f,sender:`user`,text:``}),$e.current=``),!f||!Ve.current?.connected||!Qe.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:f,socketConnected:!!Ve.current?.connected,wasTyping:Qe.current});return}Qe.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:f,sender:`user`}),Ve.current.emit(`typing:stop`,{chatId:f,sender:`user`})},bt=(e=``)=>{let t=typeof e==`string`?e:``;if(!f||!Ve.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:f,socketConnected:!!Ve.current?.connected,textLength:t.length});return}$e.current!==t&&($e.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:f,sender:`user`,textLength:t.length}),Ve.current.emit(`typing:update`,{chatId:f,sender:`user`,text:t}))},xt=async(e,t=``,n=null)=>{if(!e.trim()||!He.current||!f||o!==`ready`||Oe)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&&Ve.current?.connected){Ve.current.emit(`customer:message`,{chatId:f,content:e,sender:`user`,email:pe||void 0,...n||{}});return}xe(!0);try{let i=await He.current.sendAiMessage(f,e,r,t,{...n||{},...pe?{email:pe}:{}});h(hn(i.chat_history||[])),re(!!i.is_human_handled),x(i.is_human_handled?`agent`:`ai`),T(!1),await He.current.updateChatStatus(f,`messageSent`)}catch(e){h(e=>e.filter(e=>e.id!==i)),T(!1),e.status===429?(Ce(!0),Te(e.message),window.setTimeout(()=>{Ce(!1),Te(``)},te)):l(e)}finally{xe(!1)}},St=async e=>{if(!(!He.current||!f)){try{let t=e?`voice`:`text`;await He.current.setChatMode(f,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}De(e),e&&(tt.current=!1)}},Ct=async e=>{if(!tt.current){if(tt.current=!0,!He.current||!f||!e?.length){De(!1);return}try{let t=await He.current.syncVoice(f,e);t?.chat_history&&h(hn(t.chat_history))}catch{}finally{De(!1)}}},wt=async()=>{if(!(!He.current||!f)){Ee&&!tt.current&&et.current.length>0&&await Ct(et.current);try{await He.current.endConversation(f)}catch{try{await He.current.updateChatStatus(f,`ended`)}catch{}}ke(!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(Ne!==`connected`||!je||!f||!Fe||!rt)return;let e=new Date(Fe).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,rt*1e3-t),r=window.setTimeout(()=>{Be(`The call ended because it reached the time limit.`),mt()},n);return()=>window.clearTimeout(r)},[je,Fe,Ne,f,mt,rt]),(0,v.useEffect)(()=>{let e=()=>{let e=D.current,t=He.current;if(!t||!e)return;if(Ye.current){t.beaconEndWebRTCCall(Ye.current,e);return}let n=Xe.current||Ue.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:ie,agentHeadshot:de,visitorEmail:pe,isAgentTyping:he,isAiTyping:_e,connectionStatus:ve,isLoading:be,isVoiceMode:Ee,isRateLimited:Se,rateLimitMessage:we,isConversationEnded:Oe,incomingCall:E,activeCallId:je,callConnectionState:Ne,callConnectedAt:Fe,isCallMuted:Le,webRTCError:ze,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,ie,de,pe,he,_e,ve,be,Ee,Se,we,Oe,E,je,Ne,Fe,Le,ze,r,_t,vt,yt,bt,dt,ft,mt,ht,gt,xt,St,Ct,wt,it]);return(0,k.jsx)(en.Provider,{value:Tt,children:n})}var xn=({color:e=`#3888FF`})=>(0,k.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,k.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,k.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,k.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,k.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`})]}),Sn=()=>(0,k.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,k.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),Cn=({size:e=18,color:t=`currentColor`})=>(0,k.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,k.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,k.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),wn=({size:e=20})=>(0,k.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,k.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,k.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Tn=()=>(0,k.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,k.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,k.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),En=()=>(0,k.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,k.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,k.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),Dn=()=>(0,k.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,k.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`})}),On=({className:e=``})=>(0,k.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,k.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,k.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,k.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),kn=({size:e=18,strokeWidth:t=2.5})=>(0,k.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,k.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,k.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),An=({size:e=14})=>(0,k.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,k.jsx)(`path`,{d:`M12 8V4H8`}),(0,k.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,k.jsx)(`path`,{d:`M2 14h2`}),(0,k.jsx)(`path`,{d:`M20 14h2`}),(0,k.jsx)(`path`,{d:`M15 13v2`}),(0,k.jsx)(`path`,{d:`M9 13v2`})]});function jn({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,k.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,k.jsx)(`span`,{children:n}),a?(0,k.jsx)(xn,{color:`#fff`}):(0,k.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,k.jsx)(Sn,{})})]})}function Mn(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 Nn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function Pn(e){let[t,n]=(0,v.useState)(`loading`),r=Nn(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 Fn({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}=Pn(e),m=i===`agent`,h=Mn(n||r||a?.fallbackAgentName||`Agent`);return(0,k.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,k.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[m?(0,k.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:typeof u==`string`&&u.trim()?(0,k.jsx)(`img`,{src:u.trim(),alt:``,style:{width:`100%`,height:`100%`,objectFit:`cover`}}):(0,k.jsx)(`span`,{style:{lineHeight:1},children:h})}):(0,k.jsxs)(k.Fragment,{children:[f!==`loading`&&(f===`error`||!p&&!e?(0,k.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0}}):v.isValidElement(e)?(0,k.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,k.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,k.jsx)(e,{})}):f===`wide`?(0,k.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,k.jsx)(`img`,{src:p,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,k.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,k.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,k.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,k.jsxs)(`div`,{children:[(0,k.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,k.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,k.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,k.jsx)(An,{size:11}),(0,k.jsx)(`span`,{children:l})]})]}),(0,k.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,k.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,k.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,k.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,k.jsx)(kn,{})})})]})}var In=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Ln=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),Rn=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return t;let n=t.replace(/\r\n/g,`
16
+ `,document.head.appendChild(e)};function on(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=document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`);for(let e of r)if(e.textContent.toLowerCase().includes(n))return e;let i=n.split(/\s+/).filter(e=>e.length>2);if(i.length>1){let e=null,t=0;for(let n of r){let r=n.textContent.toLowerCase(),a=0;for(let e of i)r.includes(e)&&a++;let o=a/i.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let a=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of a){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let o=document.querySelectorAll(`p`);for(let e of o){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<800)return e}return null}function sn(e){!e||typeof document>`u`||(an(),cn(),e.classList.add(`fe-highlight-section`),e.scrollIntoView({behavior:`smooth`,block:`center`}))}function cn(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section`).forEach(e=>e.classList.remove(`fe-highlight-section`))}function ln(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 un(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 dn(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?un(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}async function fn(e){if(typeof window>`u`)return!1;try{let t=ln(e),n=new URL(t,window.location.origin);if(rn(`input:`,e,`→ normalized:`,t,`href:`,n.href),n.hash&&n.pathname===window.location.pathname){let e=n.hash.slice(1),t=document.getElementById(e);if(t)return rn(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(n.pathname===window.location.pathname&&n.search===window.location.search&&!n.hash)return rn(`branch: already on page (no nav)`),!1;let r=n.pathname+n.search+n.hash,i=window.next?.router;if(i?.push)return rn(`branch: Next.js Pages router.push`,r),new Promise(e=>{let t=()=>{i.events?.off(`routeChangeComplete`,t),e(!0)};i.events?.on(`routeChangeComplete`,t),i.push(r),setTimeout(t,4e3)});let a=window.__NEXT_ROUTER__;return a?.push?(rn(`branch: __NEXT_ROUTER__.push`,r),a.push(r),!0):(rn(`branch: location.assign (full navigation)`,n.href),window.location.assign(n.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t);try{window.location.href=ln(e)}catch{window.location.href=e}return!0}}var pn=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})),k=o(((e,t)=>{t.exports=pn()}))(),mn=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(),hn=(e=[])=>e.map(e=>({...e,message:mn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),gn=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,_n=(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}:{}}},vn=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}},yn=(e=[],t=`Agent`)=>{for(let t of e)if(typeof t==`string`&&t.trim())return t.trim();return t};function bn({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)(()=>yn([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)(oe().isOpen),[y,x]=(0,v.useState)(oe().activeScreen),[ee,re]=(0,v.useState)(oe().isHumanHandled),[ie,ue]=(0,v.useState)(oe().agentName),[de,w]=(0,v.useState)(oe().agentHeadshot),[pe,me]=(0,v.useState)(()=>ce(i?.siteId)),[he,ge]=(0,v.useState)(!1),[_e,T]=(0,v.useState)(!1),[ve,ye]=(0,v.useState)(`idle`),[be,xe]=(0,v.useState)(!1),[Se,Ce]=(0,v.useState)(!1),[we,Te]=(0,v.useState)(``),[Ee,De]=(0,v.useState)(!1),[Oe,ke]=(0,v.useState)(!1),[E,Ae]=(0,v.useState)(null),[je,Me]=(0,v.useState)(null),[Ne,Pe]=(0,v.useState)(`idle`),[Fe,Ie]=(0,v.useState)(null),[Le,Re]=(0,v.useState)(!1),[ze,Be]=(0,v.useState)(``),Ve=(0,v.useRef)(null),He=(0,v.useRef)(null),D=(0,v.useRef)(``),Ue=(0,v.useRef)(null),We=(0,v.useRef)(null),Ge=(0,v.useRef)(null),Ke=(0,v.useRef)(null),qe=(0,v.useRef)(null),Je=(0,v.useRef)([]),Ye=(0,v.useRef)(null),Xe=(0,v.useRef)(null),Ze=(0,v.useRef)(!1),Qe=(0,v.useRef)(!1),$e=(0,v.useRef)(``),et=(0,v.useRef)(ie),tt=(0,v.useRef)([]),nt=(0,v.useRef)(!1),rt=(0,v.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),it=(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)(()=>{Ue.current=E},[E]),(0,v.useEffect)(()=>{et.current=ie},[ie]);let at=()=>{Be(``)},ot=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return me(t),le(t,i?.siteId),t};(0,v.useEffect)(()=>{let e=i?.siteId;e&&me(ce(e))},[i?.siteId]);let st=()=>{We.current&&=(We.current.close(),null),Ge.current&&=(Ge.current.getTracks().forEach(e=>e.stop()),null),Ke.current&&=(Ke.current.srcObject=null,Ke.current.remove(),null),qe.current=null,Je.current=[],Ye.current=null,Xe.current=null,Ze.current=!1,Re(!1),Ae(null),Me(null),Pe(`idle`),Ie(null)},ct=(e=new Date().toISOString())=>{let t=Ve.current,n=Ye.current||qe.current?.callId;if(!t?.connected||!n||Ze.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:D.current,socketConnected:!!t?.connected,alreadyReported:Ze.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:D.current,connectedAt:e}),Ze.current=!0,t.emit(`call:connected`,{callId:n,chatId:D.current,connectedAt:e})},lt=(e={})=>{if(!e.callId)return;let t=Xe.current===e.callId,n=Ye.current===e.callId,r=Ue.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||D.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Ae(null),t||n){Ye.current=e.callId,Me(e.callId),Pe(e=>e===`connected`?e:`connecting`),_(!0);return}Pe(`idle`)}},ut=(e={})=>{if(!e.callId)return;let t=Xe.current===e.callId,n=Ye.current===e.callId,r=Ue.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||D.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){st();return}Xe.current=null,qe.current=null,Je.current=[],Ae(null),Pe(`idle`)}},dt=async(e={})=>{let t=We.current,n=Ve.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:D.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),qe.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:D.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),Je.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:D.current,queuedCount:Je.current.length});for(let e of Je.current)await t.addIceCandidate(new RTCIceCandidate(e));Je.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:D.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:D.current})};(0,v.useEffect)(()=>{se({isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:ie,agentHeadshot:de})},[g,y,ee,ie,de]),(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 fe(t);if(!e)return;let o=ae();D.current=o;let c=C({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});He.current=c,d({...n,apiBaseUrl:t.apiBaseUrl}),p(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=Qt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});Ve.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),ye(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),ye(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:D.current}),T(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:D.current}),T(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:mn(t.message)};T(!1),ge(!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:mn(t.message)};T(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&ge(!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)&&(re(!0),x(`agent`),ue(yn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&w(n.sender_headshot),_(!0))}),l.on(`agent:joined`,e=>{let t=yn([e.agent?.name,e.agentName],a);re(!0),x(`agent`),ue(t),w(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=yn([e.agent?.name,e.agentName],a);re(!0),x(`agent`),ue(t),w(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=yn([e.agent?.name,e.agentName,et.current],a);re(!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=yn([e.agent?.name,e.agentName,et.current],a);re(!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=>{ke(!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(hn(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||D.current,sender:e?.sender}),e.sender===`agent`&&ge(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||D.current,sender:e?.sender}),e.sender===`agent`&&ge(!1)}),l.on(`call:incoming`,(e={})=>{let t=yn([e.agentName,e.ownerName,e.agent?.name,ie],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:D.current,agentName:t}),at(),Ze.current=!1,Ae({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),ue(e=>yn([t,e],a)),Pe(`incoming`),Ie(null),_(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||D.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),qe.current=e;try{await dt(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||D.current,hasPeerConnection:!!We.current,hasCandidate:!!e.candidate});return}try{let t=_n(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||D.current,candidate:vn(t),hasRemoteDescription:!!We.current?.remoteDescription}),!We.current||!We.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||D.current,queueSize:Je.current.length+1}),Je.current.push(t);return}await We.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{at(),st()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||D.current}),lt(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||D.current}),lt(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||D.current,reason:e.reason}),ut(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||D.current,reason:e.reason}),ut(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||D.current,reason:e.reason}),ut(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=Xe.current===e.callId,n=Ye.current===e.callId,r=Ue.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||D.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(Ae(null),Pe(`idle`));return}Ze.current=!0,Xe.current=null,Ye.current=e.callId,Me(e.callId),Ae(null),Pe(`connected`),Ie(e.connectedAt||new Date().toISOString()),_(!0)}),l.on(`call:unavailable`,(e={})=>{st(),Be(gn(e,`This visitor is not available for a call right now.`)),_(!0)}),l.on(`call:error`,(e={})=>{st(),Be(gn(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 dn(e,{siteId:t.siteId,apiBaseUrl:t.apiBaseUrl})){console.warn(`[FlowEngageProvider] visitor:navigate blocked (not indexed)`,e);return}fn(e).then(e=>{let t=n||r;t&&setTimeout(()=>{let e=on(null,t);e&&sn(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=on(e||null,t||null);n&&sn(n)}),l.on(`visitor:clear_highlight`,()=>{cn()}),rt.current=$t({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(hn(u.chat_history||[])),re(!!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,rt.current?.cleanup?.(),st(),Ve.current?.disconnect()}},[i,r]),(0,v.useEffect)(()=>()=>{if(Ee&&!nt.current&&tt.current.length>0){let e=D.current,t=tt.current,n=He.current,r=u?.apiBaseUrl||``,i=u?.userId||``;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(r,i,e,t)||n.syncVoice(e,t).catch(()=>{}),nt.current=!0)}},[Ee,u]),(0,v.useEffect)(()=>{if(!He.current||!f||o!==`ready`||ee)return;let e=window.setInterval(async()=>{try{let e=await He.current.checkHumanHandled(f);re(!!e.is_human_handled),e.is_human_handled&&(x(`agent`),e.agent_info?.name&&ue(e.agent_info.name),e.agent_info?.headshot&&w(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[f,o,ee]);let ft=async()=>{if(!(!E?.callId||!He.current||!Ve.current||!f)){at(),Xe.current=E.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:E?.callId,chatId:f,socketConnected:!!Ve.current?.connected,hasPendingOffer:!!qe.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:E.callId,chatId:f,trackCount:e.getTracks().length}),Ge.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});We.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:E.callId,chatId:f,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Pe(`connected`),Ie(t=>t||e),ct(e);return}e===`connecting`&&Pe(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:E.callId,chatId:f,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Pe(`connected`),Ie(t=>t||e),ct(e);return}(e===`checking`||e===`new`)&&Pe(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!Ve.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:E.callId,chatId:f,hasCandidate:!!e.candidate,socketConnected:!!Ve.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:E.callId,chatId:f,candidate:vn(e.candidate)}),Ve.current.emit(`call:ice-candidate`,{callId:E.callId,candidate:e.candidate,chatId:f,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:E.callId,chatId:f,streamCount:e.streams?.length||0}),!Ke.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Ke.current=e,document.body.appendChild(e)}Ke.current.srcObject=e.streams[0]};let n=qe.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||E.callId,chatId:f}),await dt({...n,callId:n.callId||E.callId})),await He.current.acceptCall(E.callId,f),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:E.callId,chatId:f}),Ye.current=E.callId,Me(E.callId),Pe(`connecting`),Ae(null),_(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),Xe.current=null,st(),e?.status===404||e?.status===409||e?.status===422){Be(gn(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await He.current.rejectCall(E.callId,f)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}Be(`Microphone access was denied. Please allow microphone access to accept the call.`);return}Be(`We couldn't connect the call right now. Please try again.`)}}},pt=async()=>{if(!E?.callId||!He.current||!f){st();return}at();try{await He.current.rejectCall(E.callId,f)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),Be(gn(e,`We couldn't decline the call cleanly.`))}finally{st()}},mt=(0,v.useRef)(pt);mt.current=pt,(0,v.useEffect)(()=>{if(!E?.callId||je)return;let e=E.callId,t=window.setTimeout(()=>{Ue.current?.callId===e&&mt.current()},ne);return()=>window.clearTimeout(t)},[E?.callId,je]);let ht=async()=>{if(!je||!He.current||!f){st();return}at();try{await He.current.endWebRTCCall(je,f)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),Be(gn(e,`The call ended locally, but the server could not be updated.`))}finally{st()}},gt=()=>{let e=Ge.current?.getAudioTracks?.()||[],t=We.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=!Le;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),Re(r)},_t=async(e={})=>{let t=e.notifyChatInitiated===!0;if(_(!0),!(!t||!He.current||!f||typeof window>`u`)){try{await He.current.trackVisitor({chatId:f,currentPagePath:window.location.pathname||`/`})}catch{}try{await He.current.updateChatStatus(f,`open`)}catch{}}},vt=async e=>{let t=ot(e);if(!t||!He.current||!D.current)return t;try{await He.current.trackVisitor({chatId:D.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},yt=()=>{if(!f||!Ve.current?.connected||Qe.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:f,socketConnected:!!Ve.current?.connected,alreadyTyping:Qe.current});return}Qe.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:f,sender:`user`}),Ve.current.emit(`typing:start`,{chatId:f,sender:`user`})},bt=()=>{if(f&&Ve.current?.connected&&$e.current!==``&&(console.log(`[FlowEngageProvider] clearing typing draft`,{chatId:f,sender:`user`}),Ve.current.emit(`typing:update`,{chatId:f,sender:`user`,text:``}),$e.current=``),!f||!Ve.current?.connected||!Qe.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:f,socketConnected:!!Ve.current?.connected,wasTyping:Qe.current});return}Qe.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:f,sender:`user`}),Ve.current.emit(`typing:stop`,{chatId:f,sender:`user`})},xt=(e=``)=>{let t=typeof e==`string`?e:``;if(!f||!Ve.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:f,socketConnected:!!Ve.current?.connected,textLength:t.length});return}$e.current!==t&&($e.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:f,sender:`user`,textLength:t.length}),Ve.current.emit(`typing:update`,{chatId:f,sender:`user`,text:t}))},St=async(e,t=``,n=null)=>{if(!e.trim()||!He.current||!f||o!==`ready`||Oe)return;bt();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&&Ve.current?.connected){Ve.current.emit(`customer:message`,{chatId:f,content:e,sender:`user`,email:pe||void 0,...n||{}});return}xe(!0);try{let i=await He.current.sendAiMessage(f,e,r,t,{...n||{},...pe?{email:pe}:{}});h(hn(i.chat_history||[])),re(!!i.is_human_handled),x(i.is_human_handled?`agent`:`ai`),T(!1),await He.current.updateChatStatus(f,`messageSent`)}catch(e){h(e=>e.filter(e=>e.id!==i)),T(!1),e.status===429?(Ce(!0),Te(e.message),window.setTimeout(()=>{Ce(!1),Te(``)},te)):l(e)}finally{xe(!1)}},Ct=async e=>{if(!(!He.current||!f)){try{let t=e?`voice`:`text`;await He.current.setChatMode(f,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}De(e),e&&(nt.current=!1)}},wt=async e=>{if(!nt.current){if(nt.current=!0,!He.current||!f||!e?.length){De(!1);return}try{let t=await He.current.syncVoice(f,e);t?.chat_history&&h(hn(t.chat_history))}catch{}finally{De(!1)}}},Tt=async()=>{if(!(!He.current||!f)){Ee&&!nt.current&&tt.current.length>0&&await wt(tt.current);try{await He.current.endConversation(f)}catch{try{await He.current.updateChatStatus(f,`ended`)}catch{}}ke(!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(Ne!==`connected`||!je||!f||!Fe||!it)return;let e=new Date(Fe).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,it*1e3-t),r=window.setTimeout(()=>{Be(`The call ended because it reached the time limit.`),ht()},n);return()=>window.clearTimeout(r)},[je,Fe,Ne,f,ht,it]),(0,v.useEffect)(()=>{let e=()=>{let e=D.current,t=He.current;if(!t||!e)return;if(Ye.current){t.beaconEndWebRTCCall(Ye.current,e);return}let n=Xe.current||Ue.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 Et=(0,v.useMemo)(()=>({status:o,error:c,runtimeConfig:u,resolvedConfig:i,chatId:f,chatHistory:m,isOpen:g,activeScreen:y,isHumanHandled:ee,agentName:ie,agentHeadshot:de,visitorEmail:pe,isAgentTyping:he,isAiTyping:_e,connectionStatus:ve,isLoading:be,isVoiceMode:Ee,isRateLimited:Se,rateLimitMessage:we,isConversationEnded:Oe,incomingCall:E,activeCallId:je,callConnectionState:Ne,callConnectedAt:Fe,isCallMuted:Le,webRTCError:ze,language:r,historyRef:tt,hasSyncedRef:nt,dismissCallError:at,captureVisitorEmail:vt,startTyping:yt,stopTyping:bt,updateTypingDraft:xt,notifyRouteChange:()=>rt.current?.notifyRouteChange?.(),openWidget:_t,closeWidget:()=>_(!1),toggleWidget:()=>{if(g){_(!1);return}_t({notifyChatInitiated:!0})},sendMessage:St,setVoiceMode:Ct,onMessageSync:wt,endConversation:Tt,acceptCall:ft,rejectCall:pt,endWebRTCCall:ht,toggleCallMute:gt,startTyping:yt,stopTyping:bt,updateTypingDraft:xt}),[o,c,u,i,f,m,g,y,ee,ie,de,pe,he,_e,ve,be,Ee,Se,we,Oe,E,je,Ne,Fe,Le,ze,r,vt,yt,bt,xt,ft,pt,ht,gt,_t,St,Ct,wt,Tt,at]);return(0,k.jsx)(en.Provider,{value:Et,children:n})}var xn=({color:e=`#3888FF`})=>(0,k.jsxs)(`svg`,{width:`40`,height:`40`,viewBox:`0 0 40 40`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,k.jsx)(`rect`,{width:`40`,height:`40`,rx:`20`,fill:e}),(0,k.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,k.jsx)(`path`,{d:`M18 32L18 26L24 26L18 32Z`,fill:`#ECF0F0`}),(0,k.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`})]}),Sn=()=>(0,k.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,k.jsx)(`path`,{d:`M2.01 21L23 12 2.01 3 2 10l15 2-15 2z`,fill:`currentColor`})}),Cn=({size:e=18,color:t=`currentColor`})=>(0,k.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,k.jsx)(`path`,{d:`M12 1a4 4 0 014 4v6a4 4 0 01-8 0V5a4 4 0 014-4z`,fill:t}),(0,k.jsx)(`path`,{d:`M19 10a7 7 0 01-14 0M12 19v4M8 23h8`,stroke:t,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`})]}),wn=({size:e=20})=>(0,k.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,k.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,k.jsx)(`line`,{x1:`23`,y1:`1`,x2:`1`,y2:`23`})]}),Tn=()=>(0,k.jsxs)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,k.jsx)(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`5`}),(0,k.jsx)(`polyline`,{points:`5 12 12 5 19 12`})]}),En=()=>(0,k.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,k.jsx)(`polyline`,{points:`9 17 4 12 9 7`}),(0,k.jsx)(`path`,{d:`M20 18v-2a4 4 0 00-4-4H4`})]}),Dn=()=>(0,k.jsx)(`svg`,{width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,k.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`})}),On=({className:e=``})=>(0,k.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,k.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,k.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,k.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]}),kn=({size:e=18,strokeWidth:t=2.5})=>(0,k.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:t,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,k.jsx)(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),(0,k.jsx)(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})]}),An=({size:e=14})=>(0,k.jsxs)(`svg`,{width:e,height:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,k.jsx)(`path`,{d:`M12 8V4H8`}),(0,k.jsx)(`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`}),(0,k.jsx)(`path`,{d:`M2 14h2`}),(0,k.jsx)(`path`,{d:`M20 14h2`}),(0,k.jsx)(`path`,{d:`M15 13v2`}),(0,k.jsx)(`path`,{d:`M9 13v2`})]});function jn({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,k.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,k.jsx)(`span`,{children:n}),a?(0,k.jsx)(xn,{color:`#fff`}):(0,k.jsx)(`span`,{style:{width:`42px`,height:`42px`,borderRadius:`9999px`,background:`#fff`,color:r,display:`inline-flex`,alignItems:`center`,justifyContent:`center`,flexShrink:0},children:(0,k.jsx)(Sn,{})})]})}function Mn(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 Nn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function Pn(e){let[t,n]=(0,v.useState)(`loading`),r=Nn(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 Fn({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}=Pn(e),m=i===`agent`,h=Mn(n||r||a?.fallbackAgentName||`Agent`);return(0,k.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,k.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`},children:[m?(0,k.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:typeof u==`string`&&u.trim()?(0,k.jsx)(`img`,{src:u.trim(),alt:``,style:{width:`100%`,height:`100%`,objectFit:`cover`}}):(0,k.jsx)(`span`,{style:{lineHeight:1},children:h})}):(0,k.jsxs)(k.Fragment,{children:[f!==`loading`&&(f===`error`||!p&&!e?(0,k.jsx)(`div`,{className:`flowengage-logo-fallback`,style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0}}):v.isValidElement(e)?(0,k.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,k.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,k.jsx)(e,{})}):f===`wide`?(0,k.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,k.jsx)(`img`,{src:p,alt:`Logo`,style:{height:`100%`,width:`auto`,maxWidth:`100%`,objectFit:`contain`}})}):(0,k.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,flexShrink:0,overflow:`hidden`,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#fff`},children:(0,k.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,k.jsx)(`div`,{style:{width:`44px`,height:`44px`,borderRadius:`9999px`,background:`rgba(255,255,255,0.2)`,flexShrink:0}})]}),(0,k.jsxs)(`div`,{children:[(0,k.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`8px`},children:[(0,k.jsx)(`div`,{style:{fontSize:`16px`,fontWeight:700},children:i===`agent`?n||r||a.fallbackAgentName||`Agent`:t}),i!==`agent`&&(0,k.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,k.jsx)(An,{size:11}),(0,k.jsx)(`span`,{children:l})]})]}),(0,k.jsxs)(`div`,{style:{fontSize:`13px`,opacity:.95,marginTop:`2px`},children:[i===`agent`?`Live support`:`Usually replies `,i!==`agent`&&(0,k.jsx)(`span`,{style:{color:`#10b981`,fontWeight:600},children:`instantly`})]})]})]}),(0,k.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`4px`},children:(0,k.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,k.jsx)(kn,{})})})]})}var In=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),Ln=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),Rn=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return t;let n=t.replace(/\r\n/g,`
17
17
  `).replace(/\n{3,}/g,`
18
18
 
19
19
  `).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>Ln(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 n.map(e=>{let t=e.split(`
@@ -5,7 +5,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
5
5
  transition: all 0.3s ease !important;
6
6
  border-radius: 8px !important;
7
7
  }
8
- `,document.head.appendChild(e)};function en(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=document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`);for(let e of r)if(e.textContent.toLowerCase().includes(n))return e;let i=n.split(/\s+/).filter(e=>e.length>2);if(i.length>1){let e=null,t=0;for(let n of r){let r=n.textContent.toLowerCase(),a=0;for(let e of i)r.includes(e)&&a++;let o=a/i.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let a=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of a){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let o=document.querySelectorAll(`p`);for(let e of o){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<800)return e}return null}function tn(e){!e||typeof document>`u`||($t(),nn(),e.classList.add(`fe-highlight-section`),e.scrollIntoView({behavior:`smooth`,block:`center`}))}function nn(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section`).forEach(e=>e.classList.remove(`fe-highlight-section`))}function rn(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 an(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 on(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?an(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}async function sn(e){if(typeof window>`u`)return!1;try{let t=rn(e),n=new URL(t,window.location.origin);if(Qt(`input:`,e,`→ normalized:`,t,`href:`,n.href),n.hash&&n.pathname===window.location.pathname){let e=n.hash.slice(1),t=document.getElementById(e);if(t)return Qt(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(n.pathname===window.location.pathname&&n.search===window.location.search&&!n.hash)return Qt(`branch: already on page (no nav)`),!1;let r=n.pathname+n.search+n.hash,i=window.next?.router;if(i?.push)return Qt(`branch: Next.js Pages router.push`,r),new Promise(e=>{let t=()=>{i.events?.off(`routeChangeComplete`,t),e(!0)};i.events?.on(`routeChangeComplete`,t),i.push(r),setTimeout(t,4e3)});let a=window.__NEXT_ROUTER__;return a?.push?(Qt(`branch: __NEXT_ROUTER__.push`,r),a.push(r),!0):(Qt(`branch: location.assign (full navigation)`,n.href),window.location.assign(n.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t);try{window.location.href=rn(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(),ln=(e=[])=>e.map(e=>({...e,message:cn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),un=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,dn=(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}:{}}},fn=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 mn({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)(()=>pn([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)(``),[se,v]=(0,l.useState)([]),[ue,de]=(0,l.useState)(ne().isOpen),[fe,pe]=(0,l.useState)(ne().activeScreen),[me,he]=(0,l.useState)(ne().isHumanHandled),[ge,_e]=(0,l.useState)(ne().agentName),[ve,ye]=(0,l.useState)(ne().agentHeadshot),[be,xe]=(0,l.useState)(()=>ie(i?.siteId)),[Se,Ce]=(0,l.useState)(!1),[we,Te]=(0,l.useState)(!1),[Ee,De]=(0,l.useState)(`idle`),[Oe,ke]=(0,l.useState)(!1),[Ae,je]=(0,l.useState)(!1),[Me,Ne]=(0,l.useState)(``),[Pe,y]=(0,l.useState)(!1),[Fe,Ie]=(0,l.useState)(!1),[b,Le]=(0,l.useState)(null),[Re,ze]=(0,l.useState)(null),[Be,Ve]=(0,l.useState)(`idle`),[He,Ue]=(0,l.useState)(null),[We,Ge]=(0,l.useState)(!1),[Ke,qe]=(0,l.useState)(``),x=(0,l.useRef)(null),S=(0,l.useRef)(null),C=(0,l.useRef)(``),Je=(0,l.useRef)(null),Ye=(0,l.useRef)(null),Xe=(0,l.useRef)(null),Ze=(0,l.useRef)(null),Qe=(0,l.useRef)(null),$e=(0,l.useRef)([]),et=(0,l.useRef)(null),tt=(0,l.useRef)(null),nt=(0,l.useRef)(!1),rt=(0,l.useRef)(!1),it=(0,l.useRef)(``),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)(()=>{Je.current=b},[b]);let lt=()=>{qe(``)},ut=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return xe(t),ae(t,i?.siteId),t};(0,l.useEffect)(()=>{let e=i?.siteId;e&&xe(ie(e))},[i?.siteId]);let dt=()=>{Ye.current&&=(Ye.current.close(),null),Xe.current&&=(Xe.current.getTracks().forEach(e=>e.stop()),null),Ze.current&&=(Ze.current.srcObject=null,Ze.current.remove(),null),Qe.current=null,$e.current=[],et.current=null,tt.current=null,nt.current=!1,Ge(!1),Le(null),ze(null),Ve(`idle`),Ue(null)},ft=(e=new Date().toISOString())=>{let t=x.current,n=et.current||Qe.current?.callId;if(!t?.connected||!n||nt.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:C.current,socketConnected:!!t?.connected,alreadyReported:nt.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:C.current,connectedAt:e}),nt.current=!0,t.emit(`call:connected`,{callId:n,chatId:C.current,connectedAt:e})},pt=(e={})=>{if(!e.callId)return;let t=tt.current===e.callId,n=et.current===e.callId,r=Je.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||C.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Le(null),t||n){et.current=e.callId,ze(e.callId),Ve(e=>e===`connected`?e:`connecting`),de(!0);return}Ve(`idle`)}},mt=(e={})=>{if(!e.callId)return;let t=tt.current===e.callId,n=et.current===e.callId,r=Je.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||C.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){dt();return}tt.current=null,Qe.current=null,$e.current=[],Le(null),Ve(`idle`)}},ht=async(e={})=>{let t=Ye.current,n=x.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:C.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Qe.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:C.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),$e.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:C.current,queuedCount:$e.current.length});for(let e of $e.current)await t.addIceCandidate(new RTCIceCandidate(e));$e.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:C.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:C.current})};(0,l.useEffect)(()=>{re({isOpen:ue,activeScreen:fe,isHumanHandled:me,agentName:ge,agentHeadshot:ve})},[ue,fe,me,ge,ve]),(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 ce(t);if(!e)return;let o=te();C.current=o;let c=le({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});S.current=c,g({...n,apiBaseUrl:t.apiBaseUrl}),oe(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=qt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});x.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),De(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),De(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:C.current}),Te(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:C.current}),Te(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:cn(t.message)};Te(!1),Ce(!1),v(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&&v(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)};Te(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&Ce(!1),v(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)&&(he(!0),pe(`agent`),_e(pn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&ye(n.sender_headshot),de(!0))}),l.on(`agent:joined`,e=>{let t=pn([e.agent?.name,e.agentName],a);he(!0),pe(`agent`),_e(t),ye(e.agent?.headshot||null),de(!0),v(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);he(!0),pe(`agent`),_e(t),ye(e.agent?.headshot||null),de(!0),v(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,ge],a);he(!1),pe(`ai`),v(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,ge],a);he(!1),pe(`ai`),v(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=>{Ie(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;v(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{v(ln(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||C.current,sender:e?.sender}),e.sender===`agent`&&Ce(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||C.current,sender:e?.sender}),e.sender===`agent`&&Ce(!1)}),l.on(`call:incoming`,(e={})=>{let t=pn([e.agentName,e.ownerName,e.agent?.name,ge],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:C.current,agentName:t}),lt(),nt.current=!1,Le({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),_e(e=>pn([t,e],a)),Ve(`incoming`),Ue(null),de(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||C.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Qe.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||C.current,hasPeerConnection:!!Ye.current,hasCandidate:!!e.candidate});return}try{let t=dn(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||C.current,candidate:fn(t),hasRemoteDescription:!!Ye.current?.remoteDescription}),!Ye.current||!Ye.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||C.current,queueSize:$e.current.length+1}),$e.current.push(t);return}await Ye.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||C.current}),pt(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||C.current}),pt(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),mt(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),mt(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),mt(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=tt.current===e.callId,n=et.current===e.callId,r=Je.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||C.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(Le(null),Ve(`idle`));return}nt.current=!0,tt.current=null,et.current=e.callId,ze(e.callId),Le(null),Ve(`connected`),Ue(e.connectedAt||new Date().toISOString()),de(!0)}),l.on(`call:unavailable`,(e={})=>{dt(),qe(un(e,`This visitor is not available for a call right now.`)),de(!0)}),l.on(`call:error`,(e={})=>{dt(),qe(un(e,`We couldn't connect the call right now.`)),de(!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 on(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=en(null,t);e&&tn(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=en(e||null,t||null);n&&tn(n)}),l.on(`visitor:clear_highlight`,()=>{nn()}),st.current=Jt({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||(v(ln(u.chat_history||[])),he(!!u.is_human_handled),pe(u.is_human_handled?`agent`:fe),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(),x.current?.disconnect()}},[i,r]),(0,l.useEffect)(()=>()=>{if(Pe&&!ot.current&&at.current.length>0){let e=C.current,t=at.current,n=S.current,r=p?.apiBaseUrl||``,i=p?.userId||``;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(r,i,e,t)||n.syncVoice(e,t).catch(()=>{}),ot.current=!0)}},[Pe,p]),(0,l.useEffect)(()=>{if(!S.current||!_||o!==`ready`||me)return;let e=window.setInterval(async()=>{try{let e=await S.current.checkHumanHandled(_);he(!!e.is_human_handled),e.is_human_handled&&(pe(`agent`),e.agent_info?.name&&_e(e.agent_info.name),e.agent_info?.headshot&&ye(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[_,o,me]);let gt=async()=>{if(!(!b?.callId||!S.current||!x.current||!_)){lt(),tt.current=b.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:b?.callId,chatId:_,socketConnected:!!x.current?.connected,hasPendingOffer:!!Qe.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:b.callId,chatId:_,trackCount:e.getTracks().length}),Xe.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Ye.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:b.callId,chatId:_,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Ve(`connected`),Ue(t=>t||e),ft(e);return}e===`connecting`&&Ve(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:b.callId,chatId:_,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Ve(`connected`),Ue(t=>t||e),ft(e);return}(e===`checking`||e===`new`)&&Ve(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!x.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:b.callId,chatId:_,hasCandidate:!!e.candidate,socketConnected:!!x.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:b.callId,chatId:_,candidate:fn(e.candidate)}),x.current.emit(`call:ice-candidate`,{callId:b.callId,candidate:e.candidate,chatId:_,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:b.callId,chatId:_,streamCount:e.streams?.length||0}),!Ze.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Ze.current=e,document.body.appendChild(e)}Ze.current.srcObject=e.streams[0]};let n=Qe.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||b.callId,chatId:_}),await ht({...n,callId:n.callId||b.callId})),await S.current.acceptCall(b.callId,_),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:b.callId,chatId:_}),et.current=b.callId,ze(b.callId),Ve(`connecting`),Le(null),de(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),tt.current=null,dt(),e?.status===404||e?.status===409||e?.status===422){qe(un(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await S.current.rejectCall(b.callId,_)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}qe(`Microphone access was denied. Please allow microphone access to accept the call.`);return}qe(`We couldn't connect the call right now. Please try again.`)}}},_t=async()=>{if(!b?.callId||!S.current||!_){dt();return}lt();try{await S.current.rejectCall(b.callId,_)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),qe(un(e,`We couldn't decline the call cleanly.`))}finally{dt()}},vt=(0,l.useRef)(_t);vt.current=_t,(0,l.useEffect)(()=>{if(!b?.callId||Re)return;let e=b.callId,t=window.setTimeout(()=>{Je.current?.callId===e&&vt.current()},h);return()=>window.clearTimeout(t)},[b?.callId,Re]);let yt=async()=>{if(!Re||!S.current||!_){dt();return}lt();try{await S.current.endWebRTCCall(Re,_)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),qe(un(e,`The call ended locally, but the server could not be updated.`))}finally{dt()}},bt=()=>{let e=Xe.current?.getAudioTracks?.()||[],t=Ye.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=!We;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),Ge(r)},xt=async(e={})=>{let t=e.notifyChatInitiated===!0;if(de(!0),!(!t||!S.current||!_||typeof window>`u`)){try{await S.current.trackVisitor({chatId:_,currentPagePath:window.location.pathname||`/`})}catch{}try{await S.current.updateChatStatus(_,`open`)}catch{}}},St=async e=>{let t=ut(e);if(!t||!S.current||!C.current)return t;try{await S.current.trackVisitor({chatId:C.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(!_||!x.current?.connected||rt.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:_,socketConnected:!!x.current?.connected,alreadyTyping:rt.current});return}rt.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:_,sender:`user`}),x.current.emit(`typing:start`,{chatId:_,sender:`user`})},wt=()=>{if(_&&x.current?.connected&&it.current!==``&&(console.log(`[FlowEngageProvider] clearing typing draft`,{chatId:_,sender:`user`}),x.current.emit(`typing:update`,{chatId:_,sender:`user`,text:``}),it.current=``),!_||!x.current?.connected||!rt.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:_,socketConnected:!!x.current?.connected,wasTyping:rt.current});return}rt.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:_,sender:`user`}),x.current.emit(`typing:stop`,{chatId:_,sender:`user`})},Tt=(e=``)=>{let t=typeof e==`string`?e:``;if(!_||!x.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:_,socketConnected:!!x.current?.connected,textLength:t.length});return}it.current!==t&&(it.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:_,sender:`user`,textLength:t.length}),x.current.emit(`typing:update`,{chatId:_,sender:`user`,text:t}))},Et=async(e,t=``,n=null)=>{if(!e.trim()||!S.current||!_||o!==`ready`||Fe)return;wt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(v(e=>[...e,a]),me&&x.current?.connected){x.current.emit(`customer:message`,{chatId:_,content:e,sender:`user`,email:be||void 0,...n||{}});return}ke(!0);try{let i=await S.current.sendAiMessage(_,e,r,t,{...n||{},...be?{email:be}:{}});v(ln(i.chat_history||[])),he(!!i.is_human_handled),pe(i.is_human_handled?`agent`:`ai`),Te(!1),await S.current.updateChatStatus(_,`messageSent`)}catch(e){v(e=>e.filter(e=>e.id!==i)),Te(!1),e.status===429?(je(!0),Ne(e.message),window.setTimeout(()=>{je(!1),Ne(``)},m)):f(e)}finally{ke(!1)}},Dt=async e=>{if(!(!S.current||!_)){try{let t=e?`voice`:`text`;await S.current.setChatMode(_,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}y(e),e&&(ot.current=!1)}},Ot=async e=>{if(!ot.current){if(ot.current=!0,!S.current||!_||!e?.length){y(!1);return}try{let t=await S.current.syncVoice(_,e);t?.chat_history&&v(ln(t.chat_history))}catch{}finally{y(!1)}}},kt=async()=>{if(!(!S.current||!_)){Pe&&!ot.current&&at.current.length>0&&await Ot(at.current);try{await S.current.endConversation(_)}catch{try{await S.current.updateChatStatus(_,`ended`)}catch{}}Ie(!0),v(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(Be!==`connected`||!Re||!_||!He||!ct)return;let e=new Date(He).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,ct*1e3-t),r=window.setTimeout(()=>{qe(`The call ended because it reached the time limit.`),yt()},n);return()=>window.clearTimeout(r)},[Re,He,Be,_,yt,ct]),(0,l.useEffect)(()=>{let e=()=>{let e=C.current,t=S.current;if(!t||!e)return;if(et.current){t.beaconEndWebRTCCall(et.current,e);return}let n=tt.current||Je.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 At=(0,l.useMemo)(()=>({status:o,error:c,runtimeConfig:p,resolvedConfig:i,chatId:_,chatHistory:se,isOpen:ue,activeScreen:fe,isHumanHandled:me,agentName:ge,agentHeadshot:ve,visitorEmail:be,isAgentTyping:Se,isAiTyping:we,connectionStatus:Ee,isLoading:Oe,isVoiceMode:Pe,isRateLimited:Ae,rateLimitMessage:Me,isConversationEnded:Fe,incomingCall:b,activeCallId:Re,callConnectionState:Be,callConnectedAt:He,isCallMuted:We,webRTCError:Ke,language:r,historyRef:at,hasSyncedRef:ot,dismissCallError:lt,captureVisitorEmail:St,startTyping:Ct,stopTyping:wt,updateTypingDraft:Tt,notifyRouteChange:()=>st.current?.notifyRouteChange?.(),openWidget:xt,closeWidget:()=>de(!1),toggleWidget:()=>{if(ue){de(!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,_,se,ue,fe,me,ge,ve,be,Se,we,Ee,Oe,Pe,Ae,Me,Fe,b,Re,Be,He,We,Ke,r,St,Ct,wt,Tt,gt,_t,yt,bt,xt,Et,Dt,Ot,kt,lt]);return(0,u.jsx)(Yt.Provider,{value:At,children:n})}var hn=({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`})]}),gn=()=>(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`})}),_n=({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`})]}),vn=({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`})]}),yn=()=>(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`})]}),bn=()=>(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`})]}),xn=()=>(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`})}),Sn=({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`})]}),Cn=({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`})]}),wn=({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 Tn({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)(hn,{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)(gn,{})})]})}function En(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 Dn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function On(e){let[t,n]=(0,l.useState)(`loading`),r=Dn(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 kn({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}=On(e),h=i===`agent`,g=En(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:typeof f==`string`&&f.trim()?(0,u.jsx)(`img`,{src:f.trim(),alt:``,style:{width:`100%`,height:`100%`,objectFit:`cover`}}):(0,u.jsx)(`span`,{style:{lineHeight:1},children:g})}):(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)(wn,{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)(Cn,{})})})]})}var An=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),jn=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),Mn=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return t;let n=t.replace(/\r\n/g,`
8
+ `,document.head.appendChild(e)};function en(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=document.querySelectorAll(`h1, h2, h3, h4, h5, h6, [data-section]`);for(let e of r)if(e.textContent.toLowerCase().includes(n))return e;let i=n.split(/\s+/).filter(e=>e.length>2);if(i.length>1){let e=null,t=0;for(let n of r){let r=n.textContent.toLowerCase(),a=0;for(let e of i)r.includes(e)&&a++;let o=a/i.length;o>t&&o>=.6&&(t=o,e=n)}if(e)return e}let a=document.querySelectorAll(`li, strong, blockquote, dt`);for(let e of a){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<500)return e.tagName===`STRONG`&&e.parentElement?.tagName===`LI`?e.parentElement:e}let o=document.querySelectorAll(`p`);for(let e of o){let t=e.textContent.toLowerCase();if(t.includes(n)&&t.length<800)return e}return null}function tn(e){!e||typeof document>`u`||($t(),nn(),e.classList.add(`fe-highlight-section`),e.scrollIntoView({behavior:`smooth`,block:`center`}))}function nn(){typeof document>`u`||document.querySelectorAll(`.fe-highlight-section`).forEach(e=>e.classList.remove(`fe-highlight-section`))}function rn(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 an(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 on(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?an(e):!1:!1}catch(e){return console.warn(`[FlowEngage] navigate-allowed check failed:`,e?.message),!1}}async function sn(e){if(typeof window>`u`)return!1;try{let t=rn(e),n=new URL(t,window.location.origin);if(Qt(`input:`,e,`→ normalized:`,t,`href:`,n.href),n.hash&&n.pathname===window.location.pathname){let e=n.hash.slice(1),t=document.getElementById(e);if(t)return Qt(`branch: hash scroll (same path)`),t.scrollIntoView({behavior:`smooth`,block:`start`}),!0}if(n.pathname===window.location.pathname&&n.search===window.location.search&&!n.hash)return Qt(`branch: already on page (no nav)`),!1;let r=n.pathname+n.search+n.hash,i=window.next?.router;if(i?.push)return Qt(`branch: Next.js Pages router.push`,r),new Promise(e=>{let t=()=>{i.events?.off(`routeChangeComplete`,t),e(!0)};i.events?.on(`routeChangeComplete`,t),i.push(r),setTimeout(t,4e3)});let a=window.__NEXT_ROUTER__;return a?.push?(Qt(`branch: __NEXT_ROUTER__.push`,r),a.push(r),!0):(Qt(`branch: location.assign (full navigation)`,n.href),window.location.assign(n.href),!0)}catch(t){console.warn(`[FlowEngage] shadowNavigate error:`,t);try{window.location.href=rn(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(),ln=(e=[])=>e.map(e=>({...e,message:cn(e.message),isPending:!1,id:e.messageId||`${e.sender}-${e.timestamp||Date.now()}-${Math.random()}`})),un=(e,t)=>e?typeof e==`string`?e:e.message||e.error||e.reason||t:t,dn=(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}:{}}},fn=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 mn({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)(()=>pn([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)(``),[se,v]=(0,l.useState)([]),[ue,de]=(0,l.useState)(ne().isOpen),[fe,pe]=(0,l.useState)(ne().activeScreen),[me,he]=(0,l.useState)(ne().isHumanHandled),[ge,_e]=(0,l.useState)(ne().agentName),[ve,ye]=(0,l.useState)(ne().agentHeadshot),[be,xe]=(0,l.useState)(()=>ie(i?.siteId)),[Se,Ce]=(0,l.useState)(!1),[we,Te]=(0,l.useState)(!1),[Ee,De]=(0,l.useState)(`idle`),[Oe,ke]=(0,l.useState)(!1),[Ae,je]=(0,l.useState)(!1),[Me,Ne]=(0,l.useState)(``),[Pe,y]=(0,l.useState)(!1),[Fe,Ie]=(0,l.useState)(!1),[b,Le]=(0,l.useState)(null),[Re,ze]=(0,l.useState)(null),[Be,Ve]=(0,l.useState)(`idle`),[He,Ue]=(0,l.useState)(null),[We,Ge]=(0,l.useState)(!1),[Ke,qe]=(0,l.useState)(``),x=(0,l.useRef)(null),S=(0,l.useRef)(null),C=(0,l.useRef)(``),Je=(0,l.useRef)(null),Ye=(0,l.useRef)(null),Xe=(0,l.useRef)(null),Ze=(0,l.useRef)(null),Qe=(0,l.useRef)(null),$e=(0,l.useRef)([]),et=(0,l.useRef)(null),tt=(0,l.useRef)(null),nt=(0,l.useRef)(!1),rt=(0,l.useRef)(!1),it=(0,l.useRef)(``),at=(0,l.useRef)(ge),ot=(0,l.useRef)([]),st=(0,l.useRef)(!1),ct=(0,l.useRef)({notifyRouteChange:()=>{},cleanup:()=>{}}),lt=(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)(()=>{Je.current=b},[b]),(0,l.useEffect)(()=>{at.current=ge},[ge]);let ut=()=>{qe(``)},dt=e=>{let t=typeof e==`string`?e.trim().toLowerCase():``;return xe(t),ae(t,i?.siteId),t};(0,l.useEffect)(()=>{let e=i?.siteId;e&&xe(ie(e))},[i?.siteId]);let ft=()=>{Ye.current&&=(Ye.current.close(),null),Xe.current&&=(Xe.current.getTracks().forEach(e=>e.stop()),null),Ze.current&&=(Ze.current.srcObject=null,Ze.current.remove(),null),Qe.current=null,$e.current=[],et.current=null,tt.current=null,nt.current=!1,Ge(!1),Le(null),ze(null),Ve(`idle`),Ue(null)},pt=(e=new Date().toISOString())=>{let t=x.current,n=et.current||Qe.current?.callId;if(!t?.connected||!n||nt.current){console.log(`[FlowEngageProvider] skipping call:connected emit`,{callId:n,chatId:C.current,socketConnected:!!t?.connected,alreadyReported:nt.current});return}console.log(`[FlowEngageProvider] emitting call:connected`,{callId:n,chatId:C.current,connectedAt:e}),nt.current=!0,t.emit(`call:connected`,{callId:n,chatId:C.current,connectedAt:e})},mt=(e={})=>{if(!e.callId)return;let t=tt.current===e.callId,n=et.current===e.callId,r=Je.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing accepted call state`,{callId:e.callId,chatId:e.chatId||C.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),Le(null),t||n){et.current=e.callId,ze(e.callId),Ve(e=>e===`connected`?e:`connecting`),de(!0);return}Ve(`idle`)}},ht=(e={})=>{if(!e.callId)return;let t=tt.current===e.callId,n=et.current===e.callId,r=Je.current?.callId===e.callId;if(!(!t&&!n&&!r)){if(console.log(`[FlowEngageProvider] syncing ended incoming call state`,{callId:e.callId,chatId:e.chatId||C.current,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r,reason:e.reason||e.status||null}),n){ft();return}tt.current=null,Qe.current=null,$e.current=[],Le(null),Ve(`idle`)}},gt=async(e={})=>{let t=Ye.current,n=x.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:C.current,hasPeerConnection:!!t,socketConnected:!!n?.connected,hasOffer:!!r}),Qe.current=e;return}if(console.log(`[FlowEngageProvider] applying remote offer`,{callId:e.callId,chatId:C.current,offerLength:r.length,signalingState:t.signalingState}),await t.setRemoteDescription(new RTCSessionDescription({type:`offer`,sdp:r})),$e.current.length>0){console.log(`[FlowEngageProvider] flushing queued agent ICE candidates after remote offer`,{callId:e.callId,chatId:C.current,queuedCount:$e.current.length});for(let e of $e.current)await t.addIceCandidate(new RTCIceCandidate(e));$e.current=[]}let i=await t.createAnswer();await t.setLocalDescription(i),console.log(`[FlowEngageProvider] created local answer`,{callId:e.callId,chatId:C.current,answerLength:i.sdp?.length||0,signalingState:t.signalingState}),n.emit(`call:answer`,{callId:e.callId,sdpAnswer:i.sdp,chatId:C.current})};(0,l.useEffect)(()=>{re({isOpen:ue,activeScreen:fe,isHumanHandled:me,agentName:ge,agentHeadshot:ve})},[ue,fe,me,ge,ve]),(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 ce(t);if(!e)return;let o=te();C.current=o;let c=le({apiBaseUrl:t.apiBaseUrl,userId:n.userId,siteId:t.siteId});S.current=c,g({...n,apiBaseUrl:t.apiBaseUrl}),oe(o),console.log(`[FlowEngageProvider] bootstrap resolved`,{bootstrapData:n,resolvedChatId:o});let l=qt({apiBaseUrl:t.apiBaseUrl,userId:n.userId,chatId:o,siteId:t.siteId});x.current=l,l.on(`connect`,()=>{console.log(`[FlowEngageProvider] socket connected`),De(`connected`)}),l.on(`disconnect`,()=>{console.log(`[FlowEngageProvider] socket disconnected`),De(`disconnected`)}),l.on(`aiTyping`,()=>{console.log(`[FlowEngageProvider] received aiTyping`,{chatId:C.current}),Te(!0)}),l.on(`ai:typing`,()=>{console.log(`[FlowEngageProvider] received ai:typing`,{chatId:C.current}),Te(!0)}),l.on(`messageReceived`,e=>{let t=e.message||e,n={...t,message:cn(t.message)};Te(!1),Ce(!1),v(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&&v(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)};Te(!1),(n.sender===`agent`||n.agent_name||n.sender===`ai`||n.sender===`bot`)&&Ce(!1),v(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)&&(he(!0),pe(`agent`),_e(pn([n.agent_name,n.agentName,n.metadata?.agentName],a)),n.sender_headshot&&ye(n.sender_headshot),de(!0))}),l.on(`agent:joined`,e=>{let t=pn([e.agent?.name,e.agentName],a);he(!0),pe(`agent`),_e(t),ye(e.agent?.headshot||null),de(!0),v(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);he(!0),pe(`agent`),_e(t),ye(e.agent?.headshot||null),de(!0),v(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,at.current],a);he(!1),pe(`ai`),v(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,at.current],a);he(!1),pe(`ai`),v(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=>{Ie(!0);let t=e?.message||`This conversation has ended. Thank you for reaching out!`;v(e=>[...e,{id:`conversation-ended-${Date.now()}`,sender:`system`,message:t,timestamp:new Date().toISOString(),isPending:!1}])}),l.on(`chat:history_update`,e=>{v(ln(e.chat_history||[]))}),l.on(`typing:start`,e=>{console.log(`[FlowEngageProvider] received typing:start`,{chatId:e?.chatId||C.current,sender:e?.sender}),e.sender===`agent`&&Ce(!0)}),l.on(`typing:stop`,e=>{console.log(`[FlowEngageProvider] received typing:stop`,{chatId:e?.chatId||C.current,sender:e?.sender}),e.sender===`agent`&&Ce(!1)}),l.on(`call:incoming`,(e={})=>{let t=pn([e.agentName,e.ownerName,e.agent?.name,ge],a);console.log(`[FlowEngageProvider] received call:incoming`,{callId:e.callId,chatId:C.current,agentName:t}),ut(),nt.current=!1,Le({callId:e.callId,from:e.from||`owner`,agentId:e.agentId||null,agentName:t}),_e(e=>pn([t,e],a)),Ve(`incoming`),Ue(null),de(!0)}),l.on(`call:offer`,async(e={})=>{console.log(`[FlowEngageProvider] received call:offer`,{callId:e.callId,chatId:e.chatId||C.current,offerLength:(e.sdpOffer||e.offer?.sdp||``).length}),Qe.current=e;try{await gt(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||C.current,hasPeerConnection:!!Ye.current,hasCandidate:!!e.candidate});return}try{let t=dn(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||C.current,candidate:fn(t),hasRemoteDescription:!!Ye.current?.remoteDescription}),!Ye.current||!Ye.current.remoteDescription){console.log(`[FlowEngageProvider] queueing agent ICE candidate until peer/remote description is ready`,{callId:e.callId,chatId:e.chatId||C.current,queueSize:$e.current.length+1}),$e.current.push(t);return}await Ye.current.addIceCandidate(new RTCIceCandidate(t))}catch(e){console.error(`[FlowEngageProvider] failed to add ICE candidate`,e)}}),l.on(`call:ended`,()=>{ut(),ft()}),l.on(`call:accepted`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted`,{callId:e.callId,chatId:e.chatId||C.current}),mt(e)}),l.on(`call:accepted_by_other`,(e={})=>{console.log(`[FlowEngageProvider] received call:accepted_by_other`,{callId:e.callId,chatId:e.chatId||C.current}),mt(e)}),l.on(`call:rejected`,(e={})=>{console.log(`[FlowEngageProvider] received call:rejected`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),ht(e)}),l.on(`call:missed`,(e={})=>{console.log(`[FlowEngageProvider] received call:missed`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),ht(e)}),l.on(`call:failed`,(e={})=>{console.log(`[FlowEngageProvider] received call:failed`,{callId:e.callId,chatId:e.chatId||C.current,reason:e.reason}),ht(e)}),l.on(`call:connected`,(e={})=>{if(!e.callId)return;let t=tt.current===e.callId,n=et.current===e.callId,r=Je.current?.callId===e.callId;if(console.log(`[FlowEngageProvider] received call:connected`,{callId:e.callId,chatId:e.chatId||C.current,connectedAt:e.connectedAt,status:e.status,isAcceptingHere:t,isAlreadyActive:n,isIncomingHere:r}),!t&&!n){r&&(Le(null),Ve(`idle`));return}nt.current=!0,tt.current=null,et.current=e.callId,ze(e.callId),Le(null),Ve(`connected`),Ue(e.connectedAt||new Date().toISOString()),de(!0)}),l.on(`call:unavailable`,(e={})=>{ft(),qe(un(e,`This visitor is not available for a call right now.`)),de(!0)}),l.on(`call:error`,(e={})=>{ft(),qe(un(e,`We couldn't connect the call right now.`)),de(!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 on(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=en(null,t);e&&tn(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=en(e||null,t||null);n&&tn(n)}),l.on(`visitor:clear_highlight`,()=>{nn()}),ct.current=Jt({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||(v(ln(u.chat_history||[])),he(!!u.is_human_handled),pe(u.is_human_handled?`agent`:fe),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,ct.current?.cleanup?.(),ft(),x.current?.disconnect()}},[i,r]),(0,l.useEffect)(()=>()=>{if(Pe&&!st.current&&ot.current.length>0){let e=C.current,t=ot.current,n=S.current,r=p?.apiBaseUrl||``,i=p?.userId||``;n&&e&&t.length>0&&(console.log(`[FlowEngageProvider] safety-net: syncing voice transcript on unmount`),n.beaconSyncVoice(r,i,e,t)||n.syncVoice(e,t).catch(()=>{}),st.current=!0)}},[Pe,p]),(0,l.useEffect)(()=>{if(!S.current||!_||o!==`ready`||me)return;let e=window.setInterval(async()=>{try{let e=await S.current.checkHumanHandled(_);he(!!e.is_human_handled),e.is_human_handled&&(pe(`agent`),e.agent_info?.name&&_e(e.agent_info.name),e.agent_info?.headshot&&ye(e.agent_info.headshot))}catch{}},1e4);return()=>window.clearInterval(e)},[_,o,me]);let _t=async()=>{if(!(!b?.callId||!S.current||!x.current||!_)){ut(),tt.current=b.callId,console.log(`[FlowEngageProvider] acceptCall started`,{callId:b?.callId,chatId:_,socketConnected:!!x.current?.connected,hasPendingOffer:!!Qe.current});try{let e=await navigator.mediaDevices.getUserMedia({audio:!0});console.log(`[FlowEngageProvider] microphone stream acquired`,{callId:b.callId,chatId:_,trackCount:e.getTracks().length}),Xe.current=e;let t=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});Ye.current=t,t.onconnectionstatechange=()=>{let e=t.connectionState;if(console.log(`[FlowEngageProvider] peer connection state changed`,{callId:b.callId,chatId:_,connectionState:e,iceConnectionState:t.iceConnectionState,signalingState:t.signalingState}),e===`connected`){let e=new Date().toISOString();Ve(`connected`),Ue(t=>t||e),pt(e);return}e===`connecting`&&Ve(e=>e===`connected`?e:`connecting`)},t.oniceconnectionstatechange=()=>{let e=t.iceConnectionState;if(console.log(`[FlowEngageProvider] ICE connection state changed`,{callId:b.callId,chatId:_,iceConnectionState:e,connectionState:t.connectionState,signalingState:t.signalingState}),e===`connected`||e===`completed`){let e=new Date().toISOString();Ve(`connected`),Ue(t=>t||e),pt(e);return}(e===`checking`||e===`new`)&&Ve(e=>e===`connected`?e:`connecting`)},e.getTracks().forEach(n=>{t.addTrack(n,e)}),t.onicecandidate=e=>{if(!e.candidate||!x.current?.connected){console.log(`[FlowEngageProvider] local ICE candidate skipped`,{callId:b.callId,chatId:_,hasCandidate:!!e.candidate,socketConnected:!!x.current?.connected});return}console.log(`[FlowEngageProvider] emitting local ICE candidate`,{callId:b.callId,chatId:_,candidate:fn(e.candidate)}),x.current.emit(`call:ice-candidate`,{callId:b.callId,candidate:e.candidate,chatId:_,from:`customer`})},t.ontrack=e=>{if(console.log(`[FlowEngageProvider] remote audio track received`,{callId:b.callId,chatId:_,streamCount:e.streams?.length||0}),!Ze.current){let e=document.createElement(`audio`);e.id=`flowengage-remote-audio`,e.autoplay=!0,Ze.current=e,document.body.appendChild(e)}Ze.current.srcObject=e.streams[0]};let n=Qe.current;n&&(console.log(`[FlowEngageProvider] found pending remote offer during accept`,{callId:n.callId||b.callId,chatId:_}),await gt({...n,callId:n.callId||b.callId})),await S.current.acceptCall(b.callId,_),console.log(`[FlowEngageProvider] acceptCall API succeeded`,{callId:b.callId,chatId:_}),et.current=b.callId,ze(b.callId),Ve(`connecting`),Le(null),de(!0)}catch(e){if(console.error(`[FlowEngageProvider] acceptCall failed`,e),tt.current=null,ft(),e?.status===404||e?.status===409||e?.status===422){qe(un(e,`This visitor call is no longer available.`));return}if(e?.name===`NotAllowedError`||e?.name===`PermissionDeniedError`){try{await S.current.rejectCall(b.callId,_)}catch(e){console.error(`[FlowEngageProvider] failed to reject call after microphone denial`,e)}qe(`Microphone access was denied. Please allow microphone access to accept the call.`);return}qe(`We couldn't connect the call right now. Please try again.`)}}},vt=async()=>{if(!b?.callId||!S.current||!_){ft();return}ut();try{await S.current.rejectCall(b.callId,_)}catch(e){console.error(`[FlowEngageProvider] rejectCall failed`,e),qe(un(e,`We couldn't decline the call cleanly.`))}finally{ft()}},yt=(0,l.useRef)(vt);yt.current=vt,(0,l.useEffect)(()=>{if(!b?.callId||Re)return;let e=b.callId,t=window.setTimeout(()=>{Je.current?.callId===e&&yt.current()},h);return()=>window.clearTimeout(t)},[b?.callId,Re]);let bt=async()=>{if(!Re||!S.current||!_){ft();return}ut();try{await S.current.endWebRTCCall(Re,_)}catch(e){console.error(`[FlowEngageProvider] endWebRTCCall failed`,e),qe(un(e,`The call ended locally, but the server could not be updated.`))}finally{ft()}},xt=()=>{let e=Xe.current?.getAudioTracks?.()||[],t=Ye.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=!We;n.forEach(e=>{e.enabled=!r}),console.log(`[FlowEngageProvider] toggled local mute`,{nextMuted:r,trackCount:n.length}),Ge(r)},St=async(e={})=>{let t=e.notifyChatInitiated===!0;if(de(!0),!(!t||!S.current||!_||typeof window>`u`)){try{await S.current.trackVisitor({chatId:_,currentPagePath:window.location.pathname||`/`})}catch{}try{await S.current.updateChatStatus(_,`open`)}catch{}}},Ct=async e=>{let t=dt(e);if(!t||!S.current||!C.current)return t;try{await S.current.trackVisitor({chatId:C.current,currentPagePath:typeof window<`u`&&window.location.pathname||`/`,email:t})}catch(e){console.error(`[FlowEngageProvider] failed to persist visitor email`,e)}return t},wt=()=>{if(!_||!x.current?.connected||rt.current){console.log(`[FlowEngageProvider] skipped typing:start emit`,{chatId:_,socketConnected:!!x.current?.connected,alreadyTyping:rt.current});return}rt.current=!0,console.log(`[FlowEngageProvider] emitting typing:start`,{chatId:_,sender:`user`}),x.current.emit(`typing:start`,{chatId:_,sender:`user`})},Tt=()=>{if(_&&x.current?.connected&&it.current!==``&&(console.log(`[FlowEngageProvider] clearing typing draft`,{chatId:_,sender:`user`}),x.current.emit(`typing:update`,{chatId:_,sender:`user`,text:``}),it.current=``),!_||!x.current?.connected||!rt.current){console.log(`[FlowEngageProvider] skipped typing:stop emit`,{chatId:_,socketConnected:!!x.current?.connected,wasTyping:rt.current});return}rt.current=!1,console.log(`[FlowEngageProvider] emitting typing:stop`,{chatId:_,sender:`user`}),x.current.emit(`typing:stop`,{chatId:_,sender:`user`})},Et=(e=``)=>{let t=typeof e==`string`?e:``;if(!_||!x.current?.connected){console.log(`[FlowEngageProvider] skipped typing:update emit`,{chatId:_,socketConnected:!!x.current?.connected,textLength:t.length});return}it.current!==t&&(it.current=t,console.log(`[FlowEngageProvider] emitting typing:update`,{chatId:_,sender:`user`,textLength:t.length}),x.current.emit(`typing:update`,{chatId:_,sender:`user`,text:t}))},Dt=async(e,t=``,n=null)=>{if(!e.trim()||!S.current||!_||o!==`ready`||Fe)return;Tt();let i=`pending-user-${Date.now()}`,a={id:i,sender:`user`,message:e,timestamp:new Date().toISOString(),isPending:!0,...n||{}};if(v(e=>[...e,a]),me&&x.current?.connected){x.current.emit(`customer:message`,{chatId:_,content:e,sender:`user`,email:be||void 0,...n||{}});return}ke(!0);try{let i=await S.current.sendAiMessage(_,e,r,t,{...n||{},...be?{email:be}:{}});v(ln(i.chat_history||[])),he(!!i.is_human_handled),pe(i.is_human_handled?`agent`:`ai`),Te(!1),await S.current.updateChatStatus(_,`messageSent`)}catch(e){v(e=>e.filter(e=>e.id!==i)),Te(!1),e.status===429?(je(!0),Ne(e.message),window.setTimeout(()=>{je(!1),Ne(``)},m)):f(e)}finally{ke(!1)}},Ot=async e=>{if(!(!S.current||!_)){try{let t=e?`voice`:`text`;await S.current.setChatMode(_,t)}catch(e){console.error(`[FlowEngageProvider] setVoiceMode failed`,e)}y(e),e&&(st.current=!1)}},kt=async e=>{if(!st.current){if(st.current=!0,!S.current||!_||!e?.length){y(!1);return}try{let t=await S.current.syncVoice(_,e);t?.chat_history&&v(ln(t.chat_history))}catch{}finally{y(!1)}}},At=async()=>{if(!(!S.current||!_)){Pe&&!st.current&&ot.current.length>0&&await kt(ot.current);try{await S.current.endConversation(_)}catch{try{await S.current.updateChatStatus(_,`ended`)}catch{}}Ie(!0),v(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(Be!==`connected`||!Re||!_||!He||!lt)return;let e=new Date(He).getTime(),t=Number.isFinite(e)?Date.now()-e:0,n=Math.max(0,lt*1e3-t),r=window.setTimeout(()=>{qe(`The call ended because it reached the time limit.`),bt()},n);return()=>window.clearTimeout(r)},[Re,He,Be,_,bt,lt]),(0,l.useEffect)(()=>{let e=()=>{let e=C.current,t=S.current;if(!t||!e)return;if(et.current){t.beaconEndWebRTCCall(et.current,e);return}let n=tt.current||Je.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 w=(0,l.useMemo)(()=>({status:o,error:c,runtimeConfig:p,resolvedConfig:i,chatId:_,chatHistory:se,isOpen:ue,activeScreen:fe,isHumanHandled:me,agentName:ge,agentHeadshot:ve,visitorEmail:be,isAgentTyping:Se,isAiTyping:we,connectionStatus:Ee,isLoading:Oe,isVoiceMode:Pe,isRateLimited:Ae,rateLimitMessage:Me,isConversationEnded:Fe,incomingCall:b,activeCallId:Re,callConnectionState:Be,callConnectedAt:He,isCallMuted:We,webRTCError:Ke,language:r,historyRef:ot,hasSyncedRef:st,dismissCallError:ut,captureVisitorEmail:Ct,startTyping:wt,stopTyping:Tt,updateTypingDraft:Et,notifyRouteChange:()=>ct.current?.notifyRouteChange?.(),openWidget:St,closeWidget:()=>de(!1),toggleWidget:()=>{if(ue){de(!1);return}St({notifyChatInitiated:!0})},sendMessage:Dt,setVoiceMode:Ot,onMessageSync:kt,endConversation:At,acceptCall:_t,rejectCall:vt,endWebRTCCall:bt,toggleCallMute:xt,startTyping:wt,stopTyping:Tt,updateTypingDraft:Et}),[o,c,p,i,_,se,ue,fe,me,ge,ve,be,Se,we,Ee,Oe,Pe,Ae,Me,Fe,b,Re,Be,He,We,Ke,r,Ct,wt,Tt,Et,_t,vt,bt,xt,St,Dt,Ot,kt,At,ut]);return(0,u.jsx)(Yt.Provider,{value:w,children:n})}var hn=({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`})]}),gn=()=>(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`})}),_n=({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`})]}),vn=({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`})]}),yn=()=>(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`})]}),bn=()=>(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`})]}),xn=()=>(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`})}),Sn=({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`})]}),Cn=({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`})]}),wn=({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 Tn({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)(hn,{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)(gn,{})})]})}function En(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 Dn(e){return typeof e==`string`?e.trim():e&&typeof e==`object`&&typeof e.src==`string`?e.src.trim():``}function On(e){let[t,n]=(0,l.useState)(`loading`),r=Dn(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 kn({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}=On(e),h=i===`agent`,g=En(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:typeof f==`string`&&f.trim()?(0,u.jsx)(`img`,{src:f.trim(),alt:``,style:{width:`100%`,height:`100%`,objectFit:`cover`}}):(0,u.jsx)(`span`,{style:{lineHeight:1},children:g})}):(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)(wn,{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)(Cn,{})})})]})}var An=(e=``)=>String(e).replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim(),jn=(e=``)=>String(e).replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),Mn=(e=``)=>{let t=String(e||``).trim();if(!t)return``;if(/<(p|br|ul|ol|li|strong|em|a)\b/i.test(t))return t;let n=t.replace(/\r\n/g,`
9
9
  `).replace(/\n{3,}/g,`
10
10
 
11
11
  `).split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),r=e=>jn(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 n.map(e=>{let t=e.split(`
@@ -1947,19 +1947,21 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
1947
1947
  let c = a(() => e ? {
1948
1948
  ...t || {},
1949
1949
  siteId: e
1950
- } : t || null, [e, t]), u = a(() => pn([c?.widgetSettings?.branding?.fallbackAgentName, c?.widgetSettings?.branding?.headerName], "Agent"), [c]), [d, f] = s("booting"), [m, h] = s(null), [_, ne] = s(null), [v, ce] = s(""), [y, b] = s([]), [de, fe] = s(ie().isOpen), [pe, me] = s(ie().activeScreen), [he, ge] = s(ie().isHumanHandled), [_e, ve] = s(ie().agentName), [ye, be] = s(ie().agentHeadshot), [xe, Se] = s(() => oe(c?.siteId)), [Ce, we] = s(!1), [Te, Ee] = s(!1), [De, Oe] = s("idle"), [ke, Ae] = s(!1), [je, Me] = s(!1), [Ne, Pe] = s(""), [x, Fe] = s(!1), [Ie, Le] = s(!1), [S, Re] = s(null), [ze, Be] = s(null), [Ve, He] = s("idle"), [Ue, We] = s(null), [Ge, Ke] = s(!1), [qe, Je] = s(""), C = o(null), w = o(null), T = o(""), Ye = o(null), Xe = o(null), Ze = o(null), Qe = o(null), $e = o(null), et = o([]), tt = o(null), nt = o(null), rt = o(!1), it = o(!1), at = o(""), ot = o([]), st = o(!1), ct = o({
1950
+ } : t || null, [e, t]), u = a(() => pn([c?.widgetSettings?.branding?.fallbackAgentName, c?.widgetSettings?.branding?.headerName], "Agent"), [c]), [d, f] = s("booting"), [m, h] = s(null), [_, ne] = s(null), [v, ce] = s(""), [y, b] = s([]), [de, fe] = s(ie().isOpen), [pe, me] = s(ie().activeScreen), [he, ge] = s(ie().isHumanHandled), [_e, ve] = s(ie().agentName), [ye, be] = s(ie().agentHeadshot), [xe, Se] = s(() => oe(c?.siteId)), [Ce, we] = s(!1), [Te, Ee] = s(!1), [De, Oe] = s("idle"), [ke, Ae] = s(!1), [je, Me] = s(!1), [Ne, Pe] = s(""), [x, Fe] = s(!1), [Ie, Le] = s(!1), [S, Re] = s(null), [ze, Be] = s(null), [Ve, He] = s("idle"), [Ue, We] = s(null), [Ge, Ke] = s(!1), [qe, Je] = s(""), C = o(null), w = o(null), T = o(""), Ye = o(null), Xe = o(null), Ze = o(null), Qe = o(null), $e = o(null), et = o([]), tt = o(null), nt = o(null), rt = o(!1), it = o(!1), at = o(""), ot = o(_e), st = o([]), ct = o(!1), lt = o({
1951
1951
  notifyRouteChange: () => {},
1952
1952
  cleanup: () => {}
1953
- }), lt = a(() => {
1953
+ }), ut = a(() => {
1954
1954
  let e = _?.widgetSettings?.call?.maxDurationSeconds ?? c?.widgetSettings?.call?.maxDurationSeconds ?? c?.callMaxDurationSeconds, t = Number(e);
1955
1955
  return Number.isFinite(t) && t > 0 ? t : ee;
1956
1956
  }, [c, _]);
1957
1957
  i(() => {
1958
1958
  Ye.current = S;
1959
- }, [S]);
1960
- let ut = () => {
1959
+ }, [S]), i(() => {
1960
+ ot.current = _e;
1961
+ }, [_e]);
1962
+ let dt = () => {
1961
1963
  Je("");
1962
- }, dt = (e) => {
1964
+ }, ft = (e) => {
1963
1965
  let t = typeof e == "string" ? e.trim().toLowerCase() : "";
1964
1966
  return Se(t), se(t, c?.siteId), t;
1965
1967
  };
@@ -1967,9 +1969,9 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
1967
1969
  let e = c?.siteId;
1968
1970
  e && Se(oe(e));
1969
1971
  }, [c?.siteId]);
1970
- let ft = () => {
1972
+ let pt = () => {
1971
1973
  Xe.current &&= (Xe.current.close(), null), Ze.current &&= (Ze.current.getTracks().forEach((e) => e.stop()), null), Qe.current &&= (Qe.current.srcObject = null, Qe.current.remove(), null), $e.current = null, et.current = [], tt.current = null, nt.current = null, rt.current = !1, Ke(!1), Re(null), Be(null), He("idle"), We(null);
1972
- }, pt = (e = (/* @__PURE__ */ new Date()).toISOString()) => {
1974
+ }, mt = (e = (/* @__PURE__ */ new Date()).toISOString()) => {
1973
1975
  let t = C.current, n = tt.current || $e.current?.callId;
1974
1976
  if (!t?.connected || !n || rt.current) {
1975
1977
  console.log("[FlowEngageProvider] skipping call:connected emit", {
@@ -1989,7 +1991,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
1989
1991
  chatId: T.current,
1990
1992
  connectedAt: e
1991
1993
  });
1992
- }, mt = (e = {}) => {
1994
+ }, ht = (e = {}) => {
1993
1995
  if (!e.callId) return;
1994
1996
  let t = nt.current === e.callId, n = tt.current === e.callId, r = Ye.current?.callId === e.callId;
1995
1997
  if (!(!t && !n && !r)) {
@@ -2005,7 +2007,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2005
2007
  }
2006
2008
  He("idle");
2007
2009
  }
2008
- }, ht = (e = {}) => {
2010
+ }, gt = (e = {}) => {
2009
2011
  if (!e.callId) return;
2010
2012
  let t = nt.current === e.callId, n = tt.current === e.callId, r = Ye.current?.callId === e.callId;
2011
2013
  if (!(!t && !n && !r)) {
@@ -2017,12 +2019,12 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2017
2019
  isIncomingHere: r,
2018
2020
  reason: e.reason || e.status || null
2019
2021
  }), n) {
2020
- ft();
2022
+ pt();
2021
2023
  return;
2022
2024
  }
2023
2025
  nt.current = null, $e.current = null, et.current = [], Re(null), He("idle");
2024
2026
  }
2025
- }, gt = async (e = {}) => {
2027
+ }, _t = async (e = {}) => {
2026
2028
  let t = Xe.current, n = C.current, r = e.sdpOffer || e.offer?.sdp;
2027
2029
  if (!t || !n?.connected || !r || !e.callId) {
2028
2030
  console.log("[FlowEngageProvider] deferring remote offer until peer/socket ready", {
@@ -2179,7 +2181,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2179
2181
  let t = pn([
2180
2182
  e.agent?.name,
2181
2183
  e.agentName,
2182
- _e
2184
+ ot.current
2183
2185
  ], u);
2184
2186
  ge(!1), me("ai"), b((e) => [...e, {
2185
2187
  id: `agent-left-${Date.now()}`,
@@ -2192,7 +2194,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2192
2194
  let t = pn([
2193
2195
  e.agent?.name,
2194
2196
  e.agentName,
2195
- _e
2197
+ ot.current
2196
2198
  ], u);
2197
2199
  ge(!1), me("ai"), b((e) => [...e, {
2198
2200
  id: `agent-left-${Date.now()}`,
@@ -2234,7 +2236,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2234
2236
  callId: e.callId,
2235
2237
  chatId: T.current,
2236
2238
  agentName: t
2237
- }), ut(), rt.current = !1, Re({
2239
+ }), dt(), rt.current = !1, Re({
2238
2240
  callId: e.callId,
2239
2241
  from: e.from || "owner",
2240
2242
  agentId: e.agentId || null,
@@ -2247,7 +2249,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2247
2249
  offerLength: (e.sdpOffer || e.offer?.sdp || "").length
2248
2250
  }), $e.current = e;
2249
2251
  try {
2250
- await gt(e);
2252
+ await _t(e);
2251
2253
  } catch (e) {
2252
2254
  console.error("[FlowEngageProvider] failed to apply remote offer", e);
2253
2255
  }
@@ -2285,35 +2287,35 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2285
2287
  console.error("[FlowEngageProvider] failed to add ICE candidate", e);
2286
2288
  }
2287
2289
  }), o.on("call:ended", () => {
2288
- ut(), ft();
2290
+ dt(), pt();
2289
2291
  }), o.on("call:accepted", (e = {}) => {
2290
2292
  console.log("[FlowEngageProvider] received call:accepted", {
2291
2293
  callId: e.callId,
2292
2294
  chatId: e.chatId || T.current
2293
- }), mt(e);
2295
+ }), ht(e);
2294
2296
  }), o.on("call:accepted_by_other", (e = {}) => {
2295
2297
  console.log("[FlowEngageProvider] received call:accepted_by_other", {
2296
2298
  callId: e.callId,
2297
2299
  chatId: e.chatId || T.current
2298
- }), mt(e);
2300
+ }), ht(e);
2299
2301
  }), o.on("call:rejected", (e = {}) => {
2300
2302
  console.log("[FlowEngageProvider] received call:rejected", {
2301
2303
  callId: e.callId,
2302
2304
  chatId: e.chatId || T.current,
2303
2305
  reason: e.reason
2304
- }), ht(e);
2306
+ }), gt(e);
2305
2307
  }), o.on("call:missed", (e = {}) => {
2306
2308
  console.log("[FlowEngageProvider] received call:missed", {
2307
2309
  callId: e.callId,
2308
2310
  chatId: e.chatId || T.current,
2309
2311
  reason: e.reason
2310
- }), ht(e);
2312
+ }), gt(e);
2311
2313
  }), o.on("call:failed", (e = {}) => {
2312
2314
  console.log("[FlowEngageProvider] received call:failed", {
2313
2315
  callId: e.callId,
2314
2316
  chatId: e.chatId || T.current,
2315
2317
  reason: e.reason
2316
- }), ht(e);
2318
+ }), gt(e);
2317
2319
  }), o.on("call:connected", (e = {}) => {
2318
2320
  if (!e.callId) return;
2319
2321
  let t = nt.current === e.callId, n = tt.current === e.callId, r = Ye.current?.callId === e.callId;
@@ -2331,9 +2333,9 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2331
2333
  }
2332
2334
  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);
2333
2335
  }), o.on("call:unavailable", (e = {}) => {
2334
- ft(), Je(un(e, "This visitor is not available for a call right now.")), fe(!0);
2336
+ pt(), Je(un(e, "This visitor is not available for a call right now.")), fe(!0);
2335
2337
  }), o.on("call:error", (e = {}) => {
2336
- ft(), Je(un(e, "We couldn't connect the call right now.")), fe(!0);
2338
+ pt(), Je(un(e, "We couldn't connect the call right now.")), fe(!0);
2337
2339
  }), o.on("visitor:navigate", async ({ url: e, section: n, highlight: r } = {}) => {
2338
2340
  if (e) {
2339
2341
  if (console.log("[FlowEngageProvider] visitor:navigate", {
@@ -2365,7 +2367,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2365
2367
  n && tn(n);
2366
2368
  }), o.on("visitor:clear_highlight", () => {
2367
2369
  nn();
2368
- }), ct.current = Jt({
2370
+ }), lt.current = Jt({
2369
2371
  socket: o,
2370
2372
  chatId: i
2371
2373
  }), console.log("[FlowEngageProvider] tracking started", { chatId: i });
@@ -2377,12 +2379,12 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2377
2379
  console.error("[FlowEngageProvider] boot failed", t), h(t), f("error");
2378
2380
  }
2379
2381
  })(), () => {
2380
- e = !1, ct.current?.cleanup?.(), ft(), C.current?.disconnect();
2382
+ e = !1, lt.current?.cleanup?.(), pt(), C.current?.disconnect();
2381
2383
  };
2382
2384
  }, [c, r]), i(() => () => {
2383
- if (x && !st.current && ot.current.length > 0) {
2384
- let e = T.current, t = ot.current, n = w.current, r = _?.apiBaseUrl || "", i = _?.userId || "";
2385
- n && e && t.length > 0 && (console.log("[FlowEngageProvider] safety-net: syncing voice transcript on unmount"), n.beaconSyncVoice(r, i, e, t) || n.syncVoice(e, t).catch(() => {}), st.current = !0);
2385
+ if (x && !ct.current && st.current.length > 0) {
2386
+ let e = T.current, t = st.current, n = w.current, r = _?.apiBaseUrl || "", i = _?.userId || "";
2387
+ n && e && t.length > 0 && (console.log("[FlowEngageProvider] safety-net: syncing voice transcript on unmount"), n.beaconSyncVoice(r, i, e, t) || n.syncVoice(e, t).catch(() => {}), ct.current = !0);
2386
2388
  }
2387
2389
  }, [x, _]), i(() => {
2388
2390
  if (!w.current || !v || d !== "ready" || he) return;
@@ -2398,9 +2400,9 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2398
2400
  d,
2399
2401
  he
2400
2402
  ]);
2401
- let _t = async () => {
2403
+ let vt = async () => {
2402
2404
  if (!(!S?.callId || !w.current || !C.current || !v)) {
2403
- ut(), nt.current = S.callId, console.log("[FlowEngageProvider] acceptCall started", {
2405
+ dt(), nt.current = S.callId, console.log("[FlowEngageProvider] acceptCall started", {
2404
2406
  callId: S?.callId,
2405
2407
  chatId: v,
2406
2408
  socketConnected: !!C.current?.connected,
@@ -2424,7 +2426,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2424
2426
  signalingState: t.signalingState
2425
2427
  }), e === "connected") {
2426
2428
  let e = (/* @__PURE__ */ new Date()).toISOString();
2427
- He("connected"), We((t) => t || e), pt(e);
2429
+ He("connected"), We((t) => t || e), mt(e);
2428
2430
  return;
2429
2431
  }
2430
2432
  e === "connecting" && He((e) => e === "connected" ? e : "connecting");
@@ -2438,7 +2440,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2438
2440
  signalingState: t.signalingState
2439
2441
  }), e === "connected" || e === "completed") {
2440
2442
  let e = (/* @__PURE__ */ new Date()).toISOString();
2441
- He("connected"), We((t) => t || e), pt(e);
2443
+ He("connected"), We((t) => t || e), mt(e);
2442
2444
  return;
2443
2445
  }
2444
2446
  (e === "checking" || e === "new") && He((e) => e === "connected" ? e : "connecting");
@@ -2479,7 +2481,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2479
2481
  n && (console.log("[FlowEngageProvider] found pending remote offer during accept", {
2480
2482
  callId: n.callId || S.callId,
2481
2483
  chatId: v
2482
- }), await gt({
2484
+ }), await _t({
2483
2485
  ...n,
2484
2486
  callId: n.callId || S.callId
2485
2487
  })), await w.current.acceptCall(S.callId, v), console.log("[FlowEngageProvider] acceptCall API succeeded", {
@@ -2487,7 +2489,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2487
2489
  chatId: v
2488
2490
  }), tt.current = S.callId, Be(S.callId), He("connecting"), Re(null), fe(!0);
2489
2491
  } catch (e) {
2490
- if (console.error("[FlowEngageProvider] acceptCall failed", e), nt.current = null, ft(), e?.status === 404 || e?.status === 409 || e?.status === 422) {
2492
+ if (console.error("[FlowEngageProvider] acceptCall failed", e), nt.current = null, pt(), e?.status === 404 || e?.status === 409 || e?.status === 422) {
2491
2493
  Je(un(e, "This visitor call is no longer available."));
2492
2494
  return;
2493
2495
  }
@@ -2503,41 +2505,41 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2503
2505
  Je("We couldn't connect the call right now. Please try again.");
2504
2506
  }
2505
2507
  }
2506
- }, vt = async () => {
2508
+ }, yt = async () => {
2507
2509
  if (!S?.callId || !w.current || !v) {
2508
- ft();
2510
+ pt();
2509
2511
  return;
2510
2512
  }
2511
- ut();
2513
+ dt();
2512
2514
  try {
2513
2515
  await w.current.rejectCall(S.callId, v);
2514
2516
  } catch (e) {
2515
2517
  console.error("[FlowEngageProvider] rejectCall failed", e), Je(un(e, "We couldn't decline the call cleanly."));
2516
2518
  } finally {
2517
- ft();
2519
+ pt();
2518
2520
  }
2519
- }, yt = o(vt);
2520
- yt.current = vt, i(() => {
2521
+ }, bt = o(yt);
2522
+ bt.current = yt, i(() => {
2521
2523
  if (!S?.callId || ze) return;
2522
2524
  let e = S.callId, t = window.setTimeout(() => {
2523
- Ye.current?.callId === e && yt.current();
2525
+ Ye.current?.callId === e && bt.current();
2524
2526
  }, te);
2525
2527
  return () => window.clearTimeout(t);
2526
2528
  }, [S?.callId, ze]);
2527
- let bt = async () => {
2529
+ let xt = async () => {
2528
2530
  if (!ze || !w.current || !v) {
2529
- ft();
2531
+ pt();
2530
2532
  return;
2531
2533
  }
2532
- ut();
2534
+ dt();
2533
2535
  try {
2534
2536
  await w.current.endWebRTCCall(ze, v);
2535
2537
  } catch (e) {
2536
2538
  console.error("[FlowEngageProvider] endWebRTCCall failed", e), Je(un(e, "The call ended locally, but the server could not be updated."));
2537
2539
  } finally {
2538
- ft();
2540
+ pt();
2539
2541
  }
2540
- }, xt = () => {
2542
+ }, St = () => {
2541
2543
  let e = Ze.current?.getAudioTracks?.() || [], t = Xe.current?.getSenders?.().map((e) => e.track).filter((e) => e?.kind === "audio") || [], n = [...e, ...t].filter(Boolean);
2542
2544
  if (n.length === 0) {
2543
2545
  console.warn("[FlowEngageProvider] no local audio tracks available for mute");
@@ -2550,7 +2552,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2550
2552
  nextMuted: r,
2551
2553
  trackCount: n.length
2552
2554
  }), Ke(r);
2553
- }, St = async (e = {}) => {
2555
+ }, Ct = async (e = {}) => {
2554
2556
  let t = e.notifyChatInitiated === !0;
2555
2557
  if (fe(!0), !(!t || !w.current || !v || typeof window > "u")) {
2556
2558
  try {
@@ -2563,8 +2565,8 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2563
2565
  await w.current.updateChatStatus(v, "open");
2564
2566
  } catch {}
2565
2567
  }
2566
- }, Ct = async (e) => {
2567
- let t = dt(e);
2568
+ }, wt = async (e) => {
2569
+ let t = ft(e);
2568
2570
  if (!t || !w.current || !T.current) return t;
2569
2571
  try {
2570
2572
  await w.current.trackVisitor({
@@ -2576,7 +2578,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2576
2578
  console.error("[FlowEngageProvider] failed to persist visitor email", e);
2577
2579
  }
2578
2580
  return t;
2579
- }, wt = () => {
2581
+ }, Tt = () => {
2580
2582
  if (!v || !C.current?.connected || it.current) {
2581
2583
  console.log("[FlowEngageProvider] skipped typing:start emit", {
2582
2584
  chatId: v,
@@ -2592,7 +2594,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2592
2594
  chatId: v,
2593
2595
  sender: "user"
2594
2596
  });
2595
- }, Tt = () => {
2597
+ }, Et = () => {
2596
2598
  if (v && C.current?.connected && at.current !== "" && (console.log("[FlowEngageProvider] clearing typing draft", {
2597
2599
  chatId: v,
2598
2600
  sender: "user"
@@ -2615,7 +2617,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2615
2617
  chatId: v,
2616
2618
  sender: "user"
2617
2619
  });
2618
- }, Et = (e = "") => {
2620
+ }, Dt = (e = "") => {
2619
2621
  let t = typeof e == "string" ? e : "";
2620
2622
  if (!v || !C.current?.connected) {
2621
2623
  console.log("[FlowEngageProvider] skipped typing:update emit", {
@@ -2634,9 +2636,9 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2634
2636
  sender: "user",
2635
2637
  text: t
2636
2638
  }));
2637
- }, Dt = async (e, t = "", n = null) => {
2639
+ }, Ot = async (e, t = "", n = null) => {
2638
2640
  if (!e.trim() || !w.current || !v || d !== "ready" || Ie) return;
2639
- Tt();
2641
+ Et();
2640
2642
  let i = `pending-user-${Date.now()}`, a = {
2641
2643
  id: i,
2642
2644
  sender: "user",
@@ -2669,7 +2671,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2669
2671
  } finally {
2670
2672
  Ae(!1);
2671
2673
  }
2672
- }, Ot = async (e) => {
2674
+ }, kt = async (e) => {
2673
2675
  if (!(!w.current || !v)) {
2674
2676
  try {
2675
2677
  let t = e ? "voice" : "text";
@@ -2677,11 +2679,11 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2677
2679
  } catch (e) {
2678
2680
  console.error("[FlowEngageProvider] setVoiceMode failed", e);
2679
2681
  }
2680
- Fe(e), e && (st.current = !1);
2682
+ Fe(e), e && (ct.current = !1);
2681
2683
  }
2682
- }, kt = async (e) => {
2683
- if (!st.current) {
2684
- if (st.current = !0, !w.current || !v || !e?.length) {
2684
+ }, At = async (e) => {
2685
+ if (!ct.current) {
2686
+ if (ct.current = !0, !w.current || !v || !e?.length) {
2685
2687
  Fe(!1);
2686
2688
  return;
2687
2689
  }
@@ -2692,9 +2694,9 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2692
2694
  Fe(!1);
2693
2695
  }
2694
2696
  }
2695
- }, At = async () => {
2697
+ }, E = async () => {
2696
2698
  if (!(!w.current || !v)) {
2697
- x && !st.current && ot.current.length > 0 && await kt(ot.current);
2699
+ x && !ct.current && st.current.length > 0 && await At(st.current);
2698
2700
  try {
2699
2701
  await w.current.endConversation(v);
2700
2702
  } catch {
@@ -2712,9 +2714,9 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2712
2714
  }
2713
2715
  };
2714
2716
  i(() => {
2715
- if (Ve !== "connected" || !ze || !v || !Ue || !lt) return;
2716
- let e = new Date(Ue).getTime(), t = Number.isFinite(e) ? Date.now() - e : 0, n = Math.max(0, lt * 1e3 - t), r = window.setTimeout(() => {
2717
- Je("The call ended because it reached the time limit."), bt();
2717
+ if (Ve !== "connected" || !ze || !v || !Ue || !ut) return;
2718
+ let e = new Date(Ue).getTime(), t = Number.isFinite(e) ? Date.now() - e : 0, n = Math.max(0, ut * 1e3 - t), r = window.setTimeout(() => {
2719
+ Je("The call ended because it reached the time limit."), xt();
2718
2720
  }, n);
2719
2721
  return () => window.clearTimeout(r);
2720
2722
  }, [
@@ -2722,8 +2724,8 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2722
2724
  Ue,
2723
2725
  Ve,
2724
2726
  v,
2725
- bt,
2726
- lt
2727
+ xt,
2728
+ ut
2727
2729
  ]), i(() => {
2728
2730
  let e = () => {
2729
2731
  let e = T.current, t = w.current;
@@ -2739,7 +2741,7 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2739
2741
  window.removeEventListener("pagehide", e), window.removeEventListener("beforeunload", e);
2740
2742
  };
2741
2743
  }, []);
2742
- let E = a(() => ({
2744
+ let jt = a(() => ({
2743
2745
  status: d,
2744
2746
  error: m,
2745
2747
  runtimeConfig: _,
@@ -2767,34 +2769,34 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2767
2769
  isCallMuted: Ge,
2768
2770
  webRTCError: qe,
2769
2771
  language: r,
2770
- historyRef: ot,
2771
- hasSyncedRef: st,
2772
- dismissCallError: ut,
2773
- captureVisitorEmail: Ct,
2774
- startTyping: wt,
2775
- stopTyping: Tt,
2776
- updateTypingDraft: Et,
2777
- notifyRouteChange: () => ct.current?.notifyRouteChange?.(),
2778
- openWidget: St,
2772
+ historyRef: st,
2773
+ hasSyncedRef: ct,
2774
+ dismissCallError: dt,
2775
+ captureVisitorEmail: wt,
2776
+ startTyping: Tt,
2777
+ stopTyping: Et,
2778
+ updateTypingDraft: Dt,
2779
+ notifyRouteChange: () => lt.current?.notifyRouteChange?.(),
2780
+ openWidget: Ct,
2779
2781
  closeWidget: () => fe(!1),
2780
2782
  toggleWidget: () => {
2781
2783
  if (de) {
2782
2784
  fe(!1);
2783
2785
  return;
2784
2786
  }
2785
- St({ notifyChatInitiated: !0 });
2787
+ Ct({ notifyChatInitiated: !0 });
2786
2788
  },
2787
- sendMessage: Dt,
2788
- setVoiceMode: Ot,
2789
- onMessageSync: kt,
2790
- endConversation: At,
2791
- acceptCall: _t,
2792
- rejectCall: vt,
2793
- endWebRTCCall: bt,
2794
- toggleCallMute: xt,
2795
- startTyping: wt,
2796
- stopTyping: Tt,
2797
- updateTypingDraft: Et
2789
+ sendMessage: Ot,
2790
+ setVoiceMode: kt,
2791
+ onMessageSync: At,
2792
+ endConversation: E,
2793
+ acceptCall: vt,
2794
+ rejectCall: yt,
2795
+ endWebRTCCall: xt,
2796
+ toggleCallMute: St,
2797
+ startTyping: Tt,
2798
+ stopTyping: Et,
2799
+ updateTypingDraft: Dt
2798
2800
  }), [
2799
2801
  d,
2800
2802
  m,
@@ -2823,23 +2825,23 @@ function mn({ siteId: e, config: t, children: n, language: r = "en" }) {
2823
2825
  Ge,
2824
2826
  qe,
2825
2827
  r,
2826
- Ct,
2827
2828
  wt,
2828
2829
  Tt,
2829
2830
  Et,
2830
- _t,
2831
+ Dt,
2831
2832
  vt,
2832
- bt,
2833
+ yt,
2833
2834
  xt,
2834
2835
  St,
2835
- Dt,
2836
+ Ct,
2836
2837
  Ot,
2837
2838
  kt,
2838
2839
  At,
2839
- ut
2840
+ E,
2841
+ dt
2840
2842
  ]);
2841
2843
  return /* @__PURE__ */ l(Yt.Provider, {
2842
- value: E,
2844
+ value: jt,
2843
2845
  children: n
2844
2846
  });
2845
2847
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowengage/react-chatbot",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
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",