@livelayer/react 0.21.3 → 0.22.0

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.d.ts CHANGED
@@ -614,6 +614,31 @@ export declare interface FieldProviderProps {
614
614
  children: ReactNode;
615
615
  }
616
616
 
617
+ /** Runtime-inferred multi-step (wizard) structure of the current page. */
618
+ export declare interface FlowContext {
619
+ kind: "multi-step" | "single-page";
620
+ /** 1-based, best-effort (undefined when the stepper is unreadable). */
621
+ currentStep?: number;
622
+ /** best-effort total step count. */
623
+ totalSteps?: number;
624
+ /** current step's label, e.g. "Getting to know you". */
625
+ stepLabel?: string;
626
+ /** forward control if present on the current view. */
627
+ advance?: FlowControl;
628
+ /** backward control if present. */
629
+ back?: FlowControl;
630
+ /** final-step submit control if present (distinct from `advance`). */
631
+ submit?: FlowControl;
632
+ }
633
+
634
+ /** A single actionable flow control (Continue / Back / Submit) the agent can trigger. */
635
+ export declare interface FlowControl {
636
+ /** Stable logical id the SDK maps back to a live DOM node ("ll-advance" | "ll-back" | "ll-submit"). */
637
+ id: string;
638
+ /** Human label for the agent, e.g. "Continue". */
639
+ label: string;
640
+ }
641
+
617
642
  export declare function getCachedPageContext(extras?: Record<string, unknown>, opts?: ExtractOptions): PageContext;
618
643
 
619
644
  export declare function getCachedRoutes(): ExtractedRoute[];
@@ -881,6 +906,8 @@ export declare interface PageContext {
881
906
  }>;
882
907
  /** Free-form metadata bag from the consumer's pageContextExtras prop. */
883
908
  extras?: Record<string, unknown>;
909
+ /** Runtime-inferred wizard structure; absent on a plain single-page form. */
910
+ flow?: FlowContext;
884
911
  }
885
912
 
886
913
  declare interface Props {
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"&&gt.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 n=require("react/jsx-runtime"),r=require("react"),Xt=require("react-dom"),Ze=require("@livelayer/sdk"),Lt=require("livekit-client");class zn extends r.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null},this.reset=()=>{this.setState({hasError:!1,error:null})}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,i){var o,l;(l=(o=this.props).onError)==null||l.call(o,t,i)}render(){var t;return this.state.hasError?this.props.fallback?this.props.fallback:n.jsxs("div",{className:"ll-error-boundary",role:"alert",children:[n.jsx("p",{className:"ll-error-boundary__title",children:"Widget crashed"}),n.jsx("p",{className:"ll-error-boundary__message",children:((t=this.state.error)==null?void 0:t.message)||"Something went wrong."}),n.jsx("button",{type:"button",className:"ll-error-boundary__retry",onClick:this.reset,children:"Reload widget"})]}):this.props.children}}function $n(e){const[t,i]=r.useState("idle"),[o,l]=r.useState("idle"),[s,c]=r.useState([]),[a,u]=r.useState(null),[d,g]=r.useState(null),[h,m]=r.useState(null),[R,C]=r.useState(!1),[E,b]=r.useState(null),w=r.useRef(null),A=r.useRef(e.onDataMessage);A.current=e.onDataMessage,r.useEffect(()=>{const y={onConnectionStateChange:z=>{i(z),z==="connected"&&b(null)},onAgentStateChange:l,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=A.current)==null||V.call(A,z)},onResumabilityChange:C},M=new Ze.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},y);return w.current=M,i("idle"),l("idle"),c([]),u(null),g(null),m(null),C(!1),b(null),()=>{var z;(z=M.destroy)==null||z.call(M),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(M){throw b(M instanceof Error?M.message:String(M)),M}},[]),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:t,agentState:o,transcript:s,agentConfig:a,videoElement:d,audioElement:h,canResume:R,error:E,connect:S,disconnect:v,getRoom:P,session:w.current}}function Hn(){const e=r.useRef(null),t=r.useRef(new Map),i=r.useRef(null),o=r.useRef(new Set),l=r.useCallback(()=>{const C=t.current;if(C.size===0){i.current=null;return}let E=0;for(const{analyser:b,buffer:w}of C.values()){b.getByteFrequencyData(w);let A=0;for(let v=0;v<w.length;v++)A+=w[v];const S=A/w.length/255;S>E&&(E=S)}for(const b of o.current)try{b(E)}catch(w){console.error("[useAudioLevel] subscriber threw:",w)}i.current=requestAnimationFrame(l)},[]),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&&t.current.size>0&&(i.current=requestAnimationFrame(l))},[l]),a=r.useCallback(C=>{const E=t.current.get(C);if(E){try{E.node.disconnect()}catch{}try{E.analyser.disconnect()}catch{}t.current.delete(C)}},[]),u=r.useCallback((C,E)=>{const b=s();if(!b)return;a(C);const w=E(b);if(!w)return;const A=b.createAnalyser();A.fftSize=64;try{w.connect(A)}catch(S){console.warn("[useAudioLevel] connect failed for slot",C,S);return}t.current.set(C,{analyser:A,node:w,buffer:new Uint8Array(new ArrayBuffer(A.frequencyBinCount))}),c()},[a,s,c]),d=r.useCallback((C,E="agent")=>{u(E,b=>{try{return b.createMediaElementSource(C)}catch(w){return console.warn("[useAudioLevel] createMediaElementSource failed for slot",E,w),null}})},[u]),g=r.useCallback((C,E="mic")=>{u(E,b=>{try{return b.createMediaStreamSource(C)}catch(w){return console.warn("[useAudioLevel] createMediaStreamSource failed for slot",E,w),null}})},[u]),h=r.useCallback(C=>{a(C),t.current.size===0&&i.current!==null&&(cancelAnimationFrame(i.current),i.current=null)},[a]),m=r.useCallback(()=>{i.current!==null&&(cancelAnimationFrame(i.current),i.current=null);for(const C of Array.from(t.current.keys()))a(C)},[a]),R=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:R}}function Tr(e){const t=e==null?void 0:e.mediaStreamTrack;return t?new MediaStream([t]):null}function Fn(e={}){const t=e.gateUntilAgentReady??!1,i=e.agentState??null,[o,l]=r.useState(t),[s,c]=r.useState(""),[a,u]=r.useState(null),d=r.useRef(null),g=r.useRef(null),h=r.useRef({active:t,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 Lt.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,l(!0)):l(y.isMuted);const M=(P=(v=y.mediaStreamTrack)==null?void 0:v.getSettings)==null?void 0:P.call(v);M!=null&&M.deviceId&&c(M.deviceId)}catch(y){const M=y instanceof Error&&y.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw u(M),y}},[]),R=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)}},[]),E=r.useCallback(async()=>{const S=g.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]);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,l(!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:t,lastAutoIntent:null},l(t),c("")},[t]),w=r.useCallback(()=>u(null),[]),A=r.useCallback(()=>Tr(d.current),[]);return{isMuted:o,activeDeviceId:s,micError:a,toggleMute:E,setupMic:m,attachRoom:R,switchDevice:C,teardownMic:b,clearError:w,getMicStream:A}}const Pr={resolution:{width:640,height:480,frameRate:24}};function On(){const[e,t]=r.useState(!1),[i,o]=r.useState(null),[l,s]=r.useState(null),[c,a]=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,A=d.current;if(A&&w){const v=w.localParticipant.getTrackPublication(Lt.Track.Source.Camera),y=(v==null?void 0:v.track)??A;try{w.localParticipant.unpublishTrack(y)}catch{}try{(S=y.stop)==null||S.call(y)}catch{}}d.current=null,s(null),t(!1)},[]),m=r.useCallback(async w=>{const A=u.current;if(A){o(null);try{const S={...Pr};w&&(S.deviceId=w);const v=await Lt.createLocalVideoTrack(S);await A.localParticipant.publishTrack(v),d.current=v;const P=v.attach();s(P),t(!0),w&&a(w);try{A.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)}}},[]),R=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]),E=r.useCallback(()=>{h(),u.current=null,o(null),a("")},[h]),b=r.useCallback(()=>o(null),[]);return r.useEffect(()=>()=>{d.current&&d.current.stop()},[]),{isEnabled:e,error:i,previewEl:l,activeDeviceId:c,toggle:R,switchDevice:C,attachRoom:g,teardown:E,clearError:b}}function Wn(){const[e,t]=r.useState(!1),[i,o]=r.useState(null),[l,s]=r.useState(null),c=r.useRef(null),a=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(),t(!1);return}o(null);try{await m.localParticipant.setScreenShareEnabled(!0);let R=0;const C=()=>{const E=m.localParticipant.getTrackPublication(Lt.Track.Source.ScreenShare);if(E!=null&&E.track){const b=E.track.attach();s(b),t(!0);try{m.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}R++<10?setTimeout(C,100):t(!0)};C()}catch(R){const C=R instanceof Error?R.name:"";C!=="NotAllowedError"&&C!=="AbortError"&&o("Screen share unavailable. Try again."),t(!1)}}},[e,u]),g=r.useCallback(()=>{const m=c.current;if(m&&e)try{m.localParticipant.setScreenShareEnabled(!1)}catch{}u(),t(!1),o(null),c.current=null},[e,u]),h=r.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:l,toggle:d,attachRoom:a,teardown:g,clearError:h}}function Bn(){const[e,t]=r.useState([]),[i,o]=r.useState([]),l=r.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const s=await navigator.mediaDevices.enumerateDevices();t(s.filter(c=>c.kind==="audioinput")),o(s.filter(c=>c.kind==="videoinput"))}catch{}},[]);return r.useEffect(()=>{if(l(),typeof navigator>"u"||!navigator.mediaDevices)return;const s=()=>void l();return navigator.mediaDevices.addEventListener("devicechange",s),()=>navigator.mediaDevices.removeEventListener("devicechange",s)},[l]),{mics:e,cameras:i,refresh:l}}function qn(e,t,i=!1){const[o,l]=r.useState(null),[s,c]=r.useState(null),[a,u]=r.useState(!i&&!!e);return r.useEffect(()=>{if(i||!e){u(!1);return}const d=new AbortController,g=t||"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||(l(h),u(!1))}).catch(h=>{d.signal.aborted||(c(h instanceof Error?h.message:"Agent lookup failed"),u(!1))}),()=>d.abort()},[e,t,i]),{info:o,error:s,loading:a}}function Un(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function Vn(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}function Dr(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch{}}function Yn({value:e,defaultValue:t="expanded",onChange:i}={}){const o=e!==void 0,[l,s]=r.useState(t),c=o?e:l,a=r.useCallback(u=>{u!==c&&(o||s(u),i==null||i(u))},[c,o,i]);return[c,a]}const zr=["hidden","minimized","expanded"];function $r(e){return e&&zr.includes(e)?e:null}function Gn({value:e,defaultValue:t="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:l=!1}={}){const s=`${o}:display-mode`,c=r.useRef(!1),[a,u]=Yn({value:e,defaultValue:t,onChange:d=>{e===void 0&&!l&&Vn(s,d),i==null||i(d)}});return r.useEffect(()=>{if(c.current||(c.current=!0,l||e!==void 0))return;const d=$r(Un(s));d&&d!==a&&u(d)},[]),[a,u]}const Hr=640;function Xn(e=Hr){const[t,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)`,l=window.matchMedia(o),s=()=>i(l.matches);return s(),typeof l.addEventListener=="function"?(l.addEventListener("change",s),()=>l.removeEventListener("change",s)):(l.addListener(s),()=>{l.removeListener(s)})},[e]),t}const Fr=280,Or=380,Wr=8,Br=4;function Ot(e){return`${e}:geometry`}function qr(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;const i=t,{top:o,left:l,width:s,height:c}=i;return typeof o!="number"||typeof l!="number"||typeof s!="number"||typeof c!="number"||!Number.isFinite(o)||!Number.isFinite(l)||!Number.isFinite(s)||!Number.isFinite(c)?null:{top:o,left:l,width:s,height:c}}function Ct(){return typeof window>"u"?{vw:0,vh:0}:{vw:window.innerWidth,vh:window.innerHeight}}function Wt(e,t,i){const{minWidth:o,minHeight:l,edgeMargin:s,vw:c,vh:a}=i,u=Math.max(o,c-s*2),d=Math.max(l,a-s*2);return{width:Math.max(o,Math.min(u,e)),height:Math.max(l,Math.min(d,t))}}function Bt(e,t,i,o,l){const{edgeMargin:s,vw:c,vh:a}=l,u=s,d=s,g=Math.max(u,c-i-s),h=Math.max(d,a-o-s);return{top:Math.max(d,Math.min(h,e)),left:Math.max(u,Math.min(g,t))}}function Ur(e){const{draggable:t,resizable:i,persistKey:o,disablePersistence:l,minWidth:s=Fr,minHeight:c=Or,edgeMargin:a=Wr}=e,[u,d]=r.useState(null),[g,h]=r.useState(!1),[m,R]=r.useState(!1),C=r.useRef(null),E=r.useRef(null),b=r.useRef(!1),w=r.useRef(null);w.current=u;const A=r.useCallback(p=>{l||(p===null?Dr(Ot(o)):Vn(Ot(o),JSON.stringify(p)))},[l,o]);r.useEffect(()=>{if(b.current||(b.current=!0,l))return;const p=qr(Un(Ot(o)));if(!p)return;const{vw:L,vh:I}=Ct(),H=Wt(p.width,p.height,{minWidth:s,minHeight:c,edgeMargin:a,vw:L,vh:I}),U=Bt(p.top,p.left,H.width,H.height,{edgeMargin:a,vw:L,vh:I});d({...U,...H})},[]),r.useEffect(()=>{if(typeof window>"u")return;const p=()=>{d(L=>{if(L===null)return null;const{vw:I,vh:H}=Ct(),U=Wt(L.width,L.height,{minWidth:s,minHeight:c,edgeMargin:a,vw:I,vh:H});return{...Bt(L.top,L.left,U.width,U.height,{edgeMargin:a,vw:I,vh:H}),...U}})};return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[s,c,a]);const S=r.useCallback(p=>{if(!t||p.pointerType==="mouse"&&p.button!==0)return;const L=p.target;if(L&&typeof L.closest=="function"&&L.closest('button, a, input, select, textarea, [role="listbox"], [role="option"], [data-ll-no-drag]'))return;let I,H,U,K;const W=w.current;if(W)({top:I,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;I=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:I,startLeft:H,width:U,height:K,moved:!1}},[t]),v=r.useCallback(p=>{const L=C.current;if(!L)return;const I=p.clientX-L.startClientX,H=p.clientY-L.startClientY;if(!L.moved&&Math.abs(I)+Math.abs(H)>Br&&(L.moved=!0,h(!0)),!L.moved)return;const{vw:U,vh:K}=Ct(),W=Bt(L.startTop+H,L.startLeft+I,L.width,L.height,{edgeMargin:a,vw:U,vh:K});d({...W,width:L.width,height:L.height})},[a]),P=r.useCallback(p=>{const L=C.current;if(L){try{p.currentTarget.releasePointerCapture(p.pointerId)}catch{}C.current=null,L.moved&&(h(!1),d(I=>(I&&A(I),I)))}},[A]),y=r.useCallback(()=>{C.current=null,E.current=null,h(!1),R(!1),d(null),A(null)},[A]),M=r.useCallback(p=>{if(!i||p.pointerType==="mouse"&&p.button!==0)return;p.stopPropagation();let L,I,H,U;const K=w.current;if(K)({top:L,left:I,width:H,height:U}=K);else{const W=p.currentTarget.closest(".ll-widget"),J=W==null?void 0:W.getBoundingClientRect();if(!J)return;L=J.top,I=J.left,H=J.width,U=J.height}try{p.currentTarget.setPointerCapture(p.pointerId)}catch{}E.current={startClientX:p.clientX,startClientY:p.clientY,startWidth:H,startHeight:U,top:L,left:I},R(!0)},[i]),z=r.useCallback(p=>{const L=E.current;if(!L)return;const I=p.clientX-L.startClientX,H=p.clientY-L.startClientY,{vw:U,vh:K}=Ct(),W=U-L.left-a,J=K-L.top-a,te=Wt(L.startWidth+I,L.startHeight+H,{minWidth:s,minHeight:c,edgeMargin:a,vw:Math.min(U,L.left+W+a),vh:Math.min(K,L.top+J+a)});d({top:L.top,left:L.left,...te})},[a,s,c]),V=r.useCallback(p=>{if(E.current){try{p.currentTarget.releasePointerCapture(p.pointerId)}catch{}E.current=null,R(!1),d(I=>(I&&A(I),I))}},[A]);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":t?"":void 0},resizeHandleProps:{onPointerDown:M,onPointerMove:z,onPointerUp:V,onPointerCancel:V,"data-ll-resize-handle":i?"":void 0},reset:y}}const hn="__llHistoryPatched",jt="ll:pathname";function Vr(){if(typeof window>"u"||window.history[hn])return;const e=window.history.pushState,t=window.history.replaceState;window.history.pushState=function(...i){const o=e.apply(this,i);return window.dispatchEvent(new Event(jt)),o},window.history.replaceState=function(...i){const o=t.apply(this,i);return window.dispatchEvent(new Event(jt)),o},window.history[hn]=!0}function mn(){return typeof window>"u"?"/":window.location.pathname||"/"}function Kn(e){const[t,i]=r.useState(()=>e??mn());return r.useEffect(()=>{if(e!==void 0)return;Vr();const o=()=>i(mn());return o(),window.addEventListener("popstate",o),window.addEventListener(jt,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(jt,o)}},[e]),e??t}const gn=new Map,Yr=/[\\^$+?.()|{}[\]]/g;function Gr(e){return e.replace(Yr,"\\$&")}function Xr(e){const t=gn.get(e);if(t)return t;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",l="",s=i.replace(/\*\*/g,o).replace(/\*/g,l),a=Gr(s).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(l,"g"),"[^/]+"),u=new RegExp(`^${a}\\/?$`);return gn.set(e,u),u}function Kr(e,t){const i=t.length>1&&t.endsWith("/")?t.slice(0,-1):t;return Xr(e).test(i)}function Jn(e,t){return typeof e=="function"?e(t):e instanceof RegExp?e.test(t):Kr(e,t)}function yn(e,t){if(!e||e.length===0)return!1;for(const i of e)if(Jn(i,t))return!0;return!1}function Zn(e,t,i){return e===void 0?!0:yn(i,e)?!1:t&&t.length>0?yn(t,e):!0}function Qn(e,t,i){return r.useMemo(()=>Zn(e,t,i),[e,t,i])}function Jr(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 Zr(e){const t=r.useMemo(()=>Jr(e.config),[e.config]),i=e.baseUrl.replace(/\/+$/,""),o=r.useRef(null),l=r.useCallback(u=>{try{new Audio(`${i}${u}`).play().catch(()=>{})}catch{}},[i]),s=r.useCallback(()=>{t.navigate&&l("/audio/page-change-sound.mp3")},[t.navigate,l]),c=r.useCallback(()=>{t.action&&l("/audio/confirmation-sound.mp3")},[t.action,l]),a=r.useCallback(u=>{if(!t.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,t.thinking]);return r.useEffect(()=>()=>{if(o.current){try{o.current.pause()}catch{}o.current=null}},[]),r.useMemo(()=>({playPageChange:s,playConfirmation:c,setThinking:a}),[s,c,a])}const bn=({muted:e=!1,className:t})=>e?n.jsxs("svg",{className:t,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:[n.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"}),n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"})]}):n.jsx("svg",{className:t,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:n.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"})}),vn=({className:e})=>n.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:n.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})=>n.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,"aria-hidden":"true",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})}),ei={left:180,right:0,up:-90,down:90},xn=({direction:e="right",className:t})=>n.jsx("svg",{className:t,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${ei[e]}deg)`},"aria-hidden":"true",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function ti(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const er="ll-hidden-tab-center-y",ni=5,wn=16;function ri(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(er);if(!e)return null;const t=Number.parseFloat(e);return Number.isFinite(t)?t:null}catch{return null}}function _n(e){if(!(typeof window>"u"))try{window.localStorage.setItem(er,String(e))}catch{}}const ii=({position:e,isMobile:t,isSpeaking:i,onExpand:o,label:l="Open widget",avatarImageUrl:s,agentName:c,containerEl:a})=>{const u=ti(e),d=u==="right"?"left":"right",g=t?80:72,h=!!s,m=!!a,[R,C]=r.useState(null),[E,b]=r.useState(!1),w=r.useRef(null),A=r.useRef(!1),S=r.useCallback(T=>{if(typeof window>"u")return T;const q=g/2,p=wn+q,L=window.innerHeight-wn-q;return L<p?Math.max(p,T):Math.max(p,Math.min(L,T))},[g]);r.useEffect(()=>{if(m){C(null);return}const T=ri();C(S(T??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(T=>{if(!m&&!(T.pointerType==="mouse"&&T.button!==0)&&R!==null){try{T.currentTarget.setPointerCapture(T.pointerId)}catch{}w.current={startClientY:T.clientY,startCenterY:R,moved:!1}}},[R,m]),P=r.useCallback(T=>{const q=w.current;if(!q)return;const p=T.clientY-q.startClientY;!q.moved&&Math.abs(p)>ni&&(q.moved=!0,b(!0)),q.moved&&C(S(q.startCenterY+p))},[S]),y=r.useCallback(T=>{const q=w.current;if(q){try{T.currentTarget.releasePointerCapture(T.pointerId)}catch{}w.current=null,q.moved&&(b(!1),A.current=!0,C(p=>(p!==null&&_n(p),p)))}},[]),M=r.useCallback(()=>{if(A.current){A.current=!1;return}o()},[o]),z=r.useCallback(T=>{if(T.key==="ArrowUp"||T.key==="ArrowDown"){T.preventDefault();const q=T.key==="ArrowUp"?-8:8;C(p=>{if(p===null)return p;const L=S(p+q);return _n(L),L})}},[S]),V=["ll-hidden",`ll-hidden--${u}`,t?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,E?"is-dragging":null,h?"ll-hidden--with-avatar":null,m?"ll-hidden--scoped":null].filter(Boolean).join(" "),re=R===null?void 0:{top:`${R-g/2}px`,transform:"none"};return n.jsx("button",{type:"button",className:V,onPointerDown:v,onPointerMove:P,onPointerUp:y,onPointerCancel:y,onClick:M,onKeyDown:z,"aria-label":l,"data-position":e,style:re,children:h?n.jsxs(n.Fragment,{children:[n.jsx(xn,{direction:d,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),n.jsx("img",{src:s,alt:c?`${c} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):n.jsx(xn,{direction:d,className:"ll-hidden__chevron"})})},oi=({audioLevel:e,bars:t=20,maxHeight:i=20,minHeight:o=4,className:l,barClassName:s})=>{const c=r.useRef(null),a=r.useRef([]),u=r.useMemo(()=>{const g=(Math.sqrt(5)-1)/2;return Array.from({length:t},(h,m)=>.5+m*g%1*.5)},[t]);r.useEffect(()=>e.subscribe(h=>{for(let m=0;m<t;m++){const R=a.current[m];if(!R)continue;const C=Math.max(o,h*i*u[m]);R.style.height=`${C}px`}}),[e,t,i,o,u]);const d=["ll-waveform",l].filter(Boolean).join(" ");return n.jsx("div",{ref:c,className:d,"aria-hidden":"true",children:Array.from({length:t},(g,h)=>n.jsx("div",{ref:m=>{a.current[h]=m},className:["ll-waveform__bar",s].filter(Boolean).join(" "),style:{height:`${o}px`}},h))})},si=({position:e,isMobile:t,agentName:i,avatarImageUrl:o,agentState:l,isMuted:s,audioLevel:c,onExpand:a,onToggleMute:u,onClose:d})=>t?n.jsx("div",{className:"ll-minimized ll-minimized--mobile",role:"region","aria-label":`${i} widget`,children:n.jsxs("button",{type:"button",className:"ll-minimized__surface",onClick:a,"aria-label":`Expand ${i} widget`,children:[o?n.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):n.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),n.jsx(oi,{audioLevel:c,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),n.jsx("span",{className:"ll-minimized__name",children:i}),n.jsxs("div",{className:"ll-minimized__controls",children:[n.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:n.jsx(bn,{muted:s,className:"ll-minimized__icon"})}),n.jsx(vn,{className:"ll-minimized__icon ll-minimized__icon--expand"})]})]})}):n.jsx("div",{className:"ll-minimized ll-minimized--desktop","data-position":e,role:"region","aria-label":`${i} widget`,children:n.jsxs("div",{className:"ll-minimized__surface",children:[o?n.jsx("img",{src:o,alt:i,className:"ll-minimized__avatar"}):n.jsx("div",{className:"ll-minimized__avatar ll-minimized__avatar--placeholder"}),n.jsxs("div",{className:"ll-minimized__meta",children:[n.jsx("span",{className:"ll-minimized__name",children:i}),n.jsx("span",{className:"ll-minimized__state",children:l==="speaking"?"Speaking":l==="thinking"?"Thinking":"Listening"})]}),n.jsxs("div",{className:"ll-minimized__controls",children:[n.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:u,"aria-label":s?"Unmute microphone":"Mute microphone",children:n.jsx(bn,{muted:s,className:"ll-minimized__icon"})}),n.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:a,"aria-label":`Expand ${i} widget`,children:n.jsx(vn,{className:"ll-minimized__icon"})}),n.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:d,"aria-label":"Close widget",children:n.jsx(Qr,{className:"ll-minimized__icon"})})]})]})}),li=({src:e,alt:t,preCannedPlaying:i=!1,className:o,style:l})=>{const[s,c]=r.useState(!1),a=r.useRef(e);if(r.useEffect(()=>{a.current!==e&&(a.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,...l};return n.jsx("img",{src:e,alt:t,className:o,style:u,loading:"eager",fetchPriority:"high",onLoad:()=>c(!0)})},ai="#E06540";function ci({size:e=14,className:t,fill:i=ai}){return n.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 52 52",fill:"none",className:t,"aria-hidden":!0,children:[n.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}),n.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}),n.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 ui=8,Cn=8,di=({open:e,onClose:t,anchorRef:i,children:o})=>{const l=r.useRef(null),[s,c]=r.useState(null);return r.useLayoutEffect(()=>{if(!e){c(null);return}const a=i.current;if(!a)return;const u=()=>{const d=a.getBoundingClientRect(),g={top:d.top-ui,left:d.left+d.width/2},h=Cn+90,m=window.innerWidth-Cn-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 a=d=>{const g=d.target,h=l.current,m=i.current;h&&h.contains(g)||m&&m.contains(g)||t()},u=d=>{d.key==="Escape"&&(d.stopPropagation(),t())};return document.addEventListener("mousedown",a),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",a),document.removeEventListener("keydown",u)}},[e,t,i]),!e||s===null||typeof document>"u"?null:Xt.createPortal(n.jsx("div",{ref:l,className:"ll-overflow-popover",role:"menu",style:{position:"fixed",top:s.top,left:s.left,transform:"translate(-50%, -100%)"},children:o}),document.body)},fi=({isMuted:e,onToggleMute:t,isCameraEnabled:i,onToggleCamera:o,allowCamera:l,isScreenShareEnabled:s,onToggleScreenShare:c,allowScreenShare:a,isSpeakerMuted:u,onToggleSpeaker:d,allowTyping:g,isTypingOpen:h,onToggleTyping:m,onDisconnect:R})=>{const[C,E]=r.useState(!1),b=r.useRef(null);return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"ll-toolbar ll-toolbar--compact","data-testid":"compact-toolbar",onClick:w=>w.stopPropagation(),children:[n.jsx("button",{type:"button",className:`ll-tool ${e?"is-muted":""}`,onClick:t,"aria-label":e?"Unmute microphone":"Mute microphone",children:n.jsx(rr,{muted:e})}),n.jsx("button",{ref:b,type:"button",className:`ll-tool ${C?"is-on":""}`,onClick:()=>E(w=>!w),"aria-label":"More controls","aria-haspopup":"menu","aria-expanded":C,children:n.jsx(pi,{})}),n.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:R,"aria-label":"End conversation",children:n.jsx(or,{})})]}),n.jsxs(di,{open:C,onClose:()=>E(!1),anchorRef:b,children:[l&&n.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${i?"is-on":""}`,onClick:()=>{o(),E(!1)},children:[n.jsx(nr,{}),n.jsx("span",{children:i?"Stop camera":"Start camera"})]}),a&&n.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${s?"is-on":""}`,onClick:()=>{c(),E(!1)},children:[n.jsx(tr,{}),n.jsx("span",{children:s?"Stop sharing":"Share screen"})]}),n.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${u?"is-on":""}`,onClick:()=>{d(),E(!1)},children:[n.jsx(ir,{muted:u}),n.jsx("span",{children:u?"Unmute speaker":"Mute speaker"})]}),g&&n.jsxs("button",{type:"button",className:`ll-overflow-popover__item ${h?"is-on":""}`,onClick:()=>{m(),E(!1)},children:[n.jsx(hi,{}),n.jsx("span",{children:h?"Hide typing":"Type a message"})]}),n.jsxs("button",{type:"button",className:"ll-overflow-popover__item is-active",disabled:!0,"aria-current":"true",children:[n.jsx("span",{className:"ll-overflow-popover__lang-code",children:"EN"}),n.jsx("span",{children:"English"})]})]})]})};function pi(){return n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[n.jsx("circle",{cx:"6",cy:"12",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),n.jsx("circle",{cx:"18",cy:"12",r:"1.5"})]})}function hi(){return n.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:n.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 mi=({position:e,isMobile:t,agentName:i,avatarImageUrl:o,idleLoopUrl:l,greeting:s,branding:c,teamMembers:a,currentTeamMemberId:u,isSwitchingTeamMember:d,teamSwitcherOpen:g,onToggleTeamSwitcher:h,onSelectTeamMember:m,languageMenuOpen:R,onToggleLanguageMenu:C,connectionState:E,agentState:b,transcript:w,canResume:A,needsUserGesture:S,error:v,isMuted:P,micError:y,micDevices:M,activeMicId:z,isCameraEnabled:V,cameraPreviewEl:re,cameraDevices:T,activeCameraId:q,isScreenShareEnabled:p,screenPreviewEl:L,isSpeakerMuted:I,allowCamera:H,allowScreenShare:U,allowTyping:K,showMinimize:W=!0,showClose:J=!0,chromeless:te=!1,compactControls:F=!1,transforming:de,transformingLabel:X,avatarVideoContainerRef:ye,agentVideoEl:Z,onConnect:Qe,onDisconnect:et,onRetry:ft,onResumeAudio:pt,onToggleMute:tt,onSwitchMicDevice:ht,onToggleCamera:$e,onSwitchCameraDevice:He,onToggleScreenShare:Ae,onToggleSpeaker:Re,onSendMessage:Ne,onMinimize:Me,onClose:Ie,onClearMicError:Fe,dragHandleProps:Te,resizeHandleProps:D})=>{var ot;const Pe=((a==null?void 0:a.length)??0)>1,Oe=E==="connecting"||E==="connected",be=E==="connected",mt=E==="idle"||E==="disconnected"||E==="error",[De,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[Rt,gt]=r.useState(!1);r.useEffect(()=>{if(!be){gt(!1);return}if(De)return;const _=setTimeout(()=>gt(!0),8e3);return()=>clearTimeout(_)},[be,De]);const ze=E==="connecting"||be&&!!o&&!De&&!Rt,se=r.useRef(null),nt=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 _=nt.current;_&&(_.innerHTML="",L&&(L.style.width="100%",L.style.height="100%",L.style.objectFit="contain",_.appendChild(L)))},[L]);const[ne,ce]=r.useState(!1),[We,Be]=r.useState(!1),fe=r.useRef(null),ve=r.useRef(null);r.useEffect(()=>{if(!ne&&!We&&!R&&!g)return;const _=()=>{ce(!1),Be(!1),R&&C(),g&&h()};return document.addEventListener("click",_),()=>document.removeEventListener("click",_)},[ne,We,R,g,C,h]);const[yt,Nt]=r.useState(!1),Mt=r.useCallback(()=>Nt(_=>!_),[]),[rt,It]=r.useState(""),Se=r.useCallback(_=>{_.preventDefault();const Q=rt.trim();Q&&(Ne(Q),It(""))},[rt,Ne]),Ee=c.productName||"Live Layer",_e=!c.productName;let pe=null,xe=null;for(let _=w.length-1;_>=0;_--){const Q=w[_];if(!pe&&Q.role==="agent"?pe=Q:!xe&&Q.role==="user"&&(xe=Q),pe&&xe)break}const bt=be?(pe==null?void 0:pe.text)||null:s||null,qe=be&&(xe==null?void 0:xe.text)||null,it=["ll-expanded",t?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return n.jsxs("div",{className:it,"data-position":e,"data-state":be?"connected":Oe?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[n.jsxs("div",{className:"ll-expanded__bg",children:[o?n.jsx(li,{src:o,alt:i,className:"ll-expanded__bg-img"}):n.jsx("div",{className:"ll-expanded__bg-fallback",children:n.jsx("span",{className:"ll-expanded__bg-initial",children:((ot=i==null?void 0:i.charAt(0))==null?void 0:ot.toUpperCase())||"A"})}),l&&!be&&n.jsx("video",{className:"ll-expanded__bg-idle",src:l,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),n.jsx("div",{ref:ye,className:"ll-expanded__video"}),ze&&n.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--connecting",children:[n.jsx("div",{className:"ll-expanded__spinner"}),n.jsx("p",{className:"ll-expanded__overlay-text",children:d?"Switching...":"Connecting..."})]}),S&&be&&n.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:pt,children:[n.jsx("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:n.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"})}),n.jsx("p",{className:"ll-expanded__overlay-text",children:"Tap to enable audio"})]}),de&&n.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--transforming",role:"status","aria-live":"polite","aria-label":X,children:[n.jsx("div",{className:"ll-expanded__spinner"}),n.jsx("p",{className:"ll-expanded__overlay-text",children:X})]}),Oe?n.jsxs(n.Fragment,{children:[!F&&n.jsxs("div",{className:"ll-expanded__topbar",...Te,children:[!te&&n.jsxs("div",{className:"ll-expanded__topbar-left",children:[n.jsxs("div",{className:"ll-expanded__pill-wrap",children:[n.jsxs("button",{type:"button",className:"ll-hpill",onClick:_=>{Pe&&(_.stopPropagation(),h())},"aria-haspopup":Pe?"listbox":void 0,"aria-expanded":Pe?g:void 0,children:[n.jsx("span",{className:"ll-hpill__label",children:i}),Pe&&n.jsx(kt,{})]}),Pe&&g&&n.jsx("div",{className:"ll-hmenu",onClick:_=>_.stopPropagation(),role:"listbox",children:a==null?void 0:a.map(_=>n.jsxs("button",{type:"button",className:`ll-hmenu__item ${_.id===u?"is-active":""}`,onClick:()=>m(_.id),role:"option","aria-selected":_.id===u,children:[_.avatarImageUrl&&n.jsx("img",{src:_.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),n.jsx("span",{className:"ll-hmenu__name",children:_.name}),_.role&&n.jsx("span",{className:"ll-hmenu__role",children:_.role})]},_.id))})]}),n.jsxs("div",{className:"ll-expanded__pill-wrap",children:[n.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:_=>{_.stopPropagation(),C()},"aria-haspopup":"listbox","aria-expanded":R,"aria-label":"Language: English",title:"Language: English",children:[n.jsx("span",{className:"ll-hpill__label",children:"EN"}),n.jsx(kt,{})]}),R&&n.jsx("div",{className:"ll-hmenu",onClick:_=>_.stopPropagation(),role:"listbox",children:n.jsx("button",{type:"button",className:"ll-hmenu__item is-active",role:"option","aria-selected":!0,children:n.jsx("span",{className:"ll-hmenu__name",children:"English"})})})]}),n.jsx("span",{className:`ll-expanded__state ll-expanded__state--${b}`,children:b})]}),n.jsxs("div",{className:"ll-expanded__header-actions",children:[W!==!1&&n.jsx("button",{type:"button",className:"ll-hbtn",onClick:Me,"aria-label":"Minimize widget",title:"Minimize",children:n.jsx(Sn,{})}),J!==!1&&n.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ie,"aria-label":"End call",title:"End call",children:n.jsx(kn,{})})]})]}),F&&n.jsxs("div",{className:"ll-compact-status","data-state":b,children:[n.jsx("span",{className:"ll-compact-status__dot","aria-hidden":!0}),n.jsx("span",{className:"ll-compact-status__label",children:b})]})]}):n.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",...Te,children:[!F&&(_e?n.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:[n.jsx(ci,{size:14,className:"ll-expanded__brand-mark"}),n.jsx("span",{children:Ee})]}):n.jsx("span",{className:"ll-expanded__brand",children:Ee})),n.jsxs("div",{className:"ll-expanded__header-actions",children:[!F&&W!==!1&&n.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:Me,"aria-label":"Minimize widget",children:n.jsx(Sn,{})}),J!==!1&&n.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Ie,"aria-label":"Close widget",children:n.jsx(kn,{})})]})]}),mt&&(()=>{const _=A?"Resume session":E==="disconnected"?"Reconnect to agent":"Start video call",Q=!v;return n.jsxs(n.Fragment,{children:[Q&&n.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:Qe,"aria-label":_,children:[n.jsx("div",{className:"ll-expanded__play-circle",children:n.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:n.jsx("polygon",{points:"6 3 20 12 6 21 6 3"})})}),F&&n.jsx("span",{className:"ll-expanded__play-label",children:_})]}),!F&&n.jsxs("div",{className:"ll-expanded__bottom ll-expanded__bottom--idle",children:[s&&n.jsx("div",{className:"ll-expanded__transcript",children:n.jsx("p",{className:"ll-expanded__transcript-text",children:s})}),n.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:Qe,"aria-label":_,children:_})]})]})})(),n.jsxs("div",{className:`ll-expanded__pip ${Oe&&(V||p)?"is-visible":""}`,children:[n.jsx("div",{ref:nt,className:p?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),n.jsx("div",{ref:se,className:!p&&V?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),Oe?n.jsxs("div",{className:"ll-expanded__bottom",children:[!F&&bt&&n.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:n.jsx("p",{className:"ll-expanded__transcript-text",children:bt})}),!F&&qe&&n.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:n.jsx("p",{className:"ll-expanded__transcript-text",children:qe})}),!te&&!F&&n.jsxs("div",{className:"ll-toolbar",onClick:_=>_.stopPropagation(),children:[U&&n.jsx("button",{type:"button",className:`ll-tool ${p?"is-on":""}`,onClick:Ae,"aria-label":p?"Stop sharing screen":"Share screen",title:p?"Stop sharing":"Share screen",children:n.jsx(tr,{})}),H&&n.jsxs("div",{className:"ll-tool-split",children:[n.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${V?"is-on":""}`,onClick:$e,"aria-label":V?"Turn off camera":"Turn on camera",title:V?"Stop camera":"Start camera",children:n.jsx(nr,{})}),n.jsx("button",{ref:ve,type:"button",className:`ll-tool ll-tool--right ${V?"is-on":""}`,onClick:_=>{_.stopPropagation(),Be(Q=>!Q),ce(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":We,children:n.jsx(kt,{})}),We&&T.length>0&&n.jsx(En,{label:"Camera",devices:T,activeId:q,anchorRef:ve,onPick:_=>{Be(!1),He(_)}})]}),n.jsxs("div",{className:"ll-tool-split",children:[n.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${P?"is-muted":""}`,onClick:tt,"aria-label":P?"Unmute microphone":"Mute microphone",title:P?"Unmute":"Mute",children:n.jsx(rr,{muted:P})}),n.jsx("button",{ref:fe,type:"button",className:`ll-tool ll-tool--right ${P?"is-muted":""}`,onClick:_=>{_.stopPropagation(),ce(Q=>!Q),Be(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":ne,children:n.jsx(kt,{})}),ne&&M.length>0&&n.jsx(En,{label:"Microphone",devices:M,activeId:z,anchorRef:fe,onPick:_=>{ce(!1),ht(_)}})]}),n.jsx("button",{type:"button",className:`ll-tool ${I?"is-muted":""}`,onClick:Re,"aria-label":I?"Unmute speaker":"Mute speaker",title:I?"Unmute speaker":"Mute speaker",children:n.jsx(ir,{muted:I})}),n.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:et,"aria-label":"End conversation",title:"End conversation",children:n.jsx(or,{})})]}),!te&&F&&n.jsx(fi,{isMuted:P,onToggleMute:tt,isCameraEnabled:V,onToggleCamera:$e,allowCamera:H,isScreenShareEnabled:p,onToggleScreenShare:Ae,allowScreenShare:U,isSpeakerMuted:I,onToggleSpeaker:Re,allowTyping:K,isTypingOpen:yt,onToggleTyping:Mt,onDisconnect:et}),!te&&K&&(F?yt:!0)&&n.jsxs("form",{className:"ll-message-input",onSubmit:Se,children:[n.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:rt,onChange:_=>It(_.target.value),"aria-label":"Message the agent"}),rt.trim()&&n.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:n.jsx(gi,{})})]})]}):null,(()=>{if(y&&E!=="error")return n.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[n.jsx("span",{children:y}),n.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:Fe,"aria-label":"Dismiss",children:"×"})]});if(!v||E!=="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),n.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[n.jsx("span",{children:_}),n.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:ft,children:Q})]})})(),(D==null?void 0:D["data-ll-resize-handle"])!==void 0&&n.jsx("div",{className:"ll-expanded__resize-grip",...D,"aria-hidden":!0,children:n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[n.jsx("line",{x1:"11",y1:"4",x2:"4",y2:"11"}),n.jsx("line",{x1:"11",y1:"8",x2:"8",y2:"11"})]})})]})};function kt(){return n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":!0,children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}function kn(){return n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Sn(){return n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":!0,children:n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})})}function tr(){return n.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:[n.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),n.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function nr(){return n.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:[n.jsx("path",{d:"M23 7l-7 5 7 5V7z"}),n.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2"})]})}function rr({muted:e}){return n.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:[n.jsx("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),n.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),e&&n.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function ir({muted:e}){return n.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:[n.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?n.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}):n.jsxs(n.Fragment,{children:[n.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"}),n.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]})]})}function gi(){return n.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:[n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),n.jsx("polyline",{points:"12 5 19 12 12 19"})]})}function or(){return n.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:n.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 En=({label:e,devices:t,activeId:i,onPick:o,anchorRef:l})=>{const[s,c]=r.useState(null);return r.useLayoutEffect(()=>{const a=()=>{const u=l.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 a(),window.addEventListener("scroll",a,!0),window.addEventListener("resize",a),()=>{window.removeEventListener("scroll",a,!0),window.removeEventListener("resize",a)}},[l]),s===null||typeof document>"u"?null:Xt.createPortal(n.jsxs("div",{className:"ll-device-menu ll-device-menu--floating",onClick:a=>a.stopPropagation(),role:"listbox",style:{position:"fixed",top:s.top,left:s.left,transform:"translate(-50%, -100%)"},children:[n.jsx("p",{className:"ll-device-menu__label",children:e}),t.map((a,u)=>{const d=i===a.deviceId;return n.jsxs("button",{type:"button",className:`ll-device-menu__item ${d?"is-active":""}`,onClick:()=>o(a.deviceId),role:"option","aria-selected":d,children:[d&&n.jsx("span",{className:"ll-device-menu__dot",children:"●"}),n.jsx("span",{className:"ll-device-menu__name",children:a.label||`${e} ${u+1}`})]},a.deviceId||u)})]}),document.body)},yi=["[data-ll-private]","[data-ll-skip]",".ll-widget"];function At(e){let t=e;for(;t;){for(const i of yi)if(t.matches(i))return!0;t=t.parentElement}return!1}function Vt(e){if(At(e))return!1;if(e instanceof HTMLInputElement){if(e.type==="password")return!1;const t=(e.getAttribute("autocomplete")||"").toLowerCase();if(t==="off"||t.startsWith("cc-"))return!1}return!0}const bi=/\b(continue|next|proceed|move\s*on|forward)\b|→|›/i,Ln=/\b(back|previous|prev|go\s*back)\b|←|‹/i,vi=/\b(submit|finish|done|complete|send)\b/i,dt=new Map;function jn(e){const t=dt.get(e);return t&&t.isConnected?t:null}function Xe(e){if(At(e)||e.hidden||e.getAttribute("aria-hidden")==="true")return!0;const t=typeof window<"u"&&window.getComputedStyle?window.getComputedStyle(e):null;return!!(t&&(t.display==="none"||t.visibility==="hidden"))}function xi(e){return!!(e.disabled||e.getAttribute("aria-disabled")==="true")}function wi(e){return(e.innerText||e.textContent||e.getAttribute("aria-label")||e.value||"").trim()}function _i(e){return Array.from(e.querySelectorAll('button, [role="button"], input[type="submit"], input[type="button"]')).filter(i=>!Xe(i)&&!xi(i))}function sr(e){dt.clear();const t=_i(e);let i,o,l;for(const a of t){const u=wi(a);if(!u||u.length>40)continue;const d=a.getAttribute("type")==="submit"||a.tagName==="BUTTON"&&!a.getAttribute("type")&&!!a.closest("form");!i&&bi.test(u)&&!Ln.test(u)?(i={id:"ll-advance",label:u},dt.set("ll-advance",a)):!o&&Ln.test(u)?(o={id:"ll-back",label:u},dt.set("ll-back",a)):!l&&(vi.test(u)||d)&&(l={id:"ll-submit",label:u},dt.set("ll-submit",a))}const s=Ai(e);return{kind:i||s.totalSteps?"multi-step":"single-page",advance:i,back:o,submit:l,...s}}const Ci=60;function lr(e){return e.replace(/^\s*(step\s+)?\d{1,2}(?:[.):\-]+\s*|\s+)/i,"").replace(/\s+/g," ").trim().slice(0,Ci)}function ki(e){const t=e.getAttribute("class");return t?t.toLowerCase():""}const Si=/stepper|wizard|ant-steps|step-indicator/;function Ei(e){return Si.test(ki(e))}function An(e){const t=e.getAttribute("aria-current");return t==="step"||t==="true"?!0:Array.from(e.classList).some(i=>/(^|[-_])(active|current|selected)([-_]|$)/i.test(i))}const Li='[aria-current="step"],[aria-current="true"],[class*="active"],[class*="Active"],[class*="current"],[class*="Current"],[class*="selected"],[class*="Selected"]';function ji(e){return An(e)?!0:Array.from(e.querySelectorAll(Li)).some(An)}function Rn(e,t){const i=lr(e[t].innerText||e[t].textContent||"");return{totalSteps:e.length,currentStep:t+1,...i?{stepLabel:i}:{}}}function Ai(e){const t=e.querySelector('[aria-current="step"]');if(t&&t.parentElement&&!Xe(t)){const l=Array.from(t.parentElement.children).filter(c=>c.tagName===t.tagName&&!Xe(c)),s=l.indexOf(t);if(s>=0&&l.length>=2)return Rn(l,s)}const i=e.querySelector('[role="progressbar"]');if(i&&!Xe(i)){const l=Number(i.getAttribute("aria-valuenow")),s=Number(i.getAttribute("aria-valuemax"));if(Number.isFinite(l)&&Number.isFinite(s)&&s>=2){const c=(i.getAttribute("aria-valuetext")||"").trim();return{totalSteps:s,currentStep:l,...c?{stepLabel:lr(c)}:{}}}}const o=Array.from(e.querySelectorAll('[class*="step"], [class*="Step"], [class*="wizard"], [class*="Wizard"]')).filter(l=>!Xe(l)&&Ei(l));for(const l of o){const s=Array.from(l.children).filter(a=>!Xe(a)&&(a.textContent||"").trim().length>0);if(s.length<2||s.length>12)continue;const c=s.findIndex(ji);if(!(c<0))return Rn(s,c)}return{}}const St=4096,Ri=20,Ni=20,Mi=10,Ii=10,Ti=30,Pi=20,Nn=500,Di=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function ct(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let t=e;for(;t;){for(const i of Di)if(t.matches(i))return!0;t=t.parentElement}return!1}function ut(e){if(typeof window>"u")return!0;const t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return!1;const i=window.innerHeight||document.documentElement.clientHeight,o=window.innerWidth||document.documentElement.clientWidth;return t.bottom>0&&t.right>0&&t.top<i&&t.left<o}function Mn(e){const t=e.getAttribute("id");if(t){const s=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(t):t.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 a of Array.from(o.childNodes))if(a.nodeType===Node.TEXT_NODE){const u=(a.textContent||"").trim();u&&s.push(u)}else if(a instanceof HTMLElement){if(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement||a instanceof HTMLButtonElement)continue;const u=(a.textContent||"").trim();u&&s.push(u)}const c=s.join(" ").trim();if(c)return c}const l=e.getAttribute("placeholder");return l?l.trim():""}function ae(e,t){return e.length<=t?e:e.slice(0,t-1)+"…"}function zi(e){return e&&e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||null}function $i(e){const t=e.getAttribute("aria-label");if(t)return t.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 l=e.parentElement;for(let s=0;l&&s<4;s++,l=l.parentElement){const c=l.querySelector("h1, h2, h3, h4");if(c!=null&&c.textContent){const a=c.textContent.trim();if(a&&a.length<80)return a}}return null}function Ge(e){return e.length}function ar(e,t={}){const i=t.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||"/",s=i.title||"",c=Array.from(i.querySelectorAll("[data-ll-region]")),a=[];for(const y of c){if(a.length>=Mi)break;if(ct(y)||!ut(y))continue;const M=y.getAttribute("data-ll-region")??"",z=y.getAttribute("data-ll-intent")??void 0,V=ae((y.innerText||y.textContent||"").trim(),Nn*2);!M||!V||a.push({id:M,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(ct(y)||!ut(y))continue;const M=(y.textContent||"").trim();M&&u.push(`${y.tagName}: ${ae(M,200)}`)}const h=Array.from(i.querySelectorAll("p, li"));for(const y of h){if(ct(y)||!ut(y)||d.includes(y.tagName))continue;const M=(y.textContent||"").trim();M.length>10&&u.push(ae(M,Nn))}const m=u.join(`
2
+ `),R=[],C=Array.from(i.querySelectorAll("a[href]"));for(const y of C){if(R.length>=Ri)break;if(ct(y)||!ut(y))continue;const M=y.getAttribute("href")||"",z=(y.textContent||"").trim();!M||!z||R.push({href:M,text:ae(z,100)})}const E=[],b=Array.from(i.querySelectorAll("input, textarea, select"));for(const y of b){if(E.length>=Ni)break;if(ct(y)||!Vt(y)||!ut(y))continue;const M=Mn(y),z=y instanceof HTMLInputElement?y.type:y.tagName.toLowerCase();M&&E.push({label:ae(M,100),type:z})}const w=Array.from(i.querySelectorAll("form")),A=[];let S=0;for(const y of w){if(A.length>=Ii)break;if(At(y)||y.matches(".ll-widget *, .ll-widget"))continue;const M=y.getAttribute("id")||y.getAttribute("name")||zi(y.getAttribute("data-ll-intent"))||`form_${S++}`,z=y.getAttribute("data-ll-intent")||$i(y)||void 0,V=Array.from(y.querySelectorAll("input, textarea, select")),re=[];let T=0;const q=new Set;for(const p of V){if(re.length>=Ti)break;if(!Vt(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 L=p.getAttribute("name")||"",I=p.getAttribute("id")||"";let H=L||I||`field_${T}`;q.has(H)&&(H=`${H}__${T}`),q.add(H),T++;const U=Mn(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 ye=p.getAttribute("pattern");ye!==null&&(W.pattern=ae(ye,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>=Pi);de++){const X=p.options[de];if(!X||X.disabled)continue;const ye=X.value||"",Z=(X.textContent||"").trim()||ye;!ye&&!Z||F.push({value:ye,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)}A.push({id:M,intent:z,fields:re})}const v={url:o,title:s,pathname:l,regions:a,visibleText:m,visibleLinks:R,visibleFields:E,forms:A,flow:sr(i),extras:e};let P=Ge(JSON.stringify(v.regions))+Ge(v.visibleText)+Ge(JSON.stringify(v.visibleLinks))+Ge(JSON.stringify(v.visibleFields));for(;P>St&&v.visibleFields.length>0;)v.visibleFields.pop(),P=Ge(JSON.stringify(v.visibleFields));for(;P>St&&v.visibleLinks.length>0;)v.visibleLinks.pop(),P-=80;return Ge(v.visibleText)>St&&(v.visibleText=ae(v.visibleText,St-100)),v}let Ke=null;function Hi(e){const t=e.querySelectorAll("form");let i=`f${t.length}`;return t.forEach(o=>{i+=`|${o.id||o.getAttribute("name")||""}:${o.querySelectorAll("input,select,textarea").length}`}),i}function Yt(e,t={}){const i=Date.now(),o=t.doc??(typeof document<"u"?document:null),l=typeof window<"u"&&window.location.pathname||"/",s=typeof window<"u"?window.scrollY:0,c=`${l}::${s}::${o?Hi(o):""}`;if(Ke&&Ke.key===c&&i-Ke.at<1e3)return Ke.ctx;const a=ar(e,t);return Ke={key:c,at:i,ctx:a},a}function cr(){Ke=null}const Fi=200;function ur(e){const t=String(e.href||"");return{href:t,text:String(e.text??e.title??t),internal:e.internal??!0,title:e.title,description:e.description}}function Oi(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function dr(e){const t=e??(typeof document<"u"?document:null);if(!t)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,l=[],s=Array.from(t.querySelectorAll("a[href]"));for(const c of s){if(l.length>=Fi)break;if(At(c))continue;const a=c.getAttribute("href")||"";if(!Oi(a))continue;let u=a,d=!0;try{if(typeof window<"u"){const h=new URL(a,i);d=h.origin===i,d&&a.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);l.push({href:u,text:g,internal:d})}return l}let Je=null;const Wi=5e3;function Et(){const e=Date.now(),t=typeof window<"u"&&window.location.pathname||"/";if(Je&&Je.pathname===t&&e-Je.at<Wi)return Je.routes;const i=dr();return Je={at:e,pathname:t,routes:i},i}function fr(){Je=null}function Gt(e){if(e instanceof HTMLInputElement){const t=e.type;if(t==="submit"||t==="button"||t==="reset"||t==="hidden"||t==="image"||t==="file")return!1}return!0}function Bi(e,t){return e.getAttribute("name")||e.getAttribute("id")||`field_${t}`}function je(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function qt(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t+1):e}function qi(e){var o;const t=e.getAttribute("id");if(t)try{const l=(o=e.ownerDocument)==null?void 0:o.querySelector(`label[for="${t.replace(/"/g,'\\"')}"]`);if(l!=null&&l.textContent)return l.textContent}catch{}const i=e.closest("label");return i!=null&&i.textContent?i.textContent:e.getAttribute("aria-label")||e.getAttribute("placeholder")||""}function Ui(e,t){const i=je(t);if(i.length<2)return null;let o=null,l=0;for(const s of Array.from(e.querySelectorAll("input, textarea, select"))){if(!Gt(s))continue;const c=s.getAttribute("name")||"",a=s.getAttribute("id")||"",u=[je(qt(c)),je(qt(a)),je(c),je(a)];let d=0;u.some(g=>g.length>=2&&g===i)?d=4:[je(c),je(qt(c)),je(qi(s))].some(h=>h.length>=3&&(h.includes(i)||i.includes(h)))&&(d=2),d>l&&(l=d,o=s)}return l>=2?o:null}function Vi(e,t){if(!t)return null;try{const s=e.querySelector(`[name="${t.replace(/"/g,'\\"')}"]`);if(s&&Gt(s))return s}catch{}const i=Array.from(e.querySelectorAll("input, textarea, select"));let o=0;const l=new Map;for(const s of i){if(!Gt(s))continue;const c=Bi(s,o);let a=c;if(l.has(c)&&(a=`${c}__${o}`),a===t)return s;l.set(c,s),o++}return Ui(e,t)}function In(e,t){const i=Vi(e,t);return i?Vt(i)?{el:i}:{el:null,reason:"private"}:{el:null,reason:"not_found"}}function Yi(e,t){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,t):e.value=t}function Gi(e,t,i={}){const o=i.triggerInput??!0,l=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,a=t==="true"||t==="1"||t==="on";c?c.call(e,a):e.checked=a,o&&e.dispatchEvent(new Event("input",{bubbles:!0})),l&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}Yi(e,t),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),l&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function Tn(e,t){if(!t)return null;const i=t.replace(/"/g,'\\"'),o=a=>a.closest('[data-ll-private="true"], [data-ll-skip], .ll-widget')!==null;try{const a=e.querySelector(`form#${CSS.escape(t)}`);if(a&&!o(a))return a}catch{}const l=e.querySelector(`form[name="${i}"]`);if(l&&!o(l))return l;const s=e.querySelector(`form[data-ll-intent="${i}"]`);if(s&&!o(s))return s;const c=Array.from(e.querySelectorAll("form")).filter(a=>!o(a));for(const a of c){const u=a.getAttribute("data-ll-intent");if(u&&Xi(u)===t)return a}if(/^form_\d+$/.test(t)){const a=parseInt(t.slice(5),10);let u=0;for(const d of c)if(!(d.id||d.getAttribute("name")||d.getAttribute("data-ll-intent"))){if(u===a)return d;u++}}return c.length===1?c[0]:null}function Xi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||null}function Ki(){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 t=window.getComputedStyle(e);return!(t.overflowY==="hidden"||t.overflowY==="clip")}function Ji(e){if(!(e instanceof HTMLElement))return!1;const i=window.getComputedStyle(e).overflowY;return!(i!=="auto"&&i!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function Zi(){if(typeof document>"u")return null;const e=Array.from(document.querySelectorAll("body, body *"));let t=null,i=0;for(const o of e){if(!Ji(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 s=l.width*l.height;s>i&&(i=s,t=o)}return t}function Qi(){if(typeof window>"u")return null;if(Ki())return window;const e=Zi();return e||window}function Pn(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function eo(e){var t,i;return e instanceof Window?typeof document>"u"?0:Math.max(((t=document.body)==null?void 0:t.scrollHeight)??0,((i=document.documentElement)==null?void 0:i.scrollHeight)??0):e.scrollHeight-e.clientHeight}const to=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","advance_step","go_back","submit_flow","task_field_updated","task_completed"]),pr=r.forwardRef(function(t,i){var ln,an,cn,un,dn,fn,pn;const{agentId:o,apiKey:l,baseUrl:s="https://app.livelayer.studio",sessionEndpoint:c,sessionBody:a,soundEffects:u,experienceMode:d="WIDGET",autoConnect:g=!1,displayMode:h,defaultDisplayMode:m="expanded",onDisplayModeChange:R,position:C="bottom-right",mobileBreakpoint:E=640,draggable:b,resizable:w,persistKey:A="ll-widget",disablePersistence:S=!1,teamMembers:v,currentTeamMemberId:P,onTeamMemberChange:y,idleLoopUrl:M,greeting:z,avatarImageUrl:V,agentName:re,branding:T={},allowCamera:q=!0,allowScreenShare:p=!0,allowTyping:L=!0,blurUntilFirstSpeech:I=!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:ye,onNavigate:Z,onScrollToSelector:Qe,getPageContext:et,pageContextExtras:ft,getRoutes:pt,onScrollPage:tt,onClick:ht,capabilities:$e,onConnect:He,onDisconnect:Ae,onTranscript:Re,onAgentState:Ne,onConnectionStateChange:Me,onAgentEvent:Ie,onAgentCommand:Fe,onCollect:Te,controlledSession:D,className:Pe,style:Oe,zIndex:be=2147483647}=t,mt=Kn(ye),De=Qn(mt,de,X);r.useEffect(()=>{cr(),fr()},[mt]);const ke=P!==void 0,[Rt,gt]=r.useState(()=>{var x;return P??((x=v==null?void 0:v[0])==null?void 0:x.id)}),ze=ke?P:Rt,se=r.useMemo(()=>(v==null?void 0:v.find(x=>x.id===ze))??null,[v,ze]),nt=(se==null?void 0:se.agentId)??o,ne=d==="EMBEDDED",ce=Xn(E),[We,Be]=Gn({value:h,defaultValue:m,onChange:R,persistKey:A,disablePersistence:ne||S}),fe=ne?"expanded":We,ve=ne?()=>{}:Be,yt=H??!ne,Nt=U??!ne,Mt=J||!ne&&ce,Se=Ur({draggable:!ne&&(b??!ce),resizable:!ne&&(w??!ce),persistKey:A,disablePersistence:ne||S}),Ee=Hn(),_e=On(),pe=Wn(),xe=Bn(),[bt,qe]=r.useState(!1),[it,ot]=r.useState(!1),[_,Q]=r.useState(!1),[gr,yr]=r.useState(!1),[Tt,br]=r.useState(!1),vt=Zr({baseUrl:s,config:u}),xt=r.useRef(vt);xt.current=vt;const Pt=r.useRef(Z),Dt=r.useRef(Qe),zt=r.useRef(tt),$t=r.useRef(ht),Kt=r.useRef(et),Jt=r.useRef(ft),Zt=r.useRef(pt),Ht=r.useRef($e),we=r.useRef(null);Pt.current=Z,Dt.current=Qe,zt.current=tt,$t.current=ht,Kt.current=et,Jt.current=ft,Zt.current=pt,Ht.current=$e;function me(x){const f=Ht.current;return f?f.includes(x):!0}function ge(x,f){console.warn(`[LiveLayer] Agent command "${x}" blocked — capability "${f}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const st=r.useCallback(x=>{var ee,le,Ce,at,Le;const f=x;if(!(!f.type||typeof f.type!="string")){if(Ie==null||Ie({eventName:f.type,data:x}),f.type==="navigate"){if(!me("navigate")){ge("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(xt.current.playPageChange(),Pt.current){try{Pt.current(j)}catch(N){console.warn(`[LiveLayer] onNavigate threw for "${j}". Falling back. Error:`,N)}return}if(typeof document<"u"){const N=document.querySelector(`a[href="${j.replace(/"/g,'\\"')}"]`);if(N){N.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",j),window.dispatchEvent(new PopStateEvent("popstate"))}catch(N){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`,N)}return}if(f.type==="scroll_to"){if(!me("scroll")){ge("scroll_to","scroll");return}const j=typeof f.selector=="string"?f.selector:null;if(!j)return;const N=f.behavior==="instant"?"instant":"smooth";if(Dt.current){try{Dt.current(j,N)}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:N,block:"start"})}return}if(f.type==="request_page_context"){if(!me("read_page")){ge("request_page_context","read_page");return}const j=typeof f.requestId=="string"?f.requestId:void 0,N=(ee=we.current)==null?void 0:ee.call(we),B=G=>{const $=N,oe=$==null?void 0:$.localParticipant;if(oe!=null&&oe.publishData)try{const ue=j?{...G,requestId:j}:G,Ye=new TextEncoder().encode(JSON.stringify(ue));oe.publishData(Ye,{reliable:!0})}catch(ue){console.warn("[LiveLayer] publishData failed.",ue)}},O=Jt.current,Y=Kt.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:Yt(O)})});return}B({type:"page_context",context:G});return}B({type:"page_context",context:Yt(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(!me("scroll")){ge("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 N=f.behavior==="instant"?"instant":"smooth";if(zt.current){try{zt.current(j,N)}catch($){console.warn("[LiveLayer] onScrollPage threw.",$)}return}if(typeof window>"u")return;const B={behavior:N},O=Qi(),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(-Pn(O)):j==="down"?Y(Pn(O)):G(j==="top"?0:eo(O));return}if(f.type==="click"){if(!me("click")){ge("click","click");return}const j=typeof f.selector=="string"?f.selector:null;if(!j){console.warn("[LiveLayer] click: missing selector.");return}if($t.current){try{$t.current(j)}catch(B){console.warn("[LiveLayer] onClick threw.",B)}return}if(typeof document>"u")return;let N=null;try{N=document.querySelector(j)}catch{console.warn(`[LiveLayer] click: invalid selector "${j}".`);return}if(!N){console.warn(`[LiveLayer] click: no element matched "${j}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(N.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(le=N.click)==null||le.call(N);return}if(f.type==="advance_step"||f.type==="go_back"||f.type==="submit_flow"){if(!me("click")){ge(f.type,"click");return}if(typeof document>"u")return;const j=f.type==="advance_step"?"ll-advance":f.type==="go_back"?"ll-back":"ll-submit";let N=jn(j);if(N||(sr(document),N=jn(j)),!N){console.warn(`[LiveLayer] ${f.type}: no "${j}" control found.`);return}(Ce=N.click)==null||Ce.call(N);return}if(f.type==="fill_form"||f.type==="focus_field"){if(!me("fill_forms")){ge(f.type,"fill_forms");return}if(typeof document>"u")return;f.type==="fill_form"&&xt.current.playConfirmation();const j=typeof f.formId=="string"?f.formId:null;if(!j){console.warn(`[LiveLayer] ${f.type}: missing formId.`);return}const N=Tn(document,j);if(!N){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(N.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=In(N,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=In(N,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{Gi(G.el,Y)}catch($){console.warn(`[LiveLayer] fill_form: failed to set "${O}".`,$)}}return}if(f.type==="submit_form"){if(!me("submit_forms")){ge("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}xt.current.playConfirmation();const N=Tn(document,j);if(!N){console.warn(`[LiveLayer] submit_form: no <form> matched id="${j}" (or matching name / data-ll-intent slug).`);return}if(N.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=(at=we.current)==null?void 0:at.call(we),Y=oe=>{const ue=O,Ye=ue==null?void 0:ue.localParticipant;if(Ye!=null&&Ye.publishData)try{const Mr=B?{...oe,requestId:B}:oe,Ir=new TextEncoder().encode(JSON.stringify(Mr));Ye.publishData(Ir,{reliable:!0})}catch{}};let G=!1;const $=()=>{G=!0,Y({type:"form_submitted",formId:j})};N.addEventListener("submit",$,{once:!0});try{typeof N.requestSubmit=="function"?N.requestSubmit():N.submit()}catch(oe){console.warn("[LiveLayer] submit_form: requestSubmit threw.",oe),N.removeEventListener("submit",$),Y({type:"form_submit_blocked",formId:j,reason:"exception"});return}setTimeout(()=>{G||(N.removeEventListener("submit",$),Y({type:"form_submit_blocked",formId:j,reason:"validation"}))},500);return}if(f.type==="request_routes"){if(!me("read_page")){ge("request_routes","read_page");return}const j=typeof f.requestId=="string"?f.requestId:void 0,B=(Le=we.current)==null?void 0:Le.call(we),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=Zt.current;if(G){try{const $=G(),oe=ue=>{if(!Array.isArray(ue)){Y([]);return}Y(ue.map(ur).slice(0,200))};$ instanceof Promise?$.then(oe).catch(ue=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",ue),Y(Et())}):oe($)}catch($){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",$),Y(Et())}return}try{Y(Et())}catch($){console.warn("[LiveLayer] request_routes: extractRoutes threw.",$)}return}if(f.type==="task_field_updated"){if(!me("collect_data")){ge("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(!me("collect_data")){ge("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{Te==null||Te(j)}catch(N){console.warn("[LiveLayer] onCollect threw.",N)}return}to.has(f.type)||Fe==null||Fe(f)}},[Fe,Ie,Te]),ie=$n({agentId:D?"__controlled__":nt,baseUrl:s,apiKey:l,sessionEndpoint:c,sessionBody:a,onDataMessage:D?void 0:st});r.useEffect(()=>{if(D!=null&&D.subscribeToDataMessages)return D.subscribeToDataMessages(st)},[D,st]),we.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{st(le)}catch(Ce){console.warn("[LiveLayer] simulate-command threw:",Ce)}},()=>{delete window.__livelayerSimulateCommand}},[st]);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]),Qt=r.useRef(k);Qt.current=k;const en=r.useRef(D);en.current=D,r.useImperativeHandle(i,()=>({sendData:async x=>{var Ce,at;const f=en.current;if(f!=null&&f.publishData){try{await f.publishData(x)}catch(Le){console.warn("[AvatarWidget] sendData (controlled) failed:",Le)}return}const ee=(at=(Ce=Qt.current)==null?void 0:Ce.getRoom)==null?void 0:at.call(Ce),le=ee==null?void 0:ee.localParticipant;if(le!=null&&le.publishData)try{const Le=new TextEncoder().encode(JSON.stringify(x));await le.publishData(Le,{reliable:!0})}catch(Le){console.warn("[AvatarWidget] sendData failed:",Le)}}}),[]);const tn=r.useRef(null);r.useEffect(()=>{const x=k.videoElement,f=tn.current;if(!(!x||!f))return f.appendChild(x),()=>{x.parentNode===f&&f.removeChild(x)}},[k.videoElement]);const[Ue,wt]=r.useState(!1);r.useEffect(()=>{if(!I){wt(!0);return}k.agentState==="speaking"&&!Ue&&wt(!0)},[I,k.agentState,Ue]),r.useEffect(()=>{if(!I)return;const x=k.connectionState;(x==="disconnected"||x==="idle")&&wt(!1)},[I,k.connectionState]),r.useEffect(()=>{if(!I||!k.videoElement||Ue)return;const x=setTimeout(()=>wt(!0),5e3);return()=>clearTimeout(x)},[I,k.videoElement,Ue]),r.useEffect(()=>{const x=k.videoElement;if(x){if(!I){x.style.filter="";return}x.style.transition="filter 500ms ease-out",x.style.filter=Ue?"":"blur(8px)"}},[I,k.videoElement,Ue]),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),Ee.attach(x);const ee=x.play();return ee&&typeof ee.catch=="function"&&ee.catch(le=>{(le==null?void 0:le.name)==="NotAllowedError"&&qe(!0)}),()=>{Ee.detach(),x.parentNode===f&&f.removeChild(x),f.parentNode===document.body&&document.body.removeChild(f)}},[k.audioElement]);const he=Fn({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&&Ee.attachStream(f,"mic")}).catch(()=>{}),()=>{Ee.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),xe.refresh(),()=>{_e.teardown(),pe.teardown()}},[k.isControlled,k.connectionState,D]),r.useEffect(()=>{const x=k.audioElement;x&&(x.muted=Tt)},[k.audioElement,Tt]);const vr=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]),xr=r.useCallback(()=>{br(x=>!x)},[]);r.useEffect(()=>{Me==null||Me(k.connectionState),k.connectionState==="connected"?He==null||He():k.connectionState==="disconnected"&&(Ae==null||Ae())},[k.connectionState,He,Ae,Me]),r.useEffect(()=>{Re==null||Re(k.transcript)},[k.transcript,Re]),r.useEffect(()=>{Ne==null||Ne(k.agentState)},[k.agentState,Ne]),r.useEffect(()=>{vt.setThinking(k.agentState==="thinking")},[k.agentState,vt]);const nn=r.useRef(!1);r.useEffect(()=>{!g||nn.current||De&&k.connectionState==="idle"&&(nn.current=!0,k.connect())},[g,k.connectionState,k,De]);const wr=r.useCallback(x=>{const f=v==null?void 0:v.find(ee=>ee.id===x);f&&(Q(!1),x!==ze&&(ot(!0),k.disconnect(),ke||gt(x),y==null||y(f)))},[v,ze,k,ke,y]);r.useEffect(()=>{it&&k.connectionState==="connected"&&ot(!1)},[k.connectionState,it]),r.useEffect(()=>{if(!_)return;const x=f=>{f.key==="Escape"&&Q(!1)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[_]);const _r=!!V||!!(se!=null&&se.avatarImageUrl)||k.isControlled,lt=qn(nt,s,_r);$e===void 0&&((ln=lt.info)!=null&&ln.capabilities)&&(Ht.current=lt.info.capabilities);const _t=(se==null?void 0:se.name)??re??((an=k.agentConfig)==null?void 0:an.name)??((cn=lt.info)==null?void 0:cn.name)??"Live Layer",Ft=(se==null?void 0:se.avatarImageUrl)??V??((un=k.agentConfig)==null?void 0:un.avatarImageUrl)??((dn=lt.info)==null?void 0:dn.avatarImageUrl)??null,Cr=M??((fn=k.agentConfig)==null?void 0:fn.idleLoopUrl)??((pn=lt.info)==null?void 0:pn.idleLoopUrl)??null,kr=z??null,Sr=r.useCallback(()=>ve("expanded"),[ve]),Er=r.useCallback(()=>ve("minimized"),[ve]),rn=r.useCallback(()=>{k.disconnect(),ve("hidden")},[k,ve]),Lr=r.useCallback(()=>{const x=k.audioElement;x&&x.play().then(()=>qe(!1)).catch(()=>{})},[k.audioElement]),jr=r.useCallback(()=>{qe(!1),k.connect()},[k]),Ve={...Oe,...ne?{}:{zIndex:be}};T.primaryColor&&(Ve["--ll-color-primary"]=T.primaryColor),T.accentColor&&(Ve["--ll-color-accent"]=T.accentColor),T.backgroundColor&&(Ve["--ll-color-bg"]=T.backgroundColor),T.textColor&&(Ve["--ll-color-fg"]=T.textColor);const Ar={...Ve,...Se.style},Rr=["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,Pe].filter(Boolean).join(" ");if(!De)return null;const Nr=n.jsx("div",{className:Rr,style:Ar,"data-display-mode":fe,"data-position":C,"data-experience-mode":d==="EMBEDDED"?"embedded":"widget",children:fe==="expanded"&&n.jsx(mi,{position:C,isMobile:ce,agentName:_t,avatarImageUrl:Ft,idleLoopUrl:Cr,greeting:kr,branding:T,teamMembers:v,currentTeamMemberId:ze,isSwitchingTeamMember:it,teamSwitcherOpen:_,onToggleTeamSwitcher:()=>Q(x=>!x),onSelectTeamMember:wr,connectionState:k.connectionState,agentState:k.agentState,transcript:k.transcript,isMuted:he.isMuted,micDevices:xe.mics,activeMicId:he.activeDeviceId,isCameraEnabled:_e.isEnabled,cameraPreviewEl:_e.previewEl,cameraDevices:xe.cameras,activeCameraId:_e.activeDeviceId,isScreenShareEnabled:pe.isEnabled,screenPreviewEl:pe.previewEl,isSpeakerMuted:Tt,allowCamera:q,allowScreenShare:p,allowTyping:L,showMinimize:ce&&!ne?!1:yt,showClose:Nt,chromeless:K,compactControls:Mt,transforming:te,transformingLabel:F,languageMenuOpen:gr,onToggleLanguageMenu:()=>yr(x=>!x),needsUserGesture:bt,canResume:k.canResume,micError:he.micError,error:k.error,avatarVideoContainerRef:tn,agentVideoEl:k.videoElement,onConnect:()=>void k.connect(),onDisconnect:()=>k.disconnect(),onRetry:jr,onResumeAudio:Lr,onToggleMute:he.toggleMute,onSwitchMicDevice:x=>void he.switchDevice(x),onToggleCamera:()=>void _e.toggle(),onSwitchCameraDevice:x=>void _e.switchDevice(x),onToggleScreenShare:()=>void pe.toggle(),onToggleSpeaker:xr,onSendMessage:vr,onMinimize:Er,onClose:rn,onClearMicError:he.clearError,dragHandleProps:Se.dragHandleProps,resizeHandleProps:Se.resizeHandleProps})}),on=!ne&&(fe==="hidden"||fe==="minimized")?n.jsxs("div",{className:["ll-widget","ll-widget--floating",`ll-widget--${fe}`,`ll-widget--${ce?"mobile":"desktop"}`].join(" "),style:Ve,"data-display-mode":fe,"data-position":C,children:[fe==="hidden"&&n.jsx(ii,{position:C,isMobile:ce,isSpeaking:k.agentState==="speaking",onExpand:()=>ve("expanded"),label:`Open ${_t} widget`,avatarImageUrl:Ft,agentName:_t,containerEl:W}),fe==="minimized"&&n.jsx(si,{position:C,isMobile:ce,agentName:_t,avatarImageUrl:Ft,agentState:k.agentState,isMuted:he.isMuted,audioLevel:Ee,onExpand:Sr,onToggleMute:he.toggleMute,onClose:rn})]}):null,sn=W??(typeof document<"u"?document.body:null);return n.jsxs(n.Fragment,{children:[Nr,on&&sn&&Xt.createPortal(on,sn)]})});pr.displayName="AvatarWidgetInner";const hr=r.forwardRef(function(t,i){return n.jsx(zn,{children:n.jsx(pr,{...t,ref:i})})});hr.displayName="AvatarWidget";const no=({agentId:e,baseUrl:t,apiKey:i,mode:o,onAgentEvent:l,className:s,style:c})=>{const a=r.useRef(null),u=r.useRef(null),d=r.useRef(l);d.current=l;const g=r.useCallback(h=>{var R;const m=h.detail;(R=d.current)==null||R.call(d,m)},[]);return r.useEffect(()=>{const h=a.current;if(!h)return;const m=document.createElement("livelayer-widget");return m.setAttribute("agent-id",e),t&&m.setAttribute("base-url",t),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]),n.jsx("div",{ref:a,className:s,style:c})},ro=r.forwardRef(function({id:t,intent:i,as:o="div",className:l,style:s,children:c},a){return r.createElement(o,{ref:a,"data-ll-region":t,"data-ll-intent":i,className:l,style:s},c)});function io(e={}){const{onFieldUpdate:t,onComplete:i,source:o="all"}=e,[l,s]=r.useState({}),[c,a]=r.useState(!1),[u,d]=r.useState(null),g=r.useRef(t),h=r.useRef(i),m=r.useRef(o);r.useEffect(()=>{g.current=t,h.current=i,m.current=o},[t,i,o]);const R=r.useCallback(()=>{s({}),a(!1)},[]);return r.useEffect(()=>{if(typeof window>"u")return;const C=E=>{var w,A;const b=E.detail;if(b){if(b.phase==="field"){if(m.current!=="all"&&b.source!==m.current)return;a(!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),a(!1);try{(A=h.current)==null||A.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:R}}let Dn=1;function oo({onMount:e,defaultOpen:t=!1,storageKey:i="ll-debug-open"}){const[o,l]=r.useState(t),[s,c]=r.useState([]),[a,u]=r.useState(""),[d,g]=r.useState(!1),h=r.useRef(new Set),m=r.useRef([]),R=r.useRef(d);R.current=d,r.useEffect(()=>{try{const b=localStorage.getItem(i);b==="1"&&l(!0),b==="0"&&l(!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(),l(A=>!A))};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[]),r.useEffect(()=>{const b=setInterval(()=>{if(m.current.length===0||R.current)return;const w=m.current.splice(0,m.current.length);c(A=>[...w.reverse(),...A].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:Dn++,ts:Date.now(),kind:"event",type:b.eventName,data:b.data})}))},[e]),r.useEffect(()=>{const b=console.warn,w=console.log,A=(S,v)=>function(...P){try{const y=typeof P[0]=="string"?P[0]:"";y.startsWith("[LiveLayer]")&&m.current.push({id:Dn++,ts:Date.now(),kind:S,type:y.slice(0,120),data:{args:P.slice(1).map(M=>lo(M))}})}catch{}return v.apply(this,P)};return console.warn=A("warn",b),console.log=A("log",w),()=>{console.warn=b,console.log=w}},[]),!o)return n.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 E=s.filter(b=>{if(!a)return!0;const w=a.toLowerCase();return b.type.toLowerCase().includes(w)||JSON.stringify(b.data||{}).toLowerCase().includes(w)});return n.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:[n.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:[n.jsx("span",{style:{fontWeight:600,fontSize:12},children:"LiveLayer debug"}),n.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:[s.length," event",s.length===1?"":"s"]}),n.jsx("span",{style:{flex:1}}),n.jsx("button",{type:"button",onClick:()=>g(b=>!b),style:Ut(d?"#f59e0b":"transparent"),title:"Pause / resume capture",children:d?"▶ resume":"⏸ pause"}),n.jsx("button",{type:"button",onClick:()=>{c([]),m.current=[]},style:Ut("transparent"),title:"Clear buffer",children:"clear"}),n.jsx("button",{type:"button",onClick:()=>l(!1),style:Ut("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),n.jsx("input",{type:"text",value:a,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"}}),n.jsx("div",{style:{flex:1,overflowY:"auto",padding:"0 8px 8px"},children:E.length===0?n.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:",n.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(y=>t.jsx(Pi,{entry:y,expanded:h.current.has(y.id),onToggle:()=>{h.current.has(y.id)?h.current.delete(y.id):h.current.add(y.id),c(w=>[...w])}},y.id))})]})}function Pi({entry:e,expanded:r,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",l=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:l}),t.jsx("span",{style:{color:o,fontWeight:600,flexShrink:0},children:e.type.length>50?e.type.slice(0,50)+"…":e.type})]}),r&&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 Ht(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 Di(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function ir(e){const r=JSON.stringify(e);n.useEffect(()=>Xe.registerFields(e),[r])}function zi({fields:e,children:r}){return ir(e),t.jsx(t.Fragment,{children:r})}function $i(){const[e,r]=n.useState([]),i=n.useCallback(l=>{r(a=>{const c=a.findIndex(s=>s.id===l.id);if(c>=0){const s=a.slice();return s[c]=l,s}return[...a,l]})},[]),o=n.useCallback(()=>r([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}Object.defineProperty(exports,"clearFieldRegistry",{enumerable:!0,get:()=>Xe.clearFieldRegistry});Object.defineProperty(exports,"getRegisteredFields",{enumerable:!0,get:()=>Xe.getRegisteredFields});Object.defineProperty(exports,"registerFields",{enumerable:!0,get:()=>Xe.registerFields});Object.defineProperty(exports,"setFieldValue",{enumerable:!0,get:()=>Xe.setFieldValue});exports.AvatarWidget=rr;exports.ErrorBoundary=jn;exports.FieldProvider=zi;exports.LiveLayerDebugPanel=Ti;exports.LiveLayerRegion=Mi;exports.LiveLayerWidget=Ai;exports.clearPageContextCache=Zn;exports.clearRoutesCache=tr;exports.extractPageContext=Jn;exports.extractRoutes=er;exports.getCachedPageContext=Ot;exports.getCachedRoutes=_t;exports.matchesPattern=Wn;exports.normalizeRouteInput=Qn;exports.shouldRenderAtPath=Bn;exports.useAgentInfo=Pn;exports.useAudioLevel=Nn;exports.useCameraState=Mn;exports.useCollect=Ii;exports.useDisplayMode=$n;exports.useDisplayModePersistence=Hn;exports.useIsMobile=Fn;exports.useLiveKitSession=Rn;exports.useMediaDevices=Tn;exports.useMicrophoneState=An;exports.usePathname=On;exports.useRegisterFields=ir;exports.useRouteMatch=qn;exports.useScreenShareState=In;exports.useTranscript=$i;
5
+ })`})]}):E.map(b=>n.jsx(so,{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 so({entry:e,expanded:t,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",l=new Date(e.ts).toLocaleTimeString("en-US",{hour12:!1});return n.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:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[n.jsx("span",{style:{color:"rgba(255,255,255,0.4)",fontVariantNumeric:"tabular-nums",fontSize:10},children:l}),n.jsx("span",{style:{color:o,fontWeight:600,flexShrink:0},children:e.type.length>50?e.type.slice(0,50)+"…":e.type})]}),t&&e.data&&n.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 Ut(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 lo(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function mr(e){const t=JSON.stringify(e);r.useEffect(()=>Ze.registerFields(e),[t])}function ao({fields:e,children:t}){return mr(e),n.jsx(n.Fragment,{children:t})}function co(){const[e,t]=r.useState([]),i=r.useCallback(l=>{t(s=>{const c=s.findIndex(a=>a.id===l.id);if(c>=0){const a=s.slice();return a[c]=l,a}return[...s,l]})},[]),o=r.useCallback(()=>t([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}Object.defineProperty(exports,"clearFieldRegistry",{enumerable:!0,get:()=>Ze.clearFieldRegistry});Object.defineProperty(exports,"getRegisteredFields",{enumerable:!0,get:()=>Ze.getRegisteredFields});Object.defineProperty(exports,"registerFields",{enumerable:!0,get:()=>Ze.registerFields});Object.defineProperty(exports,"setFieldValue",{enumerable:!0,get:()=>Ze.setFieldValue});exports.AvatarWidget=hr;exports.ErrorBoundary=zn;exports.FieldProvider=ao;exports.LiveLayerDebugPanel=oo;exports.LiveLayerRegion=ro;exports.LiveLayerWidget=no;exports.clearPageContextCache=cr;exports.clearRoutesCache=fr;exports.extractPageContext=ar;exports.extractRoutes=dr;exports.getCachedPageContext=Yt;exports.getCachedRoutes=Et;exports.matchesPattern=Jn;exports.normalizeRouteInput=ur;exports.shouldRenderAtPath=Zn;exports.useAgentInfo=qn;exports.useAudioLevel=Hn;exports.useCameraState=On;exports.useCollect=io;exports.useDisplayMode=Yn;exports.useDisplayModePersistence=Gn;exports.useIsMobile=Xn;exports.useLiveKitSession=$n;exports.useMediaDevices=Bn;exports.useMicrophoneState=Fn;exports.usePathname=Kn;exports.useRegisterFields=mr;exports.useRouteMatch=Qn;exports.useScreenShareState=Wn;exports.useTranscript=co;