@livelayer/react 0.21.3 → 0.21.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/dist/index.js +3 -3
- package/dist/index.mjs +1037 -993
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),n=require("react"),Wt=require("react-dom"),Xe=require("@livelayer/sdk"),Ct=require("livekit-client");class jn extends n.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,i){var o,l;(l=(o=this.props).onError)==null||l.call(o,r,i)}render(){var r;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((r=this.state.error)==null?void 0:r.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function Rn(e){const[r,i]=n.useState("idle"),[o,l]=n.useState("idle"),[a,c]=n.useState([]),[s,u]=n.useState(null),[d,x]=n.useState(null),[h,m]=n.useState(null),[N,C]=n.useState(!1),[L,y]=n.useState(null),w=n.useRef(null),R=n.useRef(e.onDataMessage);R.current=e.onDataMessage,n.useEffect(()=>{const g={onConnectionStateChange:z=>{i(z),z==="connected"&&y(null)},onAgentStateChange:l,onTranscript:z=>c([...z]),onAgentConfig:u,onAudioTrack:z=>m(z),onVideoTrack:z=>x(z),onVideoTrackRemoved:()=>x(null),onError:z=>y(z),onDataMessage:z=>{var V;(V=R.current)==null||V.call(R,z)},onResumabilityChange:C},A=new Xe.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},g);return w.current=A,i("idle"),l("idle"),c([]),u(null),x(null),m(null),C(!1),y(null),()=>{var z;(z=A.destroy)==null||z.call(A),w.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const S=n.useCallback(async()=>{const g=w.current;if(g)try{await g.connect()}catch(A){throw y(A instanceof Error?A.message:String(A)),A}},[]),v=n.useCallback(()=>{const g=w.current;g&&g.disconnect()},[]),P=n.useCallback(()=>{var g;return((g=w.current)==null?void 0:g.getRoom())??null},[]);return{connectionState:r,agentState:o,transcript:a,agentConfig:s,videoElement:d,audioElement:h,canResume:N,error:L,connect:S,disconnect:v,getRoom:P,session:w.current}}function Nn(){const e=n.useRef(null),r=n.useRef(new Map),i=n.useRef(null),o=n.useRef(new Set),l=n.useCallback(()=>{const C=r.current;if(C.size===0){i.current=null;return}let L=0;for(const{analyser:y,buffer:w}of C.values()){y.getByteFrequencyData(w);let R=0;for(let v=0;v<w.length;v++)R+=w[v];const S=R/w.length/255;S>L&&(L=S)}for(const y of o.current)try{y(L)}catch(w){console.error("[useAudioLevel] subscriber threw:",w)}i.current=requestAnimationFrame(l)},[]),a=n.useCallback(()=>e.current?e.current:typeof window>"u"||typeof AudioContext>"u"?null:(e.current=new AudioContext,e.current),[]),c=n.useCallback(()=>{i.current===null&&r.current.size>0&&(i.current=requestAnimationFrame(l))},[l]),s=n.useCallback(C=>{const L=r.current.get(C);if(L){try{L.node.disconnect()}catch{}try{L.analyser.disconnect()}catch{}r.current.delete(C)}},[]),u=n.useCallback((C,L)=>{const y=a();if(!y)return;s(C);const w=L(y);if(!w)return;const R=y.createAnalyser();R.fftSize=64;try{w.connect(R)}catch(S){console.warn("[useAudioLevel] connect failed for slot",C,S);return}r.current.set(C,{analyser:R,node:w,buffer:new Uint8Array(new ArrayBuffer(R.frequencyBinCount))}),c()},[s,a,c]),d=n.useCallback((C,L="agent")=>{u(L,y=>{try{return y.createMediaElementSource(C)}catch(w){return console.warn("[useAudioLevel] createMediaElementSource failed for slot",L,w),null}})},[u]),x=n.useCallback((C,L="mic")=>{u(L,y=>{try{return y.createMediaStreamSource(C)}catch(w){return console.warn("[useAudioLevel] createMediaStreamSource failed for slot",L,w),null}})},[u]),h=n.useCallback(C=>{s(C),r.current.size===0&&i.current!==null&&(cancelAnimationFrame(i.current),i.current=null)},[s]),m=n.useCallback(()=>{i.current!==null&&(cancelAnimationFrame(i.current),i.current=null);for(const C of Array.from(r.current.keys()))s(C)},[s]),N=n.useCallback(C=>(o.current.add(C),()=>{o.current.delete(C)}),[]);return n.useEffect(()=>()=>{if(m(),e.current){try{e.current.close()}catch{}e.current=null}o.current.clear()},[m]),{attach:d,attachStream:x,detach:m,detachSlot:h,subscribe:N}}function Cr(e){const r=e==null?void 0:e.mediaStreamTrack;return r?new MediaStream([r]):null}function An(e={}){const r=e.gateUntilAgentReady??!1,i=e.agentState??null,[o,l]=n.useState(r),[a,c]=n.useState(""),[s,u]=n.useState(null),d=n.useRef(null),x=n.useRef(null),h=n.useRef({active:r,lastAutoIntent:null}),m=n.useCallback(async S=>{var v,P;if(d.current&&x.current){try{await x.current.localParticipant.unpublishTrack(d.current)}catch{}d.current.stop(),d.current=null}x.current=S,u(null);try{const g=await Ct.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await S.localParticipant.publishTrack(g),d.current=g,h.current.active?(await S.localParticipant.setMicrophoneEnabled(!1),h.current.lastAutoIntent=!1,l(!0)):l(g.isMuted);const A=(P=(v=g.mediaStreamTrack)==null?void 0:v.getSettings)==null?void 0:P.call(v);A!=null&&A.deviceId&&c(A.deviceId)}catch(g){const A=g instanceof Error&&g.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw u(A),g}},[]),N=n.useCallback(S=>{x.current=S},[]),C=n.useCallback(async S=>{const v=x.current;if(v)try{await v.switchActiveDevice("audioinput",S),c(S)}catch(P){console.warn("[useMicrophoneState] switchDevice failed:",P)}},[]),L=n.useCallback(async()=>{const S=x.current,v=!o;if(l(v),h.current.active=!1,!!S)try{await S.localParticipant.setMicrophoneEnabled(!v)}catch(P){console.warn("[useMicrophoneState] setMicrophoneEnabled failed:",P),l(!v)}},[o]);n.useEffect(()=>{if(!h.current.active||i!=="listening")return;const S=x.current,v=S==null?void 0:S.localParticipant;if(!v){h.current.active=!1;return}v.isMicrophoneEnabled===h.current.lastAutoIntent&&(v.setMicrophoneEnabled(!0),h.current.lastAutoIntent=!0,l(!1)),h.current.active=!1},[i]);const y=n.useCallback(()=>{const S=d.current,v=x.current;if(S&&v){try{v.localParticipant.unpublishTrack(S)}catch{}S.stop()}d.current=null,x.current=null,h.current={active:r,lastAutoIntent:null},l(r),c("")},[r]),w=n.useCallback(()=>u(null),[]),R=n.useCallback(()=>Cr(d.current),[]);return{isMuted:o,activeDeviceId:a,micError:s,toggleMute:L,setupMic:m,attachRoom:N,switchDevice:C,teardownMic:y,clearError:w,getMicStream:R}}const kr={resolution:{width:640,height:480,frameRate:24}};function Mn(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),[l,a]=n.useState(null),[c,s]=n.useState(""),u=n.useRef(null),d=n.useRef(null),x=n.useCallback(w=>{u.current=w},[]),h=n.useCallback(()=>{var S;const w=u.current,R=d.current;if(R&&w){const v=w.localParticipant.getTrackPublication(Ct.Track.Source.Camera),g=(v==null?void 0:v.track)??R;try{w.localParticipant.unpublishTrack(g)}catch{}try{(S=g.stop)==null||S.call(g)}catch{}}d.current=null,a(null),r(!1)},[]),m=n.useCallback(async w=>{const R=u.current;if(R){o(null);try{const S={...kr};w&&(S.deviceId=w);const v=await Ct.createLocalVideoTrack(S);await R.localParticipant.publishTrack(v),d.current=v;const P=v.attach();a(P),r(!0),w&&s(w);try{R.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(S){const v=S instanceof Error&&S.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";o(v)}}},[]),N=n.useCallback(async()=>{e?h():await m(c||void 0)},[e,c,h,m]),C=n.useCallback(async w=>{h(),await m(w)},[h,m]),L=n.useCallback(()=>{h(),u.current=null,o(null),s("")},[h]),y=n.useCallback(()=>o(null),[]);return n.useEffect(()=>()=>{d.current&&d.current.stop()},[]),{isEnabled:e,error:i,previewEl:l,activeDeviceId:c,toggle:N,switchDevice:C,attachRoom:x,teardown:L,clearError:y}}function In(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),[l,a]=n.useState(null),c=n.useRef(null),s=n.useCallback(m=>{c.current=m},[]),u=n.useCallback(()=>a(null),[]),d=n.useCallback(async()=>{const m=c.current;if(m){if(e){try{await m.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1);return}o(null);try{await m.localParticipant.setScreenShareEnabled(!0);let N=0;const C=()=>{const L=m.localParticipant.getTrackPublication(Ct.Track.Source.ScreenShare);if(L!=null&&L.track){const y=L.track.attach();a(y),r(!0);try{m.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}N++<10?setTimeout(C,100):r(!0)};C()}catch(N){const C=N instanceof Error?N.name:"";C!=="NotAllowedError"&&C!=="AbortError"&&o("Screen share unavailable. Try again."),r(!1)}}},[e,u]),x=n.useCallback(()=>{const m=c.current;if(m&&e)try{m.localParticipant.setScreenShareEnabled(!1)}catch{}u(),r(!1),o(null),c.current=null},[e,u]),h=n.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:l,toggle:d,attachRoom:s,teardown:x,clearError:h}}function Tn(){const[e,r]=n.useState([]),[i,o]=n.useState([]),l=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const a=await navigator.mediaDevices.enumerateDevices();r(a.filter(c=>c.kind==="audioinput")),o(a.filter(c=>c.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(l(),typeof navigator>"u"||!navigator.mediaDevices)return;const a=()=>void l();return navigator.mediaDevices.addEventListener("devicechange",a),()=>navigator.mediaDevices.removeEventListener("devicechange",a)},[l]),{mics:e,cameras:i,refresh:l}}function Pn(e,r,i=!1){const[o,l]=n.useState(null),[a,c]=n.useState(null),[s,u]=n.useState(!i&&!!e);return n.useEffect(()=>{if(i||!e){u(!1);return}const d=new AbortController,x=r||"https://app.livelayer.studio";return u(!0),c(null),fetch(`${x}/api/widget/agent/${encodeURIComponent(e)}`,{signal:d.signal}).then(async h=>{if(!h.ok){const m=await h.json().catch(()=>({}));throw new Error(m.error||`HTTP ${h.status}`)}return h.json()}).then(h=>{d.signal.aborted||(l(h),u(!1))}).catch(h=>{d.signal.aborted||(c(h instanceof Error?h.message:"Agent lookup failed"),u(!1))}),()=>d.abort()},[e,r,i]),{info:o,error:a,loading:s}}function Dn(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function zn(e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(e,r)}catch{}}function Sr(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch{}}function $n({value:e,defaultValue:r="expanded",onChange:i}={}){const o=e!==void 0,[l,a]=n.useState(r),c=o?e:l,s=n.useCallback(u=>{u!==c&&(o||a(u),i==null||i(u))},[c,o,i]);return[c,s]}const Lr=["hidden","minimized","expanded"];function Er(e){return e&&Lr.includes(e)?e:null}function Hn({value:e,defaultValue:r="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:l=!1}={}){const a=`${o}:display-mode`,c=n.useRef(!1),[s,u]=$n({value:e,defaultValue:r,onChange:d=>{e===void 0&&!l&&zn(a,d),i==null||i(d)}});return n.useEffect(()=>{if(c.current||(c.current=!0,l||e!==void 0))return;const d=Er(Dn(a));d&&d!==s&&u(d)},[]),[s,u]}const jr=640;function Fn(e=jr){const[r,i]=n.useState(!1);return n.useEffect(()=>{if(e===!1){i(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const o=`(max-width: ${e-1}px)`,l=window.matchMedia(o),a=()=>i(l.matches);return a(),typeof l.addEventListener=="function"?(l.addEventListener("change",a),()=>l.removeEventListener("change",a)):(l.addListener(a),()=>{l.removeListener(a)})},[e]),r}const Rr=280,Nr=380,Ar=8,Mr=4;function Dt(e){return`${e}:geometry`}function Ir(e){if(!e)return null;let r;try{r=JSON.parse(e)}catch{return null}if(typeof r!="object"||r===null)return null;const i=r,{top:o,left:l,width:a,height:c}=i;return typeof o!="number"||typeof l!="number"||typeof a!="number"||typeof c!="number"||!Number.isFinite(o)||!Number.isFinite(l)||!Number.isFinite(a)||!Number.isFinite(c)?null:{top:o,left:l,width:a,height:c}}function bt(){return typeof window>"u"?{vw:0,vh:0}:{vw:window.innerWidth,vh:window.innerHeight}}function zt(e,r,i){const{minWidth:o,minHeight:l,edgeMargin:a,vw:c,vh:s}=i,u=Math.max(o,c-a*2),d=Math.max(l,s-a*2);return{width:Math.max(o,Math.min(u,e)),height:Math.max(l,Math.min(d,r))}}function $t(e,r,i,o,l){const{edgeMargin:a,vw:c,vh:s}=l,u=a,d=a,x=Math.max(u,c-i-a),h=Math.max(d,s-o-a);return{top:Math.max(d,Math.min(h,e)),left:Math.max(u,Math.min(x,r))}}function Tr(e){const{draggable:r,resizable:i,persistKey:o,disablePersistence:l,minWidth:a=Rr,minHeight:c=Nr,edgeMargin:s=Ar}=e,[u,d]=n.useState(null),[x,h]=n.useState(!1),[m,N]=n.useState(!1),C=n.useRef(null),L=n.useRef(null),y=n.useRef(!1),w=n.useRef(null);w.current=u;const R=n.useCallback(p=>{l||(p===null?Sr(Dt(o)):zn(Dt(o),JSON.stringify(p)))},[l,o]);n.useEffect(()=>{if(y.current||(y.current=!0,l))return;const p=Ir(Dn(Dt(o)));if(!p)return;const{vw:E,vh:M}=bt(),H=zt(p.width,p.height,{minWidth:a,minHeight:c,edgeMargin:s,vw:E,vh:M}),U=$t(p.top,p.left,H.width,H.height,{edgeMargin:s,vw:E,vh:M});d({...U,...H})},[]),n.useEffect(()=>{if(typeof window>"u")return;const p=()=>{d(E=>{if(E===null)return null;const{vw:M,vh:H}=bt(),U=zt(E.width,E.height,{minWidth:a,minHeight:c,edgeMargin:s,vw:M,vh:H});return{...$t(E.top,E.left,U.width,U.height,{edgeMargin:s,vw:M,vh:H}),...U}})};return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[a,c,s]);const S=n.useCallback(p=>{if(!r||p.pointerType==="mouse"&&p.button!==0)return;const E=p.target;if(E&&typeof E.closest=="function"&&E.closest('button, a, input, select, textarea, [role="listbox"], [role="option"], [data-ll-no-drag]'))return;let M,H,U,K;const W=w.current;if(W)({top:M,left:H,width:U,height:K}=W);else{const J=p.currentTarget.closest(".ll-widget"),te=J==null?void 0:J.getBoundingClientRect();if(!te)return;M=te.top,H=te.left,U=te.width,K=te.height}try{p.currentTarget.setPointerCapture(p.pointerId)}catch{}C.current={startClientX:p.clientX,startClientY:p.clientY,startTop:M,startLeft:H,width:U,height:K,moved:!1}},[r]),v=n.useCallback(p=>{const E=C.current;if(!E)return;const M=p.clientX-E.startClientX,H=p.clientY-E.startClientY;if(!E.moved&&Math.abs(M)+Math.abs(H)>Mr&&(E.moved=!0,h(!0)),!E.moved)return;const{vw:U,vh:K}=bt(),W=$t(E.startTop+H,E.startLeft+M,E.width,E.height,{edgeMargin:s,vw:U,vh:K});d({...W,width:E.width,height:E.height})},[s]),P=n.useCallback(p=>{const E=C.current;if(E){try{p.currentTarget.releasePointerCapture(p.pointerId)}catch{}C.current=null,E.moved&&(h(!1),d(M=>(M&&R(M),M)))}},[R]),g=n.useCallback(()=>{C.current=null,L.current=null,h(!1),N(!1),d(null),R(null)},[R]),A=n.useCallback(p=>{if(!i||p.pointerType==="mouse"&&p.button!==0)return;p.stopPropagation();let E,M,H,U;const K=w.current;if(K)({top:E,left:M,width:H,height:U}=K);else{const W=p.currentTarget.closest(".ll-widget"),J=W==null?void 0:W.getBoundingClientRect();if(!J)return;E=J.top,M=J.left,H=J.width,U=J.height}try{p.currentTarget.setPointerCapture(p.pointerId)}catch{}L.current={startClientX:p.clientX,startClientY:p.clientY,startWidth:H,startHeight:U,top:E,left:M},N(!0)},[i]),z=n.useCallback(p=>{const E=L.current;if(!E)return;const M=p.clientX-E.startClientX,H=p.clientY-E.startClientY,{vw:U,vh:K}=bt(),W=U-E.left-s,J=K-E.top-s,te=zt(E.startWidth+M,E.startHeight+H,{minWidth:a,minHeight:c,edgeMargin:s,vw:Math.min(U,E.left+W+s),vh:Math.min(K,E.top+J+s)});d({top:E.top,left:E.left,...te})},[s,a,c]),V=n.useCallback(p=>{if(L.current){try{p.currentTarget.releasePointerCapture(p.pointerId)}catch{}L.current=null,N(!1),d(M=>(M&&R(M),M))}},[R]);return{style:u===null?{}:{position:"fixed",top:`${u.top}px`,left:`${u.left}px`,right:"auto",bottom:"auto",width:`${u.width}px`,height:`${u.height}px`},hasGeometry:u!==null,isDragging:x,isResizing:m,dragHandleProps:{onPointerDown:S,onPointerMove:v,onPointerUp:P,onPointerCancel:P,onDoubleClick:g,"data-ll-drag-handle":r?"":void 0},resizeHandleProps:{onPointerDown:A,onPointerMove:z,onPointerUp:V,onPointerCancel:V,"data-ll-resize-handle":i?"":void 0},reset:g}}const ln="__llHistoryPatched",kt="ll:pathname";function Pr(){if(typeof window>"u"||window.history[ln])return;const e=window.history.pushState,r=window.history.replaceState;window.history.pushState=function(...i){const o=e.apply(this,i);return window.dispatchEvent(new Event(kt)),o},window.history.replaceState=function(...i){const o=r.apply(this,i);return window.dispatchEvent(new Event(kt)),o},window.history[ln]=!0}function cn(){return typeof window>"u"?"/":window.location.pathname||"/"}function On(e){const[r,i]=n.useState(()=>e??cn());return n.useEffect(()=>{if(e!==void 0)return;Pr();const o=()=>i(cn());return o(),window.addEventListener("popstate",o),window.addEventListener(kt,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(kt,o)}},[e]),e??r}const un=new Map,Dr=/[\\^$+?.()|{}[\]]/g;function zr(e){return e.replace(Dr,"\\$&")}function $r(e){const r=un.get(e);if(r)return r;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",l="",a=i.replace(/\*\*/g,o).replace(/\*/g,l),s=zr(a).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(l,"g"),"[^/]+"),u=new RegExp(`^${s}\\/?$`);return un.set(e,u),u}function Hr(e,r){const i=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return $r(e).test(i)}function Wn(e,r){return typeof e=="function"?e(r):e instanceof RegExp?e.test(r):Hr(e,r)}function dn(e,r){if(!e||e.length===0)return!1;for(const i of e)if(Wn(i,r))return!0;return!1}function Bn(e,r,i){return e===void 0?!0:dn(i,e)?!1:r&&r.length>0?dn(r,e):!0}function qn(e,r,i){return n.useMemo(()=>Bn(e,r,i),[e,r,i])}function Fr(e){return e===!1?{navigate:!1,thinking:!1,action:!1}:e===void 0||e===!0?{navigate:!0,thinking:!0,action:!0}:{navigate:e.navigate!==!1,thinking:e.thinking!==!1,action:e.action!==!1}}function Or(e){const r=n.useMemo(()=>Fr(e.config),[e.config]),i=e.baseUrl.replace(/\/+$/,""),o=n.useRef(null),l=n.useCallback(u=>{try{new Audio(`${i}${u}`).play().catch(()=>{})}catch{}},[i]),a=n.useCallback(()=>{r.navigate&&l("/audio/page-change-sound.mp3")},[r.navigate,l]),c=n.useCallback(()=>{r.action&&l("/audio/confirmation-sound.mp3")},[r.action,l]),s=n.useCallback(u=>{if(!r.thinking){if(o.current){try{o.current.pause()}catch{}o.current=null}return}if(u){if(o.current)return;try{const d=new Audio(`${i}/audio/thinking-sound.mp3`);d.loop=!0,d.volume=.3,d.play().catch(()=>{o.current=null}),o.current=d}catch{}}else if(o.current){try{o.current.pause()}catch{}o.current=null}},[i,r.thinking]);return n.useEffect(()=>()=>{if(o.current){try{o.current.pause()}catch{}o.current=null}},[]),n.useMemo(()=>({playPageChange:a,playConfirmation:c,setThinking:s}),[a,c,s])}const fn=({muted:e=!1,className:r})=>e?t.jsxs("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),pn=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})}),Wr=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),Br={left:180,right:0,up:-90,down:90},hn=({direction:e="right",className:r})=>t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${Br[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function qr(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const Un="ll-hidden-tab-center-y",Ur=5,mn=16;function Vr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Un);if(!e)return null;const r=Number.parseFloat(e);return Number.isFinite(r)?r:null}catch{return null}}function gn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Un,String(e))}catch{}}const Yr=({position:e,isMobile:r,isSpeaking:i,onExpand:o,label:l="Open widget",avatarImageUrl:a,agentName:c,containerEl:s})=>{const u=qr(e),d=u==="right"?"left":"right",x=r?80:72,h=!!a,m=!!s,[N,C]=n.useState(null),[L,y]=n.useState(!1),w=n.useRef(null),R=n.useRef(!1),S=n.useCallback(I=>{if(typeof window>"u")return I;const q=x/2,p=mn+q,E=window.innerHeight-mn-q;return E<p?Math.max(p,I):Math.max(p,Math.min(E,I))},[x]);n.useEffect(()=>{if(m){C(null);return}const I=Vr();C(S(I??window.innerHeight/2));const q=()=>{C(p=>p===null?null:S(p))};return window.addEventListener("resize",q),()=>window.removeEventListener("resize",q)},[S,m]);const v=n.useCallback(I=>{if(!m&&!(I.pointerType==="mouse"&&I.button!==0)&&N!==null){try{I.currentTarget.setPointerCapture(I.pointerId)}catch{}w.current={startClientY:I.clientY,startCenterY:N,moved:!1}}},[N,m]),P=n.useCallback(I=>{const q=w.current;if(!q)return;const p=I.clientY-q.startClientY;!q.moved&&Math.abs(p)>Ur&&(q.moved=!0,y(!0)),q.moved&&C(S(q.startCenterY+p))},[S]),g=n.useCallback(I=>{const q=w.current;if(q){try{I.currentTarget.releasePointerCapture(I.pointerId)}catch{}w.current=null,q.moved&&(y(!1),R.current=!0,C(p=>(p!==null&&gn(p),p)))}},[]),A=n.useCallback(()=>{if(R.current){R.current=!1;return}o()},[o]),z=n.useCallback(I=>{if(I.key==="ArrowUp"||I.key==="ArrowDown"){I.preventDefault();const q=I.key==="ArrowUp"?-8:8;C(p=>{if(p===null)return p;const E=S(p+q);return gn(E),E})}},[S]),V=["ll-hidden",`ll-hidden--${u}`,r?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,L?"is-dragging":null,h?"ll-hidden--with-avatar":null,m?"ll-hidden--scoped":null].filter(Boolean).join(" "),re=N===null?void 0:{top:`${N-x/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:V,onPointerDown:v,onPointerMove:P,onPointerUp:g,onPointerCancel:g,onClick:A,onKeyDown:z,"aria-label":l,"data-position":e,style:re,children:h?t.jsxs(t.Fragment,{children:[t.jsx(hn,{direction:d,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:a,alt:c?`${c} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(hn,{direction:d,className:"ll-hidden__chevron"})})},Gr=({audioLevel:e,bars:r=20,maxHeight:i=20,minHeight:o=4,className:l,barClassName:a})=>{const c=n.useRef(null),s=n.useRef([]),u=n.useMemo(()=>{const x=(Math.sqrt(5)-1)/2;return Array.from({length:r},(h,m)=>.5+m*x%1*.5)},[r]);n.useEffect(()=>e.subscribe(h=>{for(let m=0;m<r;m++){const N=s.current[m];if(!N)continue;const C=Math.max(o,h*i*u[m]);N.style.height=`${C}px`}}),[e,r,i,o,u]);const d=["ll-waveform",l].filter(Boolean).join(" ");return t.jsx("div",{ref:c,className:d,"aria-hidden":"true",children:Array.from({length:r},(x,h)=>t.jsx("div",{ref:m=>{s.current[h]=m},className:["ll-waveform__bar",a].filter(Boolean).join(" "),style:{height:`${o}px`}},h))})},Xr=({position:e,isMobile:r,agentName:i,avatarImageUrl:o,agentState:l,isMuted:a,audioLevel:c,onExpand:s,onToggleMute:u,onClose:d})=>r?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:s,"aria-label":`Expand ${i} widget`,children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsx(Gr,{audioLevel:c,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:x=>{x.stopPropagation(),u()},onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.stopPropagation(),x.preventDefault(),u())},"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(fn,{muted:a,className:"ll-minimized__icon"})}),t.jsx(pn,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):t.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${i} widget`,children:t.jsxs("div",{className:"ll-minimized__surface",children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsxs("div",{className:"ll-minimized__meta",children:[t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsx("span",{className:"ll-minimized__state",children:l==="speaking"?"Speaking":l==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:u,"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(fn,{muted:a,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:s,"aria-label":`Expand ${i} widget`,children:t.jsx(pn,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:d,"aria-label":"Close widget",children:t.jsx(Wr,{className:"ll-minimized__icon"})})]})]})}),Kr=({src:e,alt:r,preCannedPlaying:i=!1,className:o,style:l})=>{const[a,c]=n.useState(!1),s=n.useRef(e);if(n.useEffect(()=>{s.current!==e&&(s.current=e,c(!1))},[e]),!e)return null;const u={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:i?"scale(1.02)":"scale(1)",opacity:a?1:0,...l};return t.jsx("img",{src:e,alt:r,className:o,style:u,loading:"eager",fetchPriority:"high",onLoad:()=>c(!0)})},Jr="#E06540";function Zr({size:e=14,className:r,fill:i=Jr}){return t.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 52 52",fill:"none",className:r,"aria-hidden":!0,children:[t.jsx("path",{d:"M44.5714 26C44.5714 23.5612 44.0908 21.146 43.1575 18.8928C42.2242 16.6397 40.8565 14.5924 39.132 12.868C37.4076 11.1435 35.3603 9.77577 33.1072 8.84247C30.854 7.90917 28.4388 7.42857 26 7.42857C23.5612 7.42857 21.146 7.90916 18.8928 8.84247C16.6397 9.77577 14.5924 11.1435 12.868 12.868C11.1435 14.5924 9.77577 16.6397 8.84247 18.8928C7.90917 21.146 7.42857 23.5612 7.42857 26C7.42857 28.4388 7.90916 30.854 8.84247 33.1072C9.77577 35.3603 11.1435 37.4076 12.868 39.132C14.5924 40.8565 16.6397 42.2242 18.8928 43.1575C21.146 44.0908 23.5612 44.5714 26 44.5714H48.2857C50.3371 44.5714 52 46.2344 52 48.2857C52 50.3371 50.3371 52 48.2857 52H26C22.5857 52 19.2049 51.3275 16.0505 50.021C12.896 48.7144 10.0293 46.7993 7.61501 44.385C5.20069 41.9707 3.28564 39.104 1.97902 35.9495C0.67247 32.7951 -3.54212e-07 29.4143 0 26C-1.68163e-07 22.5857 0.672469 19.2049 1.97902 16.0505C3.28564 12.896 5.20069 10.0293 7.61501 7.61501C10.0293 5.20069 12.896 3.28564 16.0505 1.97902C19.2049 0.67247 22.5857 0 26 0C29.4143 1.86048e-07 32.7951 0.67247 35.9495 1.97902C39.104 3.28564 41.9707 5.20069 44.385 7.61501C46.7993 10.0293 48.7144 12.896 50.021 16.0505C51.3275 19.2049 52 22.5857 52 26C52 28.0513 50.3371 29.7143 48.2857 29.7143C46.2344 29.7143 44.5714 28.0513 44.5714 26Z",fill:i}),t.jsx("path",{d:"M28.9717 23.7714C28.9717 21.3098 30.9672 19.3143 33.4288 19.3143C35.8904 19.3143 37.886 21.3098 37.886 23.7714C37.886 26.233 35.8904 28.2286 33.4288 28.2286C30.9672 28.2286 28.9717 26.233 28.9717 23.7714Z",fill:i}),t.jsx("path",{d:"M18.5714 19.3143C16.1098 19.3143 14.1143 21.3098 14.1143 23.7714C14.1143 26.233 16.1098 28.2286 18.5714 28.2286C21.033 28.2286 23.0285 26.233 23.0285 23.7714C23.0285 21.3098 21.033 19.3143 18.5714 19.3143Z",fill:i})]})}const Qr=8,yn=8,ei=({open:e,onClose:r,anchorRef:i,children:o})=>{const l=n.useRef(null),[a,c]=n.useState(null);return n.useLayoutEffect(()=>{if(!e){c(null);return}const s=i.current;if(!s)return;const u=()=>{const d=s.getBoundingClientRect(),x={top:d.top-Qr,left:d.left+d.width/2},h=yn+90,m=window.innerWidth-yn-90;x.left<h&&(x.left=h),x.left>m&&(x.left=m),c(x)};return u(),window.addEventListener("scroll",u,!0),window.addEventListener("resize",u),()=>{window.removeEventListener("scroll",u,!0),window.removeEventListener("resize",u)}},[e,i]),n.useEffect(()=>{if(!e)return;const s=d=>{const x=d.target,h=l.current,m=i.current;h&&h.contains(x)||m&&m.contains(x)||r()},u=d=>{d.key==="Escape"&&(d.stopPropagation(),r())};return document.addEventListener("mousedown",s),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",u)}},[e,r,i]),!e||a===null||typeof document>"u"?null:Wt.createPortal(t.jsx("div",{ref:l,className:"ll-overflow-popover",role:"menu",style:{position:"fixed",top:a.top,left:a.left,transform:"translate(-50%, -100%)"},children:o}),document.body)},ti=({isMuted:e,onToggleMute:r,isCameraEnabled:i,onToggleCamera:o,allowCamera:l,isScreenShareEnabled:a,onToggleScreenShare:c,allowScreenShare:s,isSpeakerMuted:u,onToggleSpeaker:d,allowTyping:x,isTypingOpen:h,onToggleTyping:m,onDisconnect:N})=>{const[C,L]=n.useState(!1),y=n.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"ll-toolbar ll-toolbar--compact","data-testid":"compact-toolbar",onClick:w=>w.stopPropagation(),children:[t.jsx("button",{type:"button",className:`ll-tool ${e?"is-muted":""}`,onClick:r,"aria-label":e?"Unmute microphone":"Mute microphone",children:t.jsx(Gn,{muted:e})}),t.jsx("button",{ref:y,type:"button",className:`ll-tool ${C?"is-on":""}`,onClick:()=>L(w=>!w),"aria-label":"More controls","aria-haspopup":"menu","aria-expanded":C,children:t.jsx(ni,{})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:N,"aria-label":"End conversation",children:t.jsx(Kn,{})})]}),t.jsxs(ei,{open:C,onClose:()=>L(!1),anchorRef:y,children:[l&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${i?"is-on":""}`,onClick:()=>{o(),L(!1)},children:[t.jsx(Yn,{}),t.jsx("span",{children:i?"Stop camera":"Start camera"})]}),s&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${a?"is-on":""}`,onClick:()=>{c(),L(!1)},children:[t.jsx(Vn,{}),t.jsx("span",{children:a?"Stop sharing":"Share screen"})]}),t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${u?"is-on":""}`,onClick:()=>{d(),L(!1)},children:[t.jsx(Xn,{muted:u}),t.jsx("span",{children:u?"Unmute speaker":"Mute speaker"})]}),x&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${h?"is-on":""}`,onClick:()=>{m(),L(!1)},children:[t.jsx(ri,{}),t.jsx("span",{children:h?"Hide typing":"Type a message"})]}),t.jsxs("button",{type:"button",className:"ll-overflow-popover__item is-active",disabled:!0,"aria-current":"true",children:[t.jsx("span",{className:"ll-overflow-popover__lang-code",children:"EN"}),t.jsx("span",{children:"English"})]})]})]})};function ni(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[t.jsx("circle",{cx:"6",cy:"12",r:"1.5"}),t.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),t.jsx("circle",{cx:"18",cy:"12",r:"1.5"})]})}function ri(){return t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}const ii=({position:e,isMobile:r,agentName:i,avatarImageUrl:o,idleLoopUrl:l,greeting:a,branding:c,teamMembers:s,currentTeamMemberId:u,isSwitchingTeamMember:d,teamSwitcherOpen:x,onToggleTeamSwitcher:h,onSelectTeamMember:m,languageMenuOpen:N,onToggleLanguageMenu:C,connectionState:L,agentState:y,transcript:w,canResume:R,needsUserGesture:S,error:v,isMuted:P,micError:g,micDevices:A,activeMicId:z,isCameraEnabled:V,cameraPreviewEl:re,cameraDevices:I,activeCameraId:q,isScreenShareEnabled:p,screenPreviewEl:E,isSpeakerMuted:M,allowCamera:H,allowScreenShare:U,allowTyping:K,showMinimize:W=!0,showClose:J=!0,chromeless:te=!1,compactControls:F=!1,transforming:de,transformingLabel:X,avatarVideoContainerRef:me,agentVideoEl:Z,onConnect:Ke,onDisconnect:Je,onRetry:lt,onResumeAudio:ct,onToggleMute:Ze,onSwitchMicDevice:ut,onToggleCamera:De,onSwitchCameraDevice:ze,onToggleScreenShare:Ee,onToggleSpeaker:je,onSendMessage:Re,onMinimize:Ne,onClose:Ae,onClearMicError:$e,dragHandleProps:Me,resizeHandleProps:D})=>{var nt;const Ie=((s==null?void 0:s.length)??0)>1,He=L==="connecting"||L==="connected",ge=L==="connected",dt=L==="idle"||L==="disconnected"||L==="error",[Te,ke]=n.useState(!1);n.useEffect(()=>{if(!Z){ke(!1);return}if(!Z.paused&&Z.readyState>=2){ke(!0);return}ke(!1);const _=()=>ke(!0);return Z.addEventListener("playing",_),Z.addEventListener("loadeddata",_),()=>{Z.removeEventListener("playing",_),Z.removeEventListener("loadeddata",_)}},[Z]);const[St,ft]=n.useState(!1);n.useEffect(()=>{if(!ge){ft(!1);return}if(Te)return;const _=setTimeout(()=>ft(!0),8e3);return()=>clearTimeout(_)},[ge,Te]);const Pe=L==="connecting"||ge&&!!o&&!Te&&!St,se=n.useRef(null),Qe=n.useRef(null);n.useEffect(()=>{const _=se.current;_&&(_.innerHTML="",re&&(re.style.width="100%",re.style.height="100%",re.style.objectFit="cover",re.style.transform="scaleX(-1)",_.appendChild(re)))},[re]),n.useEffect(()=>{const _=Qe.current;_&&(_.innerHTML="",E&&(E.style.width="100%",E.style.height="100%",E.style.objectFit="contain",_.appendChild(E)))},[E]);const[ne,ce]=n.useState(!1),[Fe,Oe]=n.useState(!1),fe=n.useRef(null),ye=n.useRef(null);n.useEffect(()=>{if(!ne&&!Fe&&!N&&!x)return;const _=()=>{ce(!1),Oe(!1),N&&C(),x&&h()};return document.addEventListener("click",_),()=>document.removeEventListener("click",_)},[ne,Fe,N,x,C,h]);const[pt,Lt]=n.useState(!1),Et=n.useCallback(()=>Lt(_=>!_),[]),[et,jt]=n.useState(""),Se=n.useCallback(_=>{_.preventDefault();const Q=et.trim();Q&&(Re(Q),jt(""))},[et,Re]),Le=c.productName||"Live Layer",_e=!c.productName;let pe=null,ve=null;for(let _=w.length-1;_>=0;_--){const Q=w[_];if(!pe&&Q.role==="agent"?pe=Q:!ve&&Q.role==="user"&&(ve=Q),pe&&ve)break}const ht=ge?(pe==null?void 0:pe.text)||null:a||null,We=ge&&(ve==null?void 0:ve.text)||null,tt=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:tt,"data-position":e,"data-state":ge?"connected":He?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[o?t.jsx(Kr,{src:o,alt:i,className:"ll-expanded__bg-img"}):t.jsx("div",{className:"ll-expanded__bg-fallback",children:t.jsx("span",{className:"ll-expanded__bg-initial",children:((nt=i==null?void 0:i.charAt(0))==null?void 0:nt.toUpperCase())||"A"})}),l&&!ge&&t.jsx("video",{className:"ll-expanded__bg-idle",src:l,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:me,className:"ll-expanded__video"}),Pe&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:d?"Switching...":"Connecting..."})]}),S&&ge&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:ct,children:[t.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.54.12a5 5 0 0 1 0 5.76l-1.41-1.41a3 3 0 0 0 0-2.94L16.54 9.12z"})}),t.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),de&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--transforming",role:"status","aria-live":"polite","aria-label":X,children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:X})]}),He?t.jsxs(t.Fragment,{children:[!F&&t.jsxs("div",{className:"ll-expanded__topbar",...Me,children:[!te&&t.jsxs("div",{className:"ll-expanded__topbar-left",children:[t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill",onClick:_=>{Ie&&(_.stopPropagation(),h())},"aria-haspopup":Ie?"listbox":void 0,"aria-expanded":Ie?x:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),Ie&&t.jsx(xt,{})]}),Ie&&x&&t.jsx("div",{className:"ll-hmenu",onClick:_=>_.stopPropagation(),role:"listbox",children:s==null?void 0:s.map(_=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${_.id===u?"is-active":""}`,onClick:()=>m(_.id),role:"option","aria-selected":_.id===u,children:[_.avatarImageUrl&&t.jsx("img",{src:_.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:_.name}),_.role&&t.jsx("span",{className:"ll-hmenu__role",children:_.role})]},_.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:_=>{_.stopPropagation(),C()},"aria-haspopup":"listbox","aria-expanded":N,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(xt,{})]}),N&&t.jsx("div",{className:"ll-hmenu",onClick:_=>_.stopPropagation(),role:"listbox",children:t.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:t.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),t.jsx("span",{className:`ll-expanded__state ll-expanded__state--${y}`,children:y})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[W!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn",onClick:Ne,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(bn,{})}),J!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ae,"aria-label":"End call",title:"End call",children:t.jsx(vn,{})})]})]}),F&&t.jsxs("div",{className:"ll-compact-status","data-state":y,children:[t.jsx("span",{className:"ll-compact-status__dot","aria-hidden":!0}),t.jsx("span",{className:"ll-compact-status__label",children:y})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",...Me,children:[!F&&(_e?t.jsxs("a",{className:"ll-expanded__brand ll-expanded__brand--link",href:"https://livelayer.studio?utm_source=widget&utm_medium=brand-badge",target:"_blank",rel:"noopener noreferrer","aria-label":"Powered by LiveLayer — opens livelayer.studio in a new tab",title:"Powered by LiveLayer — visit livelayer.studio",children:[t.jsx(Zr,{size:14,className:"ll-expanded__brand-mark"}),t.jsx("span",{children:Le})]}):t.jsx("span",{className:"ll-expanded__brand",children:Le})),t.jsxs("div",{className:"ll-expanded__header-actions",children:[!F&&W!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:Ne,"aria-label":"Minimize widget",children:t.jsx(bn,{})}),J!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ae,"aria-label":"Close widget",children:t.jsx(vn,{})})]})]}),dt&&(()=>{const _=R?"Resume session":L==="disconnected"?"Reconnect to agent":"Start video call",Q=!v;return t.jsxs(t.Fragment,{children:[Q&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:Ke,"aria-label":_,children:[t.jsx("div",{className:"ll-expanded__play-circle",children:t.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),F&&t.jsx("span",{className:"ll-expanded__play-label",children:_})]}),!F&&t.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[a&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:a})}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:Ke,"aria-label":_,children:_})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${He&&(V||p)?"is-visible":""}`,children:[t.jsx("div",{ref:Qe,className:p?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:se,className:!p&&V?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),He?t.jsxs("div",{className:"ll-expanded__bottom",children:[!F&&ht&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:ht})}),!F&&We&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:We})}),!te&&!F&&t.jsxs("div",{className:"ll-toolbar",onClick:_=>_.stopPropagation(),children:[U&&t.jsx("button",{type:"button",className:`ll-tool ${p?"is-on":""}`,onClick:Ee,"aria-label":p?"Stop sharing screen":"Share screen",title:p?"Stop sharing":"Share screen",children:t.jsx(Vn,{})}),H&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${V?"is-on":""}`,onClick:De,"aria-label":V?"Turn off camera":"Turn on camera",title:V?"Stop camera":"Start camera",children:t.jsx(Yn,{})}),t.jsx("button",{ref:ye,type:"button",className:`ll-tool ll-tool--right ${V?"is-on":""}`,onClick:_=>{_.stopPropagation(),Oe(Q=>!Q),ce(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":Fe,children:t.jsx(xt,{})}),Fe&&I.length>0&&t.jsx(xn,{label:"Camera",devices:I,activeId:q,anchorRef:ye,onPick:_=>{Oe(!1),ze(_)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${P?"is-muted":""}`,onClick:Ze,"aria-label":P?"Unmute microphone":"Mute microphone",title:P?"Unmute":"Mute",children:t.jsx(Gn,{muted:P})}),t.jsx("button",{ref:fe,type:"button",className:`ll-tool ll-tool--right ${P?"is-muted":""}`,onClick:_=>{_.stopPropagation(),ce(Q=>!Q),Oe(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":ne,children:t.jsx(xt,{})}),ne&&A.length>0&&t.jsx(xn,{label:"Microphone",devices:A,activeId:z,anchorRef:fe,onPick:_=>{ce(!1),ut(_)}})]}),t.jsx("button",{type:"button",className:`ll-tool ${M?"is-muted":""}`,onClick:je,"aria-label":M?"Unmute speaker":"Mute speaker",title:M?"Unmute speaker":"Mute speaker",children:t.jsx(Xn,{muted:M})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:Je,"aria-label":"End conversation",title:"End conversation",children:t.jsx(Kn,{})})]}),!te&&F&&t.jsx(ti,{isMuted:P,onToggleMute:Ze,isCameraEnabled:V,onToggleCamera:De,allowCamera:H,isScreenShareEnabled:p,onToggleScreenShare:Ee,allowScreenShare:U,isSpeakerMuted:M,onToggleSpeaker:je,allowTyping:K,isTypingOpen:pt,onToggleTyping:Et,onDisconnect:Je}),!te&&K&&(F?pt:!0)&&t.jsxs("form",{className:"ll-message-input",onSubmit:Se,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:et,onChange:_=>jt(_.target.value),"aria-label":"Message the agent"}),et.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(oi,{})})]})]}):null,(()=>{if(g&&L!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:g}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:$e,"aria-label":"Dismiss",children:"×"})]});if(!v||L!=="error")return null;let _="Failed to connect",Q="Try again";return v==="MIC_PERMISSION_DENIED"?_="Microphone blocked. Allow access to talk.":v==="MIC_NOT_FOUND"?_="No microphone found. Plug one in + retry.":v==="MIC_UNAVAILABLE"?_="Mic unavailable. Check other apps using it.":v==="AGENT_TIMEOUT"?_="Agent didn't pick up. Try again.":v==="CONNECT_FAILED"?_="Connection failed. Check your network.":v.length<80&&(_=v),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:_}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:lt,children:Q})]})})(),(D==null?void 0:D["data-ll-resize-handle"])!==void 0&&t.jsx("div",{className:"ll-expanded__resize-grip",...D,"aria-hidden":!0,children:t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[t.jsx("line",{x1:"11",y1:"4",x2:"4",y2:"11"}),t.jsx("line",{x1:"11",y1:"8",x2:"8",y2:"11"})]})})]})};function xt(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("polyline",{points:"6 9 12 15 18 9"})})}function vn(){return t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function bn(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function Vn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Yn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M23 7l-7 5 7 5V7z"}),t.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2"})]})}function Gn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),t.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),e&&t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Xn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?t.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}):t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"}),t.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]})]})}function oi(){return t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),t.jsx("polyline",{points:"12 5 19 12 12 19"})]})}function Kn(){return t.jsx("svg",{width:"16",height:"16",viewBox:"-4 -4 32 32",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:t.jsx("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.93.37 1.84.71 2.7a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.38-1.38a2 2 0 0 1 2.11-.45c.86.34 1.77.58 2.7.71A2 2 0 0 1 22 16.92z",transform:"rotate(135 12 12)"})})}const xn=({label:e,devices:r,activeId:i,onPick:o,anchorRef:l})=>{const[a,c]=n.useState(null);return n.useLayoutEffect(()=>{const s=()=>{const u=l.current;if(!u)return;const d=u.getBoundingClientRect(),x=126,h=window.innerWidth-16-110,m=d.left+d.width/2;c({top:d.top-8,left:Math.max(x,Math.min(h,m))})};return s(),window.addEventListener("scroll",s,!0),window.addEventListener("resize",s),()=>{window.removeEventListener("scroll",s,!0),window.removeEventListener("resize",s)}},[l]),a===null||typeof document>"u"?null:Wt.createPortal(t.jsxs("div",{className:"ll-device-menu ll-device-menu--floating",onClick:s=>s.stopPropagation(),role:"listbox",style:{position:"fixed",top:a.top,left:a.left,transform:"translate(-50%, -100%)"},children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),r.map((s,u)=>{const d=i===s.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${d?"is-active":""}`,onClick:()=>o(s.deviceId),role:"option","aria-selected":d,children:[d&&t.jsx("span",{className:"ll-device-menu__dot",children:"●"}),t.jsx("span",{className:"ll-device-menu__name",children:s.label||`${e} ${u+1}`})]},s.deviceId||u)})]}),document.body)},si=["[data-ll-private]","[data-ll-skip]",".ll-widget"];function Bt(e){let r=e;for(;r;){for(const i of si)if(r.matches(i))return!0;r=r.parentElement}return!1}function Ft(e){if(Bt(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const r=(e.getAttribute("autocomplete")||"").toLowerCase();if(r==="off"||r.startsWith("cc-"))return!1}return!0}const wt=4096,ai=20,li=20,ci=10,ui=10,di=30,fi=20,wn=500,pi=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function st(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let r=e;for(;r;){for(const i of pi)if(r.matches(i))return!0;r=r.parentElement}return!1}function at(e){if(typeof window>"u")return!0;const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth;return r.bottom>0&&r.right>0&&r.top<i&&r.left<o}function _n(e){const r=e.getAttribute("id");if(r){const a=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/"/g,'\\"'),c=document.querySelector(`label[for="${a}"]`);if(c!=null&&c.textContent)return c.textContent.trim()}const i=e.getAttribute("aria-label");if(i)return i.trim();const o=e.closest("label");if(o){const a=[];for(const s of Array.from(o.childNodes))if(s.nodeType===Node.TEXT_NODE){const u=(s.textContent||"").trim();u&&a.push(u)}else if(s instanceof HTMLElement){if(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement||s instanceof HTMLButtonElement)continue;const u=(s.textContent||"").trim();u&&a.push(u)}const c=a.join(" ").trim();if(c)return c}const l=e.getAttribute("placeholder");return l?l.trim():""}function le(e,r){return e.length<=r?e:e.slice(0,r-1)+"…"}function hi(e){return e&&e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||null}function mi(e){const r=e.getAttribute("aria-label");if(r)return r.trim().slice(0,80);const i=e.getAttribute("aria-labelledby");if(i){const a=document.getElementById(i);if(a!=null&&a.textContent)return a.textContent.trim().slice(0,80)}const o=e.querySelector('button[type="submit"], input[type="submit"], button:not([type])');if(o){const a=o instanceof HTMLInputElement?o.value:(o.textContent??"").trim();if(a&&a.length<60&&!/^(submit|ok|continue)$/i.test(a))return a}let l=e.parentElement;for(let a=0;l&&a<4;a++,l=l.parentElement){const c=l.querySelector("h1, h2, h3, h4");if(c!=null&&c.textContent){const s=c.textContent.trim();if(s&&s.length<80)return s}}return null}function Ve(e){return e.length}function Jn(e,r={}){const i=r.doc??(typeof document<"u"?document:null);if(!i)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const o=typeof window<"u"&&window.location.href||"",l=typeof window<"u"&&window.location.pathname||"/",a=i.title||"",c=Array.from(i.querySelectorAll("[data-ll-region]")),s=[];for(const g of c){if(s.length>=ci)break;if(st(g)||!at(g))continue;const A=g.getAttribute("data-ll-region")??"",z=g.getAttribute("data-ll-intent")??void 0,V=le((g.innerText||g.textContent||"").trim(),wn*2);!A||!V||s.push({id:A,intent:z,text:V})}const u=[],d=["H1","H2","H3","H4","H5","H6"],x=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const g of x){if(st(g)||!at(g))continue;const A=(g.textContent||"").trim();A&&u.push(`${g.tagName}: ${le(A,200)}`)}const h=Array.from(i.querySelectorAll("p, li"));for(const g of h){if(st(g)||!at(g)||d.includes(g.tagName))continue;const A=(g.textContent||"").trim();A.length>10&&u.push(le(A,wn))}const m=u.join(`
|
|
2
|
-
`),N=[],C=Array.from(i.querySelectorAll("a[href]"));for(const g of C){if(N.length>=ai)break;if(st(g)||!at(g))continue;const A=g.getAttribute("href")||"",z=(g.textContent||"").trim();!A||!z||N.push({href:A,text:le(z,100)})}const L=[],y=Array.from(i.querySelectorAll("input, textarea, select"));for(const g of y){if(L.length>=li)break;if(st(g)||!Ft(g)||!at(g))continue;const A=_n(g),z=g instanceof HTMLInputElement?g.type:g.tagName.toLowerCase();A&&L.push({label:le(A,100),type:z})}const w=Array.from(i.querySelectorAll("form")),R=[];let S=0;for(const g of w){if(R.length>=ui)break;if(Bt(g)||g.matches(".ll-widget *, .ll-widget"))continue;const A=g.getAttribute("id")||g.getAttribute("name")||hi(g.getAttribute("data-ll-intent"))||`form_${S++}`,z=g.getAttribute("data-ll-intent")||mi(g)||void 0,V=Array.from(g.querySelectorAll("input, textarea, select")),re=[];let I=0;const q=new Set;for(const p of V){if(re.length>=di)break;if(!Ft(p))continue;if(p instanceof HTMLInputElement){const F=p.type;if(F==="submit"||F==="button"||F==="reset"||F==="hidden"||F==="image"||F==="file")continue}const E=p.getAttribute("name")||"",M=p.getAttribute("id")||"";let H=E||M||`field_${I}`;q.has(H)&&(H=`${H}__${I}`),q.add(H),I++;const U=_n(p)||H,K=p instanceof HTMLInputElement?p.type:p.tagName.toLowerCase(),W={name:H,label:le(U,100),type:K};p.required===!0&&(W.required=!0);const J=p.getAttribute("placeholder");if(J&&(W.placeholder=le(J.trim(),100)),p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement){const F=p.getAttribute("minlength");if(F!==null){const X=parseInt(F,10);!Number.isNaN(X)&&X>=0&&(W.minLength=X)}const de=p.getAttribute("maxlength");if(de!==null){const X=parseInt(de,10);!Number.isNaN(X)&&X>=0&&(W.maxLength=X)}}if(p instanceof HTMLInputElement){const F=p.getAttribute("min");F!==null&&(W.min=le(F,50));const de=p.getAttribute("max");de!==null&&(W.max=le(de,50));const X=p.getAttribute("step");X!==null&&(W.step=le(X,20));const me=p.getAttribute("pattern");me!==null&&(W.pattern=le(me,200));const Z=(p.getAttribute("autocomplete")||"").toLowerCase();Z&&Z!=="off"&&!Z.startsWith("cc-")&&(W.autocomplete=le(Z,50))}if(p instanceof HTMLSelectElement){const F=[];for(let de=0;de<p.options.length&&!(F.length>=fi);de++){const X=p.options[de];if(!X||X.disabled)continue;const me=X.value||"",Z=(X.textContent||"").trim()||me;!me&&!Z||F.push({value:me,label:le(Z,60)})}F.length>0&&(W.options=F)}const te=typeof p.validationMessage=="string"?p.validationMessage:"";te&&(W.validationMessage=le(te,200)),re.push(W)}R.push({id:A,intent:z,fields:re})}const v={url:o,title:a,pathname:l,regions:s,visibleText:m,visibleLinks:N,visibleFields:L,forms:R,extras:e};let P=Ve(JSON.stringify(v.regions))+Ve(v.visibleText)+Ve(JSON.stringify(v.visibleLinks))+Ve(JSON.stringify(v.visibleFields));for(;P>wt&&v.visibleFields.length>0;)v.visibleFields.pop(),P=Ve(JSON.stringify(v.visibleFields));for(;P>wt&&v.visibleLinks.length>0;)v.visibleLinks.pop(),P-=80;return Ve(v.visibleText)>wt&&(v.visibleText=le(v.visibleText,wt-100)),v}let Ye=null;function gi(e){const r=e.querySelectorAll("form");let i=`f${r.length}`;return r.forEach(o=>{i+=`|${o.id||o.getAttribute("name")||""}:${o.querySelectorAll("input,select,textarea").length}`}),i}function Ot(e,r={}){const i=Date.now(),o=r.doc??(typeof document<"u"?document:null),l=typeof window<"u"&&window.location.pathname||"/",a=typeof window<"u"?window.scrollY:0,c=`${l}::${a}::${o?gi(o):""}`;if(Ye&&Ye.key===c&&i-Ye.at<1e3)return Ye.ctx;const s=Jn(e,r);return Ye={key:c,at:i,ctx:s},s}function Zn(){Ye=null}const yi=200;function Qn(e){const r=String(e.href||"");return{href:r,text:String(e.text??e.title??r),internal:e.internal??!0,title:e.title,description:e.description}}function vi(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function er(e){const r=e??(typeof document<"u"?document:null);if(!r)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,l=[],a=Array.from(r.querySelectorAll("a[href]"));for(const c of a){if(l.length>=yi)break;if(Bt(c))continue;const s=c.getAttribute("href")||"";if(!vi(s))continue;let u=s,d=!0;try{if(typeof window<"u"){const h=new URL(s,i);d=h.origin===i,d&&s.startsWith("http")&&(u=h.pathname+h.search+h.hash)}}catch{continue}if(o.has(u))continue;o.add(u);const x=(c.textContent||"").trim().slice(0,120);l.push({href:u,text:x,internal:d})}return l}let Ge=null;const bi=5e3;function _t(){const e=Date.now(),r=typeof window<"u"&&window.location.pathname||"/";if(Ge&&Ge.pathname===r&&e-Ge.at<bi)return Ge.routes;const i=er();return Ge={at:e,pathname:r,routes:i},i}function tr(){Ge=null}function Cn(e){if(e instanceof HTMLInputElement){const r=e.type;if(r==="submit"||r==="button"||r==="reset"||r==="hidden"||r==="image"||r==="file")return!1}return!0}function xi(e,r){return e.getAttribute("name")||e.getAttribute("id")||`field_${r}`}function wi(e,r){if(!r)return null;try{const a=e.querySelector(`[name="${r.replace(/"/g,'\\"')}"]`);if(a&&Cn(a))return a}catch{}const i=Array.from(e.querySelectorAll("input, textarea, select"));let o=0;const l=new Map;for(const a of i){if(!Cn(a))continue;const c=xi(a,o);let s=c;if(l.has(c)&&(s=`${c}__${o}`),s===r)return a;l.set(c,a),o++}return null}function kn(e,r){const i=wi(e,r);return i?Ft(i)?{el:i}:{el:null,reason:"private"}:{el:null,reason:"not_found"}}function _i(e,r){const i=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,o=Object.getOwnPropertyDescriptor(i,"value"),l=o==null?void 0:o.set;l?l.call(e,r):e.value=r}function Ci(e,r,i={}){const o=i.triggerInput??!0,l=i.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const a=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),c=a==null?void 0:a.set,s=r==="true"||r==="1"||r==="on";c?c.call(e,s):e.checked=s,o&&e.dispatchEvent(new Event("input",{bubbles:!0})),l&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}_i(e,r),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),l&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function Sn(e,r){if(!r)return null;const i=r.replace(/"/g,'\\"'),o=s=>s.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')!==null;try{const s=e.querySelector(`form#${CSS.escape(r)}`);if(s&&!o(s))return s}catch{}const l=e.querySelector(`form[name="${i}"]`);if(l&&!o(l))return l;const a=e.querySelector(`form[data-ll-intent="${i}"]`);if(a&&!o(a))return a;const c=Array.from(e.querySelectorAll("form")).filter(s=>!o(s));for(const s of c){const u=s.getAttribute("data-ll-intent");if(u&&ki(u)===r)return s}if(/^form_\d+$/.test(r)){const s=parseInt(r.slice(5),10);let u=0;for(const d of c)if(!(d.id||d.getAttribute("name")||d.getAttribute("data-ll-intent"))){if(u===s)return d;u++}}return c.length===1?c[0]:null}function ki(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||null}function Si(){if(typeof window>"u"||typeof document>"u")return!1;const e=document.scrollingElement||document.documentElement;if(!e||e.scrollHeight<=e.clientHeight+2)return!1;const r=window.getComputedStyle(e);return!(r.overflowY==="hidden"||r.overflowY==="clip")}function Li(e){if(!(e instanceof HTMLElement))return!1;const i=window.getComputedStyle(e).overflowY;return!(i!=="auto"&&i!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function Ei(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let r=null,i=0;for(const o of e){if(!Li(o))continue;const l=o.getBoundingClientRect();if(l.bottom<=0||l.top>=window.innerHeight||l.right<=0||l.left>=window.innerWidth||l.width<=0||l.height<=0||o.closest(".ll-widget"))continue;const a=l.width*l.height;a>i&&(i=a,r=o)}return r}function ji(){if(typeof window>"u")return null;if(Si())return window;const e=Ei();return e||window}function Ln(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function Ri(e){var r,i;return e instanceof Window?typeof document>"u"?0:Math.max(((r=document.body)==null?void 0:r.scrollHeight)??0,((i=document.documentElement)==null?void 0:i.scrollHeight)??0):e.scrollHeight-e.clientHeight}const Ni=new Set(["agent_state","avatar_stream_ready","avatar_active","avatar_idle","bot_ready","agent_error","idle_warning","idle_timeout","navigate","scroll_to","request_page_context","scroll_page","click","fill_form","focus_field","submit_form","request_routes","task_field_updated","task_completed"]),nr=n.forwardRef(function(r,i){var en,tn,nn,rn,on,sn,an;const{agentId:o,apiKey:l,baseUrl:a="https://app.livelayer.studio",sessionEndpoint:c,sessionBody:s,soundEffects:u,experienceMode:d="WIDGET",autoConnect:x=!1,displayMode:h,defaultDisplayMode:m="expanded",onDisplayModeChange:N,position:C="bottom-right",mobileBreakpoint:L=640,draggable:y,resizable:w,persistKey:R="ll-widget",disablePersistence:S=!1,teamMembers:v,currentTeamMemberId:P,onTeamMemberChange:g,idleLoopUrl:A,greeting:z,avatarImageUrl:V,agentName:re,branding:I={},allowCamera:q=!0,allowScreenShare:p=!0,allowTyping:E=!0,blurUntilFirstSpeech:M=!0,showMinimize:H,showClose:U,chromeless:K=!1,floatingChromeContainer:W=null,compactControls:J=!1,transforming:te=!1,transformingLabel:F="Transforming…",showOn:de,hideOn:X,pathname:me,onNavigate:Z,onScrollToSelector:Ke,getPageContext:Je,pageContextExtras:lt,getRoutes:ct,onScrollPage:Ze,onClick:ut,capabilities:De,onConnect:ze,onDisconnect:Ee,onTranscript:je,onAgentState:Re,onConnectionStateChange:Ne,onAgentEvent:Ae,onAgentCommand:$e,onCollect:Me,controlledSession:D,className:Ie,style:He,zIndex:ge=2147483647}=r,dt=On(me),Te=qn(dt,de,X);n.useEffect(()=>{Zn(),tr()},[dt]);const ke=P!==void 0,[St,ft]=n.useState(()=>{var b;return P??((b=v==null?void 0:v[0])==null?void 0:b.id)}),Pe=ke?P:St,se=n.useMemo(()=>(v==null?void 0:v.find(b=>b.id===Pe))??null,[v,Pe]),Qe=(se==null?void 0:se.agentId)??o,ne=d==="EMBEDDED",ce=Fn(L),[Fe,Oe]=Hn({value:h,defaultValue:m,onChange:N,persistKey:R,disablePersistence:ne||S}),fe=ne?"expanded":Fe,ye=ne?()=>{}:Oe,pt=H??!ne,Lt=U??!ne,Et=J||!ne&&ce,Se=Tr({draggable:!ne&&(y??!ce),resizable:!ne&&(w??!ce),persistKey:R,disablePersistence:ne||S}),Le=Nn(),_e=Mn(),pe=In(),ve=Tn(),[ht,We]=n.useState(!1),[tt,nt]=n.useState(!1),[_,Q]=n.useState(!1),[or,sr]=n.useState(!1),[Rt,ar]=n.useState(!1),mt=Or({baseUrl:a,config:u}),gt=n.useRef(mt);gt.current=mt;const Nt=n.useRef(Z),At=n.useRef(Ke),Mt=n.useRef(Ze),It=n.useRef(ut),qt=n.useRef(Je),Ut=n.useRef(lt),Vt=n.useRef(ct),Tt=n.useRef(De),be=n.useRef(null);Nt.current=Z,At.current=Ke,Mt.current=Ze,It.current=ut,qt.current=Je,Ut.current=lt,Vt.current=ct,Tt.current=De;function xe(b){const f=Tt.current;return f?f.includes(b):!0}function we(b,f){console.warn(`[LiveLayer] Agent command "${b}" blocked — capability "${f}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const rt=n.useCallback(b=>{var ee,ae,Ce,ot;const f=b;if(!(!f.type||typeof f.type!="string")){if(Ae==null||Ae({eventName:f.type,data:b}),f.type==="navigate"){if(!xe("navigate")){we("navigate","navigate");return}const j=typeof f.href=="string"?f.href:null;if(!j){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(gt.current.playPageChange(),Nt.current){try{Nt.current(j)}catch(T){console.warn(`[LiveLayer] onNavigate threw for "${j}". Falling back. Error:`,T)}return}if(typeof document<"u"){const T=document.querySelector(`a[href="${j.replace(/"/g,'\\"')}"]`);if(T){T.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",j),window.dispatchEvent(new PopStateEvent("popstate"))}catch(T){console.warn(`[LiveLayer] history.pushState fallback failed for "${j}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,T)}return}if(f.type==="scroll_to"){if(!xe("scroll")){we("scroll_to","scroll");return}const j=typeof f.selector=="string"?f.selector:null;if(!j)return;const T=f.behavior==="instant"?"instant":"smooth";if(At.current){try{At.current(j,T)}catch(B){console.warn("[LiveLayer] onScrollToSelector threw.",B)}return}if(typeof document<"u"){let B=null;try{B=document.querySelector(j)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${j}".`);return}if(!B){console.warn(`[LiveLayer] scroll_to: no element matched "${j}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}B.scrollIntoView({behavior:T,block:"start"})}return}if(f.type==="request_page_context"){if(!xe("read_page")){we("request_page_context","read_page");return}const j=typeof f.requestId=="string"?f.requestId:void 0,T=(ee=be.current)==null?void 0:ee.call(be),B=G=>{const $=T,oe=$==null?void 0:$.localParticipant;if(oe!=null&&oe.publishData)try{const ue=j?{...G,requestId:j}:G,Ue=new TextEncoder().encode(JSON.stringify(ue));oe.publishData(Ue,{reliable:!0})}catch(ue){console.warn("[LiveLayer] publishData failed.",ue)}},O=Ut.current,Y=qt.current;try{if(Y){const G=Y(O);if(G instanceof Promise){B({type:"page_context_pending"}),G.then($=>B({type:"page_context",context:$})).catch($=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",$),B({type:"page_context",context:Ot(O)})});return}B({type:"page_context",context:G});return}B({type:"page_context",context:Ot(O)})}catch(G){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",G),B({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:O}})}return}if(f.type==="scroll_page"){if(!xe("scroll")){we("scroll_page","scroll");return}const j=f.direction;if(j!=="up"&&j!=="down"&&j!=="top"&&j!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(j)}". Expected up | down | top | bottom.`);return}const T=f.behavior==="instant"?"instant":"smooth";if(Mt.current){try{Mt.current(j,T)}catch($){console.warn("[LiveLayer] onScrollPage threw.",$)}return}if(typeof window>"u")return;const B={behavior:T},O=ji(),Y=$=>{O instanceof Window?O.scrollBy({top:$,...B}):O.scrollBy({top:$,...B})},G=$=>{O instanceof Window?O.scrollTo({top:$,...B}):O.scrollTo({top:$,...B})};j==="up"?Y(-Ln(O)):j==="down"?Y(Ln(O)):G(j==="top"?0:Ri(O));return}if(f.type==="click"){if(!xe("click")){we("click","click");return}const j=typeof f.selector=="string"?f.selector:null;if(!j){console.warn("[LiveLayer] click: missing selector.");return}if(It.current){try{It.current(j)}catch(B){console.warn("[LiveLayer] onClick threw.",B)}return}if(typeof document>"u")return;let T=null;try{T=document.querySelector(j)}catch{console.warn(`[LiveLayer] click: invalid selector "${j}".`);return}if(!T){console.warn(`[LiveLayer] click: no element matched "${j}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(T.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(ae=T.click)==null||ae.call(T);return}if(f.type==="fill_form"||f.type==="focus_field"){if(!xe("fill_forms")){we(f.type,"fill_forms");return}if(typeof document>"u")return;f.type==="fill_form"&>.current.playConfirmation();const j=typeof f.formId=="string"?f.formId:null;if(!j){console.warn(`[LiveLayer] ${f.type}: missing formId.`);return}const T=Sn(document,j);if(!T){console.warn(`[LiveLayer] ${f.type}: no <form> matched id="${j}" (or matching name / data-ll-intent slug). Forms are auto-discovered — make sure the form has an \`id\`, \`name\`, or \`data-ll-intent\` attribute the agent observed in PageContext.forms.`);return}if(T.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')){console.warn(`[LiveLayer] ${f.type}: refusing to touch a form in a private / opted-out subtree.`);return}if(f.type==="focus_field"){const O=typeof f.fieldName=="string"?f.fieldName:null;if(!O){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const Y=kn(T,O);if(Y.el===null){Y.reason==="private"?console.warn(`[LiveLayer] focus_field: field "${O}" is privacy-protected and not focusable.`):console.warn(`[LiveLayer] focus_field: no input matching key="${O}" in form "${j}". The agent should use the field.name it observed in PageContext.forms[].fields[].`);return}Y.el.focus();return}const B=f.values&&typeof f.values=="object"?f.values:null;if(!B){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[O,Y]of Object.entries(B)){if(typeof Y!="string")continue;const G=kn(T,O);if(G.el===null){G.reason==="private"?console.warn(`[LiveLayer] fill_form: field "${O}" is privacy-protected (password / cc-* / data-ll-private). Skipping.`):console.warn(`[LiveLayer] fill_form: no input matching key="${O}" in form "${j}". The agent should use the field.name it observed in PageContext.forms[].fields[]. Skipping.`);continue}try{Ci(G.el,Y)}catch($){console.warn(`[LiveLayer] fill_form: failed to set "${O}".`,$)}}return}if(f.type==="submit_form"){if(!xe("submit_forms")){we("submit_form","submit_forms");return}if(typeof document>"u")return;const j=typeof f.formId=="string"?f.formId:null;if(!j){console.warn("[LiveLayer] submit_form: missing formId.");return}gt.current.playConfirmation();const T=Sn(document,j);if(!T){console.warn(`[LiveLayer] submit_form: no <form> matched id="${j}" (or matching name / data-ll-intent slug).`);return}if(T.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private / opted-out subtree.");return}const B=typeof f.requestId=="string"?f.requestId:void 0,O=(Ce=be.current)==null?void 0:Ce.call(be),Y=oe=>{const ue=O,Ue=ue==null?void 0:ue.localParticipant;if(Ue!=null&&Ue.publishData)try{const wr=B?{...oe,requestId:B}:oe,_r=new TextEncoder().encode(JSON.stringify(wr));Ue.publishData(_r,{reliable:!0})}catch{}};let G=!1;const $=()=>{G=!0,Y({type:"form_submitted",formId:j})};T.addEventListener("submit",$,{once:!0});try{typeof T.requestSubmit=="function"?T.requestSubmit():T.submit()}catch(oe){console.warn("[LiveLayer] submit_form: requestSubmit threw.",oe),T.removeEventListener("submit",$),Y({type:"form_submit_blocked",formId:j,reason:"exception"});return}setTimeout(()=>{G||(T.removeEventListener("submit",$),Y({type:"form_submit_blocked",formId:j,reason:"validation"}))},500);return}if(f.type==="request_routes"){if(!xe("read_page")){we("request_routes","read_page");return}const j=typeof f.requestId=="string"?f.requestId:void 0,B=(ot=be.current)==null?void 0:ot.call(be),O=B==null?void 0:B.localParticipant;if(!(O!=null&&O.publishData))return;const Y=$=>{try{const oe=j?{type:"routes",routes:$,requestId:j}:{type:"routes",routes:$},ue=new TextEncoder().encode(JSON.stringify(oe));O.publishData(ue,{reliable:!0})}catch(oe){console.warn("[LiveLayer] request_routes: publishData failed.",oe)}},G=Vt.current;if(G){try{const $=G(),oe=ue=>{if(!Array.isArray(ue)){Y([]);return}Y(ue.map(Qn).slice(0,200))};$ instanceof Promise?$.then(oe).catch(ue=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",ue),Y(_t())}):oe($)}catch($){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",$),Y(_t())}return}try{Y(_t())}catch($){console.warn("[LiveLayer] request_routes: extractRoutes threw.",$)}return}if(f.type==="task_field_updated"){if(!xe("collect_data")){we("task_field_updated","collect_data");return}const j={phase:"field",fieldId:typeof f.fieldId=="string"?f.fieldId:"",fieldName:typeof f.fieldName=="string"?f.fieldName:typeof f.fieldId=="string"?f.fieldId:"",value:typeof f.value=="string"?f.value:"",kind:typeof f.kind=="string"?f.kind:"text",source:f.source==="slide"?"slide":f.source==="page"?"page":"agent",...typeof f.slideId=="string"?{slideId:f.slideId}:{},...typeof f.formId=="string"?{formId:f.formId}:{}};if(typeof document<"u")try{document.dispatchEvent(new CustomEvent("ll-collected",{detail:j}))}catch{}return}if(f.type==="task_completed"){if(!xe("collect_data")){we("task_completed","collect_data");return}const j=f.result;if(!j||typeof j!="object"){console.warn("[LiveLayer] task_completed missing `result` payload.");return}if(typeof document<"u")try{document.dispatchEvent(new CustomEvent("ll-collected",{detail:{phase:"complete",result:j}}))}catch{}try{Me==null||Me(j)}catch(T){console.warn("[LiveLayer] onCollect threw.",T)}return}Ni.has(f.type)||$e==null||$e(f)}},[$e,Ae,Me]),ie=Rn({agentId:D?"__controlled__":Qe,baseUrl:a,apiKey:l,sessionEndpoint:c,sessionBody:s,onDataMessage:D?void 0:rt});n.useEffect(()=>{if(D!=null&&D.subscribeToDataMessages)return D.subscribeToDataMessages(rt)},[D,rt]),be.current=()=>{var b;return(b=ie.getRoom)==null?void 0:b.call(ie)},n.useEffect(()=>{var ee;if(typeof window>"u")return;const b=((ee=window.location)==null?void 0:ee.hostname)||"";if(b==="localhost"||b==="127.0.0.1"||b==="0.0.0.0"||b.endsWith(".local")||b.endsWith(".test"))return window.__livelayerSimulateCommand=ae=>{try{rt(ae)}catch(Ce){console.warn("[LiveLayer] simulate-command threw:",Ce)}},()=>{delete window.__livelayerSimulateCommand}},[rt]);const k=n.useMemo(()=>D?{connectionState:D.connectionState,agentState:D.agentState,transcript:D.transcript,videoElement:D.videoElement,audioElement:D.audioElement,canResume:D.canResume,error:D.error,agentConfig:null,connect:async()=>{await D.onConnect()},disconnect:()=>D.onDisconnect(),getRoom:ie.getRoom,isControlled:!0}:{connectionState:ie.connectionState,agentState:ie.agentState,transcript:ie.transcript,videoElement:ie.videoElement,audioElement:ie.audioElement,canResume:ie.canResume,error:ie.error,agentConfig:ie.agentConfig,connect:ie.connect,disconnect:ie.disconnect,getRoom:ie.getRoom,isControlled:!1},[D,ie]),Yt=n.useRef(k);Yt.current=k;const Gt=n.useRef(D);Gt.current=D,n.useImperativeHandle(i,()=>({sendData:async b=>{var Ce,ot;const f=Gt.current;if(f!=null&&f.publishData){try{await f.publishData(b)}catch(j){console.warn("[AvatarWidget] sendData (controlled) failed:",j)}return}const ee=(ot=(Ce=Yt.current)==null?void 0:Ce.getRoom)==null?void 0:ot.call(Ce),ae=ee==null?void 0:ee.localParticipant;if(ae!=null&&ae.publishData)try{const j=new TextEncoder().encode(JSON.stringify(b));await ae.publishData(j,{reliable:!0})}catch(j){console.warn("[AvatarWidget] sendData failed:",j)}}}),[]);const Xt=n.useRef(null);n.useEffect(()=>{const b=k.videoElement,f=Xt.current;if(!(!b||!f))return f.appendChild(b),()=>{b.parentNode===f&&f.removeChild(b)}},[k.videoElement]);const[Be,yt]=n.useState(!1);n.useEffect(()=>{if(!M){yt(!0);return}k.agentState==="speaking"&&!Be&&yt(!0)},[M,k.agentState,Be]),n.useEffect(()=>{if(!M)return;const b=k.connectionState;(b==="disconnected"||b==="idle")&&yt(!1)},[M,k.connectionState]),n.useEffect(()=>{if(!M||!k.videoElement||Be)return;const b=setTimeout(()=>yt(!0),5e3);return()=>clearTimeout(b)},[M,k.videoElement,Be]),n.useEffect(()=>{const b=k.videoElement;if(b){if(!M){b.style.filter="";return}b.style.transition="filter 500ms ease-out",b.style.filter=Be?"":"blur(8px)"}},[M,k.videoElement,Be]),n.useEffect(()=>{const b=k.audioElement;if(!b)return;const f=document.createElement("div");f.className="ll-audio-sink",f.setAttribute("aria-hidden","true"),f.style.cssText="position:absolute;width:0;height:0;overflow:hidden;clip:rect(0 0 0 0);pointer-events:none;",f.appendChild(b),document.body.appendChild(f),Le.attach(b);const ee=b.play();return ee&&typeof ee.catch=="function"&&ee.catch(ae=>{(ae==null?void 0:ae.name)==="NotAllowedError"&&We(!0)}),()=>{Le.detach(),b.parentNode===f&&f.removeChild(b),f.parentNode===document.body&&document.body.removeChild(f)}},[k.audioElement]);const he=An({gateUntilAgentReady:!0,agentState:k.agentState});n.useEffect(()=>{if(k.isControlled||k.connectionState!=="connected")return;const b=k.getRoom();if(b)return he.setupMic(b).then(()=>{const f=he.getMicStream();f&&Le.attachStream(f,"mic")}).catch(()=>{}),()=>{Le.detachSlot("mic"),he.teardownMic()}},[k.isControlled,k.connectionState]),n.useEffect(()=>{var f;if(k.connectionState!=="connected")return;const b=k.isControlled?(f=D==null?void 0:D.getRoom)==null?void 0:f.call(D):k.getRoom();if(b)return _e.attachRoom(b),pe.attachRoom(b),k.isControlled&&he.attachRoom(b),ve.refresh(),()=>{_e.teardown(),pe.teardown()}},[k.isControlled,k.connectionState,D]),n.useEffect(()=>{const b=k.audioElement;b&&(b.muted=Rt)},[k.audioElement,Rt]);const lr=n.useCallback(b=>{const f={type:"user_message",text:b};if(D!=null&&D.publishData){try{D.publishData(f)}catch{}return}const ee=k.getRoom();if(ee)try{const ae=new TextEncoder().encode(JSON.stringify(f));ee.localParticipant.publishData(ae,{reliable:!0})}catch{}},[k,D]),cr=n.useCallback(()=>{ar(b=>!b)},[]);n.useEffect(()=>{Ne==null||Ne(k.connectionState),k.connectionState==="connected"?ze==null||ze():k.connectionState==="disconnected"&&(Ee==null||Ee())},[k.connectionState,ze,Ee,Ne]),n.useEffect(()=>{je==null||je(k.transcript)},[k.transcript,je]),n.useEffect(()=>{Re==null||Re(k.agentState)},[k.agentState,Re]),n.useEffect(()=>{mt.setThinking(k.agentState==="thinking")},[k.agentState,mt]);const Kt=n.useRef(!1);n.useEffect(()=>{!x||Kt.current||Te&&k.connectionState==="idle"&&(Kt.current=!0,k.connect())},[x,k.connectionState,k,Te]);const ur=n.useCallback(b=>{const f=v==null?void 0:v.find(ee=>ee.id===b);f&&(Q(!1),b!==Pe&&(nt(!0),k.disconnect(),ke||ft(b),g==null||g(f)))},[v,Pe,k,ke,g]);n.useEffect(()=>{tt&&k.connectionState==="connected"&&nt(!1)},[k.connectionState,tt]),n.useEffect(()=>{if(!_)return;const b=f=>{f.key==="Escape"&&Q(!1)};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[_]);const dr=!!V||!!(se!=null&&se.avatarImageUrl)||k.isControlled,it=Pn(Qe,a,dr);De===void 0&&((en=it.info)!=null&&en.capabilities)&&(Tt.current=it.info.capabilities);const vt=(se==null?void 0:se.name)??re??((tn=k.agentConfig)==null?void 0:tn.name)??((nn=it.info)==null?void 0:nn.name)??"Live Layer",Pt=(se==null?void 0:se.avatarImageUrl)??V??((rn=k.agentConfig)==null?void 0:rn.avatarImageUrl)??((on=it.info)==null?void 0:on.avatarImageUrl)??null,fr=A??((sn=k.agentConfig)==null?void 0:sn.idleLoopUrl)??((an=it.info)==null?void 0:an.idleLoopUrl)??null,pr=z??null,hr=n.useCallback(()=>ye("expanded"),[ye]),mr=n.useCallback(()=>ye("minimized"),[ye]),Jt=n.useCallback(()=>{k.disconnect(),ye("hidden")},[k,ye]),gr=n.useCallback(()=>{const b=k.audioElement;b&&b.play().then(()=>We(!1)).catch(()=>{})},[k.audioElement]),yr=n.useCallback(()=>{We(!1),k.connect()},[k]),qe={...He,...ne?{}:{zIndex:ge}};I.primaryColor&&(qe["--ll-color-primary"]=I.primaryColor),I.accentColor&&(qe["--ll-color-accent"]=I.accentColor),I.backgroundColor&&(qe["--ll-color-bg"]=I.backgroundColor),I.textColor&&(qe["--ll-color-fg"]=I.textColor);const vr={...qe,...Se.style},br=["ll-widget",`ll-widget--${fe}`,`ll-widget--${ce?"mobile":"desktop"}`,Se.hasGeometry?"ll-widget--has-geometry":null,Se.isDragging?"is-dragging":null,Se.isResizing?"is-resizing":null,Ie].filter(Boolean).join(" ");if(!Te)return null;const xr=t.jsx("div",{className:br,style:vr,"data-display-mode":fe,"data-position":C,"data-experience-mode":d==="EMBEDDED"?"embedded":"widget",children:fe==="expanded"&&t.jsx(ii,{position:C,isMobile:ce,agentName:vt,avatarImageUrl:Pt,idleLoopUrl:fr,greeting:pr,branding:I,teamMembers:v,currentTeamMemberId:Pe,isSwitchingTeamMember:tt,teamSwitcherOpen:_,onToggleTeamSwitcher:()=>Q(b=>!b),onSelectTeamMember:ur,connectionState:k.connectionState,agentState:k.agentState,transcript:k.transcript,isMuted:he.isMuted,micDevices:ve.mics,activeMicId:he.activeDeviceId,isCameraEnabled:_e.isEnabled,cameraPreviewEl:_e.previewEl,cameraDevices:ve.cameras,activeCameraId:_e.activeDeviceId,isScreenShareEnabled:pe.isEnabled,screenPreviewEl:pe.previewEl,isSpeakerMuted:Rt,allowCamera:q,allowScreenShare:p,allowTyping:E,showMinimize:ce&&!ne?!1:pt,showClose:Lt,chromeless:K,compactControls:Et,transforming:te,transformingLabel:F,languageMenuOpen:or,onToggleLanguageMenu:()=>sr(b=>!b),needsUserGesture:ht,canResume:k.canResume,micError:he.micError,error:k.error,avatarVideoContainerRef:Xt,agentVideoEl:k.videoElement,onConnect:()=>void k.connect(),onDisconnect:()=>k.disconnect(),onRetry:yr,onResumeAudio:gr,onToggleMute:he.toggleMute,onSwitchMicDevice:b=>void he.switchDevice(b),onToggleCamera:()=>void _e.toggle(),onSwitchCameraDevice:b=>void _e.switchDevice(b),onToggleScreenShare:()=>void pe.toggle(),onToggleSpeaker:cr,onSendMessage:lr,onMinimize:mr,onClose:Jt,onClearMicError:he.clearError,dragHandleProps:Se.dragHandleProps,resizeHandleProps:Se.resizeHandleProps})}),Zt=!ne&&(fe==="hidden"||fe==="minimized")?t.jsxs("div",{className:["ll-widget","ll-widget--floating",`ll-widget--${fe}`,`ll-widget--${ce?"mobile":"desktop"}`].join(" "),style:qe,"data-display-mode":fe,"data-position":C,children:[fe==="hidden"&&t.jsx(Yr,{position:C,isMobile:ce,isSpeaking:k.agentState==="speaking",onExpand:()=>ye("expanded"),label:`Open ${vt} widget`,avatarImageUrl:Pt,agentName:vt,containerEl:W}),fe==="minimized"&&t.jsx(Xr,{position:C,isMobile:ce,agentName:vt,avatarImageUrl:Pt,agentState:k.agentState,isMuted:he.isMuted,audioLevel:Le,onExpand:hr,onToggleMute:he.toggleMute,onClose:Jt})]}):null,Qt=W??(typeof document<"u"?document.body:null);return t.jsxs(t.Fragment,{children:[xr,Zt&&Qt&&Wt.createPortal(Zt,Qt)]})});nr.displayName="AvatarWidgetInner";const rr=n.forwardRef(function(r,i){return t.jsx(jn,{children:t.jsx(nr,{...r,ref:i})})});rr.displayName="AvatarWidget";const Ai=({agentId:e,baseUrl:r,apiKey:i,mode:o,onAgentEvent:l,className:a,style:c})=>{const s=n.useRef(null),u=n.useRef(null),d=n.useRef(l);d.current=l;const x=n.useCallback(h=>{var N;const m=h.detail;(N=d.current)==null||N.call(d,m)},[]);return n.useEffect(()=>{const h=s.current;if(!h)return;const m=document.createElement("livelayer-widget");return m.setAttribute("agent-id",e),r&&m.setAttribute("base-url",r),i&&m.setAttribute("api-key",i),o&&m.setAttribute("mode",o),m.addEventListener("agent-event",x),h.appendChild(m),u.current=m,()=>{m.removeEventListener("agent-event",x),h.removeChild(m),u.current=null}},[e]),n.useEffect(()=>{u.current&&(o?u.current.setAttribute("mode",o):u.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:s,className:a,style:c})},Mi=n.forwardRef(function({id:r,intent:i,as:o="div",className:l,style:a,children:c},s){return n.createElement(o,{ref:s,"data-ll-region":r,"data-ll-intent":i,className:l,style:a},c)});function Ii(e={}){const{onFieldUpdate:r,onComplete:i,source:o="all"}=e,[l,a]=n.useState({}),[c,s]=n.useState(!1),[u,d]=n.useState(null),x=n.useRef(r),h=n.useRef(i),m=n.useRef(o);n.useEffect(()=>{x.current=r,h.current=i,m.current=o},[r,i,o]);const N=n.useCallback(()=>{a({}),s(!1)},[]);return n.useEffect(()=>{if(typeof window>"u")return;const C=L=>{var w,R;const y=L.detail;if(y){if(y.phase==="field"){if(m.current!=="all"&&y.source!==m.current)return;s(!0),a(S=>S[y.fieldName]===y.value?S:{...S,[y.fieldName]:y.value});try{(w=x.current)==null||w.call(x,y)}catch(S){console.warn("[LiveLayer] useCollect onFieldUpdate threw.",S)}return}if(y.phase==="complete"){const S=y.result;if(m.current!=="all"&&S.source!==m.current)return;d(S),s(!1);try{(R=h.current)==null||R.call(h,S)}catch(v){console.warn("[LiveLayer] useCollect onComplete threw.",v)}}}};return document.addEventListener("ll-collected",C),()=>document.removeEventListener("ll-collected",C)},[]),{fields:l,isCollecting:c,lastResult:u,reset:N}}let En=1;function Ti({onMount:e,defaultOpen:r=!1,storageKey:i="ll-debug-open"}){const[o,l]=n.useState(r),[a,c]=n.useState([]),[s,u]=n.useState(""),[d,x]=n.useState(!1),h=n.useRef(new Set),m=n.useRef([]),N=n.useRef(d);N.current=d,n.useEffect(()=>{try{const y=localStorage.getItem(i);y==="1"&&l(!0),y==="0"&&l(!1)}catch{}},[i]),n.useEffect(()=>{try{localStorage.setItem(i,o?"1":"0")}catch{}},[o,i]),n.useEffect(()=>{const y=w=>{(w.metaKey||w.ctrlKey)&&w.shiftKey&&w.key.toLowerCase()==="l"&&(w.preventDefault(),l(R=>!R))};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[]),n.useEffect(()=>{const y=setInterval(()=>{if(m.current.length===0||N.current)return;const w=m.current.splice(0,m.current.length);c(R=>[...w.reverse(),...R].slice(0,200))},100);return()=>clearInterval(y)},[]);const C=n.useRef(!1);if(n.useEffect(()=>{!e||C.current||(C.current=!0,e(y=>{m.current.push({id:En++,ts:Date.now(),kind:"event",type:y.eventName,data:y.data})}))},[e]),n.useEffect(()=>{const y=console.warn,w=console.log,R=(S,v)=>function(...P){try{const g=typeof P[0]=="string"?P[0]:"";g.startsWith("[LiveLayer]")&&m.current.push({id:En++,ts:Date.now(),kind:S,type:g.slice(0,120),data:{args:P.slice(1).map(A=>Di(A))}})}catch{}return v.apply(this,P)};return console.warn=R("warn",y),console.log=R("log",w),()=>{console.warn=y,console.log=w}},[]),!o)return t.jsx("button",{type:"button",onClick:()=>l(!0),title:"Open LiveLayer debug panel (Cmd/Ctrl + Shift + L)","aria-label":"Open LiveLayer debug panel",style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.18)",borderRadius:999,padding:"6px 10px",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",cursor:"pointer",boxShadow:"0 4px 12px rgba(0,0,0,0.35)",opacity:.85},children:"🛰 LL debug"});const L=a.filter(y=>{if(!s)return!0;const w=s.toLowerCase();return y.type.toLowerCase().includes(w)||JSON.stringify(y.data||{}).toLowerCase().includes(w)});return t.jsxs("div",{style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,width:380,maxHeight:"60vh",background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:12,boxShadow:"0 16px 48px rgba(0,0,0,0.5)",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"8px 10px",background:"rgba(255,255,255,0.04)",borderBottom:"1px solid rgba(255,255,255,0.1)",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontWeight:600,fontSize:12},children:"LiveLayer debug"}),t.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:[a.length," event",a.length===1?"":"s"]}),t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:()=>x(y=>!y),style:Ht(d?"#f59e0b":"transparent"),title:"Pause / resume capture",children:d?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{c([]),m.current=[]},style:Ht("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>l(!1),style:Ht("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:s,onChange:y=>u(y.target.value),placeholder:"filter by type or data…",style:{margin:8,padding:"6px 8px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,outline:"none"}}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"0 8px 8px"},children:L.length===0?t.jsxs("div",{style:{padding:14,fontSize:11,color:"rgba(255,255,255,0.4)",lineHeight:1.5},children:["No events yet. Connect to the agent and trigger a tool call — the events will stream in here. You can also dispatch commands manually in DevTools:",t.jsx("pre",{style:{marginTop:6,background:"rgba(255,255,255,0.04)",padding:6,borderRadius:4,fontSize:10,whiteSpace:"pre-wrap"},children:`window.__livelayerSimulateCommand({
|
|
1
|
+
"use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),r=require("react"),Ut=require("react-dom"),Ke=require("@livelayer/sdk"),kt=require("livekit-client");class Nn extends r.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,i){var o,a;(a=(o=this.props).onError)==null||a.call(o,n,i)}render(){var n;return this.state.hasError?this.props.fallback?this.props.fallback:t.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[t.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),t.jsx("p",{className:"ll-error-boundary__message",children:((n=this.state.error)==null?void 0:n.message)||"Something went wrong."}),t.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function An(e){const[n,i]=r.useState("idle"),[o,a]=r.useState("idle"),[s,c]=r.useState([]),[l,u]=r.useState(null),[d,g]=r.useState(null),[h,m]=r.useState(null),[N,C]=r.useState(!1),[L,b]=r.useState(null),w=r.useRef(null),R=r.useRef(e.onDataMessage);R.current=e.onDataMessage,r.useEffect(()=>{const y={onConnectionStateChange:z=>{i(z),z==="connected"&&b(null)},onAgentStateChange:a,onTranscript:z=>c([...z]),onAgentConfig:u,onAudioTrack:z=>m(z),onVideoTrack:z=>g(z),onVideoTrackRemoved:()=>g(null),onError:z=>b(z),onDataMessage:z=>{var V;(V=R.current)==null||V.call(R,z)},onResumabilityChange:C},A=new Ke.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},y);return w.current=A,i("idle"),a("idle"),c([]),u(null),g(null),m(null),C(!1),b(null),()=>{var z;(z=A.destroy)==null||z.call(A),w.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const S=r.useCallback(async()=>{const y=w.current;if(y)try{await y.connect()}catch(A){throw b(A instanceof Error?A.message:String(A)),A}},[]),v=r.useCallback(()=>{const y=w.current;y&&y.disconnect()},[]),P=r.useCallback(()=>{var y;return((y=w.current)==null?void 0:y.getRoom())??null},[]);return{connectionState:n,agentState:o,transcript:s,agentConfig:l,videoElement:d,audioElement:h,canResume:N,error:L,connect:S,disconnect:v,getRoom:P,session:w.current}}function Mn(){const e=r.useRef(null),n=r.useRef(new Map),i=r.useRef(null),o=r.useRef(new Set),a=r.useCallback(()=>{const C=n.current;if(C.size===0){i.current=null;return}let L=0;for(const{analyser:b,buffer:w}of C.values()){b.getByteFrequencyData(w);let R=0;for(let v=0;v<w.length;v++)R+=w[v];const S=R/w.length/255;S>L&&(L=S)}for(const b of o.current)try{b(L)}catch(w){console.error("[useAudioLevel] subscriber threw:",w)}i.current=requestAnimationFrame(a)},[]),s=r.useCallback(()=>e.current?e.current:typeof window>"u"||typeof AudioContext>"u"?null:(e.current=new AudioContext,e.current),[]),c=r.useCallback(()=>{i.current===null&&n.current.size>0&&(i.current=requestAnimationFrame(a))},[a]),l=r.useCallback(C=>{const L=n.current.get(C);if(L){try{L.node.disconnect()}catch{}try{L.analyser.disconnect()}catch{}n.current.delete(C)}},[]),u=r.useCallback((C,L)=>{const b=s();if(!b)return;l(C);const w=L(b);if(!w)return;const R=b.createAnalyser();R.fftSize=64;try{w.connect(R)}catch(S){console.warn("[useAudioLevel] connect failed for slot",C,S);return}n.current.set(C,{analyser:R,node:w,buffer:new Uint8Array(new ArrayBuffer(R.frequencyBinCount))}),c()},[l,s,c]),d=r.useCallback((C,L="agent")=>{u(L,b=>{try{return b.createMediaElementSource(C)}catch(w){return console.warn("[useAudioLevel] createMediaElementSource failed for slot",L,w),null}})},[u]),g=r.useCallback((C,L="mic")=>{u(L,b=>{try{return b.createMediaStreamSource(C)}catch(w){return console.warn("[useAudioLevel] createMediaStreamSource failed for slot",L,w),null}})},[u]),h=r.useCallback(C=>{l(C),n.current.size===0&&i.current!==null&&(cancelAnimationFrame(i.current),i.current=null)},[l]),m=r.useCallback(()=>{i.current!==null&&(cancelAnimationFrame(i.current),i.current=null);for(const C of Array.from(n.current.keys()))l(C)},[l]),N=r.useCallback(C=>(o.current.add(C),()=>{o.current.delete(C)}),[]);return r.useEffect(()=>()=>{if(m(),e.current){try{e.current.close()}catch{}e.current=null}o.current.clear()},[m]),{attach:d,attachStream:g,detach:m,detachSlot:h,subscribe:N}}function Sr(e){const n=e==null?void 0:e.mediaStreamTrack;return n?new MediaStream([n]):null}function In(e={}){const n=e.gateUntilAgentReady??!1,i=e.agentState??null,[o,a]=r.useState(n),[s,c]=r.useState(""),[l,u]=r.useState(null),d=r.useRef(null),g=r.useRef(null),h=r.useRef({active:n,lastAutoIntent:null}),m=r.useCallback(async S=>{var v,P;if(d.current&&g.current){try{await g.current.localParticipant.unpublishTrack(d.current)}catch{}d.current.stop(),d.current=null}g.current=S,u(null);try{const y=await kt.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await S.localParticipant.publishTrack(y),d.current=y,h.current.active?(await S.localParticipant.setMicrophoneEnabled(!1),h.current.lastAutoIntent=!1,a(!0)):a(y.isMuted);const A=(P=(v=y.mediaStreamTrack)==null?void 0:v.getSettings)==null?void 0:P.call(v);A!=null&&A.deviceId&&c(A.deviceId)}catch(y){const A=y instanceof Error&&y.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw u(A),y}},[]),N=r.useCallback(S=>{g.current=S},[]),C=r.useCallback(async S=>{const v=g.current;if(v)try{await v.switchActiveDevice("audioinput",S),c(S)}catch(P){console.warn("[useMicrophoneState] switchDevice failed:",P)}},[]),L=r.useCallback(async()=>{const S=g.current,v=!o;if(a(v),h.current.active=!1,!!S)try{await S.localParticipant.setMicrophoneEnabled(!v)}catch(P){console.warn("[useMicrophoneState] setMicrophoneEnabled failed:",P),a(!v)}},[o]);r.useEffect(()=>{if(!h.current.active||i!=="listening")return;const S=g.current,v=S==null?void 0:S.localParticipant;if(!v){h.current.active=!1;return}v.isMicrophoneEnabled===h.current.lastAutoIntent&&(v.setMicrophoneEnabled(!0),h.current.lastAutoIntent=!0,a(!1)),h.current.active=!1},[i]);const b=r.useCallback(()=>{const S=d.current,v=g.current;if(S&&v){try{v.localParticipant.unpublishTrack(S)}catch{}S.stop()}d.current=null,g.current=null,h.current={active:n,lastAutoIntent:null},a(n),c("")},[n]),w=r.useCallback(()=>u(null),[]),R=r.useCallback(()=>Sr(d.current),[]);return{isMuted:o,activeDeviceId:s,micError:l,toggleMute:L,setupMic:m,attachRoom:N,switchDevice:C,teardownMic:b,clearError:w,getMicStream:R}}const Lr={resolution:{width:640,height:480,frameRate:24}};function Tn(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[a,s]=r.useState(null),[c,l]=r.useState(""),u=r.useRef(null),d=r.useRef(null),g=r.useCallback(w=>{u.current=w},[]),h=r.useCallback(()=>{var S;const w=u.current,R=d.current;if(R&&w){const v=w.localParticipant.getTrackPublication(kt.Track.Source.Camera),y=(v==null?void 0:v.track)??R;try{w.localParticipant.unpublishTrack(y)}catch{}try{(S=y.stop)==null||S.call(y)}catch{}}d.current=null,s(null),n(!1)},[]),m=r.useCallback(async w=>{const R=u.current;if(R){o(null);try{const S={...Lr};w&&(S.deviceId=w);const v=await kt.createLocalVideoTrack(S);await R.localParticipant.publishTrack(v),d.current=v;const P=v.attach();s(P),n(!0),w&&l(w);try{R.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(S){const v=S instanceof Error&&S.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";o(v)}}},[]),N=r.useCallback(async()=>{e?h():await m(c||void 0)},[e,c,h,m]),C=r.useCallback(async w=>{h(),await m(w)},[h,m]),L=r.useCallback(()=>{h(),u.current=null,o(null),l("")},[h]),b=r.useCallback(()=>o(null),[]);return r.useEffect(()=>()=>{d.current&&d.current.stop()},[]),{isEnabled:e,error:i,previewEl:a,activeDeviceId:c,toggle:N,switchDevice:C,attachRoom:g,teardown:L,clearError:b}}function Pn(){const[e,n]=r.useState(!1),[i,o]=r.useState(null),[a,s]=r.useState(null),c=r.useRef(null),l=r.useCallback(m=>{c.current=m},[]),u=r.useCallback(()=>s(null),[]),d=r.useCallback(async()=>{const m=c.current;if(m){if(e){try{await m.localParticipant.setScreenShareEnabled(!1)}catch{}u(),n(!1);return}o(null);try{await m.localParticipant.setScreenShareEnabled(!0);let N=0;const C=()=>{const L=m.localParticipant.getTrackPublication(kt.Track.Source.ScreenShare);if(L!=null&&L.track){const b=L.track.attach();s(b),n(!0);try{m.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}N++<10?setTimeout(C,100):n(!0)};C()}catch(N){const C=N instanceof Error?N.name:"";C!=="NotAllowedError"&&C!=="AbortError"&&o("Screen share unavailable. Try again."),n(!1)}}},[e,u]),g=r.useCallback(()=>{const m=c.current;if(m&&e)try{m.localParticipant.setScreenShareEnabled(!1)}catch{}u(),n(!1),o(null),c.current=null},[e,u]),h=r.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:a,toggle:d,attachRoom:l,teardown:g,clearError:h}}function Dn(){const[e,n]=r.useState([]),[i,o]=r.useState([]),a=r.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const s=await navigator.mediaDevices.enumerateDevices();n(s.filter(c=>c.kind==="audioinput")),o(s.filter(c=>c.kind==="videoinput"))}catch{}},[]);return r.useEffect(()=>{if(a(),typeof navigator>"u"||!navigator.mediaDevices)return;const s=()=>void a();return navigator.mediaDevices.addEventListener("devicechange",s),()=>navigator.mediaDevices.removeEventListener("devicechange",s)},[a]),{mics:e,cameras:i,refresh:a}}function zn(e,n,i=!1){const[o,a]=r.useState(null),[s,c]=r.useState(null),[l,u]=r.useState(!i&&!!e);return r.useEffect(()=>{if(i||!e){u(!1);return}const d=new AbortController,g=n||"https://app.livelayer.studio";return u(!0),c(null),fetch(`${g}/api/widget/agent/${encodeURIComponent(e)}`,{signal:d.signal}).then(async h=>{if(!h.ok){const m=await h.json().catch(()=>({}));throw new Error(m.error||`HTTP ${h.status}`)}return h.json()}).then(h=>{d.signal.aborted||(a(h),u(!1))}).catch(h=>{d.signal.aborted||(c(h instanceof Error?h.message:"Agent lookup failed"),u(!1))}),()=>d.abort()},[e,n,i]),{info:o,error:s,loading:l}}function $n(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function Hn(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n)}catch{}}function Er(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch{}}function Fn({value:e,defaultValue:n="expanded",onChange:i}={}){const o=e!==void 0,[a,s]=r.useState(n),c=o?e:a,l=r.useCallback(u=>{u!==c&&(o||s(u),i==null||i(u))},[c,o,i]);return[c,l]}const jr=["hidden","minimized","expanded"];function Rr(e){return e&&jr.includes(e)?e:null}function On({value:e,defaultValue:n="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:a=!1}={}){const s=`${o}:display-mode`,c=r.useRef(!1),[l,u]=Fn({value:e,defaultValue:n,onChange:d=>{e===void 0&&!a&&Hn(s,d),i==null||i(d)}});return r.useEffect(()=>{if(c.current||(c.current=!0,a||e!==void 0))return;const d=Rr($n(s));d&&d!==l&&u(d)},[]),[l,u]}const Nr=640;function Wn(e=Nr){const[n,i]=r.useState(!1);return r.useEffect(()=>{if(e===!1){i(!1);return}if(typeof window>"u"||typeof window.matchMedia>"u")return;const o=`(max-width: ${e-1}px)`,a=window.matchMedia(o),s=()=>i(a.matches);return s(),typeof a.addEventListener=="function"?(a.addEventListener("change",s),()=>a.removeEventListener("change",s)):(a.addListener(s),()=>{a.removeListener(s)})},[e]),n}const Ar=280,Mr=380,Ir=8,Tr=4;function zt(e){return`${e}:geometry`}function Pr(e){if(!e)return null;let n;try{n=JSON.parse(e)}catch{return null}if(typeof n!="object"||n===null)return null;const i=n,{top:o,left:a,width:s,height:c}=i;return typeof o!="number"||typeof a!="number"||typeof s!="number"||typeof c!="number"||!Number.isFinite(o)||!Number.isFinite(a)||!Number.isFinite(s)||!Number.isFinite(c)?null:{top:o,left:a,width:s,height:c}}function xt(){return typeof window>"u"?{vw:0,vh:0}:{vw:window.innerWidth,vh:window.innerHeight}}function $t(e,n,i){const{minWidth:o,minHeight:a,edgeMargin:s,vw:c,vh:l}=i,u=Math.max(o,c-s*2),d=Math.max(a,l-s*2);return{width:Math.max(o,Math.min(u,e)),height:Math.max(a,Math.min(d,n))}}function Ht(e,n,i,o,a){const{edgeMargin:s,vw:c,vh:l}=a,u=s,d=s,g=Math.max(u,c-i-s),h=Math.max(d,l-o-s);return{top:Math.max(d,Math.min(h,e)),left:Math.max(u,Math.min(g,n))}}function Dr(e){const{draggable:n,resizable:i,persistKey:o,disablePersistence:a,minWidth:s=Ar,minHeight:c=Mr,edgeMargin:l=Ir}=e,[u,d]=r.useState(null),[g,h]=r.useState(!1),[m,N]=r.useState(!1),C=r.useRef(null),L=r.useRef(null),b=r.useRef(!1),w=r.useRef(null);w.current=u;const R=r.useCallback(p=>{a||(p===null?Er(zt(o)):Hn(zt(o),JSON.stringify(p)))},[a,o]);r.useEffect(()=>{if(b.current||(b.current=!0,a))return;const p=Pr($n(zt(o)));if(!p)return;const{vw:E,vh:M}=xt(),H=$t(p.width,p.height,{minWidth:s,minHeight:c,edgeMargin:l,vw:E,vh:M}),U=Ht(p.top,p.left,H.width,H.height,{edgeMargin:l,vw:E,vh:M});d({...U,...H})},[]),r.useEffect(()=>{if(typeof window>"u")return;const p=()=>{d(E=>{if(E===null)return null;const{vw:M,vh:H}=xt(),U=$t(E.width,E.height,{minWidth:s,minHeight:c,edgeMargin:l,vw:M,vh:H});return{...Ht(E.top,E.left,U.width,U.height,{edgeMargin:l,vw:M,vh:H}),...U}})};return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[s,c,l]);const S=r.useCallback(p=>{if(!n||p.pointerType==="mouse"&&p.button!==0)return;const E=p.target;if(E&&typeof E.closest=="function"&&E.closest('button, a, input, select, textarea, [role="listbox"], [role="option"], [data-ll-no-drag]'))return;let M,H,U,K;const W=w.current;if(W)({top:M,left:H,width:U,height:K}=W);else{const J=p.currentTarget.closest(".ll-widget"),te=J==null?void 0:J.getBoundingClientRect();if(!te)return;M=te.top,H=te.left,U=te.width,K=te.height}try{p.currentTarget.setPointerCapture(p.pointerId)}catch{}C.current={startClientX:p.clientX,startClientY:p.clientY,startTop:M,startLeft:H,width:U,height:K,moved:!1}},[n]),v=r.useCallback(p=>{const E=C.current;if(!E)return;const M=p.clientX-E.startClientX,H=p.clientY-E.startClientY;if(!E.moved&&Math.abs(M)+Math.abs(H)>Tr&&(E.moved=!0,h(!0)),!E.moved)return;const{vw:U,vh:K}=xt(),W=Ht(E.startTop+H,E.startLeft+M,E.width,E.height,{edgeMargin:l,vw:U,vh:K});d({...W,width:E.width,height:E.height})},[l]),P=r.useCallback(p=>{const E=C.current;if(E){try{p.currentTarget.releasePointerCapture(p.pointerId)}catch{}C.current=null,E.moved&&(h(!1),d(M=>(M&&R(M),M)))}},[R]),y=r.useCallback(()=>{C.current=null,L.current=null,h(!1),N(!1),d(null),R(null)},[R]),A=r.useCallback(p=>{if(!i||p.pointerType==="mouse"&&p.button!==0)return;p.stopPropagation();let E,M,H,U;const K=w.current;if(K)({top:E,left:M,width:H,height:U}=K);else{const W=p.currentTarget.closest(".ll-widget"),J=W==null?void 0:W.getBoundingClientRect();if(!J)return;E=J.top,M=J.left,H=J.width,U=J.height}try{p.currentTarget.setPointerCapture(p.pointerId)}catch{}L.current={startClientX:p.clientX,startClientY:p.clientY,startWidth:H,startHeight:U,top:E,left:M},N(!0)},[i]),z=r.useCallback(p=>{const E=L.current;if(!E)return;const M=p.clientX-E.startClientX,H=p.clientY-E.startClientY,{vw:U,vh:K}=xt(),W=U-E.left-l,J=K-E.top-l,te=$t(E.startWidth+M,E.startHeight+H,{minWidth:s,minHeight:c,edgeMargin:l,vw:Math.min(U,E.left+W+l),vh:Math.min(K,E.top+J+l)});d({top:E.top,left:E.left,...te})},[l,s,c]),V=r.useCallback(p=>{if(L.current){try{p.currentTarget.releasePointerCapture(p.pointerId)}catch{}L.current=null,N(!1),d(M=>(M&&R(M),M))}},[R]);return{style:u===null?{}:{position:"fixed",top:`${u.top}px`,left:`${u.left}px`,right:"auto",bottom:"auto",width:`${u.width}px`,height:`${u.height}px`},hasGeometry:u!==null,isDragging:g,isResizing:m,dragHandleProps:{onPointerDown:S,onPointerMove:v,onPointerUp:P,onPointerCancel:P,onDoubleClick:y,"data-ll-drag-handle":n?"":void 0},resizeHandleProps:{onPointerDown:A,onPointerMove:z,onPointerUp:V,onPointerCancel:V,"data-ll-resize-handle":i?"":void 0},reset:y}}const dn="__llHistoryPatched",St="ll:pathname";function zr(){if(typeof window>"u"||window.history[dn])return;const e=window.history.pushState,n=window.history.replaceState;window.history.pushState=function(...i){const o=e.apply(this,i);return window.dispatchEvent(new Event(St)),o},window.history.replaceState=function(...i){const o=n.apply(this,i);return window.dispatchEvent(new Event(St)),o},window.history[dn]=!0}function fn(){return typeof window>"u"?"/":window.location.pathname||"/"}function Bn(e){const[n,i]=r.useState(()=>e??fn());return r.useEffect(()=>{if(e!==void 0)return;zr();const o=()=>i(fn());return o(),window.addEventListener("popstate",o),window.addEventListener(St,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(St,o)}},[e]),e??n}const pn=new Map,$r=/[\\^$+?.()|{}[\]]/g;function Hr(e){return e.replace($r,"\\$&")}function Fr(e){const n=pn.get(e);if(n)return n;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",a="",s=i.replace(/\*\*/g,o).replace(/\*/g,a),l=Hr(s).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(a,"g"),"[^/]+"),u=new RegExp(`^${l}\\/?$`);return pn.set(e,u),u}function Or(e,n){const i=n.length>1&&n.endsWith("/")?n.slice(0,-1):n;return Fr(e).test(i)}function qn(e,n){return typeof e=="function"?e(n):e instanceof RegExp?e.test(n):Or(e,n)}function hn(e,n){if(!e||e.length===0)return!1;for(const i of e)if(qn(i,n))return!0;return!1}function Un(e,n,i){return e===void 0?!0:hn(i,e)?!1:n&&n.length>0?hn(n,e):!0}function Vn(e,n,i){return r.useMemo(()=>Un(e,n,i),[e,n,i])}function Wr(e){return e===!1?{navigate:!1,thinking:!1,action:!1}:e===void 0||e===!0?{navigate:!0,thinking:!0,action:!0}:{navigate:e.navigate!==!1,thinking:e.thinking!==!1,action:e.action!==!1}}function Br(e){const n=r.useMemo(()=>Wr(e.config),[e.config]),i=e.baseUrl.replace(/\/+$/,""),o=r.useRef(null),a=r.useCallback(u=>{try{new Audio(`${i}${u}`).play().catch(()=>{})}catch{}},[i]),s=r.useCallback(()=>{n.navigate&&a("/audio/page-change-sound.mp3")},[n.navigate,a]),c=r.useCallback(()=>{n.action&&a("/audio/confirmation-sound.mp3")},[n.action,a]),l=r.useCallback(u=>{if(!n.thinking){if(o.current){try{o.current.pause()}catch{}o.current=null}return}if(u){if(o.current)return;try{const d=new Audio(`${i}/audio/thinking-sound.mp3`);d.loop=!0,d.volume=.3,d.play().catch(()=>{o.current=null}),o.current=d}catch{}}else if(o.current){try{o.current.pause()}catch{}o.current=null}},[i,n.thinking]);return r.useEffect(()=>()=>{if(o.current){try{o.current.pause()}catch{}o.current=null}},[]),r.useMemo(()=>({playPageChange:s,playConfirmation:c,setThinking:l}),[s,c,l])}const mn=({muted:e=!1,className:n})=>e?t.jsxs("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"}),t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4M12 1a3 3 0 00-3 3v4a3 3 0 006 0V4a3 3 0 00-3-3z"})}),gn=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})}),qr=({className:e})=>t.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),Ur={left:180,right:0,up:-90,down:90},yn=({direction:e="right",className:n})=>t.jsx("svg",{className:n,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${Ur[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function Vr(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const Yn="ll-hidden-tab-center-y",Yr=5,bn=16;function Gr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(Yn);if(!e)return null;const n=Number.parseFloat(e);return Number.isFinite(n)?n:null}catch{return null}}function vn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Yn,String(e))}catch{}}const Xr=({position:e,isMobile:n,isSpeaking:i,onExpand:o,label:a="Open widget",avatarImageUrl:s,agentName:c,containerEl:l})=>{const u=Vr(e),d=u==="right"?"left":"right",g=n?80:72,h=!!s,m=!!l,[N,C]=r.useState(null),[L,b]=r.useState(!1),w=r.useRef(null),R=r.useRef(!1),S=r.useCallback(I=>{if(typeof window>"u")return I;const q=g/2,p=bn+q,E=window.innerHeight-bn-q;return E<p?Math.max(p,I):Math.max(p,Math.min(E,I))},[g]);r.useEffect(()=>{if(m){C(null);return}const I=Gr();C(S(I??window.innerHeight/2));const q=()=>{C(p=>p===null?null:S(p))};return window.addEventListener("resize",q),()=>window.removeEventListener("resize",q)},[S,m]);const v=r.useCallback(I=>{if(!m&&!(I.pointerType==="mouse"&&I.button!==0)&&N!==null){try{I.currentTarget.setPointerCapture(I.pointerId)}catch{}w.current={startClientY:I.clientY,startCenterY:N,moved:!1}}},[N,m]),P=r.useCallback(I=>{const q=w.current;if(!q)return;const p=I.clientY-q.startClientY;!q.moved&&Math.abs(p)>Yr&&(q.moved=!0,b(!0)),q.moved&&C(S(q.startCenterY+p))},[S]),y=r.useCallback(I=>{const q=w.current;if(q){try{I.currentTarget.releasePointerCapture(I.pointerId)}catch{}w.current=null,q.moved&&(b(!1),R.current=!0,C(p=>(p!==null&&vn(p),p)))}},[]),A=r.useCallback(()=>{if(R.current){R.current=!1;return}o()},[o]),z=r.useCallback(I=>{if(I.key==="ArrowUp"||I.key==="ArrowDown"){I.preventDefault();const q=I.key==="ArrowUp"?-8:8;C(p=>{if(p===null)return p;const E=S(p+q);return vn(E),E})}},[S]),V=["ll-hidden",`ll-hidden--${u}`,n?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,L?"is-dragging":null,h?"ll-hidden--with-avatar":null,m?"ll-hidden--scoped":null].filter(Boolean).join(" "),re=N===null?void 0:{top:`${N-g/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:V,onPointerDown:v,onPointerMove:P,onPointerUp:y,onPointerCancel:y,onClick:A,onKeyDown:z,"aria-label":a,"data-position":e,style:re,children:h?t.jsxs(t.Fragment,{children:[t.jsx(yn,{direction:d,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:s,alt:c?`${c} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(yn,{direction:d,className:"ll-hidden__chevron"})})},Kr=({audioLevel:e,bars:n=20,maxHeight:i=20,minHeight:o=4,className:a,barClassName:s})=>{const c=r.useRef(null),l=r.useRef([]),u=r.useMemo(()=>{const g=(Math.sqrt(5)-1)/2;return Array.from({length:n},(h,m)=>.5+m*g%1*.5)},[n]);r.useEffect(()=>e.subscribe(h=>{for(let m=0;m<n;m++){const N=l.current[m];if(!N)continue;const C=Math.max(o,h*i*u[m]);N.style.height=`${C}px`}}),[e,n,i,o,u]);const d=["ll-waveform",a].filter(Boolean).join(" ");return t.jsx("div",{ref:c,className:d,"aria-hidden":"true",children:Array.from({length:n},(g,h)=>t.jsx("div",{ref:m=>{l.current[h]=m},className:["ll-waveform__bar",s].filter(Boolean).join(" "),style:{height:`${o}px`}},h))})},Jr=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,agentState:a,isMuted:s,audioLevel:c,onExpand:l,onToggleMute:u,onClose:d})=>n?t.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:t.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:l,"aria-label":`Expand ${i} widget`,children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsx(Kr,{audioLevel:c,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:g=>{g.stopPropagation(),u()},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.stopPropagation(),g.preventDefault(),u())},"aria-label":s?"Unmute microphone":"Mute microphone",children:t.jsx(mn,{muted:s,className:"ll-minimized__icon"})}),t.jsx(gn,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):t.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${i} widget`,children:t.jsxs("div",{className:"ll-minimized__surface",children:[o?t.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):t.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),t.jsxs("div",{className:"ll-minimized__meta",children:[t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsx("span",{className:"ll-minimized__state",children:a==="speaking"?"Speaking":a==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:u,"aria-label":s?"Unmute microphone":"Mute microphone",children:t.jsx(mn,{muted:s,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:l,"aria-label":`Expand ${i} widget`,children:t.jsx(gn,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:d,"aria-label":"Close widget",children:t.jsx(qr,{className:"ll-minimized__icon"})})]})]})}),Zr=({src:e,alt:n,preCannedPlaying:i=!1,className:o,style:a})=>{const[s,c]=r.useState(!1),l=r.useRef(e);if(r.useEffect(()=>{l.current!==e&&(l.current=e,c(!1))},[e]),!e)return null;const u={position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",objectPosition:"top",transition:"opacity 500ms ease, transform 500ms ease",transform:i?"scale(1.02)":"scale(1)",opacity:s?1:0,...a};return t.jsx("img",{src:e,alt:n,className:o,style:u,loading:"eager",fetchPriority:"high",onLoad:()=>c(!0)})},Qr="#E06540";function ei({size:e=14,className:n,fill:i=Qr}){return t.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 52 52",fill:"none",className:n,"aria-hidden":!0,children:[t.jsx("path",{d:"M44.5714 26C44.5714 23.5612 44.0908 21.146 43.1575 18.8928C42.2242 16.6397 40.8565 14.5924 39.132 12.868C37.4076 11.1435 35.3603 9.77577 33.1072 8.84247C30.854 7.90917 28.4388 7.42857 26 7.42857C23.5612 7.42857 21.146 7.90916 18.8928 8.84247C16.6397 9.77577 14.5924 11.1435 12.868 12.868C11.1435 14.5924 9.77577 16.6397 8.84247 18.8928C7.90917 21.146 7.42857 23.5612 7.42857 26C7.42857 28.4388 7.90916 30.854 8.84247 33.1072C9.77577 35.3603 11.1435 37.4076 12.868 39.132C14.5924 40.8565 16.6397 42.2242 18.8928 43.1575C21.146 44.0908 23.5612 44.5714 26 44.5714H48.2857C50.3371 44.5714 52 46.2344 52 48.2857C52 50.3371 50.3371 52 48.2857 52H26C22.5857 52 19.2049 51.3275 16.0505 50.021C12.896 48.7144 10.0293 46.7993 7.61501 44.385C5.20069 41.9707 3.28564 39.104 1.97902 35.9495C0.67247 32.7951 -3.54212e-07 29.4143 0 26C-1.68163e-07 22.5857 0.672469 19.2049 1.97902 16.0505C3.28564 12.896 5.20069 10.0293 7.61501 7.61501C10.0293 5.20069 12.896 3.28564 16.0505 1.97902C19.2049 0.67247 22.5857 0 26 0C29.4143 1.86048e-07 32.7951 0.67247 35.9495 1.97902C39.104 3.28564 41.9707 5.20069 44.385 7.61501C46.7993 10.0293 48.7144 12.896 50.021 16.0505C51.3275 19.2049 52 22.5857 52 26C52 28.0513 50.3371 29.7143 48.2857 29.7143C46.2344 29.7143 44.5714 28.0513 44.5714 26Z",fill:i}),t.jsx("path",{d:"M28.9717 23.7714C28.9717 21.3098 30.9672 19.3143 33.4288 19.3143C35.8904 19.3143 37.886 21.3098 37.886 23.7714C37.886 26.233 35.8904 28.2286 33.4288 28.2286C30.9672 28.2286 28.9717 26.233 28.9717 23.7714Z",fill:i}),t.jsx("path",{d:"M18.5714 19.3143C16.1098 19.3143 14.1143 21.3098 14.1143 23.7714C14.1143 26.233 16.1098 28.2286 18.5714 28.2286C21.033 28.2286 23.0285 26.233 23.0285 23.7714C23.0285 21.3098 21.033 19.3143 18.5714 19.3143Z",fill:i})]})}const ti=8,xn=8,ni=({open:e,onClose:n,anchorRef:i,children:o})=>{const a=r.useRef(null),[s,c]=r.useState(null);return r.useLayoutEffect(()=>{if(!e){c(null);return}const l=i.current;if(!l)return;const u=()=>{const d=l.getBoundingClientRect(),g={top:d.top-ti,left:d.left+d.width/2},h=xn+90,m=window.innerWidth-xn-90;g.left<h&&(g.left=h),g.left>m&&(g.left=m),c(g)};return u(),window.addEventListener("scroll",u,!0),window.addEventListener("resize",u),()=>{window.removeEventListener("scroll",u,!0),window.removeEventListener("resize",u)}},[e,i]),r.useEffect(()=>{if(!e)return;const l=d=>{const g=d.target,h=a.current,m=i.current;h&&h.contains(g)||m&&m.contains(g)||n()},u=d=>{d.key==="Escape"&&(d.stopPropagation(),n())};return document.addEventListener("mousedown",l),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",l),document.removeEventListener("keydown",u)}},[e,n,i]),!e||s===null||typeof document>"u"?null:Ut.createPortal(t.jsx("div",{ref:a,className:"ll-overflow-popover",role:"menu",style:{position:"fixed",top:s.top,left:s.left,transform:"translate(-50%, -100%)"},children:o}),document.body)},ri=({isMuted:e,onToggleMute:n,isCameraEnabled:i,onToggleCamera:o,allowCamera:a,isScreenShareEnabled:s,onToggleScreenShare:c,allowScreenShare:l,isSpeakerMuted:u,onToggleSpeaker:d,allowTyping:g,isTypingOpen:h,onToggleTyping:m,onDisconnect:N})=>{const[C,L]=r.useState(!1),b=r.useRef(null);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"ll-toolbar ll-toolbar--compact","data-testid":"compact-toolbar",onClick:w=>w.stopPropagation(),children:[t.jsx("button",{type:"button",className:`ll-tool ${e?"is-muted":""}`,onClick:n,"aria-label":e?"Unmute microphone":"Mute microphone",children:t.jsx(Kn,{muted:e})}),t.jsx("button",{ref:b,type:"button",className:`ll-tool ${C?"is-on":""}`,onClick:()=>L(w=>!w),"aria-label":"More controls","aria-haspopup":"menu","aria-expanded":C,children:t.jsx(ii,{})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:N,"aria-label":"End conversation",children:t.jsx(Zn,{})})]}),t.jsxs(ni,{open:C,onClose:()=>L(!1),anchorRef:b,children:[a&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${i?"is-on":""}`,onClick:()=>{o(),L(!1)},children:[t.jsx(Xn,{}),t.jsx("span",{children:i?"Stop camera":"Start camera"})]}),l&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${s?"is-on":""}`,onClick:()=>{c(),L(!1)},children:[t.jsx(Gn,{}),t.jsx("span",{children:s?"Stop sharing":"Share screen"})]}),t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${u?"is-on":""}`,onClick:()=>{d(),L(!1)},children:[t.jsx(Jn,{muted:u}),t.jsx("span",{children:u?"Unmute speaker":"Mute speaker"})]}),g&&t.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${h?"is-on":""}`,onClick:()=>{m(),L(!1)},children:[t.jsx(oi,{}),t.jsx("span",{children:h?"Hide typing":"Type a message"})]}),t.jsxs("button",{type:"button",className:"ll-overflow-popover__item is-active",disabled:!0,"aria-current":"true",children:[t.jsx("span",{className:"ll-overflow-popover__lang-code",children:"EN"}),t.jsx("span",{children:"English"})]})]})]})};function ii(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[t.jsx("circle",{cx:"6",cy:"12",r:"1.5"}),t.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),t.jsx("circle",{cx:"18",cy:"12",r:"1.5"})]})}function oi(){return t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}const si=({position:e,isMobile:n,agentName:i,avatarImageUrl:o,idleLoopUrl:a,greeting:s,branding:c,teamMembers:l,currentTeamMemberId:u,isSwitchingTeamMember:d,teamSwitcherOpen:g,onToggleTeamSwitcher:h,onSelectTeamMember:m,languageMenuOpen:N,onToggleLanguageMenu:C,connectionState:L,agentState:b,transcript:w,canResume:R,needsUserGesture:S,error:v,isMuted:P,micError:y,micDevices:A,activeMicId:z,isCameraEnabled:V,cameraPreviewEl:re,cameraDevices:I,activeCameraId:q,isScreenShareEnabled:p,screenPreviewEl:E,isSpeakerMuted:M,allowCamera:H,allowScreenShare:U,allowTyping:K,showMinimize:W=!0,showClose:J=!0,chromeless:te=!1,compactControls:F=!1,transforming:de,transformingLabel:X,avatarVideoContainerRef:me,agentVideoEl:Z,onConnect:Je,onDisconnect:Ze,onRetry:ct,onResumeAudio:ut,onToggleMute:Qe,onSwitchMicDevice:dt,onToggleCamera:ze,onSwitchCameraDevice:$e,onToggleScreenShare:je,onToggleSpeaker:Re,onSendMessage:Ne,onMinimize:Ae,onClose:Me,onClearMicError:He,dragHandleProps:Ie,resizeHandleProps:D})=>{var rt;const Te=((l==null?void 0:l.length)??0)>1,Fe=L==="connecting"||L==="connected",ge=L==="connected",ft=L==="idle"||L==="disconnected"||L==="error",[Pe,ke]=r.useState(!1);r.useEffect(()=>{if(!Z){ke(!1);return}if(!Z.paused&&Z.readyState>=2){ke(!0);return}ke(!1);const _=()=>ke(!0);return Z.addEventListener("playing",_),Z.addEventListener("loadeddata",_),()=>{Z.removeEventListener("playing",_),Z.removeEventListener("loadeddata",_)}},[Z]);const[Lt,pt]=r.useState(!1);r.useEffect(()=>{if(!ge){pt(!1);return}if(Pe)return;const _=setTimeout(()=>pt(!0),8e3);return()=>clearTimeout(_)},[ge,Pe]);const De=L==="connecting"||ge&&!!o&&!Pe&&!Lt,se=r.useRef(null),et=r.useRef(null);r.useEffect(()=>{const _=se.current;_&&(_.innerHTML="",re&&(re.style.width="100%",re.style.height="100%",re.style.objectFit="cover",re.style.transform="scaleX(-1)",_.appendChild(re)))},[re]),r.useEffect(()=>{const _=et.current;_&&(_.innerHTML="",E&&(E.style.width="100%",E.style.height="100%",E.style.objectFit="contain",_.appendChild(E)))},[E]);const[ne,ce]=r.useState(!1),[Oe,We]=r.useState(!1),fe=r.useRef(null),ye=r.useRef(null);r.useEffect(()=>{if(!ne&&!Oe&&!N&&!g)return;const _=()=>{ce(!1),We(!1),N&&C(),g&&h()};return document.addEventListener("click",_),()=>document.removeEventListener("click",_)},[ne,Oe,N,g,C,h]);const[ht,Et]=r.useState(!1),jt=r.useCallback(()=>Et(_=>!_),[]),[tt,Rt]=r.useState(""),Se=r.useCallback(_=>{_.preventDefault();const Q=tt.trim();Q&&(Ne(Q),Rt(""))},[tt,Ne]),Le=c.productName||"Live Layer",_e=!c.productName;let pe=null,be=null;for(let _=w.length-1;_>=0;_--){const Q=w[_];if(!pe&&Q.role==="agent"?pe=Q:!be&&Q.role==="user"&&(be=Q),pe&&be)break}const mt=ge?(pe==null?void 0:pe.text)||null:s||null,Be=ge&&(be==null?void 0:be.text)||null,nt=["ll-expanded",n?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:nt,"data-position":e,"data-state":ge?"connected":Fe?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[o?t.jsx(Zr,{src:o,alt:i,className:"ll-expanded__bg-img"}):t.jsx("div",{className:"ll-expanded__bg-fallback",children:t.jsx("span",{className:"ll-expanded__bg-initial",children:((rt=i==null?void 0:i.charAt(0))==null?void 0:rt.toUpperCase())||"A"})}),a&&!ge&&t.jsx("video",{className:"ll-expanded__bg-idle",src:a,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:me,className:"ll-expanded__video"}),De&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:d?"Switching...":"Connecting..."})]}),S&&ge&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:ut,children:[t.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("path",{d:"M3 9v6h4l5 5V4L7 9H3zm13.54.12a5 5 0 0 1 0 5.76l-1.41-1.41a3 3 0 0 0 0-2.94L16.54 9.12z"})}),t.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),de&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--transforming",role:"status","aria-live":"polite","aria-label":X,children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:X})]}),Fe?t.jsxs(t.Fragment,{children:[!F&&t.jsxs("div",{className:"ll-expanded__topbar",...Ie,children:[!te&&t.jsxs("div",{className:"ll-expanded__topbar-left",children:[t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill",onClick:_=>{Te&&(_.stopPropagation(),h())},"aria-haspopup":Te?"listbox":void 0,"aria-expanded":Te?g:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),Te&&t.jsx(wt,{})]}),Te&&g&&t.jsx("div",{className:"ll-hmenu",onClick:_=>_.stopPropagation(),role:"listbox",children:l==null?void 0:l.map(_=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${_.id===u?"is-active":""}`,onClick:()=>m(_.id),role:"option","aria-selected":_.id===u,children:[_.avatarImageUrl&&t.jsx("img",{src:_.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:_.name}),_.role&&t.jsx("span",{className:"ll-hmenu__role",children:_.role})]},_.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:_=>{_.stopPropagation(),C()},"aria-haspopup":"listbox","aria-expanded":N,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(wt,{})]}),N&&t.jsx("div",{className:"ll-hmenu",onClick:_=>_.stopPropagation(),role:"listbox",children:t.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:t.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),t.jsx("span",{className:`ll-expanded__state ll-expanded__state--${b}`,children:b})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[W!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn",onClick:Ae,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(_n,{})}),J!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Me,"aria-label":"End call",title:"End call",children:t.jsx(wn,{})})]})]}),F&&t.jsxs("div",{className:"ll-compact-status","data-state":b,children:[t.jsx("span",{className:"ll-compact-status__dot","aria-hidden":!0}),t.jsx("span",{className:"ll-compact-status__label",children:b})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",...Ie,children:[!F&&(_e?t.jsxs("a",{className:"ll-expanded__brand ll-expanded__brand--link",href:"https://livelayer.studio?utm_source=widget&utm_medium=brand-badge",target:"_blank",rel:"noopener noreferrer","aria-label":"Powered by LiveLayer — opens livelayer.studio in a new tab",title:"Powered by LiveLayer — visit livelayer.studio",children:[t.jsx(ei,{size:14,className:"ll-expanded__brand-mark"}),t.jsx("span",{children:Le})]}):t.jsx("span",{className:"ll-expanded__brand",children:Le})),t.jsxs("div",{className:"ll-expanded__header-actions",children:[!F&&W!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:Ae,"aria-label":"Minimize widget",children:t.jsx(_n,{})}),J!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Me,"aria-label":"Close widget",children:t.jsx(wn,{})})]})]}),ft&&(()=>{const _=R?"Resume session":L==="disconnected"?"Reconnect to agent":"Start video call",Q=!v;return t.jsxs(t.Fragment,{children:[Q&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:Je,"aria-label":_,children:[t.jsx("div",{className:"ll-expanded__play-circle",children:t.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:t.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),F&&t.jsx("span",{className:"ll-expanded__play-label",children:_})]}),!F&&t.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[s&&t.jsx("div",{className:"ll-expanded__transcript",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:s})}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:Je,"aria-label":_,children:_})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${Fe&&(V||p)?"is-visible":""}`,children:[t.jsx("div",{ref:et,className:p?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:se,className:!p&&V?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),Fe?t.jsxs("div",{className:"ll-expanded__bottom",children:[!F&&mt&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:mt})}),!F&&Be&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Be})}),!te&&!F&&t.jsxs("div",{className:"ll-toolbar",onClick:_=>_.stopPropagation(),children:[U&&t.jsx("button",{type:"button",className:`ll-tool ${p?"is-on":""}`,onClick:je,"aria-label":p?"Stop sharing screen":"Share screen",title:p?"Stop sharing":"Share screen",children:t.jsx(Gn,{})}),H&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${V?"is-on":""}`,onClick:ze,"aria-label":V?"Turn off camera":"Turn on camera",title:V?"Stop camera":"Start camera",children:t.jsx(Xn,{})}),t.jsx("button",{ref:ye,type:"button",className:`ll-tool ll-tool--right ${V?"is-on":""}`,onClick:_=>{_.stopPropagation(),We(Q=>!Q),ce(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":Oe,children:t.jsx(wt,{})}),Oe&&I.length>0&&t.jsx(Cn,{label:"Camera",devices:I,activeId:q,anchorRef:ye,onPick:_=>{We(!1),$e(_)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${P?"is-muted":""}`,onClick:Qe,"aria-label":P?"Unmute microphone":"Mute microphone",title:P?"Unmute":"Mute",children:t.jsx(Kn,{muted:P})}),t.jsx("button",{ref:fe,type:"button",className:`ll-tool ll-tool--right ${P?"is-muted":""}`,onClick:_=>{_.stopPropagation(),ce(Q=>!Q),We(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":ne,children:t.jsx(wt,{})}),ne&&A.length>0&&t.jsx(Cn,{label:"Microphone",devices:A,activeId:z,anchorRef:fe,onPick:_=>{ce(!1),dt(_)}})]}),t.jsx("button",{type:"button",className:`ll-tool ${M?"is-muted":""}`,onClick:Re,"aria-label":M?"Unmute speaker":"Mute speaker",title:M?"Unmute speaker":"Mute speaker",children:t.jsx(Jn,{muted:M})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:Ze,"aria-label":"End conversation",title:"End conversation",children:t.jsx(Zn,{})})]}),!te&&F&&t.jsx(ri,{isMuted:P,onToggleMute:Qe,isCameraEnabled:V,onToggleCamera:ze,allowCamera:H,isScreenShareEnabled:p,onToggleScreenShare:je,allowScreenShare:U,isSpeakerMuted:M,onToggleSpeaker:Re,allowTyping:K,isTypingOpen:ht,onToggleTyping:jt,onDisconnect:Ze}),!te&&K&&(F?ht:!0)&&t.jsxs("form",{className:"ll-message-input",onSubmit:Se,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:tt,onChange:_=>Rt(_.target.value),"aria-label":"Message the agent"}),tt.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(li,{})})]})]}):null,(()=>{if(y&&L!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:y}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:He,"aria-label":"Dismiss",children:"×"})]});if(!v||L!=="error")return null;let _="Failed to connect",Q="Try again";return v==="MIC_PERMISSION_DENIED"?_="Microphone blocked. Allow access to talk.":v==="MIC_NOT_FOUND"?_="No microphone found. Plug one in + retry.":v==="MIC_UNAVAILABLE"?_="Mic unavailable. Check other apps using it.":v==="AGENT_TIMEOUT"?_="Agent didn't pick up. Try again.":v==="CONNECT_FAILED"?_="Connection failed. Check your network.":v.length<80&&(_=v),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:_}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:ct,children:Q})]})})(),(D==null?void 0:D["data-ll-resize-handle"])!==void 0&&t.jsx("div",{className:"ll-expanded__resize-grip",...D,"aria-hidden":!0,children:t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[t.jsx("line",{x1:"11",y1:"4",x2:"4",y2:"11"}),t.jsx("line",{x1:"11",y1:"8",x2:"8",y2:"11"})]})})]})};function wt(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("polyline",{points:"6 9 12 15 18 9"})})}function wn(){return t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function _n(){return t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function Gn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Xn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M23 7l-7 5 7 5V7z"}),t.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2"})]})}function Kn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),t.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),e&&t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Jn({muted:e}){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?t.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}):t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"}),t.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]})]})}function li(){return t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),t.jsx("polyline",{points:"12 5 19 12 12 19"})]})}function Zn(){return t.jsx("svg",{width:"16",height:"16",viewBox:"-4 -4 32 32",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:t.jsx("path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.93.37 1.84.71 2.7a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.38-1.38a2 2 0 0 1 2.11-.45c.86.34 1.77.58 2.7.71A2 2 0 0 1 22 16.92z",transform:"rotate(135 12 12)"})})}const Cn=({label:e,devices:n,activeId:i,onPick:o,anchorRef:a})=>{const[s,c]=r.useState(null);return r.useLayoutEffect(()=>{const l=()=>{const u=a.current;if(!u)return;const d=u.getBoundingClientRect(),g=126,h=window.innerWidth-16-110,m=d.left+d.width/2;c({top:d.top-8,left:Math.max(g,Math.min(h,m))})};return l(),window.addEventListener("scroll",l,!0),window.addEventListener("resize",l),()=>{window.removeEventListener("scroll",l,!0),window.removeEventListener("resize",l)}},[a]),s===null||typeof document>"u"?null:Ut.createPortal(t.jsxs("div",{className:"ll-device-menu ll-device-menu--floating",onClick:l=>l.stopPropagation(),role:"listbox",style:{position:"fixed",top:s.top,left:s.left,transform:"translate(-50%, -100%)"},children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),n.map((l,u)=>{const d=i===l.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${d?"is-active":""}`,onClick:()=>o(l.deviceId),role:"option","aria-selected":d,children:[d&&t.jsx("span",{className:"ll-device-menu__dot",children:"●"}),t.jsx("span",{className:"ll-device-menu__name",children:l.label||`${e} ${u+1}`})]},l.deviceId||u)})]}),document.body)},ai=["[data-ll-private]","[data-ll-skip]",".ll-widget"];function Vt(e){let n=e;for(;n;){for(const i of ai)if(n.matches(i))return!0;n=n.parentElement}return!1}function Wt(e){if(Vt(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const n=(e.getAttribute("autocomplete")||"").toLowerCase();if(n==="off"||n.startsWith("cc-"))return!1}return!0}const _t=4096,ci=20,ui=20,di=10,fi=10,pi=30,hi=20,kn=500,mi=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function lt(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let n=e;for(;n;){for(const i of mi)if(n.matches(i))return!0;n=n.parentElement}return!1}function at(e){if(typeof window>"u")return!0;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth;return n.bottom>0&&n.right>0&&n.top<i&&n.left<o}function Sn(e){const n=e.getAttribute("id");if(n){const s=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/"/g,'\\"'),c=document.querySelector(`label[for="${s}"]`);if(c!=null&&c.textContent)return c.textContent.trim()}const i=e.getAttribute("aria-label");if(i)return i.trim();const o=e.closest("label");if(o){const s=[];for(const l of Array.from(o.childNodes))if(l.nodeType===Node.TEXT_NODE){const u=(l.textContent||"").trim();u&&s.push(u)}else if(l instanceof HTMLElement){if(l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement||l instanceof HTMLButtonElement)continue;const u=(l.textContent||"").trim();u&&s.push(u)}const c=s.join(" ").trim();if(c)return c}const a=e.getAttribute("placeholder");return a?a.trim():""}function ae(e,n){return e.length<=n?e:e.slice(0,n-1)+"…"}function gi(e){return e&&e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||null}function yi(e){const n=e.getAttribute("aria-label");if(n)return n.trim().slice(0,80);const i=e.getAttribute("aria-labelledby");if(i){const s=document.getElementById(i);if(s!=null&&s.textContent)return s.textContent.trim().slice(0,80)}const o=e.querySelector('button[type="submit"], input[type="submit"], button:not([type])');if(o){const s=o instanceof HTMLInputElement?o.value:(o.textContent??"").trim();if(s&&s.length<60&&!/^(submit|ok|continue)$/i.test(s))return s}let a=e.parentElement;for(let s=0;a&&s<4;s++,a=a.parentElement){const c=a.querySelector("h1, h2, h3, h4");if(c!=null&&c.textContent){const l=c.textContent.trim();if(l&&l.length<80)return l}}return null}function Ye(e){return e.length}function Qn(e,n={}){const i=n.doc??(typeof document<"u"?document:null);if(!i)return{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:e};const o=typeof window<"u"&&window.location.href||"",a=typeof window<"u"&&window.location.pathname||"/",s=i.title||"",c=Array.from(i.querySelectorAll("[data-ll-region]")),l=[];for(const y of c){if(l.length>=di)break;if(lt(y)||!at(y))continue;const A=y.getAttribute("data-ll-region")??"",z=y.getAttribute("data-ll-intent")??void 0,V=ae((y.innerText||y.textContent||"").trim(),kn*2);!A||!V||l.push({id:A,intent:z,text:V})}const u=[],d=["H1","H2","H3","H4","H5","H6"],g=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const y of g){if(lt(y)||!at(y))continue;const A=(y.textContent||"").trim();A&&u.push(`${y.tagName}: ${ae(A,200)}`)}const h=Array.from(i.querySelectorAll("p, li"));for(const y of h){if(lt(y)||!at(y)||d.includes(y.tagName))continue;const A=(y.textContent||"").trim();A.length>10&&u.push(ae(A,kn))}const m=u.join(`
|
|
2
|
+
`),N=[],C=Array.from(i.querySelectorAll("a[href]"));for(const y of C){if(N.length>=ci)break;if(lt(y)||!at(y))continue;const A=y.getAttribute("href")||"",z=(y.textContent||"").trim();!A||!z||N.push({href:A,text:ae(z,100)})}const L=[],b=Array.from(i.querySelectorAll("input, textarea, select"));for(const y of b){if(L.length>=ui)break;if(lt(y)||!Wt(y)||!at(y))continue;const A=Sn(y),z=y instanceof HTMLInputElement?y.type:y.tagName.toLowerCase();A&&L.push({label:ae(A,100),type:z})}const w=Array.from(i.querySelectorAll("form")),R=[];let S=0;for(const y of w){if(R.length>=fi)break;if(Vt(y)||y.matches(".ll-widget *, .ll-widget"))continue;const A=y.getAttribute("id")||y.getAttribute("name")||gi(y.getAttribute("data-ll-intent"))||`form_${S++}`,z=y.getAttribute("data-ll-intent")||yi(y)||void 0,V=Array.from(y.querySelectorAll("input, textarea, select")),re=[];let I=0;const q=new Set;for(const p of V){if(re.length>=pi)break;if(!Wt(p))continue;if(p instanceof HTMLInputElement){const F=p.type;if(F==="submit"||F==="button"||F==="reset"||F==="hidden"||F==="image"||F==="file")continue}const E=p.getAttribute("name")||"",M=p.getAttribute("id")||"";let H=E||M||`field_${I}`;q.has(H)&&(H=`${H}__${I}`),q.add(H),I++;const U=Sn(p)||H,K=p instanceof HTMLInputElement?p.type:p.tagName.toLowerCase(),W={name:H,label:ae(U,100),type:K};p.required===!0&&(W.required=!0);const J=p.getAttribute("placeholder");if(J&&(W.placeholder=ae(J.trim(),100)),p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement){const F=p.getAttribute("minlength");if(F!==null){const X=parseInt(F,10);!Number.isNaN(X)&&X>=0&&(W.minLength=X)}const de=p.getAttribute("maxlength");if(de!==null){const X=parseInt(de,10);!Number.isNaN(X)&&X>=0&&(W.maxLength=X)}}if(p instanceof HTMLInputElement){const F=p.getAttribute("min");F!==null&&(W.min=ae(F,50));const de=p.getAttribute("max");de!==null&&(W.max=ae(de,50));const X=p.getAttribute("step");X!==null&&(W.step=ae(X,20));const me=p.getAttribute("pattern");me!==null&&(W.pattern=ae(me,200));const Z=(p.getAttribute("autocomplete")||"").toLowerCase();Z&&Z!=="off"&&!Z.startsWith("cc-")&&(W.autocomplete=ae(Z,50))}if(p instanceof HTMLSelectElement){const F=[];for(let de=0;de<p.options.length&&!(F.length>=hi);de++){const X=p.options[de];if(!X||X.disabled)continue;const me=X.value||"",Z=(X.textContent||"").trim()||me;!me&&!Z||F.push({value:me,label:ae(Z,60)})}F.length>0&&(W.options=F)}const te=typeof p.validationMessage=="string"?p.validationMessage:"";te&&(W.validationMessage=ae(te,200)),re.push(W)}R.push({id:A,intent:z,fields:re})}const v={url:o,title:s,pathname:a,regions:l,visibleText:m,visibleLinks:N,visibleFields:L,forms:R,extras:e};let P=Ye(JSON.stringify(v.regions))+Ye(v.visibleText)+Ye(JSON.stringify(v.visibleLinks))+Ye(JSON.stringify(v.visibleFields));for(;P>_t&&v.visibleFields.length>0;)v.visibleFields.pop(),P=Ye(JSON.stringify(v.visibleFields));for(;P>_t&&v.visibleLinks.length>0;)v.visibleLinks.pop(),P-=80;return Ye(v.visibleText)>_t&&(v.visibleText=ae(v.visibleText,_t-100)),v}let Ge=null;function bi(e){const n=e.querySelectorAll("form");let i=`f${n.length}`;return n.forEach(o=>{i+=`|${o.id||o.getAttribute("name")||""}:${o.querySelectorAll("input,select,textarea").length}`}),i}function Bt(e,n={}){const i=Date.now(),o=n.doc??(typeof document<"u"?document:null),a=typeof window<"u"&&window.location.pathname||"/",s=typeof window<"u"?window.scrollY:0,c=`${a}::${s}::${o?bi(o):""}`;if(Ge&&Ge.key===c&&i-Ge.at<1e3)return Ge.ctx;const l=Qn(e,n);return Ge={key:c,at:i,ctx:l},l}function er(){Ge=null}const vi=200;function tr(e){const n=String(e.href||"");return{href:n,text:String(e.text??e.title??n),internal:e.internal??!0,title:e.title,description:e.description}}function xi(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function nr(e){const n=e??(typeof document<"u"?document:null);if(!n)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,a=[],s=Array.from(n.querySelectorAll("a[href]"));for(const c of s){if(a.length>=vi)break;if(Vt(c))continue;const l=c.getAttribute("href")||"";if(!xi(l))continue;let u=l,d=!0;try{if(typeof window<"u"){const h=new URL(l,i);d=h.origin===i,d&&l.startsWith("http")&&(u=h.pathname+h.search+h.hash)}}catch{continue}if(o.has(u))continue;o.add(u);const g=(c.textContent||"").trim().slice(0,120);a.push({href:u,text:g,internal:d})}return a}let Xe=null;const wi=5e3;function Ct(){const e=Date.now(),n=typeof window<"u"&&window.location.pathname||"/";if(Xe&&Xe.pathname===n&&e-Xe.at<wi)return Xe.routes;const i=nr();return Xe={at:e,pathname:n,routes:i},i}function rr(){Xe=null}function qt(e){if(e instanceof HTMLInputElement){const n=e.type;if(n==="submit"||n==="button"||n==="reset"||n==="hidden"||n==="image"||n==="file")return!1}return!0}function _i(e,n){return e.getAttribute("name")||e.getAttribute("id")||`field_${n}`}function Ee(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Ft(e){const n=e.lastIndexOf(".");return n>=0?e.slice(n+1):e}function Ci(e){var o;const n=e.getAttribute("id");if(n)try{const a=(o=e.ownerDocument)==null?void 0:o.querySelector(`label[for="${n.replace(/"/g,'\\"')}"]`);if(a!=null&&a.textContent)return a.textContent}catch{}const i=e.closest("label");return i!=null&&i.textContent?i.textContent:e.getAttribute("aria-label")||e.getAttribute("placeholder")||""}function ki(e,n){const i=Ee(n);if(i.length<2)return null;let o=null,a=0;for(const s of Array.from(e.querySelectorAll("input, textarea, select"))){if(!qt(s))continue;const c=s.getAttribute("name")||"",l=s.getAttribute("id")||"",u=[Ee(Ft(c)),Ee(Ft(l)),Ee(c),Ee(l)];let d=0;u.some(g=>g.length>=2&&g===i)?d=4:[Ee(c),Ee(Ft(c)),Ee(Ci(s))].some(h=>h.length>=3&&(h.includes(i)||i.includes(h)))&&(d=2),d>a&&(a=d,o=s)}return a>=2?o:null}function Si(e,n){if(!n)return null;try{const s=e.querySelector(`[name="${n.replace(/"/g,'\\"')}"]`);if(s&&qt(s))return s}catch{}const i=Array.from(e.querySelectorAll("input, textarea, select"));let o=0;const a=new Map;for(const s of i){if(!qt(s))continue;const c=_i(s,o);let l=c;if(a.has(c)&&(l=`${c}__${o}`),l===n)return s;a.set(c,s),o++}return ki(e,n)}function Ln(e,n){const i=Si(e,n);return i?Wt(i)?{el:i}:{el:null,reason:"private"}:{el:null,reason:"not_found"}}function Li(e,n){const i=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,o=Object.getOwnPropertyDescriptor(i,"value"),a=o==null?void 0:o.set;a?a.call(e,n):e.value=n}function Ei(e,n,i={}){const o=i.triggerInput??!0,a=i.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const s=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),c=s==null?void 0:s.set,l=n==="true"||n==="1"||n==="on";c?c.call(e,l):e.checked=l,o&&e.dispatchEvent(new Event("input",{bubbles:!0})),a&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}Li(e,n),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),a&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function En(e,n){if(!n)return null;const i=n.replace(/"/g,'\\"'),o=l=>l.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')!==null;try{const l=e.querySelector(`form#${CSS.escape(n)}`);if(l&&!o(l))return l}catch{}const a=e.querySelector(`form[name="${i}"]`);if(a&&!o(a))return a;const s=e.querySelector(`form[data-ll-intent="${i}"]`);if(s&&!o(s))return s;const c=Array.from(e.querySelectorAll("form")).filter(l=>!o(l));for(const l of c){const u=l.getAttribute("data-ll-intent");if(u&&ji(u)===n)return l}if(/^form_\d+$/.test(n)){const l=parseInt(n.slice(5),10);let u=0;for(const d of c)if(!(d.id||d.getAttribute("name")||d.getAttribute("data-ll-intent"))){if(u===l)return d;u++}}return c.length===1?c[0]:null}function ji(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||null}function Ri(){if(typeof window>"u"||typeof document>"u")return!1;const e=document.scrollingElement||document.documentElement;if(!e||e.scrollHeight<=e.clientHeight+2)return!1;const n=window.getComputedStyle(e);return!(n.overflowY==="hidden"||n.overflowY==="clip")}function Ni(e){if(!(e instanceof HTMLElement))return!1;const i=window.getComputedStyle(e).overflowY;return!(i!=="auto"&&i!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function Ai(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let n=null,i=0;for(const o of e){if(!Ni(o))continue;const a=o.getBoundingClientRect();if(a.bottom<=0||a.top>=window.innerHeight||a.right<=0||a.left>=window.innerWidth||a.width<=0||a.height<=0||o.closest(".ll-widget"))continue;const s=a.width*a.height;s>i&&(i=s,n=o)}return n}function Mi(){if(typeof window>"u")return null;if(Ri())return window;const e=Ai();return e||window}function jn(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function Ii(e){var n,i;return e instanceof Window?typeof document>"u"?0:Math.max(((n=document.body)==null?void 0:n.scrollHeight)??0,((i=document.documentElement)==null?void 0:i.scrollHeight)??0):e.scrollHeight-e.clientHeight}const Ti=new Set(["agent_state","avatar_stream_ready","avatar_active","avatar_idle","bot_ready","agent_error","idle_warning","idle_timeout","navigate","scroll_to","request_page_context","scroll_page","click","fill_form","focus_field","submit_form","request_routes","task_field_updated","task_completed"]),ir=r.forwardRef(function(n,i){var rn,on,sn,ln,an,cn,un;const{agentId:o,apiKey:a,baseUrl:s="https://app.livelayer.studio",sessionEndpoint:c,sessionBody:l,soundEffects:u,experienceMode:d="WIDGET",autoConnect:g=!1,displayMode:h,defaultDisplayMode:m="expanded",onDisplayModeChange:N,position:C="bottom-right",mobileBreakpoint:L=640,draggable:b,resizable:w,persistKey:R="ll-widget",disablePersistence:S=!1,teamMembers:v,currentTeamMemberId:P,onTeamMemberChange:y,idleLoopUrl:A,greeting:z,avatarImageUrl:V,agentName:re,branding:I={},allowCamera:q=!0,allowScreenShare:p=!0,allowTyping:E=!0,blurUntilFirstSpeech:M=!0,showMinimize:H,showClose:U,chromeless:K=!1,floatingChromeContainer:W=null,compactControls:J=!1,transforming:te=!1,transformingLabel:F="Transforming…",showOn:de,hideOn:X,pathname:me,onNavigate:Z,onScrollToSelector:Je,getPageContext:Ze,pageContextExtras:ct,getRoutes:ut,onScrollPage:Qe,onClick:dt,capabilities:ze,onConnect:$e,onDisconnect:je,onTranscript:Re,onAgentState:Ne,onConnectionStateChange:Ae,onAgentEvent:Me,onAgentCommand:He,onCollect:Ie,controlledSession:D,className:Te,style:Fe,zIndex:ge=2147483647}=n,ft=Bn(me),Pe=Vn(ft,de,X);r.useEffect(()=>{er(),rr()},[ft]);const ke=P!==void 0,[Lt,pt]=r.useState(()=>{var x;return P??((x=v==null?void 0:v[0])==null?void 0:x.id)}),De=ke?P:Lt,se=r.useMemo(()=>(v==null?void 0:v.find(x=>x.id===De))??null,[v,De]),et=(se==null?void 0:se.agentId)??o,ne=d==="EMBEDDED",ce=Wn(L),[Oe,We]=On({value:h,defaultValue:m,onChange:N,persistKey:R,disablePersistence:ne||S}),fe=ne?"expanded":Oe,ye=ne?()=>{}:We,ht=H??!ne,Et=U??!ne,jt=J||!ne&&ce,Se=Dr({draggable:!ne&&(b??!ce),resizable:!ne&&(w??!ce),persistKey:R,disablePersistence:ne||S}),Le=Mn(),_e=Tn(),pe=Pn(),be=Dn(),[mt,Be]=r.useState(!1),[nt,rt]=r.useState(!1),[_,Q]=r.useState(!1),[lr,ar]=r.useState(!1),[Nt,cr]=r.useState(!1),gt=Br({baseUrl:s,config:u}),yt=r.useRef(gt);yt.current=gt;const At=r.useRef(Z),Mt=r.useRef(Je),It=r.useRef(Qe),Tt=r.useRef(dt),Yt=r.useRef(Ze),Gt=r.useRef(ct),Xt=r.useRef(ut),Pt=r.useRef(ze),ve=r.useRef(null);At.current=Z,Mt.current=Je,It.current=Qe,Tt.current=dt,Yt.current=Ze,Gt.current=ct,Xt.current=ut,Pt.current=ze;function xe(x){const f=Pt.current;return f?f.includes(x):!0}function we(x,f){console.warn(`[LiveLayer] Agent command "${x}" blocked — capability "${f}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const it=r.useCallback(x=>{var ee,le,Ce,st;const f=x;if(!(!f.type||typeof f.type!="string")){if(Me==null||Me({eventName:f.type,data:x}),f.type==="navigate"){if(!xe("navigate")){we("navigate","navigate");return}const j=typeof f.href=="string"?f.href:null;if(!j){console.warn(`[LiveLayer] Agent emitted "navigate" without href. Skipping. Check your agent's tool schema. See https://livelayer.studio/docs/errors/navigate-missing-href`);return}if(yt.current.playPageChange(),At.current){try{At.current(j)}catch(T){console.warn(`[LiveLayer] onNavigate threw for "${j}". Falling back. Error:`,T)}return}if(typeof document<"u"){const T=document.querySelector(`a[href="${j.replace(/"/g,'\\"')}"]`);if(T){T.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",j),window.dispatchEvent(new PopStateEvent("popstate"))}catch(T){console.warn(`[LiveLayer] history.pushState fallback failed for "${j}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,T)}return}if(f.type==="scroll_to"){if(!xe("scroll")){we("scroll_to","scroll");return}const j=typeof f.selector=="string"?f.selector:null;if(!j)return;const T=f.behavior==="instant"?"instant":"smooth";if(Mt.current){try{Mt.current(j,T)}catch(B){console.warn("[LiveLayer] onScrollToSelector threw.",B)}return}if(typeof document<"u"){let B=null;try{B=document.querySelector(j)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${j}".`);return}if(!B){console.warn(`[LiveLayer] scroll_to: no element matched "${j}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}B.scrollIntoView({behavior:T,block:"start"})}return}if(f.type==="request_page_context"){if(!xe("read_page")){we("request_page_context","read_page");return}const j=typeof f.requestId=="string"?f.requestId:void 0,T=(ee=ve.current)==null?void 0:ee.call(ve),B=G=>{const $=T,oe=$==null?void 0:$.localParticipant;if(oe!=null&&oe.publishData)try{const ue=j?{...G,requestId:j}:G,Ve=new TextEncoder().encode(JSON.stringify(ue));oe.publishData(Ve,{reliable:!0})}catch(ue){console.warn("[LiveLayer] publishData failed.",ue)}},O=Gt.current,Y=Yt.current;try{if(Y){const G=Y(O);if(G instanceof Promise){B({type:"page_context_pending"}),G.then($=>B({type:"page_context",context:$})).catch($=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",$),B({type:"page_context",context:Bt(O)})});return}B({type:"page_context",context:G});return}B({type:"page_context",context:Bt(O)})}catch(G){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",G),B({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:O}})}return}if(f.type==="scroll_page"){if(!xe("scroll")){we("scroll_page","scroll");return}const j=f.direction;if(j!=="up"&&j!=="down"&&j!=="top"&&j!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(j)}". Expected up | down | top | bottom.`);return}const T=f.behavior==="instant"?"instant":"smooth";if(It.current){try{It.current(j,T)}catch($){console.warn("[LiveLayer] onScrollPage threw.",$)}return}if(typeof window>"u")return;const B={behavior:T},O=Mi(),Y=$=>{O instanceof Window?O.scrollBy({top:$,...B}):O.scrollBy({top:$,...B})},G=$=>{O instanceof Window?O.scrollTo({top:$,...B}):O.scrollTo({top:$,...B})};j==="up"?Y(-jn(O)):j==="down"?Y(jn(O)):G(j==="top"?0:Ii(O));return}if(f.type==="click"){if(!xe("click")){we("click","click");return}const j=typeof f.selector=="string"?f.selector:null;if(!j){console.warn("[LiveLayer] click: missing selector.");return}if(Tt.current){try{Tt.current(j)}catch(B){console.warn("[LiveLayer] onClick threw.",B)}return}if(typeof document>"u")return;let T=null;try{T=document.querySelector(j)}catch{console.warn(`[LiveLayer] click: invalid selector "${j}".`);return}if(!T){console.warn(`[LiveLayer] click: no element matched "${j}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(T.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(le=T.click)==null||le.call(T);return}if(f.type==="fill_form"||f.type==="focus_field"){if(!xe("fill_forms")){we(f.type,"fill_forms");return}if(typeof document>"u")return;f.type==="fill_form"&&yt.current.playConfirmation();const j=typeof f.formId=="string"?f.formId:null;if(!j){console.warn(`[LiveLayer] ${f.type}: missing formId.`);return}const T=En(document,j);if(!T){console.warn(`[LiveLayer] ${f.type}: no <form> matched id="${j}" (or matching name / data-ll-intent slug). Forms are auto-discovered — make sure the form has an \`id\`, \`name\`, or \`data-ll-intent\` attribute the agent observed in PageContext.forms.`);return}if(T.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')){console.warn(`[LiveLayer] ${f.type}: refusing to touch a form in a private / opted-out subtree.`);return}if(f.type==="focus_field"){const O=typeof f.fieldName=="string"?f.fieldName:null;if(!O){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const Y=Ln(T,O);if(Y.el===null){Y.reason==="private"?console.warn(`[LiveLayer] focus_field: field "${O}" is privacy-protected and not focusable.`):console.warn(`[LiveLayer] focus_field: no input matching key="${O}" in form "${j}". The agent should use the field.name it observed in PageContext.forms[].fields[].`);return}Y.el.focus();return}const B=f.values&&typeof f.values=="object"?f.values:null;if(!B){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[O,Y]of Object.entries(B)){if(typeof Y!="string")continue;const G=Ln(T,O);if(G.el===null){G.reason==="private"?console.warn(`[LiveLayer] fill_form: field "${O}" is privacy-protected (password / cc-* / data-ll-private). Skipping.`):console.warn(`[LiveLayer] fill_form: no input matching key="${O}" in form "${j}". The agent should use the field.name it observed in PageContext.forms[].fields[]. Skipping.`);continue}try{Ei(G.el,Y)}catch($){console.warn(`[LiveLayer] fill_form: failed to set "${O}".`,$)}}return}if(f.type==="submit_form"){if(!xe("submit_forms")){we("submit_form","submit_forms");return}if(typeof document>"u")return;const j=typeof f.formId=="string"?f.formId:null;if(!j){console.warn("[LiveLayer] submit_form: missing formId.");return}yt.current.playConfirmation();const T=En(document,j);if(!T){console.warn(`[LiveLayer] submit_form: no <form> matched id="${j}" (or matching name / data-ll-intent slug).`);return}if(T.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private / opted-out subtree.");return}const B=typeof f.requestId=="string"?f.requestId:void 0,O=(Ce=ve.current)==null?void 0:Ce.call(ve),Y=oe=>{const ue=O,Ve=ue==null?void 0:ue.localParticipant;if(Ve!=null&&Ve.publishData)try{const Cr=B?{...oe,requestId:B}:oe,kr=new TextEncoder().encode(JSON.stringify(Cr));Ve.publishData(kr,{reliable:!0})}catch{}};let G=!1;const $=()=>{G=!0,Y({type:"form_submitted",formId:j})};T.addEventListener("submit",$,{once:!0});try{typeof T.requestSubmit=="function"?T.requestSubmit():T.submit()}catch(oe){console.warn("[LiveLayer] submit_form: requestSubmit threw.",oe),T.removeEventListener("submit",$),Y({type:"form_submit_blocked",formId:j,reason:"exception"});return}setTimeout(()=>{G||(T.removeEventListener("submit",$),Y({type:"form_submit_blocked",formId:j,reason:"validation"}))},500);return}if(f.type==="request_routes"){if(!xe("read_page")){we("request_routes","read_page");return}const j=typeof f.requestId=="string"?f.requestId:void 0,B=(st=ve.current)==null?void 0:st.call(ve),O=B==null?void 0:B.localParticipant;if(!(O!=null&&O.publishData))return;const Y=$=>{try{const oe=j?{type:"routes",routes:$,requestId:j}:{type:"routes",routes:$},ue=new TextEncoder().encode(JSON.stringify(oe));O.publishData(ue,{reliable:!0})}catch(oe){console.warn("[LiveLayer] request_routes: publishData failed.",oe)}},G=Xt.current;if(G){try{const $=G(),oe=ue=>{if(!Array.isArray(ue)){Y([]);return}Y(ue.map(tr).slice(0,200))};$ instanceof Promise?$.then(oe).catch(ue=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",ue),Y(Ct())}):oe($)}catch($){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",$),Y(Ct())}return}try{Y(Ct())}catch($){console.warn("[LiveLayer] request_routes: extractRoutes threw.",$)}return}if(f.type==="task_field_updated"){if(!xe("collect_data")){we("task_field_updated","collect_data");return}const j={phase:"field",fieldId:typeof f.fieldId=="string"?f.fieldId:"",fieldName:typeof f.fieldName=="string"?f.fieldName:typeof f.fieldId=="string"?f.fieldId:"",value:typeof f.value=="string"?f.value:"",kind:typeof f.kind=="string"?f.kind:"text",source:f.source==="slide"?"slide":f.source==="page"?"page":"agent",...typeof f.slideId=="string"?{slideId:f.slideId}:{},...typeof f.formId=="string"?{formId:f.formId}:{}};if(typeof document<"u")try{document.dispatchEvent(new CustomEvent("ll-collected",{detail:j}))}catch{}return}if(f.type==="task_completed"){if(!xe("collect_data")){we("task_completed","collect_data");return}const j=f.result;if(!j||typeof j!="object"){console.warn("[LiveLayer] task_completed missing `result` payload.");return}if(typeof document<"u")try{document.dispatchEvent(new CustomEvent("ll-collected",{detail:{phase:"complete",result:j}}))}catch{}try{Ie==null||Ie(j)}catch(T){console.warn("[LiveLayer] onCollect threw.",T)}return}Ti.has(f.type)||He==null||He(f)}},[He,Me,Ie]),ie=An({agentId:D?"__controlled__":et,baseUrl:s,apiKey:a,sessionEndpoint:c,sessionBody:l,onDataMessage:D?void 0:it});r.useEffect(()=>{if(D!=null&&D.subscribeToDataMessages)return D.subscribeToDataMessages(it)},[D,it]),ve.current=()=>{var x;return(x=ie.getRoom)==null?void 0:x.call(ie)},r.useEffect(()=>{var ee;if(typeof window>"u")return;const x=((ee=window.location)==null?void 0:ee.hostname)||"";if(x==="localhost"||x==="127.0.0.1"||x==="0.0.0.0"||x.endsWith(".local")||x.endsWith(".test"))return window.__livelayerSimulateCommand=le=>{try{it(le)}catch(Ce){console.warn("[LiveLayer] simulate-command threw:",Ce)}},()=>{delete window.__livelayerSimulateCommand}},[it]);const k=r.useMemo(()=>D?{connectionState:D.connectionState,agentState:D.agentState,transcript:D.transcript,videoElement:D.videoElement,audioElement:D.audioElement,canResume:D.canResume,error:D.error,agentConfig:null,connect:async()=>{await D.onConnect()},disconnect:()=>D.onDisconnect(),getRoom:ie.getRoom,isControlled:!0}:{connectionState:ie.connectionState,agentState:ie.agentState,transcript:ie.transcript,videoElement:ie.videoElement,audioElement:ie.audioElement,canResume:ie.canResume,error:ie.error,agentConfig:ie.agentConfig,connect:ie.connect,disconnect:ie.disconnect,getRoom:ie.getRoom,isControlled:!1},[D,ie]),Kt=r.useRef(k);Kt.current=k;const Jt=r.useRef(D);Jt.current=D,r.useImperativeHandle(i,()=>({sendData:async x=>{var Ce,st;const f=Jt.current;if(f!=null&&f.publishData){try{await f.publishData(x)}catch(j){console.warn("[AvatarWidget] sendData (controlled) failed:",j)}return}const ee=(st=(Ce=Kt.current)==null?void 0:Ce.getRoom)==null?void 0:st.call(Ce),le=ee==null?void 0:ee.localParticipant;if(le!=null&&le.publishData)try{const j=new TextEncoder().encode(JSON.stringify(x));await le.publishData(j,{reliable:!0})}catch(j){console.warn("[AvatarWidget] sendData failed:",j)}}}),[]);const Zt=r.useRef(null);r.useEffect(()=>{const x=k.videoElement,f=Zt.current;if(!(!x||!f))return f.appendChild(x),()=>{x.parentNode===f&&f.removeChild(x)}},[k.videoElement]);const[qe,bt]=r.useState(!1);r.useEffect(()=>{if(!M){bt(!0);return}k.agentState==="speaking"&&!qe&&bt(!0)},[M,k.agentState,qe]),r.useEffect(()=>{if(!M)return;const x=k.connectionState;(x==="disconnected"||x==="idle")&&bt(!1)},[M,k.connectionState]),r.useEffect(()=>{if(!M||!k.videoElement||qe)return;const x=setTimeout(()=>bt(!0),5e3);return()=>clearTimeout(x)},[M,k.videoElement,qe]),r.useEffect(()=>{const x=k.videoElement;if(x){if(!M){x.style.filter="";return}x.style.transition="filter 500ms ease-out",x.style.filter=qe?"":"blur(8px)"}},[M,k.videoElement,qe]),r.useEffect(()=>{const x=k.audioElement;if(!x)return;const f=document.createElement("div");f.className="ll-audio-sink",f.setAttribute("aria-hidden","true"),f.style.cssText="position:absolute;width:0;height:0;overflow:hidden;clip:rect(0 0 0 0);pointer-events:none;",f.appendChild(x),document.body.appendChild(f),Le.attach(x);const ee=x.play();return ee&&typeof ee.catch=="function"&&ee.catch(le=>{(le==null?void 0:le.name)==="NotAllowedError"&&Be(!0)}),()=>{Le.detach(),x.parentNode===f&&f.removeChild(x),f.parentNode===document.body&&document.body.removeChild(f)}},[k.audioElement]);const he=In({gateUntilAgentReady:!0,agentState:k.agentState});r.useEffect(()=>{if(k.isControlled||k.connectionState!=="connected")return;const x=k.getRoom();if(x)return he.setupMic(x).then(()=>{const f=he.getMicStream();f&&Le.attachStream(f,"mic")}).catch(()=>{}),()=>{Le.detachSlot("mic"),he.teardownMic()}},[k.isControlled,k.connectionState]),r.useEffect(()=>{var f;if(k.connectionState!=="connected")return;const x=k.isControlled?(f=D==null?void 0:D.getRoom)==null?void 0:f.call(D):k.getRoom();if(x)return _e.attachRoom(x),pe.attachRoom(x),k.isControlled&&he.attachRoom(x),be.refresh(),()=>{_e.teardown(),pe.teardown()}},[k.isControlled,k.connectionState,D]),r.useEffect(()=>{const x=k.audioElement;x&&(x.muted=Nt)},[k.audioElement,Nt]);const ur=r.useCallback(x=>{const f={type:"user_message",text:x};if(D!=null&&D.publishData){try{D.publishData(f)}catch{}return}const ee=k.getRoom();if(ee)try{const le=new TextEncoder().encode(JSON.stringify(f));ee.localParticipant.publishData(le,{reliable:!0})}catch{}},[k,D]),dr=r.useCallback(()=>{cr(x=>!x)},[]);r.useEffect(()=>{Ae==null||Ae(k.connectionState),k.connectionState==="connected"?$e==null||$e():k.connectionState==="disconnected"&&(je==null||je())},[k.connectionState,$e,je,Ae]),r.useEffect(()=>{Re==null||Re(k.transcript)},[k.transcript,Re]),r.useEffect(()=>{Ne==null||Ne(k.agentState)},[k.agentState,Ne]),r.useEffect(()=>{gt.setThinking(k.agentState==="thinking")},[k.agentState,gt]);const Qt=r.useRef(!1);r.useEffect(()=>{!g||Qt.current||Pe&&k.connectionState==="idle"&&(Qt.current=!0,k.connect())},[g,k.connectionState,k,Pe]);const fr=r.useCallback(x=>{const f=v==null?void 0:v.find(ee=>ee.id===x);f&&(Q(!1),x!==De&&(rt(!0),k.disconnect(),ke||pt(x),y==null||y(f)))},[v,De,k,ke,y]);r.useEffect(()=>{nt&&k.connectionState==="connected"&&rt(!1)},[k.connectionState,nt]),r.useEffect(()=>{if(!_)return;const x=f=>{f.key==="Escape"&&Q(!1)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[_]);const pr=!!V||!!(se!=null&&se.avatarImageUrl)||k.isControlled,ot=zn(et,s,pr);ze===void 0&&((rn=ot.info)!=null&&rn.capabilities)&&(Pt.current=ot.info.capabilities);const vt=(se==null?void 0:se.name)??re??((on=k.agentConfig)==null?void 0:on.name)??((sn=ot.info)==null?void 0:sn.name)??"Live Layer",Dt=(se==null?void 0:se.avatarImageUrl)??V??((ln=k.agentConfig)==null?void 0:ln.avatarImageUrl)??((an=ot.info)==null?void 0:an.avatarImageUrl)??null,hr=A??((cn=k.agentConfig)==null?void 0:cn.idleLoopUrl)??((un=ot.info)==null?void 0:un.idleLoopUrl)??null,mr=z??null,gr=r.useCallback(()=>ye("expanded"),[ye]),yr=r.useCallback(()=>ye("minimized"),[ye]),en=r.useCallback(()=>{k.disconnect(),ye("hidden")},[k,ye]),br=r.useCallback(()=>{const x=k.audioElement;x&&x.play().then(()=>Be(!1)).catch(()=>{})},[k.audioElement]),vr=r.useCallback(()=>{Be(!1),k.connect()},[k]),Ue={...Fe,...ne?{}:{zIndex:ge}};I.primaryColor&&(Ue["--ll-color-primary"]=I.primaryColor),I.accentColor&&(Ue["--ll-color-accent"]=I.accentColor),I.backgroundColor&&(Ue["--ll-color-bg"]=I.backgroundColor),I.textColor&&(Ue["--ll-color-fg"]=I.textColor);const xr={...Ue,...Se.style},wr=["ll-widget",`ll-widget--${fe}`,`ll-widget--${ce?"mobile":"desktop"}`,Se.hasGeometry?"ll-widget--has-geometry":null,Se.isDragging?"is-dragging":null,Se.isResizing?"is-resizing":null,Te].filter(Boolean).join(" ");if(!Pe)return null;const _r=t.jsx("div",{className:wr,style:xr,"data-display-mode":fe,"data-position":C,"data-experience-mode":d==="EMBEDDED"?"embedded":"widget",children:fe==="expanded"&&t.jsx(si,{position:C,isMobile:ce,agentName:vt,avatarImageUrl:Dt,idleLoopUrl:hr,greeting:mr,branding:I,teamMembers:v,currentTeamMemberId:De,isSwitchingTeamMember:nt,teamSwitcherOpen:_,onToggleTeamSwitcher:()=>Q(x=>!x),onSelectTeamMember:fr,connectionState:k.connectionState,agentState:k.agentState,transcript:k.transcript,isMuted:he.isMuted,micDevices:be.mics,activeMicId:he.activeDeviceId,isCameraEnabled:_e.isEnabled,cameraPreviewEl:_e.previewEl,cameraDevices:be.cameras,activeCameraId:_e.activeDeviceId,isScreenShareEnabled:pe.isEnabled,screenPreviewEl:pe.previewEl,isSpeakerMuted:Nt,allowCamera:q,allowScreenShare:p,allowTyping:E,showMinimize:ce&&!ne?!1:ht,showClose:Et,chromeless:K,compactControls:jt,transforming:te,transformingLabel:F,languageMenuOpen:lr,onToggleLanguageMenu:()=>ar(x=>!x),needsUserGesture:mt,canResume:k.canResume,micError:he.micError,error:k.error,avatarVideoContainerRef:Zt,agentVideoEl:k.videoElement,onConnect:()=>void k.connect(),onDisconnect:()=>k.disconnect(),onRetry:vr,onResumeAudio:br,onToggleMute:he.toggleMute,onSwitchMicDevice:x=>void he.switchDevice(x),onToggleCamera:()=>void _e.toggle(),onSwitchCameraDevice:x=>void _e.switchDevice(x),onToggleScreenShare:()=>void pe.toggle(),onToggleSpeaker:dr,onSendMessage:ur,onMinimize:yr,onClose:en,onClearMicError:he.clearError,dragHandleProps:Se.dragHandleProps,resizeHandleProps:Se.resizeHandleProps})}),tn=!ne&&(fe==="hidden"||fe==="minimized")?t.jsxs("div",{className:["ll-widget","ll-widget--floating",`ll-widget--${fe}`,`ll-widget--${ce?"mobile":"desktop"}`].join(" "),style:Ue,"data-display-mode":fe,"data-position":C,children:[fe==="hidden"&&t.jsx(Xr,{position:C,isMobile:ce,isSpeaking:k.agentState==="speaking",onExpand:()=>ye("expanded"),label:`Open ${vt} widget`,avatarImageUrl:Dt,agentName:vt,containerEl:W}),fe==="minimized"&&t.jsx(Jr,{position:C,isMobile:ce,agentName:vt,avatarImageUrl:Dt,agentState:k.agentState,isMuted:he.isMuted,audioLevel:Le,onExpand:gr,onToggleMute:he.toggleMute,onClose:en})]}):null,nn=W??(typeof document<"u"?document.body:null);return t.jsxs(t.Fragment,{children:[_r,tn&&nn&&Ut.createPortal(tn,nn)]})});ir.displayName="AvatarWidgetInner";const or=r.forwardRef(function(n,i){return t.jsx(Nn,{children:t.jsx(ir,{...n,ref:i})})});or.displayName="AvatarWidget";const Pi=({agentId:e,baseUrl:n,apiKey:i,mode:o,onAgentEvent:a,className:s,style:c})=>{const l=r.useRef(null),u=r.useRef(null),d=r.useRef(a);d.current=a;const g=r.useCallback(h=>{var N;const m=h.detail;(N=d.current)==null||N.call(d,m)},[]);return r.useEffect(()=>{const h=l.current;if(!h)return;const m=document.createElement("livelayer-widget");return m.setAttribute("agent-id",e),n&&m.setAttribute("base-url",n),i&&m.setAttribute("api-key",i),o&&m.setAttribute("mode",o),m.addEventListener("agent-event",g),h.appendChild(m),u.current=m,()=>{m.removeEventListener("agent-event",g),h.removeChild(m),u.current=null}},[e]),r.useEffect(()=>{u.current&&(o?u.current.setAttribute("mode",o):u.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:l,className:s,style:c})},Di=r.forwardRef(function({id:n,intent:i,as:o="div",className:a,style:s,children:c},l){return r.createElement(o,{ref:l,"data-ll-region":n,"data-ll-intent":i,className:a,style:s},c)});function zi(e={}){const{onFieldUpdate:n,onComplete:i,source:o="all"}=e,[a,s]=r.useState({}),[c,l]=r.useState(!1),[u,d]=r.useState(null),g=r.useRef(n),h=r.useRef(i),m=r.useRef(o);r.useEffect(()=>{g.current=n,h.current=i,m.current=o},[n,i,o]);const N=r.useCallback(()=>{s({}),l(!1)},[]);return r.useEffect(()=>{if(typeof window>"u")return;const C=L=>{var w,R;const b=L.detail;if(b){if(b.phase==="field"){if(m.current!=="all"&&b.source!==m.current)return;l(!0),s(S=>S[b.fieldName]===b.value?S:{...S,[b.fieldName]:b.value});try{(w=g.current)==null||w.call(g,b)}catch(S){console.warn("[LiveLayer] useCollect onFieldUpdate threw.",S)}return}if(b.phase==="complete"){const S=b.result;if(m.current!=="all"&&S.source!==m.current)return;d(S),l(!1);try{(R=h.current)==null||R.call(h,S)}catch(v){console.warn("[LiveLayer] useCollect onComplete threw.",v)}}}};return document.addEventListener("ll-collected",C),()=>document.removeEventListener("ll-collected",C)},[]),{fields:a,isCollecting:c,lastResult:u,reset:N}}let Rn=1;function $i({onMount:e,defaultOpen:n=!1,storageKey:i="ll-debug-open"}){const[o,a]=r.useState(n),[s,c]=r.useState([]),[l,u]=r.useState(""),[d,g]=r.useState(!1),h=r.useRef(new Set),m=r.useRef([]),N=r.useRef(d);N.current=d,r.useEffect(()=>{try{const b=localStorage.getItem(i);b==="1"&&a(!0),b==="0"&&a(!1)}catch{}},[i]),r.useEffect(()=>{try{localStorage.setItem(i,o?"1":"0")}catch{}},[o,i]),r.useEffect(()=>{const b=w=>{(w.metaKey||w.ctrlKey)&&w.shiftKey&&w.key.toLowerCase()==="l"&&(w.preventDefault(),a(R=>!R))};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[]),r.useEffect(()=>{const b=setInterval(()=>{if(m.current.length===0||N.current)return;const w=m.current.splice(0,m.current.length);c(R=>[...w.reverse(),...R].slice(0,200))},100);return()=>clearInterval(b)},[]);const C=r.useRef(!1);if(r.useEffect(()=>{!e||C.current||(C.current=!0,e(b=>{m.current.push({id:Rn++,ts:Date.now(),kind:"event",type:b.eventName,data:b.data})}))},[e]),r.useEffect(()=>{const b=console.warn,w=console.log,R=(S,v)=>function(...P){try{const y=typeof P[0]=="string"?P[0]:"";y.startsWith("[LiveLayer]")&&m.current.push({id:Rn++,ts:Date.now(),kind:S,type:y.slice(0,120),data:{args:P.slice(1).map(A=>Fi(A))}})}catch{}return v.apply(this,P)};return console.warn=R("warn",b),console.log=R("log",w),()=>{console.warn=b,console.log=w}},[]),!o)return t.jsx("button",{type:"button",onClick:()=>a(!0),title:"Open LiveLayer debug panel (Cmd/Ctrl + Shift + L)","aria-label":"Open LiveLayer debug panel",style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.18)",borderRadius:999,padding:"6px 10px",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",cursor:"pointer",boxShadow:"0 4px 12px rgba(0,0,0,0.35)",opacity:.85},children:"🛰 LL debug"});const L=s.filter(b=>{if(!l)return!0;const w=l.toLowerCase();return b.type.toLowerCase().includes(w)||JSON.stringify(b.data||{}).toLowerCase().includes(w)});return t.jsxs("div",{style:{position:"fixed",left:16,bottom:16,zIndex:2147483640,width:380,maxHeight:"60vh",background:"#0d0d0d",color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:12,boxShadow:"0 16px 48px rgba(0,0,0,0.5)",font:"500 11px -apple-system, BlinkMacSystemFont, system-ui, sans-serif",letterSpacing:"-0.1px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"8px 10px",background:"rgba(255,255,255,0.04)",borderBottom:"1px solid rgba(255,255,255,0.1)",display:"flex",alignItems:"center",gap:8},children:[t.jsx("span",{style:{fontWeight:600,fontSize:12},children:"LiveLayer debug"}),t.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:[s.length," event",s.length===1?"":"s"]}),t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:()=>g(b=>!b),style:Ot(d?"#f59e0b":"transparent"),title:"Pause / resume capture",children:d?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{c([]),m.current=[]},style:Ot("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>a(!1),style:Ot("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:l,onChange:b=>u(b.target.value),placeholder:"filter by type or data…",style:{margin:8,padding:"6px 8px",background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,outline:"none"}}),t.jsx("div",{style:{flex:1,overflowY:"auto",padding:"0 8px 8px"},children:L.length===0?t.jsxs("div",{style:{padding:14,fontSize:11,color:"rgba(255,255,255,0.4)",lineHeight:1.5},children:["No events yet. Connect to the agent and trigger a tool call — the events will stream in here. You can also dispatch commands manually in DevTools:",t.jsx("pre",{style:{marginTop:6,background:"rgba(255,255,255,0.04)",padding:6,borderRadius:4,fontSize:10,whiteSpace:"pre-wrap"},children:`window.__livelayerSimulateCommand({
|
|
3
3
|
type: "navigate",
|
|
4
4
|
href: "/about"
|
|
5
|
-
})`})]}):L.map(
|
|
5
|
+
})`})]}):L.map(b=>t.jsx(Hi,{entry:b,expanded:h.current.has(b.id),onToggle:()=>{h.current.has(b.id)?h.current.delete(b.id):h.current.add(b.id),c(w=>[...w])}},b.id))})]})}function Hi({entry:e,expanded:n,onToggle:i}){const o=e.kind==="warn"?"#f59e0b":e.type.startsWith("[LiveLayer]")?"#94a3b8":e.type==="navigate"||e.type==="scroll_page"||e.type==="scroll_to"||e.type==="click"?"#22c55e":e.type==="fill_form"||e.type==="submit_form"||e.type==="focus_field"?"#a78bfa":e.type==="request_page_context"||e.type==="request_routes"?"#38bdf8":e.type==="agent_state"?"#facc15":"#cbd5e1",a=new Date(e.ts).toLocaleTimeString("en-US",{hour12:!1});return t.jsxs("button",{type:"button",onClick:i,style:{textAlign:"left",background:"transparent",border:0,color:"#fff",width:"100%",padding:"6px 4px",cursor:"pointer",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:11,lineHeight:1.4},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[t.jsx("span",{style:{color:"rgba(255,255,255,0.4)",fontVariantNumeric:"tabular-nums",fontSize:10},children:a}),t.jsx("span",{style:{color:o,fontWeight:600,flexShrink:0},children:e.type.length>50?e.type.slice(0,50)+"…":e.type})]}),n&&e.data&&t.jsx("pre",{style:{marginTop:6,padding:6,background:"rgba(255,255,255,0.04)",borderRadius:4,fontSize:10,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:JSON.stringify(e.data,null,2)})]})}function Ot(e){return{background:e,color:"#fff",border:"1px solid rgba(255,255,255,0.16)",borderRadius:999,padding:"3px 8px",fontSize:10,cursor:"pointer"}}function Fi(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function sr(e){const n=JSON.stringify(e);r.useEffect(()=>Ke.registerFields(e),[n])}function Oi({fields:e,children:n}){return sr(e),t.jsx(t.Fragment,{children:n})}function Wi(){const[e,n]=r.useState([]),i=r.useCallback(a=>{n(s=>{const c=s.findIndex(l=>l.id===a.id);if(c>=0){const l=s.slice();return l[c]=a,l}return[...s,a]})},[]),o=r.useCallback(()=>n([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}Object.defineProperty(exports,"clearFieldRegistry",{enumerable:!0,get:()=>Ke.clearFieldRegistry});Object.defineProperty(exports,"getRegisteredFields",{enumerable:!0,get:()=>Ke.getRegisteredFields});Object.defineProperty(exports,"registerFields",{enumerable:!0,get:()=>Ke.registerFields});Object.defineProperty(exports,"setFieldValue",{enumerable:!0,get:()=>Ke.setFieldValue});exports.AvatarWidget=or;exports.ErrorBoundary=Nn;exports.FieldProvider=Oi;exports.LiveLayerDebugPanel=$i;exports.LiveLayerRegion=Di;exports.LiveLayerWidget=Pi;exports.clearPageContextCache=er;exports.clearRoutesCache=rr;exports.extractPageContext=Qn;exports.extractRoutes=nr;exports.getCachedPageContext=Bt;exports.getCachedRoutes=Ct;exports.matchesPattern=qn;exports.normalizeRouteInput=tr;exports.shouldRenderAtPath=Un;exports.useAgentInfo=zn;exports.useAudioLevel=Mn;exports.useCameraState=Tn;exports.useCollect=zi;exports.useDisplayMode=Fn;exports.useDisplayModePersistence=On;exports.useIsMobile=Wn;exports.useLiveKitSession=An;exports.useMediaDevices=Dn;exports.useMicrophoneState=In;exports.usePathname=Bn;exports.useRegisterFields=sr;exports.useRouteMatch=Vn;exports.useScreenShareState=Pn;exports.useTranscript=Wi;
|