@flowengage/react-chatbot 1.0.3 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/flowengage-embed.js +5 -5
- package/dist/flowengage-react-chatbot.cjs +12 -12
- package/dist/flowengage-react-chatbot.mjs +55 -38
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -77,6 +77,12 @@ export default function App() {
|
|
|
77
77
|
|
|
78
78
|
Ensure the package resolves once at app level so you do not mount duplicate providers.
|
|
79
79
|
|
|
80
|
+
### Dashboard styling vs code (`widgetSettings`)
|
|
81
|
+
|
|
82
|
+
Use **only** `siteId` (and optional `apiBaseUrl` for local dev) on `FlowEngageProvider` so the widget **loads branding, theme, greetings, and recommendations from the FlowEngage dashboard** on every page load—same as the CDN embed.
|
|
83
|
+
|
|
84
|
+
If you also pass `config={{ widgetSettings: { ... } }}`, those fields act as **defaults only**; **saved dashboard settings override** them. Avoid pasting a full widget JSON into your app unless you intentionally want offline defaults; otherwise you would have to update code after each dashboard change.
|
|
85
|
+
|
|
80
86
|
---
|
|
81
87
|
|
|
82
88
|
## B. CDN / script tag (no React project required)
|
package/dist/flowengage-embed.js
CHANGED
|
@@ -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)(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,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),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);if(t?.chat_history?.length)h(hn(t.chat_history));else if(t?.success)try{let e=await He.current.loadHistory(f,r);e?.chat_history?.length&&h(hn(e.chat_history))}catch{}}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,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),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(`
|
|
@@ -323,16 +323,16 @@ class ScribeAudioProcessor extends AudioWorkletProcessor {
|
|
|
323
323
|
|
|
324
324
|
registerProcessor("scribeAudioProcessor", ScribeAudioProcessor);
|
|
325
325
|
|
|
326
|
-
`),Ah,jh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(Ah||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(jh||={});var Mh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new Oh(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await kh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};Mh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var Nh=class extends ih{static startSession(e){return e.textOnly?xh.startSession(e):Eh.startSession(e)}};function $(...e){nn()&&console.log(`[FlowEngage:voice-tools]`,...e)}var Ph=`#flowengage-root, .flowengage-shell`;function Fh(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(Ph)}catch{return!1}}function Ih(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Lh(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!Fh(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function Rh(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function zh(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return Rh(r.join(` `))}if(e.labels&&e.labels.length)return Rh(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return Rh(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return Rh(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return Rh(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=Rh(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return Rh(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return Rh(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?Rh(o):null}function Bh(){let e=[];return Lh(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Fh(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=Ih(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function Vh(){return Bh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:zh(e),placeholder:e.placeholder||null}))}function Hh(){let e=[];return Lh(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Fh(e)||e.disabled)return!1;try{let t=Ih(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function Uh(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function Wh(e){let t=Uh(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Gh(e,t){let n=Wh(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,zh(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Uh(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var Kh=28;function qh(e,t){let n=null,r=0;for(let i of e){let e=Gh(i,t);e>r&&(r=e,n=i)}return!n||r<Kh?null:n}function Jh(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,zh(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function Yh(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function Xh(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function Zh(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function Qh(e){if(!Zh(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,zh(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function $h(e,t,n){let r=String(t??``),i=String(n??``),a=ng(e,r)||qh(e,r)||Jh(e,r,i);if(!a)return[];let o=new Set([a]);if(Yh(i)&&Xh(r))for(let t of e)t!==a&&Qh(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function eg(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function tg(e){if(!e||typeof e!=`string`)return null;let t=null;return Lh(n=>{try{let r=n.getElementById(e);r&&!Fh(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function ng(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=tg(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=tg(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function rg(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function ig(e,t){let n=[];Lh(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Fh(e)||e.disabled)return!1;try{let t=Ih(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:rg(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=eg(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function ag(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function og(e){let t=ag(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function sg(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function cg(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function lg(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function ug(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function dg(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function fg(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={navigate_to_page:async n=>{$(`navigate_to_page ▶ raw parameters:`,n);let r=ag(n),i=lg(r),a=r.section_text??r.sectionText??r.section;if($(`navigate_to_page · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}if(!await dn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`That page is not available in the site index; answer without navigating.`;return $(`navigate_to_page ✖ blocked`,e),e}try{if($(`navigate_to_page → shadowNavigate`,i),await fn(i),await new Promise(e=>setTimeout(e,400)),a&&typeof a==`string`){let e=on(null,a);e&&sn(e),$(`navigate_to_page · highlight`,{sectionText:a,found:!!e})}let e=`OK_NAVIGATION ${i}`;return $(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{$(`highlight_on_page ▶`,e);let t=ag(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=on(n||null,r||null);return i?(sn(i),$(`highlight_on_page ✓`),`Highlighted the section.`):($(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=ug(ag(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return $(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},list_page_forms:async()=>{let e=Vh(),t=Hh();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, fill_form_fields sets all matching URL inputs. click_page_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},fill_form_fields:async e=>{try{$(`fill_form_fields ▶ raw:`,e);let t=og(e);if(!t.length&&r){let e=r(),n=sg(e);n.length?$(`fill_form_fields · inferred URL from last user utterance (model omitted usable fields):`,n):(n=cg(e),n.length&&$(`fill_form_fields · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms for field_key strings, then fill_form_fields with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let a=Bh(),o=$h(a,String(t),r);if(o.length){o.forEach((e,t)=>{dg(e,r,{skipScroll:t>0})}),i=o,n.push(String(t));continue}let s=ng(a,String(t));s||=qh(a,String(t)),s||=Jh(a,String(t),r),s&&(dg(s,r),i=[s],n.push(String(t)))}if(!n.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`fill_form_fields ✓`,a),a}catch(e){let t=`fill_form_fields error: ${e?.message||String(e)}`;return $(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=ag(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=ig(n,i);if(!r)return $(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}r.focus?.(),r.click();let e=`OK_CLICK ${(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`}`;return $(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}};return{...a,navigateToPage:a.navigate_to_page,highlightOnPage:a.highlight_on_page,searchSiteContent:a.search_site_content,listPageForms:a.list_page_forms,fillFormFields:a.fill_form_fields,clickPageButton:a.click_page_button}}function pg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=nn();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i=await t(n),a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var mg={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},hg={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function gg({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[l,u]=(0,v.useState)(`idle`),[d,f]=(0,v.useState)(null),[p,m]=(0,v.useState)(!1),h=(0,v.useRef)(null),g=(0,v.useRef)(null),_=(0,v.useRef)(``);(0,v.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;a.current=[],_.current=``;let o=pg(fg({siteId:n||null,apiBaseUrl:r||null,getLastUserVoiceText:()=>_.current})),s=await Nh.startSession({agentId:e,clientTools:o,onUnhandledClientToolCall:e=>{console.error(`[VoiceInterface] ElevenLabs requested a client tool that is not registered in the widget:`,e?.tool_name,e?.parameters,`Add a matching handler in voiceClientTools (snake_case and camelCase are both supported).`)},onModeChange:({mode:e})=>{t||u(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};n===`user`&&(_.current=r),a.current=[...a.current,i]},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),u(`error`),f(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),m(!1),u(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,h.current=s,m(!0),u(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: search_site_content then navigate_to_page with section_text when relevant — no permission ask. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit) when the user wants to submit.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),u(`error`),f(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):h.current&&h.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let y=(0,v.useCallback)(async()=>{try{await h.current?.endSession?.()}catch{}h.current=null,m(!1),u(`idle`),typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]),b=l===`listening`||l===`speaking`,x=hg[l]||hg.idle,ee=mg[l]||mg.idle;return(0,k.jsxs)(`div`,{ref:g,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,k.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[b&&(0,k.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${x}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),b&&(0,k.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${x}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,k.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:ee,border:`3px solid ${x}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:l===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${ee}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,k.jsx)(Cn,{size:44,color:x})})]}),(0,k.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:l===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[l===`idle`&&`Starting voice session…`,l===`listening`&&`Listening…`,l===`speaking`&&`AI is speaking…`,l===`error`&&(d||`Error`)]}),(0,k.jsxs)(`button`,{onClick:y,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,k.jsx)(wn,{size:18}),`End Voice Session`]}),(0,k.jsx)(`style`,{children:`
|
|
326
|
+
`),Ah,jh;(function(e){e.PCM_8000=`pcm_8000`,e.PCM_16000=`pcm_16000`,e.PCM_22050=`pcm_22050`,e.PCM_24000=`pcm_24000`,e.PCM_44100=`pcm_44100`,e.PCM_48000=`pcm_48000`,e.ULAW_8000=`ulaw_8000`})(Ah||={}),function(e){e.MANUAL=`manual`,e.VAD=`vad`}(jh||={});var Mh=class e{static getWebSocketUri(t=e.DEFAULT_BASE_URI){return`${t}/v1/speech-to-text/realtime`}static buildWebSocketUri(t){let n=e.getWebSocketUri(t.baseUri),r=new URLSearchParams;if(r.append(`model_id`,t.modelId),r.append(`token`,t.token),t.commitStrategy!==void 0&&r.append(`commit_strategy`,t.commitStrategy),t.audioFormat!==void 0&&r.append(`audio_format`,t.audioFormat),t.vadSilenceThresholdSecs!==void 0){if(t.vadSilenceThresholdSecs<=.3||t.vadSilenceThresholdSecs>3)throw Error(`vadSilenceThresholdSecs must be between 0.3 and 3.0`);r.append(`vad_silence_threshold_secs`,t.vadSilenceThresholdSecs.toString())}if(t.vadThreshold!==void 0){if(t.vadThreshold<.1||t.vadThreshold>.9)throw Error(`vadThreshold must be between 0.1 and 0.9`);r.append(`vad_threshold`,t.vadThreshold.toString())}if(t.minSpeechDurationMs!==void 0){if(t.minSpeechDurationMs<=50||t.minSpeechDurationMs>2e3)throw Error(`minSpeechDurationMs must be between 50 and 2000`);r.append(`min_speech_duration_ms`,t.minSpeechDurationMs.toString())}if(t.minSilenceDurationMs!==void 0){if(t.minSilenceDurationMs<=50||t.minSilenceDurationMs>2e3)throw Error(`minSilenceDurationMs must be between 50 and 2000`);r.append(`min_silence_duration_ms`,t.minSilenceDurationMs.toString())}t.languageCode!==void 0&&r.append(`language_code`,t.languageCode),t.includeTimestamps!==void 0&&r.append(`include_timestamps`,t.includeTimestamps?`true`:`false`);let i=r.toString();return i?`${n}?${i}`:n}static connect(t){if(!t.modelId)throw Error(`modelId is required`);let n=new Oh(`microphone`in t&&t.microphone?16e3:t.sampleRate),r=e.buildWebSocketUri(t),i=new WebSocket(r);return`microphone`in t&&t.microphone&&i.addEventListener(`open`,()=>{e.streamFromMicrophone(t,n)}),n.setWebSocket(i),n}static async streamFromMicrophone(e,t){try{var n,r,i;let a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:e.microphone?.deviceId,echoCancellation:(n=e.microphone?.echoCancellation)==null||n,noiseSuppression:(r=e.microphone?.noiseSuppression)==null||r,autoGainControl:(i=e.microphone?.autoGainControl)==null||i,channelCount:e.microphone?.channelCount??1,sampleRate:{ideal:16e3}}}),o=new AudioContext({sampleRate:16e3});await kh(o.audioWorklet);let s=o.createMediaStreamSource(a),c=new AudioWorkletNode(o,`scribeAudioProcessor`);c.port.onmessage=e=>{let{audioData:n}=e.data,r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=String.fromCharCode(r[e]);let a=btoa(i);t.send({audioBase64:a})},s.connect(c),o.state===`suspended`&&await o.resume(),t._audioCleanup=()=>{a.getTracks().forEach(e=>{e.stop()}),s.disconnect(),c.disconnect(),o.close()}}catch(e){throw console.error(`Failed to start microphone streaming:`,e),e}}};Mh.DEFAULT_BASE_URI=`wss://api.elevenlabs.io`;var Nh=class extends ih{static startSession(e){return e.textOnly?xh.startSession(e):Eh.startSession(e)}};function $(...e){nn()&&console.log(`[FlowEngage:voice-tools]`,...e)}var Ph=`#flowengage-root, .flowengage-shell`;function Fh(e){if(!e||typeof e.closest!=`function`)return!1;try{return!!e.closest(Ph)}catch{return!1}}function Ih(e){try{let t=e.ownerDocument?.defaultView;if(t)return t.getComputedStyle(e)}catch{}return window.getComputedStyle(e)}function Lh(e){let t=new Set;function n(r){if(!r||t.has(r))return;t.add(r),e(r);let i=r.querySelectorAll(`iframe`);for(let e of i)if(!Fh(e))try{let t=e.contentDocument;t&&n(t)}catch{}}typeof document<`u`&&n(document)}function Rh(e){return e==null?null:String(e).replace(/\u00a0/g,` `).replace(/\s*\*+\s*$/u,``).replace(/\s+/g,` `).trim()}function zh(e){let t=e.ownerDocument||document,n=e.getAttribute(`aria-labelledby`);if(n){let e=n.trim().split(/\s+/).filter(Boolean),r=[];for(let n of e)try{let e=t.getElementById(n);e?.textContent&&r.push(e.textContent.trim())}catch{}if(r.length)return Rh(r.join(` `))}if(e.labels&&e.labels.length)return Rh(e.labels[0].textContent);let r=e.id;if(r)try{let e=t.querySelector(`label[for="${CSS.escape(r)}"]`);if(e)return Rh(e.textContent)}catch{let e=t.querySelector(`label[for="${r.replace(/"/g,`\\"`)}"]`);if(e)return Rh(e.textContent)}let i=e.previousElementSibling;for(let e=0;e<6&&i;e+=1){if(i.tagName===`LABEL`)return Rh(i.textContent);let e=(i.className||``).toString().toLowerCase();if(/chakra-form__label|formlabel|field-label|form-label|mui-form-label/.test(e)){let e=Rh(i.textContent);if(e)return e}i=i.previousElementSibling}let a=e.parentElement;for(let e=0;e<5&&a;e+=1){if(a.tagName===`LABEL`)return Rh(a.textContent);let e=a.querySelector?.(`:scope > label, :scope > [class*='FormLabel'], :scope > [class*='form__label']`);if(e?.textContent)return Rh(e.textContent);a=a.parentElement}let o=e.getAttribute(`aria-label`);return o?Rh(o):null}function Bh(){let e=[];return Lh(t=>{e.push(...Array.from(t.querySelectorAll(`input, select, textarea`)).filter(e=>{if(Fh(e))return!1;let t=(e.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`image`].includes(t)||e.disabled||e.readOnly)return!1;try{let t=Ih(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e}function Vh(){return Bh().map((e,t)=>({formIndex:0,fieldIndex:t,tag:e.tagName,type:e.type||`text`,name:e.name||null,id:e.id||null,label:zh(e),placeholder:e.placeholder||null}))}function Hh(){let e=[];return Lh(t=>{e.push(...Array.from(t.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Fh(e)||e.disabled)return!1;try{let t=Ih(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))}),e.slice(0,60).map((e,t)=>({index:t,text:(e.textContent||e.value||``).replace(/\s+/g,` `).trim().slice(0,120)||null,ariaLabel:e.getAttribute(`aria-label`),type:e.type||e.tagName}))}function Uh(e){return String(e||``).toLowerCase().replace(/\u00a0/g,` `).replace(/\*/g,``).replace(/\s+/g,` `).trim()}function Wh(e){let t=Uh(e);return t=t.replace(/\s+field\s*$/i,``).trim(),t}function Gh(e,t){let n=Wh(t);if(!n)return 0;let r=(e.name||``).toLowerCase(),i=(e.id||``).toLowerCase();if(r===`url`&&/url|website|domain|site|audit/.test(n)||(i===`url-input`||i.endsWith(`-url-input`))&&/url|website|domain|site|audit/.test(n))return 100;let a=[e.name,e.id,e.placeholder,zh(e),e.getAttribute(`aria-label`),e.getAttribute(`title`),e.getAttribute(`data-testid`),e.getAttribute(`autocomplete`)].filter(Boolean).map(e=>Uh(e)),o=0;for(let e of a){if(!e)continue;if(e.includes(n)||n.includes(e)){o=Math.max(o,100);continue}let t=n.split(/\s+/).filter(e=>e.length>1);if(!t.length)continue;let r=0;for(let n of t)e.includes(n)&&(r+=1);o=Math.max(o,r/t.length*88)}return o}var Kh=28;function qh(e,t){let n=null,r=0;for(let i of e){let e=Gh(i,t);e>r&&(r=e,n=i)}return!n||r<Kh?null:n}function Jh(e,t,n){let r=String(t||``).toLowerCase().trim(),i=String(n||``).trim();if(!(/^https?:\/\//i.test(i)||/\.\w{2,}(\/|\s|$)/.test(i)||r.includes(`url`)||r.includes(`website`)||r.includes(`domain`)||r.includes(`site`)))return null;let a=null,o=0;for(let t of e){if(t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`)continue;let e=(t.type||``).toLowerCase();if([`hidden`,`submit`,`button`,`checkbox`,`radio`].includes(e))continue;let n=0;(e===`url`||e===`text`||e===`search`)&&(n+=45);let r=[t.name,t.id,t.placeholder,zh(t),t.getAttribute(`aria-label`),t.getAttribute(`autocomplete`)].filter(Boolean).join(` `).toLowerCase();/(website|url|domain|site\s*url)/.test(r)&&(n+=55),n>o&&(o=n,a=t)}return!a||o<42?null:a}function Yh(e){let t=String(e??``).trim();return t?/^https?:\/\//i.test(t)?!0:/\.\w{2,}(\/|\s|$)/.test(t):!1}function Xh(e){let t=String(e??``).toLowerCase().trim();return t?!!(t===`url`||t===`website`||t===`website url`||t===`website_url`||t===`enter website url`||t.includes(`website`)||t.includes(`domain`)||/(enter\s+website|site\s*url|page\s*url)/.test(t)):!1}function Zh(e){if(!e||e.tagName!==`INPUT`&&e.tagName!==`TEXTAREA`)return!1;let t=(e.type||``).toLowerCase();return![`hidden`,`submit`,`button`,`checkbox`,`radio`,`file`].includes(t)}function Qh(e){if(!Zh(e))return!1;let t=(e.name||``).toLowerCase(),n=(e.id||``).toLowerCase(),r=[e.name,e.id,e.placeholder,zh(e),e.getAttribute(`aria-label`)].filter(Boolean).join(` `).toLowerCase();return t===`url`||n===`url-input`||n.endsWith(`-url-input`)||/(website\s*url|enter\s+website|site\s*url)/.test(r)||/(website|domain)/.test(r)&&/(url|site)/.test(r)}function $h(e,t,n){let r=String(t??``),i=String(n??``),a=ng(e,r)||qh(e,r)||Jh(e,r,i);if(!a)return[];let o=new Set([a]);if(Yh(i)&&Xh(r))for(let t of e)t!==a&&Qh(t)&&o.add(t);let s=Array.from(o);return s.sort((e,t)=>{if(e===t)return 0;let n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}),s}function eg(e,t){try{if(!e?.getBoundingClientRect||!t?.getBoundingClientRect)return 1/0;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i={x:n.left+n.width/2,y:n.top+n.height/2},a={x:r.left+r.width/2,y:r.top+r.height/2};return Math.hypot(i.x-a.x,i.y-a.y)}catch{return 1/0}}function tg(e){if(!e||typeof e!=`string`)return null;let t=null;return Lh(n=>{try{let r=n.getElementById(e);r&&!Fh(r)&&r.matches?.(`input, select, textarea`)&&(t=r)}catch{}}),t}function ng(e,t){let n=String(t??``).trim();if(!n)return null;let r=n.match(/^name:\s*([\w.-]+)$/i);if(r){let t=r[1];for(let n of e)if(n.name===t)return n}let i=n.match(/^id:\s*([\w.-]+)$/i);if(i){let e=tg(i[1]);if(e)return e}let a=n.startsWith(`#`)?n.slice(1):n;if(/^[\w-]+$/.test(a)){let e=tg(a);if(e)return e}let o=n.toLowerCase().replace(/\s+/g,` `);if(o===`url`||o===`website`||o===`website url`||o===`website_url`||o===`enter website url`)for(let t of e){let e=(t.name||``).toLowerCase(),n=(t.id||``).toLowerCase();if(e===`url`||n===`url-input`||n.endsWith(`-url-input`))return t}return null}function rg(e,t){let n=String(t||``).toLowerCase().trim();if(!n)return 0;let r=[e.textContent,e.value,e.getAttribute(`aria-label`),e.getAttribute(`title`)].filter(Boolean).join(` `).toLowerCase().replace(/\s+/g,` `);if(r.includes(n))return 100;let i=n.split(/\s+/).filter(e=>e.length>1);if(!i.length)return 0;let a=0;for(let e of i)r.includes(e)&&(a+=1);return a/i.length*92}function ig(e,t){let n=[];Lh(e=>{n.push(...Array.from(e.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`)).filter(e=>{if(Fh(e)||e.disabled)return!1;try{let t=Ih(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return!0}))});let r=0,i=n.map(t=>({el:t,s:rg(t,e)}));for(let{s:e}of i)e>r&&(r=e);if(r<36)return null;let a=i.filter(({s:e})=>e===r).map(({el:e})=>e);if(a.length===1)return a[0];let o=Array.isArray(t)?t.filter(e=>e&&e.isConnected):[];if(o.length){let e=a[0],t=1/0;for(let n of a)for(let r of o){let i=eg(n,r);i<t&&(t=i,e=n)}return e}return a[0]}function ag(e){if(e==null)return{};if(typeof e==`string`){let t=e.trim();if(!t)return{};try{return JSON.parse(t)}catch{return{url:t}}}return e}function og(e){let t=ag(e);if(Array.isArray(t)&&t.length>0){let e=t[0];if(e?.field_key!=null||e?.fieldKey!=null)return t.map(e=>({field_key:e.field_key??e.fieldKey,value:e.value}))}if(!t||typeof t!=`object`)return[];let n=t.fields??t.Fields??t.field_list??t.fieldList??t.data?.fields;if(typeof n==`string`)try{n=JSON.parse(n)}catch{n=null}n&&!Array.isArray(n)&&typeof n==`object`&&(n=Object.values(n)),(!n||n.length===0)&&(t.field_key!=null||t.fieldKey!=null)&&t.value!=null&&(n=[{field_key:t.field_key??t.fieldKey,value:t.value}]);let r=t.website_url??t.websiteUrl??t.url??t.website??t.domain??t.site_url??t.siteUrl;return(!n||n.length===0)&&r!=null&&String(r).trim()&&(n=[{field_key:t.field_key??t.fieldKey??`url`,value:String(r).trim()}]),Array.isArray(n)?n.map(e=>({field_key:e?.field_key??e?.fieldKey,value:e?.value??e?.Value})):[]}function sg(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t||/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i.test(t))return[];let n=t.match(/https?:\/\/[^\s<>"']+/i);if(n)return[{field_key:`url`,value:n[0].replace(/[.,;:)]+$/,``)}];let r=t.match(/\b(?:[\w-]+\.)+[a-z]{2,}\b/i);if(r){let e=r[0].replace(/[.,;:)]+$/,``);return/^https?:/i.test(e)||(e=`https://${e}`),[{field_key:`url`,value:e}]}return[]}function cg(e){if(!e||typeof e!=`string`)return[];let t=e.trim();if(!t)return[];let n=[],r=new Set,i=/\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i,a=(e,t)=>{let i=String(t??``).trim().replace(/^["']|["']$/g,``);if(!i||i.length>800)return;let a=`${e}\0${i}`;r.has(a)||(r.add(a),n.push({field_key:e,value:i}))},o=t.match(/^\s*([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\s*$/i);if(o)return a(`Email Address`,o[1]),n;let s=t.match(/\b(?:please\s+)?(?:enter|type|put)\s+(.+?)\s+in(?:to)?\s+(?:the\s+)?(?:full\s*name|full\s*name\s*field|name\s*field)\b/i);if(s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name,?\s*(?:please\s+)?(?:enter|type|put)\s+(.+?)(?:\.|$|!|\?)/i),s&&a(`Full Name`,s[1]),s=t.match(/\bfull\s*name\s*(?:is|:|please\s+enter|-)\s*(.+?)(?:\.|$|(?=\s+(?:and|my\s+email|email|message))\b)/i),s&&a(`Full Name`,s[1]),s=t.match(/\b(.+?)\s+for\s+(?:the\s+)?full\s*name\b/i),s){let e=s[1].trim();e.length>1&&e.length<120&&!/@/.test(e)&&a(`Full Name`,e)}if(s=t.match(/\b(?:email|e-mail)(?:\s*address)?\s*(?:is|:|please\s+use|enter|-)\s*([^\s@]+@[^\s@]+\.[^\s,]+)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:enter|type|put)\s+([^\s@]+@[^\s@]+\.[^\s,]+)\s+in(?:to)?\s+(?:the\s+)?(?:email|e-mail)/i),s&&a(`Email Address`,s[1]),s=t.match(/\b(?:message|comment)\s*(?:is|:|please\s+enter|-)\s*(.+)$/is),s){let e=s[1].trim();e.length>0&&a(`Message`,e)}if(!n.some(e=>/email/i.test(String(e.field_key)))){let e=t.match(i);if(e){let r=t.replace(e[0],``).trim().replace(/^(please|it's|it is|use|is|my email is|e-?mail is)\s*/i,``).replace(/[.,;:!?]+$/,``).trim();if(t.length<=96&&r.length<=36)return a(`Email Address`,e[1]),n}}if(n.length===0){let e=t.split(/\s+/).filter(Boolean).length,n=/[.!?]/.test(t)||e>=6||t.length>=24&&e>=5||t.length>=42,r=/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(t.trim());n&&t.length>=16&&!i.test(t)&&!r&&a(`Message`,t)}return n}function lg(e){if(!e||typeof e!=`object`)return null;let t=e.url??e.target_url??e.page_url??e.pageUrl??e.link??e.href??e.path;return t==null?null:String(t).trim()||null}function ug(e){if(!e||typeof e!=`object`)return null;let t=e.query??e.q??e.search??e.text??e.keywords;return t==null?null:String(t).trim()||null}function dg(e,t,n){if(!n?.skipScroll)try{e.scrollIntoView({block:`center`,inline:`nearest`})}catch{try{e.scrollIntoView(!0)}catch{}}try{e.focus({preventScroll:!0})}catch{try{e.focus()}catch{}}let r=e.tagName,i=(e.type||``).toLowerCase();if(r===`SELECT`)return e.value=String(t),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;if(i===`checkbox`||i===`radio`)return e.checked=[`1`,`true`,`yes`,`on`].includes(String(t).toLowerCase().trim()),e.dispatchEvent(new Event(`input`,{bubbles:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0})),!0;let a=String(t);if(r===`INPUT`||r===`TEXTAREA`){let t=e.ownerDocument?.defaultView||window,n=r===`TEXTAREA`?t.HTMLTextAreaElement.prototype:t.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(n,`value`);i?.set?i.set.call(e,a):e.value=a}else e.value=a;let o={bubbles:!0,cancelable:!0,composed:!0};try{e.dispatchEvent(new InputEvent(`input`,{...o,inputType:`insertText`,data:a}))}catch{e.dispatchEvent(new Event(`input`,o))}e.dispatchEvent(new Event(`change`,o));try{queueMicrotask(()=>{try{e.dispatchEvent(new Event(`input`,o)),e.dispatchEvent(new Event(`change`,o))}catch{}})}catch{}return!0}function fg(e){let t=e.siteId||null,n=(e.apiBaseUrl||``).replace(/\/$/,``),r=typeof e.getLastUserVoiceText==`function`?e.getLastUserVoiceText:null,i=[],a={navigate_to_page:async n=>{$(`navigate_to_page ▶ raw parameters:`,n);let r=ag(n),i=lg(r),a=r.section_text??r.sectionText??r.section;if($(`navigate_to_page · coerced:`,{url:i,sectionText:a}),!i){let e=`Missing url: pass a string url, path like /pricing, or JSON with a url field.`;return $(`navigate_to_page ✖`,e),e}if(!await dn(i,{siteId:t,apiBaseUrl:e.apiBaseUrl})){let e=`That page is not available in the site index; answer without navigating.`;return $(`navigate_to_page ✖ blocked`,e),e}try{if($(`navigate_to_page → shadowNavigate`,i),await fn(i),await new Promise(e=>setTimeout(e,400)),a&&typeof a==`string`){let e=on(null,a);e&&sn(e),$(`navigate_to_page · highlight`,{sectionText:a,found:!!e})}let e=`OK_NAVIGATION ${i}`;return $(`navigate_to_page ✓`,e),e}catch(e){let t=`Navigation error: ${e?.message||String(e)}`;return $(`navigate_to_page ✖`,t),t}},highlight_on_page:async e=>{$(`highlight_on_page ▶`,e);let t=ag(e),n=t?.section_id||t?.sectionId,r=t?.section_text||t?.sectionText,i=on(n||null,r||null);return i?(sn(i),$(`highlight_on_page ✓`),`Highlighted the section.`):($(`highlight_on_page ✖ no element`),`Could not find that section on the page.`)},search_site_content:async e=>{$(`search_site_content ▶`,e);let r=ug(ag(e));if($(`search_site_content · query:`,r,`siteId:`,t,`apiBase:`,n||`(empty)`),!r)return $(`search_site_content ✖ missing query`),`Missing query parameter.`;if(!t)return $(`search_site_content ✖ no siteId`),`Site is not configured for search.`;if(!n)return $(`search_site_content ✖ no api base`),`API base URL is missing; cannot search.`;try{let e=`${n}/api/site-tools/search`;$(`search_site_content → POST`,e);let i=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({siteId:t,query:r,currentUrl:typeof window<`u`?window.location.href:``})}),a=await i.json();if($(`search_site_content · HTTP`,i.status,`success:`,a.success),!a.success){let e=a.error||`Search failed.`;return $(`search_site_content ✖`,e),e}let o=a.results||[];return $(`search_site_content ✓`,`${o.length} result(s)`,o.slice(0,3).map(e=>e?.url||e)),JSON.stringify(o)}catch(e){let t=`Search error: ${e.message||`network`}`;return $(`search_site_content ✖`,t),t}},end_voice_session:async()=>($(`end_voice_session ▶`),typeof e.requestEndSession==`function`&&e.requestEndSession(),`Voice session is ending.`),list_page_forms:async()=>{let e=Vh(),t=Hh();return $(`list_page_forms ✓`,`${e.length} field(s)`,`${t.length} button(s)`),JSON.stringify({fields:e,buttons:t,hint:`field_key: placeholder/label, name (e.g. url), id (e.g. url-input). If the page has two URL boxes, fill_form_fields sets all matching URL inputs. click_page_button picks the Conduct Audit nearest the filled field when labels duplicate.`})},fill_form_fields:async e=>{try{$(`fill_form_fields ▶ raw:`,e);let t=og(e);if(!t.length&&r){let e=r(),n=sg(e);n.length?$(`fill_form_fields · inferred URL from last user utterance (model omitted usable fields):`,n):(n=cg(e),n.length&&$(`fill_form_fields · inferred contact fields from last user utterance (empty tool params):`,n)),n.length&&(t=n)}if($(`fill_form_fields · normalized fields:`,t),!t.length)return`No fields provided. Call list_page_forms for field_key strings, then fill_form_fields with { "fields": [ { "field_key": "<label or placeholder from list>", "value": "<user value>" } ] }. Never use empty {}. Pass the value the user just said (email, message, name, URL) in fields.`;let n=[];for(let e of t){let t=e?.field_key??e?.fieldKey,r=e?.value;if(t==null||r==null)continue;let a=Bh(),o=$h(a,String(t),r);if(o.length){o.forEach((e,t)=>{dg(e,r,{skipScroll:t>0})}),i=o,n.push(String(t));continue}let s=ng(a,String(t));s||=qh(a,String(t)),s||=Jh(a,String(t),r),s&&(dg(s,r),i=[s],n.push(String(t)))}if(!n.length)return $(`fill_form_fields ✖ no matches`),`Could not match any fields. Call list_page_forms and use field_key values that match placeholder, label, name, or id (e.g. Enter Website URL). Ensure the form is on the page, not the chat panel.`;let a=`OK_FILLED: ${n.join(`, `)}`;return $(`fill_form_fields ✓`,a),a}catch(e){let t=`fill_form_fields error: ${e?.message||String(e)}`;return $(`fill_form_fields ✖`,t),t}},click_page_button:async e=>{let t=ag(e),n=(t.button_text??t.buttonText??t.text??``).trim();if($(`click_page_button ▶`,n),!n)return`Missing button_text: pass the visible label, e.g. Conduct Audit.`;let r=ig(n,i);if(!r)return $(`click_page_button ✖ no match`),`Could not find a button matching "${n}". Call list_page_forms to see button texts.`;try{try{r.scrollIntoView({block:`center`,inline:`nearest`})}catch{r.scrollIntoView(!0)}r.focus?.(),r.click();let e=`OK_CLICK ${(r.textContent||r.value||r.getAttribute(`aria-label`)||``).trim().slice(0,80)||`button`}`;return $(`click_page_button ✓`,e),e}catch(e){let t=`Click failed: ${e?.message||String(e)}`;return $(`click_page_button ✖`,t),t}}};return{...a,navigateToPage:a.navigate_to_page,highlightOnPage:a.highlight_on_page,searchSiteContent:a.search_site_content,endVoiceSession:a.end_voice_session,listPageForms:a.list_page_forms,fillFormFields:a.fill_form_fields,clickPageButton:a.click_page_button}}function pg(e){return!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,async n=>{let r=nn();r?console.log(`[FlowEngage:voice-tool] ▶`,e,n):console.info(`[FlowEngage] voice tool » ${e}`);let i=await t(n),a=typeof i==`string`?i.length>220?`${i.slice(0,220)}…`:i:String(i);return r?console.log(`[FlowEngage:voice-tool] ◀`,e,a):console.info(`[FlowEngage] voice tool « ${e}:`,a),i}]))}var mg={idle:`rgba(99,102,241,0.18)`,listening:`rgba(16,185,129,0.25)`,speaking:`rgba(245,158,11,0.25)`,error:`rgba(239,68,68,0.2)`},hg={idle:`#6366f1`,listening:`#10b981`,speaking:`#f59e0b`,error:`#ef4444`};function gg(e,t){let n=(t||``).trim();return n?!!(/\b(let'?s|let us)\s+(end|stop|finish|wrap up|close)\s+(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\bend\s+(this\s+)?(the\s+)?(voice\s+)?(session|call|chat)\b/i.test(n)||/\b(hang\s+up|disconnect)\b/i.test(n)||/\b(that'?s all|we'?re done)\b/i.test(n)||e===`bot`&&(/\b(I'?ll|I will|Let me|I can|I'?m going to)\s+(end|close)\s+(the\s+)?(voice\s+)?(session|call)\b/i.test(n)||/\b(ending|closing)\s+(the\s+)?(voice\s+)?session\b|\bvoice\s+session\s+(is\s+)?(now\s+)?(ended|over|closing)\b/i.test(n)||/\b(session|call)\s+(is\s+)?(now\s+)?(ended|over)\b/i.test(n)||/\bwe\s+can\s+end\s+(the\s+)?(session|call)?\s*(here|now)\b/i.test(n)||/\b(wrapping\s+up|signing\s+off)\b/i.test(n))||/^(goodbye|bye|that'?s all|we'?re done|hang up|disconnect)\b/i.test(n)):!1}function _g({agentId:e,chatId:t,siteId:n,apiBaseUrl:r,onEnd:i,historyRef:a,hasSyncedRef:o,onMessageSync:s,onStartSync:c}){let[l,u]=(0,v.useState)(`idle`),[d,f]=(0,v.useState)(null),[p,m]=(0,v.useState)(!1),h=(0,v.useRef)(null),g=(0,v.useRef)(null),_=(0,v.useRef)(``),y=(0,v.useRef)(async()=>{}),b=(0,v.useRef)(!1),x=(0,v.useCallback)(async()=>{try{await h.current?.endSession?.()}catch{}h.current=null,m(!1),u(`idle`),b.current=!1,typeof s==`function`&&await s(a.current),typeof i==`function`&&i()},[a,s,i]);y.current=x,(0,v.useEffect)(()=>{let t=!1,i=null;return(async()=>{try{if(await navigator.mediaDevices.getUserMedia({audio:!0}),t)return;a.current=[],_.current=``,b.current=!1;let o=pg(fg({siteId:n||null,apiBaseUrl:r||null,getLastUserVoiceText:()=>_.current,requestEndSession:()=>{queueMicrotask(()=>{b.current||(b.current=!0,y.current?.())})}})),s=await Nh.startSession({agentId:e,clientTools:o,onUnhandledClientToolCall:e=>{console.error(`[VoiceInterface] ElevenLabs requested a client tool that is not registered in the widget:`,e?.tool_name,e?.parameters,`Add a matching handler in voiceClientTools (snake_case and camelCase are both supported).`)},onModeChange:({mode:e})=>{t||u(e===`speaking`?`speaking`:`listening`)},onMessage:e=>{if(t)return;let n=e.role===`user`?`user`:`bot`,r=e.message||e.text||e.content||``;if(!r)return;let i={sender:n,message:r,timestamp:new Date().toISOString()};n===`user`&&(_.current=r),a.current=[...a.current,i],gg(n,r)&&queueMicrotask(()=>{b.current||(b.current=!0,y.current?.())})},onError:e=>{t||(console.error(`[VoiceInterface] ElevenLabs error`,e),u(`error`),f(`Voice session encountered an error.`))},onDisconnect:()=>{t||(console.log(`[VoiceInterface] session disconnected`),m(!1),u(`idle`))}});if(t){s.endSession().catch(()=>{});return}i=s,h.current=s,m(!0),u(`listening`);try{let e=typeof window<`u`?window.location.href:``,t=``;try{t=await o.list_page_forms()}catch{t=`[]`}s.sendContextualUpdate(`Current page URL: ${e}. Site ID: ${n||`unknown`}. Page fields/buttons JSON: ${t}. Navigation: search_site_content then navigate_to_page with section_text when relevant — no permission ask. Forms: use fill_form_fields then click_page_button (e.g. Conduct Audit) when the user wants to submit. Voice: if the user wants to end the voice session, call end_voice_session or confirm and end; you may also say you are ending the voice session.`)}catch{}typeof c==`function`&&c()}catch(e){t||(console.error(`[VoiceInterface] startSession failed`,e),u(`error`),f(`Could not start voice session. Please try again.`))}})(),()=>{t=!0,i?i.endSession().catch(()=>{}):h.current&&h.current.endSession().catch(()=>{})}},[e,n,r,a,c]);let ee=l===`listening`||l===`speaking`,te=hg[l]||hg.idle,S=mg[l]||mg.idle;return(0,k.jsxs)(`div`,{ref:g,style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,flex:1,gap:`24px`,padding:`24px 20px`,background:`transparent`},children:[(0,k.jsxs)(`div`,{style:{position:`relative`,width:`140px`,height:`140px`,display:`flex`,alignItems:`center`,justifyContent:`center`},children:[ee&&(0,k.jsx)(`div`,{style:{position:`absolute`,inset:`-16px`,borderRadius:`50%`,border:`2px solid ${te}`,animation:`fe-orb-pulse 1.4s ease-in-out infinite`,opacity:.6}}),ee&&(0,k.jsx)(`div`,{style:{position:`absolute`,inset:`-8px`,borderRadius:`50%`,border:`2px solid ${te}`,animation:`fe-orb-pulse 1.4s ease-in-out 0.35s infinite`,opacity:.4}}),(0,k.jsx)(`div`,{style:{width:`140px`,height:`140px`,borderRadius:`50%`,background:S,border:`3px solid ${te}`,display:`flex`,alignItems:`center`,justifyContent:`center`,transition:`all 0.35s ease`,transform:l===`speaking`?`scale(1.08)`:`scale(1)`,boxShadow:`0 0 40px ${S}, 0 8px 32px rgba(0,0,0,0.08)`},children:(0,k.jsx)(Cn,{size:44,color:te})})]}),(0,k.jsxs)(`div`,{style:{fontSize:`15px`,fontWeight:600,color:l===`error`?`#ef4444`:`#374151`,letterSpacing:`0.01em`,textAlign:`center`},children:[l===`idle`&&`Starting voice session…`,l===`listening`&&`Listening…`,l===`speaking`&&`AI is speaking…`,l===`error`&&(d||`Error`)]}),(0,k.jsxs)(`button`,{onClick:x,style:{display:`flex`,alignItems:`center`,gap:`8px`,padding:`12px 24px`,borderRadius:`999px`,background:`#fee2e2`,color:`#dc2626`,border:`1px solid #fca5a5`,fontWeight:600,fontSize:`14px`,cursor:`pointer`,transition:`all 0.2s ease`},onMouseEnter:e=>{e.currentTarget.style.background=`#fecaca`},onMouseLeave:e=>{e.currentTarget.style.background=`#fee2e2`},children:[(0,k.jsx)(wn,{size:18}),`End Voice Session`]}),(0,k.jsx)(`style`,{children:`
|
|
327
327
|
@keyframes fe-orb-pulse {
|
|
328
328
|
0% { transform: scale(1); opacity: 0.6; }
|
|
329
329
|
50% { transform: scale(1.18); opacity: 0.15; }
|
|
330
330
|
100% { transform: scale(1); opacity: 0.6; }
|
|
331
331
|
}
|
|
332
|
-
`})]})}var
|
|
332
|
+
`})]})}var vg=[{key:`become_client`,label:`Become a Client`},{key:`sales_enquiry`,label:`Sales Enquiry`},{key:`learn_services`,label:`Learn about our Services`},{key:`get_support`,label:`Get Support`},{key:`looking_for_job`,label:`Looking for a Job`}],yg=()=>(0,k.jsx)(`div`,{style:{display:`flex`,marginBottom:`12px`,justifyContent:`flex-start`},children:(0,k.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`5px`,padding:`12px 16px`,borderRadius:`18px`,background:`#fff`,color:`#111827`,boxShadow:`0 2px 6px rgba(0,0,0,0.04)`},children:[[0,1,2].map(e=>(0,k.jsx)(`span`,{style:{width:`7px`,height:`7px`,borderRadius:`50%`,background:`#9ca3af`,animation:`fe-dot-bounce 1.2s ease-in-out ${e*.2}s infinite`,display:`inline-block`}},e)),(0,k.jsx)(`style`,{children:`
|
|
333
333
|
@keyframes fe-dot-bounce {
|
|
334
334
|
0%, 80%, 100% { transform: translateY(0); opacity: 0.5; }
|
|
335
335
|
40% { transform: translateY(-5px); opacity: 1; }
|
|
336
336
|
}
|
|
337
|
-
`})]})});function
|
|
338
|
-
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-ease:initial}}:root,:host{--spacing:.25rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1)}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.start{inset-inline-start:var(--spacing)}.end{inset-inline-end:var(--spacing)}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.block{display:block}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.flowengage-shell,.flowengage-shell *{font-family:inherit}.flowengage-chat-panel{border:none;border-radius:0;outline:none;flex-direction:column;width:100%;height:100%;display:flex;position:relative;overflow:hidden;box-shadow:0 20px 50px #00000026}@media (width>=768px){.flowengage-chat-panel{border-radius:24px;width:min(423px,100vw - 40px);height:min(700px,100vh - 120px)}}.flowengage-shell[data-open=true]{inset:0}@media (width>=768px){.flowengage-shell[data-open=true]{inset:auto 1.5rem 1.5rem auto}}.flowengage-logo-fallback{background:conic-gradient(from 180deg, var(--flowengage-primary) 0%, #2b70b5 50%, #f59e0b 100%)}.fe-bot-message p{margin:0 0 .5em}.fe-bot-message p:last-child{margin-bottom:0}.fe-bot-message ul,.fe-bot-message ol{margin:.4em 0 .4em 1.2em;padding:0}.fe-bot-message li{margin-bottom:.25em}.fe-bot-message strong{font-weight:600}.fe-bot-message a{color:var(--flowengage-primary);text-decoration:underline}.fe-bot-message a:hover{opacity:.8}.incoming-call-overlay{z-index:1000;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#1a1a2ef2;justify-content:center;align-items:center;transition:all .3s ease-in-out;display:flex;position:absolute;left:0;right:0}.incoming-call-overlay.bottom-mode{border-top:2px solid #ffffff1a;min-height:120px;animation:.4s cubic-bezier(.16,1,.3,1) slideUpBanner;top:auto;bottom:0;box-shadow:0 -10px 30px #00000080}.incoming-call-overlay.header-mode{border-bottom:2px solid #ffffff1a;min-height:80px;animation:.4s cubic-bezier(.16,1,.3,1) slideDownBanner;top:0;bottom:auto;box-shadow:0 10px 30px #00000080}.incoming-call-container{justify-content:space-between;align-items:center;gap:14px;width:100%;padding:14px 16px;display:flex}.incoming-call-container.connected-layout{flex-direction:column;justify-content:center;align-items:stretch;gap:14px}.call-connected-top{justify-content:space-between;align-items:center;gap:16px;width:100%;display:flex}.call-connected-identity{flex:1;align-items:center;gap:14px;min-width:0;display:flex}.call-icon-wrapper{color:#fff;z-index:1;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;width:54px;height:54px;margin-right:4px;display:flex;position:relative}.call-icon-wrapper.incoming{background:linear-gradient(135deg,#4caf50,#45a049);animation:1s ease-in-out infinite bounce}.call-icon-wrapper.connecting{background:linear-gradient(135deg,#2196f3,#1976d2)}.call-icon-wrapper.connected{background:linear-gradient(135deg,#4caf50,#45a049)}.call-pulse-animation{z-index:-1;background:#4caf504d;border-radius:50%;width:120px;height:120px;animation:1.5s ease-out infinite pulse;position:absolute}.call-connecting-animation{z-index:-1;border:3px solid #0000;border-top-color:#2196f3;border-radius:50%;width:100px;height:100px;animation:1s linear infinite spin;position:absolute}.call-info-group{flex-direction:column;flex:1;min-width:0;margin-right:8px;display:flex}.call-title{color:#fff;white-space:normal;text-overflow:clip;margin:0;font-size:16px;font-weight:700;line-height:1.2;overflow:visible}.call-subtitle{color:#ffffffb3;white-space:normal;text-overflow:clip;margin:4px 0 0;font-size:12px;line-height:1.35;overflow:visible}.call-timer{text-align:center;color:#fff;flex-shrink:0;min-width:54px;font-size:13px;font-weight:700}.call-actions{flex-shrink:0;align-items:center;gap:8px;display:flex}.call-actions.connected{justify-content:center;width:100%}.flowengage-call-btn{cursor:pointer;color:#fff;border:none;border-radius:8px;justify-content:center;align-items:center;gap:6px;min-width:92px;padding:8px 12px;font-size:12px;font-weight:600;line-height:1;transition:transform .2s,box-shadow .2s,background .2s;display:flex}.flowengage-call-btn svg{flex-shrink:0;display:block}.flowengage-call-btn span{justify-content:center;align-items:center;line-height:1;display:flex}.flowengage-call-btn.icon-only{border-radius:9999px;width:46px;min-width:46px;height:46px;padding:0}.flowengage-call-btn-accept{background:linear-gradient(135deg,#4caf50,#45a049);box-shadow:0 8px 24px #4caf5066}.flowengage-call-btn-reject,.flowengage-call-btn-end{background:linear-gradient(135deg,#f44336,#d32f2f);box-shadow:0 4px 12px #f4433666}.flowengage-call-btn-mute{background:#ffffff1a;border:2px solid #fff3}.flowengage-call-btn-mute.active{background:#f443364d;border-color:#f44336}.flowengage-call-btn:hover:not(:disabled){transform:scale(1.05)}.incoming-call-overlay.header-mode .flowengage-call-btn{border-radius:9999px!important;width:36px!important;min-width:36px!important;height:36px!important;padding:0!important}.incoming-call-overlay.header-mode .flowengage-call-btn span{display:none!important}.incoming-call-overlay.header-mode .call-icon-wrapper{width:40px;height:40px;margin-right:0}.incoming-call-overlay.header-mode .call-info-group{min-width:0}.incoming-call-overlay.header-mode .call-title,.incoming-call-overlay.header-mode .call-subtitle{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}@media (width<=640px){.incoming-call-container{align-items:flex-start;gap:10px;padding:12px 14px}.incoming-call-container.connected-layout{align-items:stretch}.call-connected-top{flex-direction:column;align-items:flex-start;gap:10px}.call-connected-identity{width:100%}.call-info-group{margin-right:0}.call-actions{flex-wrap:wrap;align-self:stretch;gap:6px}.call-actions.connected{justify-content:stretch}.call-actions.connected .flowengage-call-btn{flex:1}.flowengage-call-btn{min-width:78px;padding:8px 10px}}@keyframes slideUpBanner{0%{transform:translateY(100%)}to{transform:translateY(0)}}@keyframes slideDownBanner{0%{transform:translateY(-100%)}to{transform:translateY(0)}}@keyframes bounce{0%,to{animation-timing-function:cubic-bezier(.8,0,1,1);transform:translateY(-25%)}50%{animation-timing-function:cubic-bezier(0,0,.2,1);transform:none}}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.fe-screen-fade-in{animation:.4s cubic-bezier(.16,1,.3,1) forwards feFadeIn}@keyframes feFadeIn{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.flowengage-initial-bg{background-color:#fff;position:relative;overflow:hidden}.flowengage-initial-bg:before{content:"";background:linear-gradient(to bottom, var(--flowengage-primary) 0%, var(--flowengage-primary) 55%, white 82%);opacity:0;pointer-events:none;z-index:0;transition:opacity .6s cubic-bezier(.4,0,.2,1);position:absolute;inset:0}.flowengage-initial-bg.is-initial:before{opacity:1}.flowengage-content-wrapper{z-index:1;flex-direction:column;flex:1;min-height:0;display:flex;position:relative}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}`,xg=null,Sg=!1;function Cg(){if(typeof document>`u`||document.getElementById(`flowengage-styles`))return;let e=document.createElement(`style`);e.id=`flowengage-styles`,e.innerHTML=bg,document.head.appendChild(e)}function wg(e){if(document.body){e();return}let t=new MutationObserver(()=>{document.body&&(t.disconnect(),e())});t.observe(document.documentElement,{childList:!0})}function Tg({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}){if(Sg){console.warn(`[FlowEngage] Already initialized. Call FlowEngage.destroy() first to re-initialize.`);return}if(!e){console.error(`[FlowEngage] siteId is required. Pass it via data-site-id attribute or FlowEngage.init({ siteId: 'YOUR_SITE_ID' }).`);return}if(!document.body){console.error(`[FlowEngage] document.body is not available yet. The widget will auto-retry once the DOM is ready.`),wg(()=>Tg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}));return}if(document.getElementById(`flowengage-root`)){console.warn(`[FlowEngage] #flowengage-root already exists. Skipping duplicate mount.`);return}let i=document.createElement(`div`);i.id=`flowengage-root`,document.body.appendChild(i),Cg(),xg=(0,y.createRoot)(i);let a={widgetSettings:n,...r&&{apiBaseUrl:r}};xg.render(v.createElement(bn,{siteId:e,language:t,config:a},v.createElement(yg))),Sg=!0}var Eg={init({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}={}){document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>wg(()=>Tg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))):wg(()=>Tg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))},destroy(){xg&&=(xg.unmount(),null);let e=document.getElementById(`flowengage-root`);e&&e.remove();let t=document.getElementById(`flowengage-styles`);t&&t.remove(),Sg=!1}},Dg=()=>{let e=document.currentScript;(!e||!e.getAttribute(`data-site-id`))&&(e=document.querySelector(`script[data-site-id]`));let t=e?.getAttribute(`data-site-id`);if(!t)return;let n=e?.getAttribute(`data-language`)||`en`,r=e?.getAttribute(`data-api-url`)||void 0,i={};try{let t=e?.getAttribute(`data-widget-settings`);t&&(i=JSON.parse(t))}catch{}let a={widgetSettings:i,...r&&{apiBaseUrl:r}};wg(()=>Tg({siteId:t,language:n,widgetSettings:a.widgetSettings,apiBaseUrl:r}))};return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,Dg):Dg(),typeof window<`u`&&(window.FlowEngage=Eg),Eg})();
|
|
337
|
+
`})]})});function bg(){let{status:e,runtimeConfig:t,resolvedConfig:n,chatId:r,chatHistory:i,isOpen:a,activeScreen:o,isHumanHandled:s,agentName:c,agentHeadshot:l,visitorEmail:u,isAgentTyping:d,isAiTyping:f,isLoading:p,isVoiceMode:m,isRateLimited:h,rateLimitMessage:g,isConversationEnded:_,incomingCall:y,activeCallId:b,callConnectionState:x,callConnectedAt:ee,isCallMuted:te,webRTCError:S,language:ne,historyRef:re,onMessageSync:ie,endConversation:ae,acceptCall:oe,rejectCall:se,endWebRTCCall:ce,toggleCallMute:le,dismissCallError:ue,captureVisitorEmail:de,openWidget:fe,closeWidget:C,sendMessage:w,setVoiceMode:pe,startTyping:me,stopTyping:he,updateTypingDraft:ge}=tn(),[_e,T]=(0,v.useState)(``),[ve,ye]=(0,v.useState)(null),[be,xe]=(0,v.useState)(null),[Se,Ce]=(0,v.useState)(null),[we,Te]=(0,v.useState)(0),[Ee,De]=(0,v.useState)(u||``),[Oe,ke]=(0,v.useState)(``),E=t?.widgetSettings||{},Ae=n?.widgetSettings||{},je={...Ae.branding||{},...E.branding||{}},Me={...Ae.theme||{},...E.theme||{}},Ne=Me.primaryColor||`#3B82F6`,Pe=Me.accentColor||`#1D4ED8`,Fe=(Me.position||`bottom-right`)===`bottom-left`?{left:`1.5rem`,bottom:`1.5rem`}:{right:`1.5rem`,bottom:`1.5rem`},Ie={"--flowengage-primary":Ne,"--flowengage-accent":Pe,position:`fixed`,zIndex:999999,border:`none`,outline:`none`,fontFamily:`ui-sans-serif, system-ui, sans-serif`,...a?{}:Fe},Le=E.recommendations?.[ne]||Ae.recommendations?.[ne]||vg,Re=E.greetings?.[ne]||Ae.greetings?.[ne],ze=je.chatButtonText||`Chat with us`,Be=je.headerName||t?.websiteName||`OpenSense Labs`,Ve=je.logoUrl||null,He=je.hideWatermark||!1,D=Ae.elevenLabsAgentId||t?.elevenLabsAgentId||null,Ue=t?.siteId||n?.siteId||null,We=t?.apiBaseUrl||``,Ge=je.fallbackAgentName||`Agent`,Ke=je.botLabel||`AI`,qe=l&&String(l).trim()||t?.ownerProfileImageUrl&&String(t.ownerProfileImageUrl).trim()||null,Je=y?.agentName||c||Ge,Ye=i.some(e=>e.sender===`user`),Xe=(0,v.useMemo)(()=>{let e=i.findIndex(e=>e.sender===`user`);return e===-1?!1:i.slice(e+1).some(e=>e.sender===`bot`||e.sender===`ai`||e.sender===`agent`)},[i]),Ze=!u&&Ye&&Xe;(0,v.useEffect)(()=>{De(u||``),u&&ke(``)},[u]),(0,v.useEffect)(()=>{if(!ee||x!==`connected`){Te(0);return}let e=()=>{let e=new Date(ee).getTime();isNaN(e)||Te(Math.max(0,Math.floor((Date.now()-e)/1e3)))};e();let t=window.setInterval(e,1e3);return()=>window.clearInterval(t)},[ee,x]),(0,v.useEffect)(()=>{if(!s||m||_){ge(``),he();return}if(!_e.trim()){ge(``),he();return}me();let e=window.setTimeout(()=>{ge(_e)},120),t=window.setTimeout(()=>{he()},1200);return()=>{window.clearTimeout(e),window.clearTimeout(t)}},[_e,s,m,_,me,he,ge]);let Qe=e=>e?{replyTo:e.messageId||e.id||null,replyToContent:(e.replyToContent||e.message||``).replace(/<[^>]+>/g,``).trim().slice(0,200),replyToSender:e.sender||null}:null,$e=async e=>{if(e.preventDefault(),_)return;if(Ze){let e=Ee.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){ke(`Please enter a valid email so we can continue helping you.`);return}await de(e),ke(``);return}if(!_e.trim())return;let t=_e.trim(),n=Qe(Se);T(``),Ce(null),await w(t,``,n)},et=async()=>{if(Ze){ke(`Please share your email before starting a call.`);return}if(m){pe(!1);return}xe(null);try{ye(await navigator.mediaDevices.getUserMedia({audio:!0})),pe(!0)}catch(e){xe(e.message||`Could not access microphone.`)}},tt=()=>{ve&&(ve.getTracks().forEach(e=>e.stop()),ye(null)),pe(!1)},nt=e=>{let t=Math.floor(e/60),n=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}`};return e===`ready`?(0,k.jsxs)(`div`,{className:`flowengage-shell`,"data-open":a?`true`:`false`,style:Ie,children:[(0,k.jsx)(jn,{isOpen:a,openWidget:fe,launcherText:ze,primaryColor:Ne,posInline:Fe}),a&&(0,k.jsxs)(`div`,{className:`flowengage-chat-panel`,style:{background:i.length===0&&!m?`linear-gradient(to bottom, ${Ne} 0%, ${Ne} 70%, white 85%)`:`white`},children:[(0,k.jsx)(Fn,{logoUrl:Ve,brandName:Be,agentName:c,fallbackAgentName:Ge,activeScreen:o,branding:je,isConversationEnded:_,endConversation:ae,closeWidget:C,isInitial:i.length===0&&!m,botLabel:Ke,agentAvatarUrl:o===`agent`?qe:null,primaryColor:Ne}),(0,k.jsx)(`div`,{style:{flex:1,overflowY:`auto`,display:`flex`,flexDirection:`column`},className:`flowengage-content-wrapper`,children:m?(0,k.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,k.jsx)(_g,{agentId:D,chatId:r,siteId:Ue,apiBaseUrl:We,historyRef:re,onMessageSync:ie,onEnd:tt})},`voice`):i.length===0?(0,k.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,k.jsx)(Hn,{greetings:Re,recommendations:Le,onSendMessage:w})},`welcome`):(0,k.jsx)(`div`,{style:{flex:1,display:`flex`,flexDirection:`column`},className:`fe-screen-fade-in`,children:(0,k.jsx)(zn,{chatHistory:i,isAiTyping:f,isAgentTyping:d,setReplyContext:Ce,TypingDots:yg,primaryColor:Ne,agentHeadshot:qe,agentDisplayName:c||Ge})},`history`)}),(0,k.jsx)(Kn,{webRTCError:S,micError:be,setMicError:xe,dismissCallError:ue,incomingCall:y,rejectCall:se,acceptCall:oe,activeCallId:b,callConnectionState:x,formatCallDuration:nt,callDurationSeconds:we,endWebRTCCall:ce,isCallMuted:te,toggleCallMute:le,isAIVoiceActive:m,currentCallAgentName:Je,isRateLimited:h,rateLimitMessage:g}),!m&&(0,k.jsx)(`div`,{style:{position:`relative`,zIndex:1},children:(0,k.jsx)(Un,{input:_e,setInput:T,onSubmit:$e,isConversationEnded:_,callUiActive:!!(y||b),handleToggleVoice:et,activeScreen:o,inputDisabled:p||h||_,replyContext:Se,clearReplyContext:()=>Ce(null),requiresEmail:Ze,emailInput:Ee,setEmailInput:De,emailError:Oe})}),!He&&(0,k.jsx)(`div`,{style:{position:`relative`,zIndex:1,display:`flex`,alignItems:`center`,justifyContent:`center`,gap:`12px`,paddingTop:`12px`,paddingBottom:`16px`,fontSize:`12px`,color:`#9ca3af`},children:(0,k.jsxs)(`div`,{children:[`Powered by `,(0,k.jsx)(`span`,{style:{color:`#3b82f6`},children:`Flow`}),(0,k.jsx)(`span`,{style:{color:`#ef4444`},children:`Engage`})]})})]})]}):null}var xg=`/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */
|
|
338
|
+
@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-ease:initial}}:root,:host{--spacing:.25rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1)}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.start{inset-inline-start:var(--spacing)}.end{inset-inline-end:var(--spacing)}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.block{display:block}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.flowengage-shell,.flowengage-shell *{font-family:inherit}.flowengage-chat-panel{border:none;border-radius:0;outline:none;flex-direction:column;width:100%;height:100%;display:flex;position:relative;overflow:hidden;box-shadow:0 20px 50px #00000026}@media (width>=768px){.flowengage-chat-panel{border-radius:24px;width:min(423px,100vw - 40px);height:min(700px,100vh - 120px)}}.flowengage-shell[data-open=true]{inset:0}@media (width>=768px){.flowengage-shell[data-open=true]{inset:auto 1.5rem 1.5rem auto}}.flowengage-logo-fallback{background:conic-gradient(from 180deg, var(--flowengage-primary) 0%, #2b70b5 50%, #f59e0b 100%)}.fe-bot-message p{margin:0 0 .5em}.fe-bot-message p:last-child{margin-bottom:0}.fe-bot-message ul,.fe-bot-message ol{margin:.4em 0 .4em 1.2em;padding:0}.fe-bot-message li{margin-bottom:.25em}.fe-bot-message strong{font-weight:600}.fe-bot-message a{color:var(--flowengage-primary);text-decoration:underline}.fe-bot-message a:hover{opacity:.8}.incoming-call-overlay{z-index:1000;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#1a1a2ef2;justify-content:center;align-items:center;transition:all .3s ease-in-out;display:flex;position:absolute;left:0;right:0}.incoming-call-overlay.bottom-mode{border-top:2px solid #ffffff1a;min-height:120px;animation:.4s cubic-bezier(.16,1,.3,1) slideUpBanner;top:auto;bottom:0;box-shadow:0 -10px 30px #00000080}.incoming-call-overlay.header-mode{border-bottom:2px solid #ffffff1a;min-height:80px;animation:.4s cubic-bezier(.16,1,.3,1) slideDownBanner;top:0;bottom:auto;box-shadow:0 10px 30px #00000080}.incoming-call-container{justify-content:space-between;align-items:center;gap:14px;width:100%;padding:14px 16px;display:flex}.incoming-call-container.connected-layout{flex-direction:column;justify-content:center;align-items:stretch;gap:14px}.call-connected-top{justify-content:space-between;align-items:center;gap:16px;width:100%;display:flex}.call-connected-identity{flex:1;align-items:center;gap:14px;min-width:0;display:flex}.call-icon-wrapper{color:#fff;z-index:1;border-radius:9999px;flex-shrink:0;justify-content:center;align-items:center;width:54px;height:54px;margin-right:4px;display:flex;position:relative}.call-icon-wrapper.incoming{background:linear-gradient(135deg,#4caf50,#45a049);animation:1s ease-in-out infinite bounce}.call-icon-wrapper.connecting{background:linear-gradient(135deg,#2196f3,#1976d2)}.call-icon-wrapper.connected{background:linear-gradient(135deg,#4caf50,#45a049)}.call-pulse-animation{z-index:-1;background:#4caf504d;border-radius:50%;width:120px;height:120px;animation:1.5s ease-out infinite pulse;position:absolute}.call-connecting-animation{z-index:-1;border:3px solid #0000;border-top-color:#2196f3;border-radius:50%;width:100px;height:100px;animation:1s linear infinite spin;position:absolute}.call-info-group{flex-direction:column;flex:1;min-width:0;margin-right:8px;display:flex}.call-title{color:#fff;white-space:normal;text-overflow:clip;margin:0;font-size:16px;font-weight:700;line-height:1.2;overflow:visible}.call-subtitle{color:#ffffffb3;white-space:normal;text-overflow:clip;margin:4px 0 0;font-size:12px;line-height:1.35;overflow:visible}.call-timer{text-align:center;color:#fff;flex-shrink:0;min-width:54px;font-size:13px;font-weight:700}.call-actions{flex-shrink:0;align-items:center;gap:8px;display:flex}.call-actions.connected{justify-content:center;width:100%}.flowengage-call-btn{cursor:pointer;color:#fff;border:none;border-radius:8px;justify-content:center;align-items:center;gap:6px;min-width:92px;padding:8px 12px;font-size:12px;font-weight:600;line-height:1;transition:transform .2s,box-shadow .2s,background .2s;display:flex}.flowengage-call-btn svg{flex-shrink:0;display:block}.flowengage-call-btn span{justify-content:center;align-items:center;line-height:1;display:flex}.flowengage-call-btn.icon-only{border-radius:9999px;width:46px;min-width:46px;height:46px;padding:0}.flowengage-call-btn-accept{background:linear-gradient(135deg,#4caf50,#45a049);box-shadow:0 8px 24px #4caf5066}.flowengage-call-btn-reject,.flowengage-call-btn-end{background:linear-gradient(135deg,#f44336,#d32f2f);box-shadow:0 4px 12px #f4433666}.flowengage-call-btn-mute{background:#ffffff1a;border:2px solid #fff3}.flowengage-call-btn-mute.active{background:#f443364d;border-color:#f44336}.flowengage-call-btn:hover:not(:disabled){transform:scale(1.05)}.incoming-call-overlay.header-mode .flowengage-call-btn{border-radius:9999px!important;width:36px!important;min-width:36px!important;height:36px!important;padding:0!important}.incoming-call-overlay.header-mode .flowengage-call-btn span{display:none!important}.incoming-call-overlay.header-mode .call-icon-wrapper{width:40px;height:40px;margin-right:0}.incoming-call-overlay.header-mode .call-info-group{min-width:0}.incoming-call-overlay.header-mode .call-title,.incoming-call-overlay.header-mode .call-subtitle{white-space:nowrap;text-overflow:ellipsis;overflow:hidden}@media (width<=640px){.incoming-call-container{align-items:flex-start;gap:10px;padding:12px 14px}.incoming-call-container.connected-layout{align-items:stretch}.call-connected-top{flex-direction:column;align-items:flex-start;gap:10px}.call-connected-identity{width:100%}.call-info-group{margin-right:0}.call-actions{flex-wrap:wrap;align-self:stretch;gap:6px}.call-actions.connected{justify-content:stretch}.call-actions.connected .flowengage-call-btn{flex:1}.flowengage-call-btn{min-width:78px;padding:8px 10px}}@keyframes slideUpBanner{0%{transform:translateY(100%)}to{transform:translateY(0)}}@keyframes slideDownBanner{0%{transform:translateY(-100%)}to{transform:translateY(0)}}@keyframes bounce{0%,to{animation-timing-function:cubic-bezier(.8,0,1,1);transform:translateY(-25%)}50%{animation-timing-function:cubic-bezier(0,0,.2,1);transform:none}}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.fe-screen-fade-in{animation:.4s cubic-bezier(.16,1,.3,1) forwards feFadeIn}@keyframes feFadeIn{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.flowengage-initial-bg{background-color:#fff;position:relative;overflow:hidden}.flowengage-initial-bg:before{content:"";background:linear-gradient(to bottom, var(--flowengage-primary) 0%, var(--flowengage-primary) 55%, white 82%);opacity:0;pointer-events:none;z-index:0;transition:opacity .6s cubic-bezier(.4,0,.2,1);position:absolute;inset:0}.flowengage-initial-bg.is-initial:before{opacity:1}.flowengage-content-wrapper{z-index:1;flex-direction:column;flex:1;min-height:0;display:flex;position:relative}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}`,Sg=null,Cg=!1;function wg(){if(typeof document>`u`||document.getElementById(`flowengage-styles`))return;let e=document.createElement(`style`);e.id=`flowengage-styles`,e.innerHTML=xg,document.head.appendChild(e)}function Tg(e){if(document.body){e();return}let t=new MutationObserver(()=>{document.body&&(t.disconnect(),e())});t.observe(document.documentElement,{childList:!0})}function Eg({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}){if(Cg){console.warn(`[FlowEngage] Already initialized. Call FlowEngage.destroy() first to re-initialize.`);return}if(!e){console.error(`[FlowEngage] siteId is required. Pass it via data-site-id attribute or FlowEngage.init({ siteId: 'YOUR_SITE_ID' }).`);return}if(!document.body){console.error(`[FlowEngage] document.body is not available yet. The widget will auto-retry once the DOM is ready.`),Tg(()=>Eg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}));return}if(document.getElementById(`flowengage-root`)){console.warn(`[FlowEngage] #flowengage-root already exists. Skipping duplicate mount.`);return}let i=document.createElement(`div`);i.id=`flowengage-root`,document.body.appendChild(i),wg(),Sg=(0,y.createRoot)(i);let a={widgetSettings:n,...r&&{apiBaseUrl:r}};Sg.render(v.createElement(bn,{siteId:e,language:t,config:a},v.createElement(bg))),Cg=!0}var Dg={init({siteId:e,language:t=`en`,widgetSettings:n={},apiBaseUrl:r}={}){document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>Tg(()=>Eg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))):Tg(()=>Eg({siteId:e,language:t,widgetSettings:n,apiBaseUrl:r}))},destroy(){Sg&&=(Sg.unmount(),null);let e=document.getElementById(`flowengage-root`);e&&e.remove();let t=document.getElementById(`flowengage-styles`);t&&t.remove(),Cg=!1}},Og=()=>{let e=document.currentScript;(!e||!e.getAttribute(`data-site-id`))&&(e=document.querySelector(`script[data-site-id]`));let t=e?.getAttribute(`data-site-id`);if(!t)return;let n=e?.getAttribute(`data-language`)||`en`,r=e?.getAttribute(`data-api-url`)||void 0,i={};try{let t=e?.getAttribute(`data-widget-settings`);t&&(i=JSON.parse(t))}catch{}let a={widgetSettings:i,...r&&{apiBaseUrl:r}};Tg(()=>Eg({siteId:t,language:n,widgetSettings:a.widgetSettings,apiBaseUrl:r}))};return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,Og):Og(),typeof window<`u`&&(window.FlowEngage=Dg),Dg})();
|