@livelayer/react 0.6.2 → 0.8.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
@@ -100,7 +100,24 @@ export declare interface AudioLevelHandle {
100
100
  * Import the stylesheet once in your app:
101
101
  * import "@livelayer/react/styles.css";
102
102
  */
103
- export declare function AvatarWidget(props: AvatarWidgetProps): JSX.Element;
103
+ export declare const AvatarWidget: ForwardRefExoticComponent<AvatarWidgetProps & RefAttributes<AvatarWidgetHandle>>;
104
+
105
+ /**
106
+ * Imperative methods exposed via forwardRef. Consumers attach a ref to
107
+ * <AvatarWidget> and call these methods directly — used when the widget
108
+ * needs to publish data to the agent in response to host-side events
109
+ * (e.g. user clicked a layout button, picked a quiz answer, etc.).
110
+ */
111
+ export declare interface AvatarWidgetHandle {
112
+ /**
113
+ * Publish a JSON-serializable object over the LiveKit data channel
114
+ * (reliable). No-ops if the session isn't connected yet. Returns a
115
+ * promise that resolves when the publish completes; rejects on
116
+ * publish failure (extremely rare in practice — the LiveKit SDK
117
+ * queues unreliable transports automatically).
118
+ */
119
+ sendData: (data: Record<string, unknown>) => Promise<void>;
120
+ }
104
121
 
105
122
  export declare interface AvatarWidgetProps {
106
123
  agentId: string;
@@ -136,6 +153,37 @@ export declare interface AvatarWidgetProps {
136
153
  allowScreenShare?: boolean;
137
154
  allowTyping?: boolean;
138
155
  allowMic?: boolean;
156
+ /**
157
+ * Show the minimize ("—") button in the expanded layout's header.
158
+ * Default `true`. Set to `false` on hosts where minimize doesn't
159
+ * make sense — e.g. fullscreen `/a/<slug>` (the widget IS the
160
+ * experience) or tightly-embedded marketing slots.
161
+ */
162
+ showMinimize?: boolean;
163
+ /**
164
+ * Hide the top header (agent name, language, state) and the
165
+ * bottom media-control bar. Used in tight embedded slots where
166
+ * the video should fill the surface (e.g. the marketing fork
167
+ * card at ~180×260). The close button still renders so visitors
168
+ * can dismiss the widget. Default `false`.
169
+ */
170
+ chromeless?: boolean;
171
+ /**
172
+ * When true, render a centered spinner + label overlay above the video
173
+ * and any other state overlays (Connecting, Loading avatar, etc.).
174
+ *
175
+ * Caller-controlled — flip this on while the consumer's app is in the
176
+ * middle of a swap operation that the widget can't observe directly
177
+ * (avatar URL change, voice change, agent handoff in progress, etc.).
178
+ * The overlay wins over connection-state overlays for as long as the
179
+ * caller keeps it true.
180
+ */
181
+ transforming?: boolean;
182
+ /**
183
+ * Optional caption shown beneath the spinner when `transforming` is true.
184
+ * Defaults to "Transforming…".
185
+ */
186
+ transformingLabel?: string;
139
187
  /**
140
188
  * Patterns where the widget MAY render. If set, widget renders ONLY on
141
189
  * matching paths. See `RoutePattern` for accepted forms (string globs,
@@ -687,7 +735,7 @@ export declare function useIsMobile(breakpoint?: number | false): boolean;
687
735
 
688
736
  export declare function useLiveKitSession(options: UseLiveKitSessionOptions): UseLiveKitSessionResult;
689
737
 
690
- declare interface UseLiveKitSessionOptions extends SessionOptions {
738
+ export declare interface UseLiveKitSessionOptions extends SessionOptions {
691
739
  /**
692
740
  * Fires for every data channel message from the agent. The hook also
693
741
  * interprets recognized state-bearing messages (agent_state) and updates
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"),Ln=require("@livelayer/sdk"),rt=require("livekit-client");class Ut 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,s;(s=(o=this.props).onError)==null||s.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 Vt(e){const[r,i]=n.useState("idle"),[o,s]=n.useState("idle"),[a,u]=n.useState([]),[d,f]=n.useState(null),[m,g]=n.useState(null),[l,c]=n.useState(null),[L,D]=n.useState(!1),[_,w]=n.useState(null),b=n.useRef(null),T=n.useRef(e.onDataMessage);T.current=e.onDataMessage,n.useEffect(()=>{const S={onConnectionStateChange:A=>{i(A),A==="connected"&&w(null)},onAgentStateChange:s,onTranscript:A=>u([...A]),onAgentConfig:f,onAudioTrack:A=>c(A),onVideoTrack:A=>g(A),onVideoTrackRemoved:()=>g(null),onError:A=>w(A),onDataMessage:A=>{var C;(C=T.current)==null||C.call(T,A)},onResumabilityChange:D},$=new Ln.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},S);return b.current=$,i("idle"),s("idle"),u([]),f(null),g(null),c(null),D(!1),w(null),()=>{var A;(A=$.destroy)==null||A.call($),b.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const E=n.useCallback(async()=>{const S=b.current;if(S)try{await S.connect()}catch($){throw w($ instanceof Error?$.message:String($)),$}},[]),I=n.useCallback(()=>{const S=b.current;S&&S.disconnect()},[]),x=n.useCallback(()=>{var S;return((S=b.current)==null?void 0:S.getRoom())??null},[]);return{connectionState:r,agentState:o,transcript:a,agentConfig:d,videoElement:m,audioElement:l,canResume:L,error:_,connect:E,disconnect:I,getRoom:x,session:b.current}}function Yt(){const e=n.useRef(null),r=n.useRef(null),i=n.useRef(null),o=n.useRef(null),s=n.useRef(new Set),a=n.useRef(null),u=n.useCallback(()=>{const l=r.current;if(!l){o.current=null;return}(!a.current||a.current.length!==l.frequencyBinCount)&&(a.current=new Uint8Array(new ArrayBuffer(l.frequencyBinCount)));const c=a.current;l.getByteFrequencyData(c);let L=0;for(let _=0;_<c.length;_++)L+=c[_];const D=L/c.length/255;for(const _ of s.current)try{_(D)}catch(w){console.error("[useAudioLevel] subscriber threw:",w)}o.current=requestAnimationFrame(u)},[]),d=n.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const l=new AudioContext,c=l.createAnalyser();c.fftSize=64,c.connect(l.destination),e.current=l,r.current=c},[]),f=n.useCallback(l=>{if(d(),!(!e.current||!r.current)){if(i.current){try{i.current.disconnect()}catch{}i.current=null}try{const c=e.current.createMediaElementSource(l);c.connect(r.current),i.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}o.current===null&&(o.current=requestAnimationFrame(u))}},[d,u]),m=n.useCallback(()=>{if(o.current!==null&&(cancelAnimationFrame(o.current),o.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),g=n.useCallback(l=>(s.current.add(l),()=>{s.current.delete(l)}),[]);return n.useEffect(()=>()=>{if(m(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),a.current=null},[m]),{attach:f,detach:m,subscribe:g}}function Gt(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),s=n.useRef(null),a=n.useRef(null),u=n.useCallback(async g=>{if(s.current&&a.current){try{await a.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}a.current=g,o(null);try{const l=await rt.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await g.localParticipant.publishTrack(l),s.current=l,r(l.isMuted)}catch(l){const c=l instanceof Error&&l.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw o(c),l}},[]),d=n.useCallback(()=>{const g=s.current;g&&(g.isMuted?(g.unmute(),r(!1)):(g.mute(),r(!0)))},[]),f=n.useCallback(()=>{const g=s.current,l=a.current;if(g&&l){try{l.localParticipant.unpublishTrack(g)}catch{}g.stop()}s.current=null,a.current=null,r(!1)},[]),m=n.useCallback(()=>o(null),[]);return{isMuted:e,micError:i,toggleMute:d,setupMic:u,teardownMic:f,clearError:m}}const jn={resolution:{width:640,height:480,frameRate:24}};function Kt(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),[s,a]=n.useState(null),[u,d]=n.useState(""),f=n.useRef(null),m=n.useRef(null),g=n.useCallback(b=>{f.current=b},[]),l=n.useCallback(()=>{const b=f.current,T=m.current;if(T&&b){const E=b.localParticipant.getTrackPublication(rt.Track.Source.Camera);if(E!=null&&E.track){try{b.localParticipant.unpublishTrack(E.track)}catch{}E.track.stop()}else T.stop()}m.current=null,a(null),r(!1)},[]),c=n.useCallback(async b=>{const T=f.current;if(T){o(null);try{const E={...jn};b&&(E.deviceId=b);const I=await rt.createLocalVideoTrack(E);await T.localParticipant.publishTrack(I),m.current=I;const x=I.attach();a(x),r(!0),b&&d(b);try{T.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(E){const I=E instanceof Error&&E.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";o(I)}}},[]),L=n.useCallback(async()=>{e?l():await c(u||void 0)},[e,u,l,c]),D=n.useCallback(async b=>{l(),await c(b)},[l,c]),_=n.useCallback(()=>{l(),f.current=null,o(null),d("")},[l]),w=n.useCallback(()=>o(null),[]);return n.useEffect(()=>()=>{m.current&&m.current.stop()},[]),{isEnabled:e,error:i,previewEl:s,activeDeviceId:u,toggle:L,switchDevice:D,attachRoom:g,teardown:_,clearError:w}}function Xt(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),[s,a]=n.useState(null),u=n.useRef(null),d=n.useCallback(c=>{u.current=c},[]),f=n.useCallback(()=>a(null),[]),m=n.useCallback(async()=>{const c=u.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),r(!1);return}o(null);try{await c.localParticipant.setScreenShareEnabled(!0);let L=0;const D=()=>{const _=c.localParticipant.getTrackPublication(rt.Track.Source.ScreenShare);if(_!=null&&_.track){const w=_.track.attach();a(w),r(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}L++<10?setTimeout(D,100):r(!0)};D()}catch(L){const D=L instanceof Error?L.name:"";D!=="NotAllowedError"&&D!=="AbortError"&&o("Screen share unavailable. Try again."),r(!1)}}},[e,f]),g=n.useCallback(()=>{const c=u.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),r(!1),o(null),u.current=null},[e,f]),l=n.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:s,toggle:m,attachRoom:d,teardown:g,clearError:l}}function Jt(){const[e,r]=n.useState([]),[i,o]=n.useState([]),s=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const a=await navigator.mediaDevices.enumerateDevices();r(a.filter(u=>u.kind==="audioinput")),o(a.filter(u=>u.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const a=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",a),()=>navigator.mediaDevices.removeEventListener("devicechange",a)},[s]),{mics:e,cameras:i,refresh:s}}function Qt(e,r,i=!1){const[o,s]=n.useState(null),[a,u]=n.useState(null),[d,f]=n.useState(!i&&!!e);return n.useEffect(()=>{if(i||!e){f(!1);return}const m=new AbortController,g=r||"https://app.livelayer.studio";return f(!0),u(null),fetch(`${g}/api/widget/agent/${encodeURIComponent(e)}`,{signal:m.signal}).then(async l=>{if(!l.ok){const c=await l.json().catch(()=>({}));throw new Error(c.error||`HTTP ${l.status}`)}return l.json()}).then(l=>{m.signal.aborted||(s(l),f(!1))}).catch(l=>{m.signal.aborted||(u(l instanceof Error?l.message:"Agent lookup failed"),f(!1))}),()=>m.abort()},[e,r,i]),{info:o,error:a,loading:d}}function En(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function Rn(e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(e,r)}catch{}}function Zt({value:e,defaultValue:r="expanded",onChange:i}={}){const o=e!==void 0,[s,a]=n.useState(r),u=o?e:s,d=n.useCallback(f=>{f!==u&&(o||a(f),i==null||i(f))},[u,o,i]);return[u,d]}const Nn=["hidden","minimized","expanded"];function An(e){return e&&Nn.includes(e)?e:null}function en({value:e,defaultValue:r="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:s=!1}={}){const a=`${o}:display-mode`,u=n.useRef(!1),[d,f]=Zt({value:e,defaultValue:r,onChange:m=>{e===void 0&&!s&&Rn(a,m),i==null||i(m)}});return n.useEffect(()=>{if(u.current||(u.current=!0,s||e!==void 0))return;const m=An(En(a));m&&m!==d&&f(m)},[]),[d,f]}const Mn=640;function tn(e=Mn){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)`,s=window.matchMedia(o),a=()=>i(s.matches);return a(),typeof s.addEventListener=="function"?(s.addEventListener("change",a),()=>s.removeEventListener("change",a)):(s.addListener(a),()=>{s.removeListener(a)})},[e]),r}const Rt="__llHistoryPatched",it="ll:pathname";function In(){if(typeof window>"u"||window.history[Rt])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(it)),o},window.history.replaceState=function(...i){const o=r.apply(this,i);return window.dispatchEvent(new Event(it)),o},window.history[Rt]=!0}function Nt(){return typeof window>"u"?"/":window.location.pathname||"/"}function nn(e){const[r,i]=n.useState(()=>e??Nt());return n.useEffect(()=>{if(e!==void 0)return;In();const o=()=>i(Nt());return o(),window.addEventListener("popstate",o),window.addEventListener(it,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(it,o)}},[e]),e??r}const At=new Map,Tn=/[\\^$+?.()|{}[\]]/g;function Pn(e){return e.replace(Tn,"\\$&")}function Dn(e){const r=At.get(e);if(r)return r;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",s="",a=i.replace(/\*\*/g,o).replace(/\*/g,s),d=Pn(a).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),f=new RegExp(`^${d}\\/?$`);return At.set(e,f),f}function $n(e,r){const i=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return Dn(e).test(i)}function rn(e,r){return typeof e=="function"?e(r):e instanceof RegExp?e.test(r):$n(e,r)}function Mt(e,r){if(!e||e.length===0)return!1;for(const i of e)if(rn(i,r))return!0;return!1}function on(e,r,i){return e===void 0?!0:Mt(i,e)?!1:r&&r.length>0?Mt(r,e):!0}function sn(e,r,i){return n.useMemo(()=>on(e,r,i),[e,r,i])}function zn(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 Hn(e){const r=n.useMemo(()=>zn(e.config),[e.config]),i=e.baseUrl.replace(/\/+$/,""),o=n.useRef(null),s=n.useCallback(f=>{try{new Audio(`${i}${f}`).play().catch(()=>{})}catch{}},[i]),a=n.useCallback(()=>{r.navigate&&s("/audio/page-change-sound.mp3")},[r.navigate,s]),u=n.useCallback(()=>{r.action&&s("/audio/confirmation-sound.mp3")},[r.action,s]),d=n.useCallback(f=>{if(!r.thinking){if(o.current){try{o.current.pause()}catch{}o.current=null}return}if(f){if(o.current)return;try{const m=new Audio(`${i}/audio/thinking-sound.mp3`);m.loop=!0,m.volume=.3,m.play().catch(()=>{o.current=null}),o.current=m}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:u,setThinking:d}),[a,u,d])}const It=({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"})}),Tt=({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"})}),On=({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"})}),qn={left:180,right:0,up:-90,down:90},Pt=({direction:e="right",className:r})=>t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${qn[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function Bn(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const an="ll-hidden-tab-center-y",Wn=5,Dt=16;function Fn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(an);if(!e)return null;const r=Number.parseFloat(e);return Number.isFinite(r)?r:null}catch{return null}}function $t(e){if(!(typeof window>"u"))try{window.localStorage.setItem(an,String(e))}catch{}}const Un=({position:e,isMobile:r,isSpeaking:i,onExpand:o,label:s="Open widget",avatarImageUrl:a,agentName:u})=>{const d=Bn(e),f=d==="right"?"left":"right",m=r?80:72,g=!!a,[l,c]=n.useState(null),[L,D]=n.useState(!1),_=n.useRef(null),w=n.useRef(!1),b=n.useCallback(C=>{if(typeof window>"u")return C;const R=m/2,z=Dt+R,F=window.innerHeight-Dt-R;return F<z?Math.max(z,C):Math.max(z,Math.min(F,C))},[m]);n.useEffect(()=>{const C=Fn();c(b(C??window.innerHeight/2));const R=()=>{c(z=>z===null?null:b(z))};return window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[b]);const T=n.useCallback(C=>{if(!(C.pointerType==="mouse"&&C.button!==0)&&l!==null){try{C.currentTarget.setPointerCapture(C.pointerId)}catch{}_.current={startClientY:C.clientY,startCenterY:l,moved:!1}}},[l]),E=n.useCallback(C=>{const R=_.current;if(!R)return;const z=C.clientY-R.startClientY;!R.moved&&Math.abs(z)>Wn&&(R.moved=!0,D(!0)),R.moved&&c(b(R.startCenterY+z))},[b]),I=n.useCallback(C=>{const R=_.current;if(R){try{C.currentTarget.releasePointerCapture(C.pointerId)}catch{}_.current=null,R.moved&&(D(!1),w.current=!0,c(z=>(z!==null&&$t(z),z)))}},[]),x=n.useCallback(()=>{if(w.current){w.current=!1;return}o()},[o]),S=n.useCallback(C=>{if(C.key==="ArrowUp"||C.key==="ArrowDown"){C.preventDefault();const R=C.key==="ArrowUp"?-8:8;c(z=>{if(z===null)return z;const F=b(z+R);return $t(F),F})}},[b]),$=["ll-hidden",`ll-hidden--${d}`,r?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,L?"is-dragging":null,g?"ll-hidden--with-avatar":null].filter(Boolean).join(" "),A=l===null?void 0:{top:`${l-m/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:$,onPointerDown:T,onPointerMove:E,onPointerUp:I,onPointerCancel:I,onClick:x,onKeyDown:S,"aria-label":s,"data-position":e,style:A,children:g?t.jsxs(t.Fragment,{children:[t.jsx(Pt,{direction:f,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:a,alt:u?`${u} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(Pt,{direction:f,className:"ll-hidden__chevron"})})},Vn=({audioLevel:e,bars:r=20,maxHeight:i=20,minHeight:o=4,className:s,barClassName:a})=>{const u=n.useRef(null),d=n.useRef([]),f=n.useMemo(()=>{const g=(Math.sqrt(5)-1)/2;return Array.from({length:r},(l,c)=>.5+c*g%1*.5)},[r]);n.useEffect(()=>e.subscribe(l=>{for(let c=0;c<r;c++){const L=d.current[c];if(!L)continue;const D=Math.max(o,l*i*f[c]);L.style.height=`${D}px`}}),[e,r,i,o,f]);const m=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:u,className:m,"aria-hidden":"true",children:Array.from({length:r},(g,l)=>t.jsx("div",{ref:c=>{d.current[l]=c},className:["ll-waveform__bar",a].filter(Boolean).join(" "),style:{height:`${o}px`}},l))})},Yn=({position:e,isMobile:r,agentName:i,avatarImageUrl:o,agentState:s,isMuted:a,audioLevel:u,onExpand:d,onToggleMute:f,onClose:m})=>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:d,"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(Vn,{audioLevel:u,bars:16,maxHeight:18,className:"ll-minimized__waveform"}),t.jsx("span",{className:"ll-minimized__name",children:i}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("span",{className:"ll-minimized__btn",role:"button",tabIndex:0,onClick:g=>{g.stopPropagation(),f()},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.stopPropagation(),g.preventDefault(),f())},"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(It,{muted:a,className:"ll-minimized__icon"})}),t.jsx(Tt,{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:s==="speaking"?"Speaking":s==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:f,"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(It,{muted:a,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:d,"aria-label":`Expand ${i} widget`,children:t.jsx(Tt,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:m,"aria-label":"Close widget",children:t.jsx(On,{className:"ll-minimized__icon"})})]})]})}),Gn=({src:e,alt:r,preCannedPlaying:i=!1,className:o,style:s})=>{const[a,u]=n.useState(!1),d=n.useRef(e);if(n.useEffect(()=>{d.current!==e&&(d.current=e,u(!1))},[e]),!e)return null;const f={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,...s};return t.jsx("img",{src:e,alt:r,className:o,style:f,loading:"eager",fetchPriority:"high",onLoad:()=>u(!0)})},Kn=({position:e,isMobile:r,agentName:i,avatarImageUrl:o,idleLoopUrl:s,greeting:a,branding:u,teamMembers:d,currentTeamMemberId:f,isSwitchingTeamMember:m,teamSwitcherOpen:g,onToggleTeamSwitcher:l,onSelectTeamMember:c,languageMenuOpen:L,onToggleLanguageMenu:D,connectionState:_,agentState:w,transcript:b,canResume:T,needsUserGesture:E,error:I,isMuted:x,micError:S,micDevices:$,isCameraEnabled:A,cameraPreviewEl:C,cameraDevices:R,activeCameraId:z,isScreenShareEnabled:F,screenPreviewEl:Z,isSpeakerMuted:J,allowCamera:be,allowScreenShare:oe,allowTyping:fe,avatarVideoContainerRef:se,agentVideoEl:Y,onConnect:ae,onDisconnect:ve,onRetry:we,onResumeAudio:_e,onToggleMute:ke,onToggleCamera:Se,onSwitchCameraDevice:Ce,onToggleScreenShare:Le,onToggleSpeaker:B,onSendMessage:Be,onMinimize:We,onClose:Fe,onClearMicError:Ue})=>{var Xe;const le=((d==null?void 0:d.length)??0)>1,pe=_==="connecting"||_==="connected",ee=_==="connected",st=_==="idle"||_==="disconnected"||_==="error",[ce,W]=n.useState(!1);n.useEffect(()=>{if(!Y){W(!1);return}if(!Y.paused&&Y.readyState>=2){W(!0);return}W(!1);const p=()=>W(!0);return Y.addEventListener("playing",p),Y.addEventListener("loadeddata",p),()=>{Y.removeEventListener("playing",p),Y.removeEventListener("loadeddata",p)}},[Y]);const[Ve,he]=n.useState(!1);n.useEffect(()=>{if(!ee){he(!1);return}if(ce)return;const p=setTimeout(()=>he(!0),8e3);return()=>clearTimeout(p)},[ee,ce]);const ue=_==="connecting"||ee&&!!o&&!ce&&!Ve,xe=n.useRef(null),je=n.useRef(null);n.useEffect(()=>{const p=xe.current;p&&(p.innerHTML="",C&&(C.style.width="100%",C.style.height="100%",C.style.objectFit="cover",C.style.transform="scaleX(-1)",p.appendChild(C)))},[C]),n.useEffect(()=>{const p=je.current;p&&(p.innerHTML="",Z&&(Z.style.width="100%",Z.style.height="100%",Z.style.objectFit="contain",p.appendChild(Z)))},[Z]);const[K,Q]=n.useState(!1),[te,me]=n.useState(!1);n.useEffect(()=>{if(!K&&!te&&!L&&!g)return;const p=()=>{Q(!1),me(!1),L&&D(),g&&l()};return document.addEventListener("click",p),()=>document.removeEventListener("click",p)},[K,te,L,g,D,l]);const[Ee,Re]=n.useState(""),Te=n.useCallback(p=>{p.preventDefault();const O=Ee.trim();O&&(Be(O),Re(""))},[Ee,Be]),Ye=u.productName||"Live Layer";let ne=null,re=null;for(let p=b.length-1;p>=0;p--){const O=b[p];if(!ne&&O.role==="agent"?ne=O:!re&&O.role==="user"&&(re=O),ne&&re)break}const Ge=ee?(ne==null?void 0:ne.text)||null:a||null,Ke=ee&&(re==null?void 0:re.text)||null,Pe=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Pe,"data-position":e,"data-state":ee?"connected":pe?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[o?t.jsx(Gn,{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:((Xe=i==null?void 0:i.charAt(0))==null?void 0:Xe.toUpperCase())||"A"})}),s&&!ee&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:se,className:"ll-expanded__video"}),ue&&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:m?"Switching...":"Connecting..."})]}),E&&ee&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:_e,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"})]}),pe?t.jsxs("div",{className:"ll-expanded__topbar",children:[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:p=>{le&&(p.stopPropagation(),l())},"aria-haspopup":le?"listbox":void 0,"aria-expanded":le?g:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),le&&t.jsx(et,{})]}),le&&g&&t.jsx("div",{className:"ll-hmenu",onClick:p=>p.stopPropagation(),role:"listbox",children:d==null?void 0:d.map(p=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${p.id===f?"is-active":""}`,onClick:()=>c(p.id),role:"option","aria-selected":p.id===f,children:[p.avatarImageUrl&&t.jsx("img",{src:p.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:p.name}),p.role&&t.jsx("span",{className:"ll-hmenu__role",children:p.role})]},p.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:p=>{p.stopPropagation(),D()},"aria-haspopup":"listbox","aria-expanded":L,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(et,{})]}),L&&t.jsx("div",{className:"ll-hmenu",onClick:p=>p.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--${w}`,children:w})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn",onClick:We,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(Ht,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Fe,"aria-label":"End call",title:"End call",children:t.jsx(zt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:Ye}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:We,"aria-label":"Minimize widget",children:t.jsx(Ht,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:Fe,"aria-label":"Close widget",children:t.jsx(zt,{})})]})]}),st&&(()=>{const p=T?"Restart paused session":_==="disconnected"?"Reconnect to agent":"Start video call",O=T?"Pick up where you left off":null,De=!I;return t.jsxs(t.Fragment,{children:[De&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:ae,"aria-label":p,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"})})}),t.jsx("span",{className:"ll-expanded__play-label",children:p})]}),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})}),O&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:O}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:ae,"aria-label":p,children:p})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${pe&&(A||F)?"is-visible":""}`,children:[t.jsx("div",{ref:je,className:F?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:xe,className:!F&&A?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),pe?t.jsxs("div",{className:"ll-expanded__bottom",children:[Ge&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Ge})}),Ke&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Ke})}),t.jsxs("div",{className:"ll-toolbar",onClick:p=>p.stopPropagation(),children:[oe&&t.jsx("button",{type:"button",className:`ll-tool ${F?"is-on":""}`,onClick:Le,"aria-label":F?"Stop sharing screen":"Share screen",title:F?"Stop sharing":"Share screen",children:t.jsx(Xn,{})}),be&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${A?"is-on":""}`,onClick:Se,"aria-label":A?"Turn off camera":"Turn on camera",title:A?"Stop camera":"Start camera",children:t.jsx(Jn,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${A?"is-on":""}`,onClick:p=>{p.stopPropagation(),me(O=>!O),Q(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":te,children:t.jsx(et,{})}),te&&R.length>0&&t.jsx(Ot,{label:"Camera",devices:R,activeId:z,onPick:p=>{me(!1),Ce(p)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${x?"is-muted":""}`,onClick:ke,"aria-label":x?"Unmute microphone":"Mute microphone",title:x?"Unmute":"Mute",children:t.jsx(Qn,{muted:x})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${x?"is-muted":""}`,onClick:p=>{p.stopPropagation(),Q(O=>!O),me(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":K,children:t.jsx(et,{})}),K&&$.length>0&&t.jsx(Ot,{label:"Microphone",devices:$,activeId:"",onPick:()=>Q(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${J?"is-muted":""}`,onClick:B,"aria-label":J?"Unmute speaker":"Mute speaker",title:J?"Unmute speaker":"Mute speaker",children:t.jsx(Zn,{muted:J})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:ve,"aria-label":"End conversation",title:"End conversation",children:t.jsx(tr,{})})]}),fe&&t.jsxs("form",{className:"ll-message-input",onSubmit:Te,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:Ee,onChange:p=>Re(p.target.value),"aria-label":"Message the agent"}),Ee.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(er,{})})]})]}):null,(()=>{if(S&&_!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:S}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:Ue,"aria-label":"Dismiss",children:"×"})]});if(!I||_!=="error")return null;let p="Failed to connect",O="Try again";return I==="MIC_PERMISSION_DENIED"?p="Microphone blocked. Allow access to talk.":I==="MIC_NOT_FOUND"?p="No microphone found. Plug one in + retry.":I==="MIC_UNAVAILABLE"?p="Mic unavailable. Check other apps using it.":I==="AGENT_TIMEOUT"?p="Agent didn't pick up. Try again.":I==="CONNECT_FAILED"?p="Connection failed. Check your network.":I.length<80&&(p=I),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:p}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:we,children:O})]})})()]})};function et(){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 zt(){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 Ht(){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 Xn(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[t.jsx("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 Jn(){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 Qn({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 Zn({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 er(){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 tr(){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 Ot=({label:e,devices:r,activeId:i,onPick:o})=>t.jsxs("div",{className:"ll-device-menu",onClick:s=>s.stopPropagation(),role:"listbox",children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),r.map((s,a)=>{const u=i===s.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${u?"is-active":""}`,onClick:()=>o(s.deviceId),role:"option","aria-selected":u,children:[u&&t.jsx("span",{className:"ll-device-menu__dot",children:"●"}),t.jsx("span",{className:"ll-device-menu__name",children:s.label||`${e} ${a+1}`})]},s.deviceId||a)})]}),nr=['[data-ll-private="true"]',".ll-widget"];function ht(e){let r=e;for(;r;){for(const i of nr)if(r.matches(i))return!0;r=r.parentElement}return!1}function ot(e){if(ht(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 tt=4096,rr=20,ir=20,or=10,sr=10,ar=30,lr=20,qt=500,cr=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function Oe(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let r=e;for(;r;){for(const i of cr)if(r.matches(i))return!0;r=r.parentElement}return!1}function qe(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 Bt(e){const r=e.getAttribute("id");if(r){const a=document.querySelector(`label[for="${CSS.escape(r)}"]`);if(a!=null&&a.textContent)return a.textContent.trim()}const i=e.getAttribute("aria-label");if(i)return i.trim();const o=e.getAttribute("placeholder");if(o)return o.trim();const s=e.closest("label");return s!=null&&s.textContent?s.textContent.trim():""}function de(e,r){return e.length<=r?e:e.slice(0,r-1)+"…"}function Ae(e){return e.length}function ln(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||"",s=typeof window<"u"&&window.location.pathname||"/",a=i.title||"",u=Array.from(i.querySelectorAll("[data-ll-region]")),d=[];for(const x of u){if(d.length>=or)break;if(Oe(x)||!qe(x))continue;const S=x.getAttribute("data-ll-region")??"",$=x.getAttribute("data-ll-intent")??void 0,A=de((x.innerText||x.textContent||"").trim(),qt*2);!S||!A||d.push({id:S,intent:$,text:A})}const f=[],m=["H1","H2","H3","H4","H5","H6"],g=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const x of g){if(Oe(x)||!qe(x))continue;const S=(x.textContent||"").trim();S&&f.push(`${x.tagName}: ${de(S,200)}`)}const l=Array.from(i.querySelectorAll("p, li"));for(const x of l){if(Oe(x)||!qe(x)||m.includes(x.tagName))continue;const S=(x.textContent||"").trim();S.length>10&&f.push(de(S,qt))}const c=f.join(`
2
- `),L=[],D=Array.from(i.querySelectorAll("a[href]"));for(const x of D){if(L.length>=rr)break;if(Oe(x)||!qe(x))continue;const S=x.getAttribute("href")||"",$=(x.textContent||"").trim();!S||!$||L.push({href:S,text:de($,100)})}const _=[],w=Array.from(i.querySelectorAll("input, textarea, select"));for(const x of w){if(_.length>=ir)break;if(Oe(x)||!ot(x)||!qe(x))continue;const S=Bt(x),$=x instanceof HTMLInputElement?x.type:x.tagName.toLowerCase();S&&_.push({label:de(S,100),type:$})}const b=Array.from(i.querySelectorAll("[data-ll-form]")),T=[];for(const x of b){if(T.length>=sr)break;if(ht(x))continue;const S=x.getAttribute("data-ll-form")||"";if(!S)continue;const $=x.getAttribute("data-ll-intent")||void 0,A=Array.from(x.querySelectorAll("[data-ll-field]")),C=[];for(const R of A){if(C.length>=ar)break;if(!ot(R))continue;const z=R.getAttribute("data-ll-field")||"";if(!z)continue;const F=Bt(R)||z,Z=R instanceof HTMLInputElement?R.type:R.tagName.toLowerCase(),J={name:z,label:de(F,100),type:Z};if(R.required===!0&&(J.required=!0),R instanceof HTMLSelectElement){const oe=[];for(let fe=0;fe<R.options.length&&!(oe.length>=lr);fe++){const se=R.options[fe];if(!se||se.disabled)continue;const Y=se.value||"",ae=(se.textContent||"").trim()||Y;!Y&&!ae||oe.push({value:Y,label:de(ae,60)})}oe.length>0&&(J.options=oe)}const be=typeof R.validationMessage=="string"?R.validationMessage:"";be&&(J.validationMessage=de(be,200)),C.push(J)}T.push({id:S,intent:$,fields:C})}const E={url:o,title:a,pathname:s,regions:d,visibleText:c,visibleLinks:L,visibleFields:_,forms:T,extras:e};let I=Ae(JSON.stringify(E.regions))+Ae(E.visibleText)+Ae(JSON.stringify(E.visibleLinks))+Ae(JSON.stringify(E.visibleFields));for(;I>tt&&E.visibleFields.length>0;)E.visibleFields.pop(),I=Ae(JSON.stringify(E.visibleFields));for(;I>tt&&E.visibleLinks.length>0;)E.visibleLinks.pop(),I-=80;return Ae(E.visibleText)>tt&&(E.visibleText=de(E.visibleText,tt-100)),E}let Me=null;function pt(e,r={}){const i=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(Me&&Me.key===s&&i-Me.at<1e3)return Me.ctx;const a=ln(e,r);return Me={key:s,at:i,ctx:a},a}function cn(){Me=null}const ur=200;function un(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 dr(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function dn(e){const r=e??(typeof document<"u"?document:null);if(!r)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,s=[],a=Array.from(r.querySelectorAll("a[href]"));for(const u of a){if(s.length>=ur)break;if(ht(u))continue;const d=u.getAttribute("href")||"";if(!dr(d))continue;let f=d,m=!0;try{if(typeof window<"u"){const l=new URL(d,i);m=l.origin===i,m&&d.startsWith("http")&&(f=l.pathname+l.search+l.hash)}}catch{continue}if(o.has(f))continue;o.add(f);const g=(u.textContent||"").trim().slice(0,120);s.push({href:f,text:g,internal:m})}return s}let Ie=null;const fr=5e3;function nt(){const e=Date.now(),r=typeof window<"u"&&window.location.pathname||"/";if(Ie&&Ie.pathname===r&&e-Ie.at<fr)return Ie.routes;const i=dn();return Ie={at:e,pathname:r,routes:i},i}function fn(){Ie=null}function pr(e,r){const i=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,o=Object.getOwnPropertyDescriptor(i,"value"),s=o==null?void 0:o.set;s?s.call(e,r):e.value=r}function hr(e,r,i={}){const o=i.triggerInput??!0,s=i.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const a=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),u=a==null?void 0:a.set,d=r==="true"||r==="1"||r==="on";u?u.call(e,d):e.checked=d,o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}pr(e,r),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function mr(){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 gr(e){if(!(e instanceof HTMLElement))return!1;const i=window.getComputedStyle(e).overflowY;return!(i!=="auto"&&i!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function yr(){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(!gr(o))continue;const s=o.getBoundingClientRect();if(s.bottom<=0||s.top>=window.innerHeight||s.right<=0||s.left>=window.innerWidth||s.width<=0||s.height<=0||o.closest(".ll-widget"))continue;const a=s.width*s.height;a>i&&(i=a,r=o)}return r}function br(){if(typeof window>"u")return null;if(mr())return window;const e=yr();return e||window}function Wt(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function xr(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 vr=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"]);function wr(e){var wt,_t,kt,St,Ct,Lt,jt;const{agentId:r,apiKey:i,baseUrl:o="https://app.livelayer.studio",sessionEndpoint:s,sessionBody:a,soundEffects:u,autoConnect:d=!1,displayMode:f,defaultDisplayMode:m="expanded",onDisplayModeChange:g,position:l="bottom-right",mobileBreakpoint:c=640,persistKey:L="ll-widget",disablePersistence:D=!1,teamMembers:_,currentTeamMemberId:w,onTeamMemberChange:b,idleLoopUrl:T,greeting:E,avatarImageUrl:I,agentName:x,branding:S={},allowCamera:$=!0,allowScreenShare:A=!0,allowTyping:C=!0,showOn:R,hideOn:z,pathname:F,onNavigate:Z,onScrollToSelector:J,getPageContext:be,pageContextExtras:oe,getRoutes:fe,onScrollPage:se,onClick:Y,capabilities:ae,onConnect:ve,onDisconnect:we,onTranscript:_e,onAgentState:ke,onConnectionStateChange:Se,onAgentEvent:Ce,onAgentCommand:Le,controlledSession:B,className:Be,style:We,zIndex:Fe=2147483647}=e,Ue=nn(F),le=sn(Ue,R,z);n.useEffect(()=>{cn(),fn()},[Ue]);const pe=w!==void 0,[ee,st]=n.useState(()=>{var y;return w??((y=_==null?void 0:_[0])==null?void 0:y.id)}),ce=pe?w:ee,W=n.useMemo(()=>(_==null?void 0:_.find(y=>y.id===ce))??null,[_,ce]),Ve=(W==null?void 0:W.agentId)??r,[he,ue]=en({value:f,defaultValue:m,onChange:g,persistKey:L,disablePersistence:D}),xe=tn(c),je=Yt(),K=Gt(),Q=Kt(),te=Xt(),me=Jt(),[Ee,Re]=n.useState(!1),[Te,Ye]=n.useState(!1),[ne,re]=n.useState(!1),[Ge,Ke]=n.useState(!1),[Pe,Xe]=n.useState(!1),p=Hn({baseUrl:o,config:u}),O=n.useRef(p);O.current=p;const De=n.useRef(Z),at=n.useRef(J),lt=n.useRef(se),ct=n.useRef(Y),mt=n.useRef(be),gt=n.useRef(oe),yt=n.useRef(fe),ut=n.useRef(ae),ie=n.useRef(null);De.current=Z,at.current=J,lt.current=se,ct.current=Y,mt.current=be,gt.current=oe,yt.current=fe,ut.current=ae;function ge(y){const h=ut.current;return h?h.includes(y):!0}function ye(y,h){console.warn(`[LiveLayer] Agent command "${y}" blocked — capability "${h}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const $e=n.useCallback(y=>{var X,Qe,Ze,Et;const h=y;if(!(!h.type||typeof h.type!="string")){if(Ce==null||Ce({eventName:h.type,data:y}),h.type==="navigate"){if(!ge("navigate")){ye("navigate","navigate");return}const k=typeof h.href=="string"?h.href:null;if(!k){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(O.current.playPageChange(),De.current){try{De.current(k)}catch(j){console.warn(`[LiveLayer] onNavigate threw for "${k}". Falling back. Error:`,j)}return}if(typeof document<"u"){const j=document.querySelector(`a[href="${k.replace(/"/g,'\\"')}"]`);if(j){j.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",k),window.dispatchEvent(new PopStateEvent("popstate"))}catch(j){console.warn(`[LiveLayer] history.pushState fallback failed for "${k}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,j)}return}if(h.type==="scroll_to"){if(!ge("scroll")){ye("scroll_to","scroll");return}const k=typeof h.selector=="string"?h.selector:null;if(!k)return;const j=h.behavior==="instant"?"instant":"smooth";if(at.current){try{at.current(k,j)}catch(P){console.warn("[LiveLayer] onScrollToSelector threw.",P)}return}if(typeof document<"u"){let P=null;try{P=document.querySelector(k)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${k}".`);return}if(!P){console.warn(`[LiveLayer] scroll_to: no element matched "${k}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}P.scrollIntoView({behavior:j,block:"start"})}return}if(h.type==="request_page_context"){if(!ge("read_page")){ye("request_page_context","read_page");return}const k=typeof h.requestId=="string"?h.requestId:void 0,j=(X=ie.current)==null?void 0:X.call(ie),P=q=>{const N=j,V=N==null?void 0:N.localParticipant;if(V!=null&&V.publishData)try{const G=k?{...q,requestId:k}:q,Ne=new TextEncoder().encode(JSON.stringify(G));V.publishData(Ne,{reliable:!0})}catch(G){console.warn("[LiveLayer] publishData failed.",G)}},M=gt.current,H=mt.current;try{if(H){const q=H(M);if(q instanceof Promise){P({type:"page_context_pending"}),q.then(N=>P({type:"page_context",context:N})).catch(N=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",N),P({type:"page_context",context:pt(M)})});return}P({type:"page_context",context:q});return}P({type:"page_context",context:pt(M)})}catch(q){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",q),P({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:M}})}return}if(h.type==="scroll_page"){if(!ge("scroll")){ye("scroll_page","scroll");return}const k=h.direction;if(k!=="up"&&k!=="down"&&k!=="top"&&k!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(k)}". Expected up | down | top | bottom.`);return}const j=h.behavior==="instant"?"instant":"smooth";if(lt.current){try{lt.current(k,j)}catch(N){console.warn("[LiveLayer] onScrollPage threw.",N)}return}if(typeof window>"u")return;const P={behavior:j},M=br(),H=N=>{M instanceof Window?M.scrollBy({top:N,...P}):M.scrollBy({top:N,...P})},q=N=>{M instanceof Window?M.scrollTo({top:N,...P}):M.scrollTo({top:N,...P})};k==="up"?H(-Wt(M)):k==="down"?H(Wt(M)):q(k==="top"?0:xr(M));return}if(h.type==="click"){if(!ge("click")){ye("click","click");return}const k=typeof h.selector=="string"?h.selector:null;if(!k){console.warn("[LiveLayer] click: missing selector.");return}if(ct.current){try{ct.current(k)}catch(P){console.warn("[LiveLayer] onClick threw.",P)}return}if(typeof document>"u")return;let j=null;try{j=document.querySelector(k)}catch{console.warn(`[LiveLayer] click: invalid selector "${k}".`);return}if(!j){console.warn(`[LiveLayer] click: no element matched "${k}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(j.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(Qe=j.click)==null||Qe.call(j);return}if(h.type==="fill_form"||h.type==="focus_field"){if(!ge("fill_forms")){ye(h.type,"fill_forms");return}if(typeof document>"u")return;h.type==="fill_form"&&O.current.playConfirmation();const k=typeof h.formId=="string"?h.formId:null;if(!k){console.warn(`[LiveLayer] ${h.type}: missing formId.`);return}const j=document.querySelector(`[data-ll-form="${k.replace(/"/g,'\\"')}"]`);if(!j){console.warn(`[LiveLayer] ${h.type}: no form with data-ll-form="${k}". Tag your form with <LiveLayerForm id> or data-ll-form. See https://livelayer.studio/docs/react/forms`);return}if(j.closest('[data-ll-private="true"], .ll-widget')){console.warn(`[LiveLayer] ${h.type}: refusing to touch a form in a private subtree.`);return}if(h.type==="focus_field"){const M=typeof h.fieldName=="string"?h.fieldName:null;if(!M){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const H=j.querySelector(`[data-ll-field="${M.replace(/"/g,'\\"')}"]`);if(!H){console.warn(`[LiveLayer] focus_field: no field "${M}" in form "${k}".`);return}if(!ot(H)){console.warn(`[LiveLayer] focus_field: field "${M}" is privacy-protected and not focusable.`);return}H.focus();return}const P=h.values&&typeof h.values=="object"?h.values:null;if(!P){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[M,H]of Object.entries(P)){if(typeof H!="string")continue;const q=j.querySelector(`[data-ll-field="${M.replace(/"/g,'\\"')}"]`);if(!q){console.warn(`[LiveLayer] fill_form: no field "${M}" in form "${k}". Skipping.`);continue}if(!ot(q)){console.warn(`[LiveLayer] fill_form: field "${M}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{hr(q,H)}catch(N){console.warn(`[LiveLayer] fill_form: failed to set "${M}".`,N)}}return}if(h.type==="submit_form"){if(!ge("submit_forms")){ye("submit_form","submit_forms");return}if(typeof document>"u")return;const k=typeof h.formId=="string"?h.formId:null;if(!k){console.warn("[LiveLayer] submit_form: missing formId.");return}O.current.playConfirmation();const j=document.querySelector(`[data-ll-form="${k.replace(/"/g,'\\"')}"]`);if(!j){console.warn(`[LiveLayer] submit_form: no form with data-ll-form="${k}".`);return}if(j.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private subtree.");return}const P=typeof h.requestId=="string"?h.requestId:void 0,M=(Ze=ie.current)==null?void 0:Ze.call(ie),H=V=>{const G=M,Ne=G==null?void 0:G.localParticipant;if(Ne!=null&&Ne.publishData)try{const Sn=P?{...V,requestId:P}:V,Cn=new TextEncoder().encode(JSON.stringify(Sn));Ne.publishData(Cn,{reliable:!0})}catch{}};let q=!1;const N=()=>{q=!0,H({type:"form_submitted",formId:k})};j.addEventListener("submit",N,{once:!0});try{typeof j.requestSubmit=="function"?j.requestSubmit():j.submit()}catch(V){console.warn("[LiveLayer] submit_form: requestSubmit threw.",V),j.removeEventListener("submit",N),H({type:"form_submit_blocked",formId:k,reason:"exception"});return}setTimeout(()=>{q||(j.removeEventListener("submit",N),H({type:"form_submit_blocked",formId:k,reason:"validation"}))},500);return}if(h.type==="request_routes"){if(!ge("read_page")){ye("request_routes","read_page");return}const k=typeof h.requestId=="string"?h.requestId:void 0,P=(Et=ie.current)==null?void 0:Et.call(ie),M=P==null?void 0:P.localParticipant;if(!(M!=null&&M.publishData))return;const H=N=>{try{const V=k?{type:"routes",routes:N,requestId:k}:{type:"routes",routes:N},G=new TextEncoder().encode(JSON.stringify(V));M.publishData(G,{reliable:!0})}catch(V){console.warn("[LiveLayer] request_routes: publishData failed.",V)}},q=yt.current;if(q){try{const N=q(),V=G=>{if(!Array.isArray(G)){H([]);return}H(G.map(un).slice(0,200))};N instanceof Promise?N.then(V).catch(G=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",G),H(nt())}):V(N)}catch(N){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",N),H(nt())}return}try{H(nt())}catch(N){console.warn("[LiveLayer] request_routes: extractRoutes threw.",N)}return}vr.has(h.type)||Le==null||Le(h)}},[Le,Ce]),U=Vt({agentId:B?"__controlled__":Ve,baseUrl:o,apiKey:i,sessionEndpoint:s,sessionBody:a,onDataMessage:B?void 0:$e});n.useEffect(()=>{if(B!=null&&B.subscribeToDataMessages)return B.subscribeToDataMessages($e)},[B,$e]),ie.current=()=>{var y;return(y=U.getRoom)==null?void 0:y.call(U)},n.useEffect(()=>{var X;if(typeof window>"u")return;const y=((X=window.location)==null?void 0:X.hostname)||"";if(y==="localhost"||y==="127.0.0.1"||y==="0.0.0.0"||y.endsWith(".local")||y.endsWith(".test"))return window.__livelayerSimulateCommand=Qe=>{try{$e(Qe)}catch(Ze){console.warn("[LiveLayer] simulate-command threw:",Ze)}},()=>{delete window.__livelayerSimulateCommand}},[$e]);const v=n.useMemo(()=>B?{connectionState:B.connectionState,agentState:B.agentState,transcript:B.transcript,videoElement:B.videoElement,audioElement:B.audioElement,canResume:B.canResume,error:B.error,agentConfig:null,connect:async()=>{await B.onConnect()},disconnect:()=>B.onDisconnect(),getRoom:U.getRoom,isControlled:!0}:{connectionState:U.connectionState,agentState:U.agentState,transcript:U.transcript,videoElement:U.videoElement,audioElement:U.audioElement,canResume:U.canResume,error:U.error,agentConfig:U.agentConfig,connect:U.connect,disconnect:U.disconnect,getRoom:U.getRoom,isControlled:!1},[B,U]),bt=n.useRef(null);n.useEffect(()=>{const y=v.videoElement,h=bt.current;if(!(!y||!h))return h.appendChild(y),()=>{y.parentNode===h&&h.removeChild(y)}},[v.videoElement]),n.useEffect(()=>{const y=v.audioElement;if(!y)return;je.attach(y);const h=y.play();return h&&typeof h.catch=="function"&&h.catch(X=>{(X==null?void 0:X.name)==="NotAllowedError"&&Re(!0)}),()=>{je.detach()}},[v.audioElement]),n.useEffect(()=>{if(v.isControlled||v.connectionState!=="connected")return;const y=v.getRoom();if(y)return K.setupMic(y).catch(()=>{}),Q.attachRoom(y),te.attachRoom(y),me.refresh(),()=>{K.teardownMic(),Q.teardown(),te.teardown()}},[v.isControlled,v.connectionState]),n.useEffect(()=>{const y=v.audioElement;y&&(y.muted=Pe)},[v.audioElement,Pe]);const pn=n.useCallback(y=>{const h=v.getRoom();if(h)try{const X=new TextEncoder().encode(JSON.stringify({type:"user_message",text:y}));h.localParticipant.publishData(X,{reliable:!0})}catch{}},[v]),hn=n.useCallback(()=>{Xe(y=>!y)},[]);n.useEffect(()=>{Se==null||Se(v.connectionState),v.connectionState==="connected"?ve==null||ve():v.connectionState==="disconnected"&&(we==null||we())},[v.connectionState,ve,we,Se]),n.useEffect(()=>{_e==null||_e(v.transcript)},[v.transcript,_e]),n.useEffect(()=>{ke==null||ke(v.agentState)},[v.agentState,ke]),n.useEffect(()=>{p.setThinking(v.agentState==="thinking")},[v.agentState,p]);const xt=n.useRef(!1);n.useEffect(()=>{v.isControlled||!d||xt.current||le&&v.connectionState==="idle"&&(xt.current=!0,v.connect())},[d,v.connectionState,v,le]);const mn=n.useCallback(y=>{const h=_==null?void 0:_.find(X=>X.id===y);h&&(re(!1),y!==ce&&(Ye(!0),v.disconnect(),pe||st(y),b==null||b(h)))},[_,ce,v,pe,b]);n.useEffect(()=>{Te&&v.connectionState==="connected"&&Ye(!1)},[v.connectionState,Te]),n.useEffect(()=>{if(!ne)return;const y=h=>{h.key==="Escape"&&re(!1)};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[ne]);const gn=!!I||!!(W!=null&&W.avatarImageUrl)||v.isControlled,ze=Qt(Ve,o,gn);ae===void 0&&((wt=ze.info)!=null&&wt.capabilities)&&(ut.current=ze.info.capabilities);const Je=(W==null?void 0:W.name)??x??((_t=v.agentConfig)==null?void 0:_t.name)??((kt=ze.info)==null?void 0:kt.name)??"Live Layer",dt=(W==null?void 0:W.avatarImageUrl)??I??((St=v.agentConfig)==null?void 0:St.avatarImageUrl)??((Ct=ze.info)==null?void 0:Ct.avatarImageUrl)??null,yn=T??((Lt=v.agentConfig)==null?void 0:Lt.idleLoopUrl)??((jt=ze.info)==null?void 0:jt.idleLoopUrl)??null,bn=E??null,xn=n.useCallback(()=>ue("expanded"),[ue]),vn=n.useCallback(()=>ue("minimized"),[ue]),vt=n.useCallback(()=>{v.disconnect(),ue("hidden")},[v,ue]),wn=n.useCallback(()=>{const y=v.audioElement;y&&y.play().then(()=>Re(!1)).catch(()=>{})},[v.audioElement]),_n=n.useCallback(()=>{Re(!1),v.connect()},[v]),He={...We,zIndex:Fe};S.primaryColor&&(He["--ll-color-primary"]=S.primaryColor),S.accentColor&&(He["--ll-color-accent"]=S.accentColor),S.backgroundColor&&(He["--ll-color-bg"]=S.backgroundColor),S.textColor&&(He["--ll-color-fg"]=S.textColor);const kn=["ll-widget",`ll-widget--${he}`,`ll-widget--${xe?"mobile":"desktop"}`,Be].filter(Boolean).join(" ");return le?t.jsxs("div",{className:kn,style:He,"data-display-mode":he,"data-position":l,children:[he==="hidden"&&t.jsx(Un,{position:l,isMobile:xe,isSpeaking:v.agentState==="speaking",onExpand:()=>ue("expanded"),label:`Open ${Je} widget`,avatarImageUrl:dt,agentName:Je}),he==="minimized"&&t.jsx(Yn,{position:l,isMobile:xe,agentName:Je,avatarImageUrl:dt,agentState:v.agentState,isMuted:K.isMuted,audioLevel:je,onExpand:xn,onToggleMute:K.toggleMute,onClose:vt}),he==="expanded"&&t.jsx(Kn,{position:l,isMobile:xe,agentName:Je,avatarImageUrl:dt,idleLoopUrl:yn,greeting:bn,branding:S,teamMembers:_,currentTeamMemberId:ce,isSwitchingTeamMember:Te,teamSwitcherOpen:ne,onToggleTeamSwitcher:()=>re(y=>!y),onSelectTeamMember:mn,connectionState:v.connectionState,agentState:v.agentState,transcript:v.transcript,isMuted:K.isMuted,micDevices:me.mics,isCameraEnabled:Q.isEnabled,cameraPreviewEl:Q.previewEl,cameraDevices:me.cameras,activeCameraId:Q.activeDeviceId,isScreenShareEnabled:te.isEnabled,screenPreviewEl:te.previewEl,isSpeakerMuted:Pe,allowCamera:$,allowScreenShare:A,allowTyping:C,languageMenuOpen:Ge,onToggleLanguageMenu:()=>Ke(y=>!y),needsUserGesture:Ee,canResume:v.canResume,micError:K.micError,error:v.error,avatarVideoContainerRef:bt,agentVideoEl:v.videoElement,onConnect:()=>void v.connect(),onDisconnect:()=>v.disconnect(),onRetry:_n,onResumeAudio:wn,onToggleMute:K.toggleMute,onToggleCamera:()=>void Q.toggle(),onSwitchCameraDevice:y=>void Q.switchDevice(y),onToggleScreenShare:()=>void te.toggle(),onToggleSpeaker:hn,onSendMessage:pn,onMinimize:vn,onClose:vt,onClearMicError:K.clearError})]}):null}function _r(e){return t.jsx(Ut,{children:t.jsx(wr,{...e})})}const kr=({agentId:e,baseUrl:r,apiKey:i,mode:o,onAgentEvent:s,className:a,style:u})=>{const d=n.useRef(null),f=n.useRef(null),m=n.useRef(s);m.current=s;const g=n.useCallback(l=>{var L;const c=l.detail;(L=m.current)==null||L.call(m,c)},[]);return n.useEffect(()=>{const l=d.current;if(!l)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",e),r&&c.setAttribute("base-url",r),i&&c.setAttribute("api-key",i),o&&c.setAttribute("mode",o),c.addEventListener("agent-event",g),l.appendChild(c),f.current=c,()=>{c.removeEventListener("agent-event",g),l.removeChild(c),f.current=null}},[e]),n.useEffect(()=>{f.current&&(o?f.current.setAttribute("mode",o):f.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:d,className:a,style:u})},Sr=n.forwardRef(function({id:r,intent:i,as:o="div",className:s,style:a,children:u},d){return n.createElement(o,{ref:d,"data-ll-region":r,"data-ll-intent":i,className:s,style:a},u)}),Cr=n.forwardRef(function({id:r,intent:i,children:o,...s},a){return t.jsx("form",{ref:a,"data-ll-form":r,"data-ll-intent":i,...s,children:o})}),Lr=n.forwardRef(function(r,i){const{name:o,label:s,labelClassName:a}=r,u={name:o,"data-ll-field":o};let d;if("as"in r&&r.as==="textarea"){const{name:f,label:m,labelClassName:g,as:l,...c}=r;d=t.jsx("textarea",{ref:i,...u,...c})}else if("as"in r&&r.as==="select"){const{name:f,label:m,labelClassName:g,as:l,children:c,...L}=r;d=t.jsx("select",{ref:i,...u,...L,children:c})}else{const{name:f,label:m,labelClassName:g,as:l,...c}=r;d=t.jsx("input",{ref:i,...u,...c})}return s===void 0?d:t.jsxs("label",{className:a,children:[s,d]})});let Ft=1;function jr({onMount:e,defaultOpen:r=!1,storageKey:i="ll-debug-open"}){const[o,s]=n.useState(r),[a,u]=n.useState([]),[d,f]=n.useState(""),[m,g]=n.useState(!1),l=n.useRef(new Set),c=n.useRef([]),L=n.useRef(m);L.current=m,n.useEffect(()=>{try{const w=localStorage.getItem(i);w==="1"&&s(!0),w==="0"&&s(!1)}catch{}},[i]),n.useEffect(()=>{try{localStorage.setItem(i,o?"1":"0")}catch{}},[o,i]),n.useEffect(()=>{const w=b=>{(b.metaKey||b.ctrlKey)&&b.shiftKey&&b.key.toLowerCase()==="l"&&(b.preventDefault(),s(T=>!T))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[]),n.useEffect(()=>{const w=setInterval(()=>{if(c.current.length===0||L.current)return;const b=c.current.splice(0,c.current.length);u(T=>[...b.reverse(),...T].slice(0,200))},100);return()=>clearInterval(w)},[]);const D=n.useRef(!1);if(n.useEffect(()=>{!e||D.current||(D.current=!0,e(w=>{c.current.push({id:Ft++,ts:Date.now(),kind:"event",type:w.eventName,data:w.data})}))},[e]),n.useEffect(()=>{const w=console.warn,b=console.log,T=(E,I)=>function(...x){try{const S=typeof x[0]=="string"?x[0]:"";S.startsWith("[LiveLayer]")&&c.current.push({id:Ft++,ts:Date.now(),kind:E,type:S.slice(0,120),data:{args:x.slice(1).map($=>Rr($))}})}catch{}return I.apply(this,x)};return console.warn=T("warn",w),console.log=T("log",b),()=>{console.warn=w,console.log=b}},[]),!o)return t.jsx("button",{type:"button",onClick:()=>s(!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 _=a.filter(w=>{if(!d)return!0;const b=d.toLowerCase();return w.type.toLowerCase().includes(b)||JSON.stringify(w.data||{}).toLowerCase().includes(b)});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:()=>g(w=>!w),style:ft(m?"#f59e0b":"transparent"),title:"Pause / resume capture",children:m?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{u([]),c.current=[]},style:ft("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:ft("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:d,onChange:w=>f(w.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:_.length===0?t.jsxs("div",{style:{padding:14,fontSize:11,color:"rgba(255,255,255,0.4)",lineHeight:1.5},children:["No events yet. Connect to the agent and trigger a tool call — the events will stream in here. You can also dispatch commands manually in DevTools:",t.jsx("pre",{style:{marginTop:6,background:"rgba(255,255,255,0.04)",padding:6,borderRadius:4,fontSize:10,whiteSpace:"pre-wrap"},children:`window.__livelayerSimulateCommand({
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),n=require("react"),$n=require("@livelayer/sdk"),ct=require("livekit-client");class Zt 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,s;(s=(o=this.props).onError)==null||s.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 en(e){const[r,i]=n.useState("idle"),[o,s]=n.useState("idle"),[a,u]=n.useState([]),[d,f]=n.useState(null),[m,y]=n.useState(null),[l,c]=n.useState(null),[E,I]=n.useState(!1),[C,w]=n.useState(null),v=n.useRef(null),S=n.useRef(e.onDataMessage);S.current=e.onDataMessage,n.useEffect(()=>{const L={onConnectionStateChange:T=>{i(T),T==="connected"&&w(null)},onAgentStateChange:s,onTranscript:T=>u([...T]),onAgentConfig:f,onAudioTrack:T=>c(T),onVideoTrack:T=>y(T),onVideoTrackRemoved:()=>y(null),onError:T=>w(T),onDataMessage:T=>{var k;(k=S.current)==null||k.call(S,T)},onResumabilityChange:I},$=new $n.LiveKitSession({agentId:e.agentId,baseUrl:e.baseUrl,apiKey:e.apiKey,sessionEndpoint:e.sessionEndpoint,sessionBody:e.sessionBody},L);return v.current=$,i("idle"),s("idle"),u([]),f(null),y(null),c(null),I(!1),w(null),()=>{var T;(T=$.destroy)==null||T.call($),v.current=null}},[e.agentId,e.baseUrl,e.apiKey,e.sessionEndpoint,JSON.stringify(e.sessionBody??{})]);const j=n.useCallback(async()=>{const L=v.current;if(L)try{await L.connect()}catch($){throw w($ instanceof Error?$.message:String($)),$}},[]),A=n.useCallback(()=>{const L=v.current;L&&L.disconnect()},[]),b=n.useCallback(()=>{var L;return((L=v.current)==null?void 0:L.getRoom())??null},[]);return{connectionState:r,agentState:o,transcript:a,agentConfig:d,videoElement:m,audioElement:l,canResume:E,error:C,connect:j,disconnect:A,getRoom:b,session:v.current}}function tn(){const e=n.useRef(null),r=n.useRef(null),i=n.useRef(null),o=n.useRef(null),s=n.useRef(new Set),a=n.useRef(null),u=n.useCallback(()=>{const l=r.current;if(!l){o.current=null;return}(!a.current||a.current.length!==l.frequencyBinCount)&&(a.current=new Uint8Array(new ArrayBuffer(l.frequencyBinCount)));const c=a.current;l.getByteFrequencyData(c);let E=0;for(let C=0;C<c.length;C++)E+=c[C];const I=E/c.length/255;for(const C of s.current)try{C(I)}catch(w){console.error("[useAudioLevel] subscriber threw:",w)}o.current=requestAnimationFrame(u)},[]),d=n.useCallback(()=>{if(e.current||typeof window>"u"||typeof AudioContext>"u")return;const l=new AudioContext,c=l.createAnalyser();c.fftSize=64,c.connect(l.destination),e.current=l,r.current=c},[]),f=n.useCallback(l=>{if(d(),!(!e.current||!r.current)){if(i.current){try{i.current.disconnect()}catch{}i.current=null}try{const c=e.current.createMediaElementSource(l);c.connect(r.current),i.current=c}catch(c){console.warn("[useAudioLevel] createMediaElementSource failed:",c);return}o.current===null&&(o.current=requestAnimationFrame(u))}},[d,u]),m=n.useCallback(()=>{if(o.current!==null&&(cancelAnimationFrame(o.current),o.current=null),i.current){try{i.current.disconnect()}catch{}i.current=null}},[]),y=n.useCallback(l=>(s.current.add(l),()=>{s.current.delete(l)}),[]);return n.useEffect(()=>()=>{if(m(),r.current){try{r.current.disconnect()}catch{}r.current=null}if(e.current){try{e.current.close()}catch{}e.current=null}s.current.clear(),a.current=null},[m]),{attach:f,detach:m,subscribe:y}}function nn(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),s=n.useRef(null),a=n.useRef(null),u=n.useCallback(async y=>{if(s.current&&a.current){try{await a.current.localParticipant.unpublishTrack(s.current)}catch{}s.current.stop(),s.current=null}a.current=y,o(null);try{const l=await ct.createLocalAudioTrack({echoCancellation:!0,noiseSuppression:!0});await y.localParticipant.publishTrack(l),s.current=l,r(l.isMuted)}catch(l){const c=l instanceof Error&&l.name==="NotAllowedError"?"Enable your microphone to talk with the agent.":"Microphone unavailable. Check browser permissions and try again.";throw o(c),l}},[]),d=n.useCallback(()=>{const y=s.current;y&&(y.isMuted?(y.unmute(),r(!1)):(y.mute(),r(!0)))},[]),f=n.useCallback(()=>{const y=s.current,l=a.current;if(y&&l){try{l.localParticipant.unpublishTrack(y)}catch{}y.stop()}s.current=null,a.current=null,r(!1)},[]),m=n.useCallback(()=>o(null),[]);return{isMuted:e,micError:i,toggleMute:d,setupMic:u,teardownMic:f,clearError:m}}const zn={resolution:{width:640,height:480,frameRate:24}};function rn(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),[s,a]=n.useState(null),[u,d]=n.useState(""),f=n.useRef(null),m=n.useRef(null),y=n.useCallback(v=>{f.current=v},[]),l=n.useCallback(()=>{const v=f.current,S=m.current;if(S&&v){const j=v.localParticipant.getTrackPublication(ct.Track.Source.Camera);if(j!=null&&j.track){try{v.localParticipant.unpublishTrack(j.track)}catch{}j.track.stop()}else S.stop()}m.current=null,a(null),r(!1)},[]),c=n.useCallback(async v=>{const S=f.current;if(S){o(null);try{const j={...zn};v&&(j.deviceId=v);const A=await ct.createLocalVideoTrack(j);await S.localParticipant.publishTrack(A),m.current=A;const b=A.attach();a(b),r(!0),v&&d(v);try{S.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_camera_on"})),{reliable:!0})}catch{}}catch(j){const A=j instanceof Error&&j.name==="NotAllowedError"?"Enable your camera in the browser to share video.":"Camera unavailable. Check permissions and try again.";o(A)}}},[]),E=n.useCallback(async()=>{e?l():await c(u||void 0)},[e,u,l,c]),I=n.useCallback(async v=>{l(),await c(v)},[l,c]),C=n.useCallback(()=>{l(),f.current=null,o(null),d("")},[l]),w=n.useCallback(()=>o(null),[]);return n.useEffect(()=>()=>{m.current&&m.current.stop()},[]),{isEnabled:e,error:i,previewEl:s,activeDeviceId:u,toggle:E,switchDevice:I,attachRoom:y,teardown:C,clearError:w}}function on(){const[e,r]=n.useState(!1),[i,o]=n.useState(null),[s,a]=n.useState(null),u=n.useRef(null),d=n.useCallback(c=>{u.current=c},[]),f=n.useCallback(()=>a(null),[]),m=n.useCallback(async()=>{const c=u.current;if(c){if(e){try{await c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),r(!1);return}o(null);try{await c.localParticipant.setScreenShareEnabled(!0);let E=0;const I=()=>{const C=c.localParticipant.getTrackPublication(ct.Track.Source.ScreenShare);if(C!=null&&C.track){const w=C.track.attach();a(w),r(!0);try{c.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({type:"user_screen_share_on"})),{reliable:!0})}catch{}return}E++<10?setTimeout(I,100):r(!0)};I()}catch(E){const I=E instanceof Error?E.name:"";I!=="NotAllowedError"&&I!=="AbortError"&&o("Screen share unavailable. Try again."),r(!1)}}},[e,f]),y=n.useCallback(()=>{const c=u.current;if(c&&e)try{c.localParticipant.setScreenShareEnabled(!1)}catch{}f(),r(!1),o(null),u.current=null},[e,f]),l=n.useCallback(()=>o(null),[]);return{isEnabled:e,error:i,previewEl:s,toggle:m,attachRoom:d,teardown:y,clearError:l}}function sn(){const[e,r]=n.useState([]),[i,o]=n.useState([]),s=n.useCallback(async()=>{if(!(typeof navigator>"u"||!navigator.mediaDevices))try{const a=await navigator.mediaDevices.enumerateDevices();r(a.filter(u=>u.kind==="audioinput")),o(a.filter(u=>u.kind==="videoinput"))}catch{}},[]);return n.useEffect(()=>{if(s(),typeof navigator>"u"||!navigator.mediaDevices)return;const a=()=>void s();return navigator.mediaDevices.addEventListener("devicechange",a),()=>navigator.mediaDevices.removeEventListener("devicechange",a)},[s]),{mics:e,cameras:i,refresh:s}}function an(e,r,i=!1){const[o,s]=n.useState(null),[a,u]=n.useState(null),[d,f]=n.useState(!i&&!!e);return n.useEffect(()=>{if(i||!e){f(!1);return}const m=new AbortController,y=r||"https://app.livelayer.studio";return f(!0),u(null),fetch(`${y}/api/widget/agent/${encodeURIComponent(e)}`,{signal:m.signal}).then(async l=>{if(!l.ok){const c=await l.json().catch(()=>({}));throw new Error(c.error||`HTTP ${l.status}`)}return l.json()}).then(l=>{m.signal.aborted||(s(l),f(!1))}).catch(l=>{m.signal.aborted||(u(l instanceof Error?l.message:"Agent lookup failed"),f(!1))}),()=>m.abort()},[e,r,i]),{info:o,error:a,loading:d}}function Hn(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function On(e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(e,r)}catch{}}function ln({value:e,defaultValue:r="expanded",onChange:i}={}){const o=e!==void 0,[s,a]=n.useState(r),u=o?e:s,d=n.useCallback(f=>{f!==u&&(o||a(f),i==null||i(f))},[u,o,i]);return[u,d]}const qn=["hidden","minimized","expanded"];function Wn(e){return e&&qn.includes(e)?e:null}function cn({value:e,defaultValue:r="expanded",onChange:i,persistKey:o="ll-widget",disablePersistence:s=!1}={}){const a=`${o}:display-mode`,u=n.useRef(!1),[d,f]=ln({value:e,defaultValue:r,onChange:m=>{e===void 0&&!s&&On(a,m),i==null||i(m)}});return n.useEffect(()=>{if(u.current||(u.current=!0,s||e!==void 0))return;const m=Wn(Hn(a));m&&m!==d&&f(m)},[]),[d,f]}const Bn=640;function un(e=Bn){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)`,s=window.matchMedia(o),a=()=>i(s.matches);return a(),typeof s.addEventListener=="function"?(s.addEventListener("change",a),()=>s.removeEventListener("change",a)):(s.addListener(a),()=>{s.removeListener(a)})},[e]),r}const $t="__llHistoryPatched",ut="ll:pathname";function Fn(){if(typeof window>"u"||window.history[$t])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(ut)),o},window.history.replaceState=function(...i){const o=r.apply(this,i);return window.dispatchEvent(new Event(ut)),o},window.history[$t]=!0}function zt(){return typeof window>"u"?"/":window.location.pathname||"/"}function dn(e){const[r,i]=n.useState(()=>e??zt());return n.useEffect(()=>{if(e!==void 0)return;Fn();const o=()=>i(zt());return o(),window.addEventListener("popstate",o),window.addEventListener(ut,o),()=>{window.removeEventListener("popstate",o),window.removeEventListener(ut,o)}},[e]),e??r}const Ht=new Map,Un=/[\\^$+?.()|{}[\]]/g;function Vn(e){return e.replace(Un,"\\$&")}function Yn(e){const r=Ht.get(e);if(r)return r;const i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e,o="",s="",a=i.replace(/\*\*/g,o).replace(/\*/g,s),d=Vn(a).replace(new RegExp(`\\/${o}`,"g"),"(?:\\/.*)?").replace(new RegExp(o,"g"),".*").replace(new RegExp(s,"g"),"[^/]+"),f=new RegExp(`^${d}\\/?$`);return Ht.set(e,f),f}function Gn(e,r){const i=r.length>1&&r.endsWith("/")?r.slice(0,-1):r;return Yn(e).test(i)}function fn(e,r){return typeof e=="function"?e(r):e instanceof RegExp?e.test(r):Gn(e,r)}function Ot(e,r){if(!e||e.length===0)return!1;for(const i of e)if(fn(i,r))return!0;return!1}function pn(e,r,i){return e===void 0?!0:Ot(i,e)?!1:r&&r.length>0?Ot(r,e):!0}function hn(e,r,i){return n.useMemo(()=>pn(e,r,i),[e,r,i])}function Jn(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 Kn(e){const r=n.useMemo(()=>Jn(e.config),[e.config]),i=e.baseUrl.replace(/\/+$/,""),o=n.useRef(null),s=n.useCallback(f=>{try{new Audio(`${i}${f}`).play().catch(()=>{})}catch{}},[i]),a=n.useCallback(()=>{r.navigate&&s("/audio/page-change-sound.mp3")},[r.navigate,s]),u=n.useCallback(()=>{r.action&&s("/audio/confirmation-sound.mp3")},[r.action,s]),d=n.useCallback(f=>{if(!r.thinking){if(o.current){try{o.current.pause()}catch{}o.current=null}return}if(f){if(o.current)return;try{const m=new Audio(`${i}/audio/thinking-sound.mp3`);m.loop=!0,m.volume=.3,m.play().catch(()=>{o.current=null}),o.current=m}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:u,setThinking:d}),[a,u,d])}const qt=({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"})}),Wt=({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"})}),Xn=({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"})}),Qn={left:180,right:0,up:-90,down:90},Bt=({direction:e="right",className:r})=>t.jsx("svg",{className:r,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:{transform:`rotate(${Qn[e]}deg)`},"aria-hidden":"true",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 6l6 6-6 6"})});function Zn(e){return e==="top-left"||e==="bottom-left"?"left":"right"}const mn="ll-hidden-tab-center-y",er=5,Ft=16;function tr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(mn);if(!e)return null;const r=Number.parseFloat(e);return Number.isFinite(r)?r:null}catch{return null}}function Ut(e){if(!(typeof window>"u"))try{window.localStorage.setItem(mn,String(e))}catch{}}const nr=({position:e,isMobile:r,isSpeaking:i,onExpand:o,label:s="Open widget",avatarImageUrl:a,agentName:u})=>{const d=Zn(e),f=d==="right"?"left":"right",m=r?80:72,y=!!a,[l,c]=n.useState(null),[E,I]=n.useState(!1),C=n.useRef(null),w=n.useRef(!1),v=n.useCallback(k=>{if(typeof window>"u")return k;const N=m/2,z=Ft+N,F=window.innerHeight-Ft-N;return F<z?Math.max(z,k):Math.max(z,Math.min(F,k))},[m]);n.useEffect(()=>{const k=tr();c(v(k??window.innerHeight/2));const N=()=>{c(z=>z===null?null:v(z))};return window.addEventListener("resize",N),()=>window.removeEventListener("resize",N)},[v]);const S=n.useCallback(k=>{if(!(k.pointerType==="mouse"&&k.button!==0)&&l!==null){try{k.currentTarget.setPointerCapture(k.pointerId)}catch{}C.current={startClientY:k.clientY,startCenterY:l,moved:!1}}},[l]),j=n.useCallback(k=>{const N=C.current;if(!N)return;const z=k.clientY-N.startClientY;!N.moved&&Math.abs(z)>er&&(N.moved=!0,I(!0)),N.moved&&c(v(N.startCenterY+z))},[v]),A=n.useCallback(k=>{const N=C.current;if(N){try{k.currentTarget.releasePointerCapture(k.pointerId)}catch{}C.current=null,N.moved&&(I(!1),w.current=!0,c(z=>(z!==null&&Ut(z),z)))}},[]),b=n.useCallback(()=>{if(w.current){w.current=!1;return}o()},[o]),L=n.useCallback(k=>{if(k.key==="ArrowUp"||k.key==="ArrowDown"){k.preventDefault();const N=k.key==="ArrowUp"?-8:8;c(z=>{if(z===null)return z;const F=v(z+N);return Ut(F),F})}},[v]),$=["ll-hidden",`ll-hidden--${d}`,r?"ll-hidden--mobile":"ll-hidden--desktop",i?"ll-hidden--speaking":null,E?"is-dragging":null,y?"ll-hidden--with-avatar":null].filter(Boolean).join(" "),T=l===null?void 0:{top:`${l-m/2}px`,transform:"none"};return t.jsx("button",{type:"button",className:$,onPointerDown:S,onPointerMove:j,onPointerUp:A,onPointerCancel:A,onClick:b,onKeyDown:L,"aria-label":s,"data-position":e,style:T,children:y?t.jsxs(t.Fragment,{children:[t.jsx(Bt,{direction:f,className:"ll-hidden__chevron ll-hidden__chevron--mini"}),t.jsx("img",{src:a,alt:u?`${u} avatar`:"Agent avatar",className:"ll-hidden__avatar",draggable:!1})]}):t.jsx(Bt,{direction:f,className:"ll-hidden__chevron"})})},rr=({audioLevel:e,bars:r=20,maxHeight:i=20,minHeight:o=4,className:s,barClassName:a})=>{const u=n.useRef(null),d=n.useRef([]),f=n.useMemo(()=>{const y=(Math.sqrt(5)-1)/2;return Array.from({length:r},(l,c)=>.5+c*y%1*.5)},[r]);n.useEffect(()=>e.subscribe(l=>{for(let c=0;c<r;c++){const E=d.current[c];if(!E)continue;const I=Math.max(o,l*i*f[c]);E.style.height=`${I}px`}}),[e,r,i,o,f]);const m=["ll-waveform",s].filter(Boolean).join(" ");return t.jsx("div",{ref:u,className:m,"aria-hidden":"true",children:Array.from({length:r},(y,l)=>t.jsx("div",{ref:c=>{d.current[l]=c},className:["ll-waveform__bar",a].filter(Boolean).join(" "),style:{height:`${o}px`}},l))})},ir=({position:e,isMobile:r,agentName:i,avatarImageUrl:o,agentState:s,isMuted:a,audioLevel:u,onExpand:d,onToggleMute:f,onClose:m})=>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:d,"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(rr,{audioLevel:u,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:y=>{y.stopPropagation(),f()},onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.stopPropagation(),y.preventDefault(),f())},"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(qt,{muted:a,className:"ll-minimized__icon"})}),t.jsx(Wt,{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:s==="speaking"?"Speaking":s==="thinking"?"Thinking":"Listening"})]}),t.jsxs("div",{className:"ll-minimized__controls",children:[t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:f,"aria-label":a?"Unmute microphone":"Mute microphone",children:t.jsx(qt,{muted:a,className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn",onClick:d,"aria-label":`Expand ${i} widget`,children:t.jsx(Wt,{className:"ll-minimized__icon"})}),t.jsx("button",{type:"button",className:"ll-minimized__btn ll-minimized__btn--close",onClick:m,"aria-label":"Close widget",children:t.jsx(Xn,{className:"ll-minimized__icon"})})]})]})}),or=({src:e,alt:r,preCannedPlaying:i=!1,className:o,style:s})=>{const[a,u]=n.useState(!1),d=n.useRef(e);if(n.useEffect(()=>{d.current!==e&&(d.current=e,u(!1))},[e]),!e)return null;const f={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,...s};return t.jsx("img",{src:e,alt:r,className:o,style:f,loading:"eager",fetchPriority:"high",onLoad:()=>u(!0)})},sr=({position:e,isMobile:r,agentName:i,avatarImageUrl:o,idleLoopUrl:s,greeting:a,branding:u,teamMembers:d,currentTeamMemberId:f,isSwitchingTeamMember:m,teamSwitcherOpen:y,onToggleTeamSwitcher:l,onSelectTeamMember:c,languageMenuOpen:E,onToggleLanguageMenu:I,connectionState:C,agentState:w,transcript:v,canResume:S,needsUserGesture:j,error:A,isMuted:b,micError:L,micDevices:$,isCameraEnabled:T,cameraPreviewEl:k,cameraDevices:N,activeCameraId:z,isScreenShareEnabled:F,screenPreviewEl:ee,isSpeakerMuted:X,allowCamera:Ce,allowScreenShare:ue,allowTyping:ge,showMinimize:oe=!0,chromeless:se=!1,transforming:ye,transformingLabel:Oe,avatarVideoContainerRef:et,agentVideoEl:Q,onConnect:qe,onDisconnect:tt,onRetry:nt,onResumeAudio:We,onToggleMute:Le,onToggleCamera:Ee,onSwitchCameraDevice:je,onToggleScreenShare:Re,onToggleSpeaker:Ne,onSendMessage:xe,onMinimize:be,onClose:O,onClearMicError:ft})=>{var Te;const ve=((d==null?void 0:d.length)??0)>1,Ae=C==="connecting"||C==="connected",Z=C==="connected",Be=C==="idle"||C==="disconnected"||C==="error",[we,Me]=n.useState(!1);n.useEffect(()=>{if(!Q){Me(!1);return}if(!Q.paused&&Q.readyState>=2){Me(!0);return}Me(!1);const h=()=>Me(!0);return Q.addEventListener("playing",h),Q.addEventListener("loadeddata",h),()=>{Q.removeEventListener("playing",h),Q.removeEventListener("loadeddata",h)}},[Q]);const[pt,de]=n.useState(!1);n.useEffect(()=>{if(!Z){de(!1);return}if(we)return;const h=setTimeout(()=>de(!0),8e3);return()=>clearTimeout(h)},[Z,we]);const Y=C==="connecting"||Z&&!!o&&!we&&!pt,Fe=n.useRef(null),_e=n.useRef(null);n.useEffect(()=>{const h=Fe.current;h&&(h.innerHTML="",k&&(k.style.width="100%",k.style.height="100%",k.style.objectFit="cover",k.style.transform="scaleX(-1)",h.appendChild(k)))},[k]),n.useEffect(()=>{const h=_e.current;h&&(h.innerHTML="",ee&&(ee.style.width="100%",ee.style.height="100%",ee.style.objectFit="contain",h.appendChild(ee)))},[ee]);const[te,K]=n.useState(!1),[ae,fe]=n.useState(!1);n.useEffect(()=>{if(!te&&!ae&&!E&&!y)return;const h=()=>{K(!1),fe(!1),E&&I(),y&&l()};return document.addEventListener("click",h),()=>document.removeEventListener("click",h)},[te,ae,E,y,I,l]);const[J,ne]=n.useState(""),ke=n.useCallback(h=>{h.preventDefault();const W=J.trim();W&&(xe(W),ne(""))},[J,xe]),Ue=u.productName||"Live Layer";let pe=null,re=null;for(let h=v.length-1;h>=0;h--){const W=v[h];if(!pe&&W.role==="agent"?pe=W:!re&&W.role==="user"&&(re=W),pe&&re)break}const Ie=Z?(pe==null?void 0:pe.text)||null:a||null,Ve=Z&&(re==null?void 0:re.text)||null,Ye=["ll-expanded",r?"ll-expanded--mobile":"ll-expanded--desktop"].join(" ");return t.jsxs("div",{className:Ye,"data-position":e,"data-state":Z?"connected":Ae?"connecting":"idle",role:"dialog","aria-label":`${i} widget`,children:[t.jsxs("div",{className:"ll-expanded__bg",children:[o?t.jsx(or,{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:((Te=i==null?void 0:i.charAt(0))==null?void 0:Te.toUpperCase())||"A"})}),s&&!Z&&t.jsx("video",{className:"ll-expanded__bg-idle",src:s,autoPlay:!0,loop:!0,muted:!0,playsInline:!0})]}),t.jsx("div",{ref:et,className:"ll-expanded__video"}),Y&&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:m?"Switching...":"Connecting..."})]}),j&&Z&&t.jsxs("button",{type:"button",className:"ll-expanded__overlay ll-expanded__overlay--gesture",onClick:We,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"})]}),ye&&t.jsxs("div",{className:"ll-expanded__overlay ll-expanded__overlay--transforming",role:"status","aria-live":"polite","aria-label":Oe,children:[t.jsx("div",{className:"ll-expanded__spinner"}),t.jsx("p",{className:"ll-expanded__overlay-text",children:Oe})]}),Ae?t.jsxs("div",{className:"ll-expanded__topbar",children:[!se&&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:h=>{ve&&(h.stopPropagation(),l())},"aria-haspopup":ve?"listbox":void 0,"aria-expanded":ve?y:void 0,children:[t.jsx("span",{className:"ll-hpill__label",children:i}),ve&&t.jsx(st,{})]}),ve&&y&&t.jsx("div",{className:"ll-hmenu",onClick:h=>h.stopPropagation(),role:"listbox",children:d==null?void 0:d.map(h=>t.jsxs("button",{type:"button",className:`ll-hmenu__item ${h.id===f?"is-active":""}`,onClick:()=>c(h.id),role:"option","aria-selected":h.id===f,children:[h.avatarImageUrl&&t.jsx("img",{src:h.avatarImageUrl,alt:"",className:"ll-hmenu__avatar"}),t.jsx("span",{className:"ll-hmenu__name",children:h.name}),h.role&&t.jsx("span",{className:"ll-hmenu__role",children:h.role})]},h.id))})]}),t.jsxs("div",{className:"ll-expanded__pill-wrap",children:[t.jsxs("button",{type:"button",className:"ll-hpill ll-hpill--compact",onClick:h=>{h.stopPropagation(),I()},"aria-haspopup":"listbox","aria-expanded":E,"aria-label":"Language: English",title:"Language: English",children:[t.jsx("span",{className:"ll-hpill__label",children:"EN"}),t.jsx(st,{})]}),E&&t.jsx("div",{className:"ll-hmenu",onClick:h=>h.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--${w}`,children:w})]}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[oe!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn",onClick:be,"aria-label":"Minimize widget",title:"Minimize",children:t.jsx(Yt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:O,"aria-label":"End call",title:"End call",children:t.jsx(Vt,{})})]})]}):t.jsxs("div",{className:"ll-expanded__header ll-expanded__header--idle",children:[t.jsx("span",{className:"ll-expanded__brand",children:Ue}),t.jsxs("div",{className:"ll-expanded__header-actions",children:[oe!==!1&&t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--ghost",onClick:be,"aria-label":"Minimize widget",children:t.jsx(Yt,{})}),t.jsx("button",{type:"button",className:"ll-hbtn ll-hbtn--danger",onClick:O,"aria-label":"Close widget",children:t.jsx(Vt,{})})]})]}),Be&&(()=>{const h=S?"Restart paused session":C==="disconnected"?"Reconnect to agent":"Start video call",W=S?"Pick up where you left off":null,Ge=!A;return t.jsxs(t.Fragment,{children:[Ge&&t.jsxs("button",{type:"button",className:"ll-expanded__play",onClick:qe,"aria-label":h,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"})})}),t.jsx("span",{className:"ll-expanded__play-label",children:h})]}),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})}),W&&t.jsx("p",{className:"ll-expanded__cta-sublabel",children:W}),t.jsx("button",{type:"button",className:"ll-expanded__cta",onClick:qe,"aria-label":h,children:h})]})]})})(),t.jsxs("div",{className:`ll-expanded__pip ${Ae&&(T||F)?"is-visible":""}`,children:[t.jsx("div",{ref:_e,className:F?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"}),t.jsx("div",{ref:Fe,className:!F&&T?"ll-expanded__pip-host":"ll-expanded__pip-host is-hidden"})]}),Ae?t.jsxs("div",{className:"ll-expanded__bottom",children:[Ie&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--agent","data-role":"agent",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Ie})}),Ve&&t.jsx("div",{className:"ll-expanded__transcript ll-expanded__transcript--user","data-role":"user",children:t.jsx("p",{className:"ll-expanded__transcript-text",children:Ve})}),!se&&t.jsxs("div",{className:"ll-toolbar",onClick:h=>h.stopPropagation(),children:[ue&&t.jsx("button",{type:"button",className:`ll-tool ${F?"is-on":""}`,onClick:Re,"aria-label":F?"Stop sharing screen":"Share screen",title:F?"Stop sharing":"Share screen",children:t.jsx(ar,{})}),Ce&&t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${T?"is-on":""}`,onClick:Ee,"aria-label":T?"Turn off camera":"Turn on camera",title:T?"Stop camera":"Start camera",children:t.jsx(lr,{})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${T?"is-on":""}`,onClick:h=>{h.stopPropagation(),fe(W=>!W),K(!1)},"aria-label":"Camera devices","aria-haspopup":"listbox","aria-expanded":ae,children:t.jsx(st,{})}),ae&&N.length>0&&t.jsx(Gt,{label:"Camera",devices:N,activeId:z,onPick:h=>{fe(!1),je(h)}})]}),t.jsxs("div",{className:"ll-tool-split",children:[t.jsx("button",{type:"button",className:`ll-tool ll-tool--left ${b?"is-muted":""}`,onClick:Le,"aria-label":b?"Unmute microphone":"Mute microphone",title:b?"Unmute":"Mute",children:t.jsx(cr,{muted:b})}),t.jsx("button",{type:"button",className:`ll-tool ll-tool--right ${b?"is-muted":""}`,onClick:h=>{h.stopPropagation(),K(W=>!W),fe(!1)},"aria-label":"Microphone devices","aria-haspopup":"listbox","aria-expanded":te,children:t.jsx(st,{})}),te&&$.length>0&&t.jsx(Gt,{label:"Microphone",devices:$,activeId:"",onPick:()=>K(!1)})]}),t.jsx("button",{type:"button",className:`ll-tool ${X?"is-muted":""}`,onClick:Ne,"aria-label":X?"Unmute speaker":"Mute speaker",title:X?"Unmute speaker":"Mute speaker",children:t.jsx(ur,{muted:X})}),t.jsx("button",{type:"button",className:"ll-tool ll-tool--danger",onClick:tt,"aria-label":"End conversation",title:"End conversation",children:t.jsx(fr,{})})]}),!se&&ge&&t.jsxs("form",{className:"ll-message-input",onSubmit:ke,children:[t.jsx("input",{type:"text",className:"ll-message-input__field",placeholder:"Message...",value:J,onChange:h=>ne(h.target.value),"aria-label":"Message the agent"}),J.trim()&&t.jsx("button",{type:"submit",className:"ll-message-input__send","aria-label":"Send message",children:t.jsx(dr,{})})]})]}):null,(()=>{if(L&&C!=="error")return t.jsxs("div",{className:"ll-expanded__banner",role:"alert",children:[t.jsx("span",{children:L}),t.jsx("button",{type:"button",className:"ll-expanded__banner-x",onClick:ft,"aria-label":"Dismiss",children:"×"})]});if(!A||C!=="error")return null;let h="Failed to connect",W="Try again";return A==="MIC_PERMISSION_DENIED"?h="Microphone blocked. Allow access to talk.":A==="MIC_NOT_FOUND"?h="No microphone found. Plug one in + retry.":A==="MIC_UNAVAILABLE"?h="Mic unavailable. Check other apps using it.":A==="AGENT_TIMEOUT"?h="Agent didn't pick up. Try again.":A==="CONNECT_FAILED"?h="Connection failed. Check your network.":A.length<80&&(h=A),t.jsxs("div",{className:"ll-expanded__banner ll-expanded__banner--error",role:"alert",children:[t.jsx("span",{children:h}),t.jsx("button",{type:"button",className:"ll-expanded__banner-retry",onClick:nt,children:W})]})})()]})};function st(){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 Vt(){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 Yt(){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 ar(){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 lr(){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 cr({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 ur({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 dr(){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 fr(){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 Gt=({label:e,devices:r,activeId:i,onPick:o})=>t.jsxs("div",{className:"ll-device-menu",onClick:s=>s.stopPropagation(),role:"listbox",children:[t.jsx("p",{className:"ll-device-menu__label",children:e}),r.map((s,a)=>{const u=i===s.deviceId;return t.jsxs("button",{type:"button",className:`ll-device-menu__item ${u?"is-active":""}`,onClick:()=>o(s.deviceId),role:"option","aria-selected":u,children:[u&&t.jsx("span",{className:"ll-device-menu__dot",children:"●"}),t.jsx("span",{className:"ll-device-menu__name",children:s.label||`${e} ${a+1}`})]},s.deviceId||a)})]}),pr=['[data-ll-private="true"]',".ll-widget"];function _t(e){let r=e;for(;r;){for(const i of pr)if(r.matches(i))return!0;r=r.parentElement}return!1}function dt(e){if(_t(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 at=4096,hr=20,mr=20,gr=10,yr=10,xr=30,br=20,Jt=500,vr=['[data-ll-private="true"]',".ll-widget","script","style","noscript","iframe"];function Qe(e){if(e.getAttribute("aria-hidden")==="true"||e.hasAttribute("hidden"))return!0;let r=e;for(;r;){for(const i of vr)if(r.matches(i))return!0;r=r.parentElement}return!1}function Ze(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 Kt(e){const r=e.getAttribute("id");if(r){const a=document.querySelector(`label[for="${CSS.escape(r)}"]`);if(a!=null&&a.textContent)return a.textContent.trim()}const i=e.getAttribute("aria-label");if(i)return i.trim();const o=e.getAttribute("placeholder");if(o)return o.trim();const s=e.closest("label");return s!=null&&s.textContent?s.textContent.trim():""}function ce(e,r){return e.length<=r?e:e.slice(0,r-1)+"…"}function $e(e){return e.length}function gn(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||"",s=typeof window<"u"&&window.location.pathname||"/",a=i.title||"",u=Array.from(i.querySelectorAll("[data-ll-region]")),d=[];for(const b of u){if(d.length>=gr)break;if(Qe(b)||!Ze(b))continue;const L=b.getAttribute("data-ll-region")??"",$=b.getAttribute("data-ll-intent")??void 0,T=ce((b.innerText||b.textContent||"").trim(),Jt*2);!L||!T||d.push({id:L,intent:$,text:T})}const f=[],m=["H1","H2","H3","H4","H5","H6"],y=Array.from(i.querySelectorAll("h1, h2, h3, h4, h5, h6"));for(const b of y){if(Qe(b)||!Ze(b))continue;const L=(b.textContent||"").trim();L&&f.push(`${b.tagName}: ${ce(L,200)}`)}const l=Array.from(i.querySelectorAll("p, li"));for(const b of l){if(Qe(b)||!Ze(b)||m.includes(b.tagName))continue;const L=(b.textContent||"").trim();L.length>10&&f.push(ce(L,Jt))}const c=f.join(`
2
+ `),E=[],I=Array.from(i.querySelectorAll("a[href]"));for(const b of I){if(E.length>=hr)break;if(Qe(b)||!Ze(b))continue;const L=b.getAttribute("href")||"",$=(b.textContent||"").trim();!L||!$||E.push({href:L,text:ce($,100)})}const C=[],w=Array.from(i.querySelectorAll("input, textarea, select"));for(const b of w){if(C.length>=mr)break;if(Qe(b)||!dt(b)||!Ze(b))continue;const L=Kt(b),$=b instanceof HTMLInputElement?b.type:b.tagName.toLowerCase();L&&C.push({label:ce(L,100),type:$})}const v=Array.from(i.querySelectorAll("[data-ll-form]")),S=[];for(const b of v){if(S.length>=yr)break;if(_t(b))continue;const L=b.getAttribute("data-ll-form")||"";if(!L)continue;const $=b.getAttribute("data-ll-intent")||void 0,T=Array.from(b.querySelectorAll("[data-ll-field]")),k=[];for(const N of T){if(k.length>=xr)break;if(!dt(N))continue;const z=N.getAttribute("data-ll-field")||"";if(!z)continue;const F=Kt(N)||z,ee=N instanceof HTMLInputElement?N.type:N.tagName.toLowerCase(),X={name:z,label:ce(F,100),type:ee};if(N.required===!0&&(X.required=!0),N instanceof HTMLSelectElement){const ue=[];for(let ge=0;ge<N.options.length&&!(ue.length>=br);ge++){const oe=N.options[ge];if(!oe||oe.disabled)continue;const se=oe.value||"",ye=(oe.textContent||"").trim()||se;!se&&!ye||ue.push({value:se,label:ce(ye,60)})}ue.length>0&&(X.options=ue)}const Ce=typeof N.validationMessage=="string"?N.validationMessage:"";Ce&&(X.validationMessage=ce(Ce,200)),k.push(X)}S.push({id:L,intent:$,fields:k})}const j={url:o,title:a,pathname:s,regions:d,visibleText:c,visibleLinks:E,visibleFields:C,forms:S,extras:e};let A=$e(JSON.stringify(j.regions))+$e(j.visibleText)+$e(JSON.stringify(j.visibleLinks))+$e(JSON.stringify(j.visibleFields));for(;A>at&&j.visibleFields.length>0;)j.visibleFields.pop(),A=$e(JSON.stringify(j.visibleFields));for(;A>at&&j.visibleLinks.length>0;)j.visibleLinks.pop(),A-=80;return $e(j.visibleText)>at&&(j.visibleText=ce(j.visibleText,at-100)),j}let ze=null;function wt(e,r={}){const i=Date.now(),s=`${typeof window<"u"&&window.location.pathname||"/"}::${typeof window<"u"?window.scrollY:0}`;if(ze&&ze.key===s&&i-ze.at<1e3)return ze.ctx;const a=gn(e,r);return ze={key:s,at:i,ctx:a},a}function yn(){ze=null}const wr=200;function xn(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 _r(e){return!(!e||e.startsWith("#")||e.startsWith("javascript:")||e.startsWith("mailto:")||e.startsWith("tel:"))}function bn(e){const r=e??(typeof document<"u"?document:null);if(!r)return[];const i=typeof window<"u"&&window.location.origin||"",o=new Set,s=[],a=Array.from(r.querySelectorAll("a[href]"));for(const u of a){if(s.length>=wr)break;if(_t(u))continue;const d=u.getAttribute("href")||"";if(!_r(d))continue;let f=d,m=!0;try{if(typeof window<"u"){const l=new URL(d,i);m=l.origin===i,m&&d.startsWith("http")&&(f=l.pathname+l.search+l.hash)}}catch{continue}if(o.has(f))continue;o.add(f);const y=(u.textContent||"").trim().slice(0,120);s.push({href:f,text:y,internal:m})}return s}let He=null;const kr=5e3;function lt(){const e=Date.now(),r=typeof window<"u"&&window.location.pathname||"/";if(He&&He.pathname===r&&e-He.at<kr)return He.routes;const i=bn();return He={at:e,pathname:r,routes:i},i}function vn(){He=null}function Sr(e,r){const i=e instanceof HTMLInputElement?HTMLInputElement.prototype:e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLSelectElement.prototype,o=Object.getOwnPropertyDescriptor(i,"value"),s=o==null?void 0:o.set;s?s.call(e,r):e.value=r}function Cr(e,r,i={}){const o=i.triggerInput??!0,s=i.triggerChange??!0;if(e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")){const a=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"),u=a==null?void 0:a.set,d=r==="true"||r==="1"||r==="on";u?u.call(e,d):e.checked=d,o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}));return}Sr(e,r),o&&e.dispatchEvent(new Event("input",{bubbles:!0})),s&&e.dispatchEvent(new Event("change",{bubbles:!0}))}function Lr(){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 Er(e){if(!(e instanceof HTMLElement))return!1;const i=window.getComputedStyle(e).overflowY;return!(i!=="auto"&&i!=="scroll"||e.scrollHeight<=e.clientHeight+2)}function jr(){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(!Er(o))continue;const s=o.getBoundingClientRect();if(s.bottom<=0||s.top>=window.innerHeight||s.right<=0||s.left>=window.innerWidth||s.width<=0||s.height<=0||o.closest(".ll-widget"))continue;const a=s.width*s.height;a>i&&(i=a,r=o)}return r}function Rr(){if(typeof window>"u")return null;if(Lr())return window;const e=jr();return e||window}function Xt(e){return e instanceof Window?e.innerHeight||0:e.clientHeight||0}function Nr(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 Ar=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"]),wn=n.forwardRef(function(r,i){var Nt,At,Mt,It,Tt,Pt,Dt;const{agentId:o,apiKey:s,baseUrl:a="https://app.livelayer.studio",sessionEndpoint:u,sessionBody:d,soundEffects:f,experienceMode:m="WIDGET",autoConnect:y=!1,displayMode:l,defaultDisplayMode:c="expanded",onDisplayModeChange:E,position:I="bottom-right",mobileBreakpoint:C=640,persistKey:w="ll-widget",disablePersistence:v=!1,teamMembers:S,currentTeamMemberId:j,onTeamMemberChange:A,idleLoopUrl:b,greeting:L,avatarImageUrl:$,agentName:T,branding:k={},allowCamera:N=!0,allowScreenShare:z=!0,allowTyping:F=!0,showMinimize:ee=!0,chromeless:X=!1,transforming:Ce=!1,transformingLabel:ue="Transforming…",showOn:ge,hideOn:oe,pathname:se,onNavigate:ye,onScrollToSelector:Oe,getPageContext:et,pageContextExtras:Q,getRoutes:qe,onScrollPage:tt,onClick:nt,capabilities:We,onConnect:Le,onDisconnect:Ee,onTranscript:je,onAgentState:Re,onConnectionStateChange:Ne,onAgentEvent:xe,onAgentCommand:be,controlledSession:O,className:ft,style:ve,zIndex:Ae=2147483647}=r,Z=dn(se),Be=hn(Z,ge,oe);n.useEffect(()=>{yn(),vn()},[Z]);const we=j!==void 0,[Me,pt]=n.useState(()=>{var g;return j??((g=S==null?void 0:S[0])==null?void 0:g.id)}),de=we?j:Me,Y=n.useMemo(()=>(S==null?void 0:S.find(g=>g.id===de))??null,[S,de]),Fe=(Y==null?void 0:Y.agentId)??o,_e=m==="EMBEDDED",[te,K]=cn({value:_e?"expanded":l,defaultValue:_e?"expanded":c,onChange:E,persistKey:w,disablePersistence:_e||v}),ae=un(C),fe=tn(),J=nn(),ne=rn(),ke=on(),Ue=sn(),[pe,re]=n.useState(!1),[Ie,Ve]=n.useState(!1),[Ye,Te]=n.useState(!1),[h,W]=n.useState(!1),[Ge,kn]=n.useState(!1),rt=Kn({baseUrl:a,config:f}),it=n.useRef(rt);it.current=rt;const ht=n.useRef(ye),mt=n.useRef(Oe),gt=n.useRef(tt),yt=n.useRef(nt),kt=n.useRef(et),St=n.useRef(Q),Ct=n.useRef(qe),xt=n.useRef(We),ie=n.useRef(null);ht.current=ye,mt.current=Oe,gt.current=tt,yt.current=nt,kt.current=et,St.current=Q,Ct.current=qe,xt.current=We;function he(g){const p=xt.current;return p?p.includes(g):!0}function me(g,p){console.warn(`[LiveLayer] Agent command "${g}" blocked — capability "${p}" not in allowlist. See https://livelayer.studio/docs/react/capabilities`)}const Je=n.useCallback(g=>{var B,le,Se,Pe;const p=g;if(!(!p.type||typeof p.type!="string")){if(xe==null||xe({eventName:p.type,data:g}),p.type==="navigate"){if(!he("navigate")){me("navigate","navigate");return}const _=typeof p.href=="string"?p.href:null;if(!_){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(it.current.playPageChange(),ht.current){try{ht.current(_)}catch(R){console.warn(`[LiveLayer] onNavigate threw for "${_}". Falling back. Error:`,R)}return}if(typeof document<"u"){const R=document.querySelector(`a[href="${_.replace(/"/g,'\\"')}"]`);if(R){R.click();return}}if(typeof window<"u"&&typeof history<"u")try{history.pushState({},"",_),window.dispatchEvent(new PopStateEvent("popstate"))}catch(R){console.warn(`[LiveLayer] history.pushState fallback failed for "${_}". Pass an onNavigate prop to use your router directly. See https://livelayer.studio/docs/react/navigation`,R)}return}if(p.type==="scroll_to"){if(!he("scroll")){me("scroll_to","scroll");return}const _=typeof p.selector=="string"?p.selector:null;if(!_)return;const R=p.behavior==="instant"?"instant":"smooth";if(mt.current){try{mt.current(_,R)}catch(D){console.warn("[LiveLayer] onScrollToSelector threw.",D)}return}if(typeof document<"u"){let D=null;try{D=document.querySelector(_)}catch{console.warn(`[LiveLayer] scroll_to: invalid selector "${_}".`);return}if(!D){console.warn(`[LiveLayer] scroll_to: no element matched "${_}". The user may be on a different page. See https://livelayer.studio/docs/errors/scroll-no-match`);return}D.scrollIntoView({behavior:R,block:"start"})}return}if(p.type==="request_page_context"){if(!he("read_page")){me("request_page_context","read_page");return}const _=typeof p.requestId=="string"?p.requestId:void 0,R=(B=ie.current)==null?void 0:B.call(ie),D=q=>{const M=R,V=M==null?void 0:M.localParticipant;if(V!=null&&V.publishData)try{const G=_?{...q,requestId:_}:q,De=new TextEncoder().encode(JSON.stringify(G));V.publishData(De,{reliable:!0})}catch(G){console.warn("[LiveLayer] publishData failed.",G)}},P=St.current,H=kt.current;try{if(H){const q=H(P);if(q instanceof Promise){D({type:"page_context_pending"}),q.then(M=>D({type:"page_context",context:M})).catch(M=>{console.warn("[LiveLayer] getPageContext rejected; falling back to default walker.",M),D({type:"page_context",context:wt(P)})});return}D({type:"page_context",context:q});return}D({type:"page_context",context:wt(P)})}catch(q){console.warn("[LiveLayer] page-context extraction threw. Sending empty context.",q),D({type:"page_context",context:{url:"",title:"",pathname:"/",regions:[],visibleText:"",visibleLinks:[],visibleFields:[],forms:[],extras:P}})}return}if(p.type==="scroll_page"){if(!he("scroll")){me("scroll_page","scroll");return}const _=p.direction;if(_!=="up"&&_!=="down"&&_!=="top"&&_!=="bottom"){console.warn(`[LiveLayer] scroll_page: invalid direction "${String(_)}". Expected up | down | top | bottom.`);return}const R=p.behavior==="instant"?"instant":"smooth";if(gt.current){try{gt.current(_,R)}catch(M){console.warn("[LiveLayer] onScrollPage threw.",M)}return}if(typeof window>"u")return;const D={behavior:R},P=Rr(),H=M=>{P instanceof Window?P.scrollBy({top:M,...D}):P.scrollBy({top:M,...D})},q=M=>{P instanceof Window?P.scrollTo({top:M,...D}):P.scrollTo({top:M,...D})};_==="up"?H(-Xt(P)):_==="down"?H(Xt(P)):q(_==="top"?0:Nr(P));return}if(p.type==="click"){if(!he("click")){me("click","click");return}const _=typeof p.selector=="string"?p.selector:null;if(!_){console.warn("[LiveLayer] click: missing selector.");return}if(yt.current){try{yt.current(_)}catch(D){console.warn("[LiveLayer] onClick threw.",D)}return}if(typeof document>"u")return;let R=null;try{R=document.querySelector(_)}catch{console.warn(`[LiveLayer] click: invalid selector "${_}".`);return}if(!R){console.warn(`[LiveLayer] click: no element matched "${_}". See https://livelayer.studio/docs/errors/click-no-match`);return}if(R.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] click: refusing to click element inside a private subtree.");return}(le=R.click)==null||le.call(R);return}if(p.type==="fill_form"||p.type==="focus_field"){if(!he("fill_forms")){me(p.type,"fill_forms");return}if(typeof document>"u")return;p.type==="fill_form"&&it.current.playConfirmation();const _=typeof p.formId=="string"?p.formId:null;if(!_){console.warn(`[LiveLayer] ${p.type}: missing formId.`);return}const R=document.querySelector(`[data-ll-form="${_.replace(/"/g,'\\"')}"]`);if(!R){console.warn(`[LiveLayer] ${p.type}: no form with data-ll-form="${_}". Tag your form with <LiveLayerForm id> or data-ll-form. See https://livelayer.studio/docs/react/forms`);return}if(R.closest('[data-ll-private="true"], .ll-widget')){console.warn(`[LiveLayer] ${p.type}: refusing to touch a form in a private subtree.`);return}if(p.type==="focus_field"){const P=typeof p.fieldName=="string"?p.fieldName:null;if(!P){console.warn("[LiveLayer] focus_field: missing fieldName.");return}const H=R.querySelector(`[data-ll-field="${P.replace(/"/g,'\\"')}"]`);if(!H){console.warn(`[LiveLayer] focus_field: no field "${P}" in form "${_}".`);return}if(!dt(H)){console.warn(`[LiveLayer] focus_field: field "${P}" is privacy-protected and not focusable.`);return}H.focus();return}const D=p.values&&typeof p.values=="object"?p.values:null;if(!D){console.warn("[LiveLayer] fill_form: missing or invalid values.");return}for(const[P,H]of Object.entries(D)){if(typeof H!="string")continue;const q=R.querySelector(`[data-ll-field="${P.replace(/"/g,'\\"')}"]`);if(!q){console.warn(`[LiveLayer] fill_form: no field "${P}" in form "${_}". Skipping.`);continue}if(!dt(q)){console.warn(`[LiveLayer] fill_form: field "${P}" is privacy-protected (password / cc-* / private). Skipping.`);continue}try{Cr(q,H)}catch(M){console.warn(`[LiveLayer] fill_form: failed to set "${P}".`,M)}}return}if(p.type==="submit_form"){if(!he("submit_forms")){me("submit_form","submit_forms");return}if(typeof document>"u")return;const _=typeof p.formId=="string"?p.formId:null;if(!_){console.warn("[LiveLayer] submit_form: missing formId.");return}it.current.playConfirmation();const R=document.querySelector(`[data-ll-form="${_.replace(/"/g,'\\"')}"]`);if(!R){console.warn(`[LiveLayer] submit_form: no form with data-ll-form="${_}".`);return}if(R.closest('[data-ll-private="true"], .ll-widget')){console.warn("[LiveLayer] submit_form: refusing to submit a form in a private subtree.");return}const D=typeof p.requestId=="string"?p.requestId:void 0,P=(Se=ie.current)==null?void 0:Se.call(ie),H=V=>{const G=P,De=G==null?void 0:G.localParticipant;if(De!=null&&De.publishData)try{const Pn=D?{...V,requestId:D}:V,Dn=new TextEncoder().encode(JSON.stringify(Pn));De.publishData(Dn,{reliable:!0})}catch{}};let q=!1;const M=()=>{q=!0,H({type:"form_submitted",formId:_})};R.addEventListener("submit",M,{once:!0});try{typeof R.requestSubmit=="function"?R.requestSubmit():R.submit()}catch(V){console.warn("[LiveLayer] submit_form: requestSubmit threw.",V),R.removeEventListener("submit",M),H({type:"form_submit_blocked",formId:_,reason:"exception"});return}setTimeout(()=>{q||(R.removeEventListener("submit",M),H({type:"form_submit_blocked",formId:_,reason:"validation"}))},500);return}if(p.type==="request_routes"){if(!he("read_page")){me("request_routes","read_page");return}const _=typeof p.requestId=="string"?p.requestId:void 0,D=(Pe=ie.current)==null?void 0:Pe.call(ie),P=D==null?void 0:D.localParticipant;if(!(P!=null&&P.publishData))return;const H=M=>{try{const V=_?{type:"routes",routes:M,requestId:_}:{type:"routes",routes:M},G=new TextEncoder().encode(JSON.stringify(V));P.publishData(G,{reliable:!0})}catch(V){console.warn("[LiveLayer] request_routes: publishData failed.",V)}},q=Ct.current;if(q){try{const M=q(),V=G=>{if(!Array.isArray(G)){H([]);return}H(G.map(xn).slice(0,200))};M instanceof Promise?M.then(V).catch(G=>{console.warn("[LiveLayer] getRoutes rejected; falling back to DOM walker.",G),H(lt())}):V(M)}catch(M){console.warn("[LiveLayer] getRoutes threw; falling back to DOM walker.",M),H(lt())}return}try{H(lt())}catch(M){console.warn("[LiveLayer] request_routes: extractRoutes threw.",M)}return}Ar.has(p.type)||be==null||be(p)}},[be,xe]),U=en({agentId:O?"__controlled__":Fe,baseUrl:a,apiKey:s,sessionEndpoint:u,sessionBody:d,onDataMessage:O?void 0:Je});n.useEffect(()=>{if(O!=null&&O.subscribeToDataMessages)return O.subscribeToDataMessages(Je)},[O,Je]),ie.current=()=>{var g;return(g=U.getRoom)==null?void 0:g.call(U)},n.useEffect(()=>{var B;if(typeof window>"u")return;const g=((B=window.location)==null?void 0:B.hostname)||"";if(g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g.endsWith(".local")||g.endsWith(".test"))return window.__livelayerSimulateCommand=le=>{try{Je(le)}catch(Se){console.warn("[LiveLayer] simulate-command threw:",Se)}},()=>{delete window.__livelayerSimulateCommand}},[Je]);const x=n.useMemo(()=>O?{connectionState:O.connectionState,agentState:O.agentState,transcript:O.transcript,videoElement:O.videoElement,audioElement:O.audioElement,canResume:O.canResume,error:O.error,agentConfig:null,connect:async()=>{await O.onConnect()},disconnect:()=>O.onDisconnect(),getRoom:U.getRoom,isControlled:!0}:{connectionState:U.connectionState,agentState:U.agentState,transcript:U.transcript,videoElement:U.videoElement,audioElement:U.audioElement,canResume:U.canResume,error:U.error,agentConfig:U.agentConfig,connect:U.connect,disconnect:U.disconnect,getRoom:U.getRoom,isControlled:!1},[O,U]),Lt=n.useRef(x);Lt.current=x,n.useImperativeHandle(i,()=>({sendData:async g=>{var le,Se;const p=(Se=(le=Lt.current)==null?void 0:le.getRoom)==null?void 0:Se.call(le),B=p==null?void 0:p.localParticipant;if(B!=null&&B.publishData)try{const Pe=new TextEncoder().encode(JSON.stringify(g));await B.publishData(Pe,{reliable:!0})}catch(Pe){console.warn("[AvatarWidget] sendData failed:",Pe)}}}),[]);const Et=n.useRef(null);n.useEffect(()=>{const g=x.videoElement,p=Et.current;if(!(!g||!p))return p.appendChild(g),()=>{g.parentNode===p&&p.removeChild(g)}},[x.videoElement]),n.useEffect(()=>{const g=x.audioElement;if(!g)return;fe.attach(g);const p=g.play();return p&&typeof p.catch=="function"&&p.catch(B=>{(B==null?void 0:B.name)==="NotAllowedError"&&re(!0)}),()=>{fe.detach()}},[x.audioElement]),n.useEffect(()=>{if(x.isControlled||x.connectionState!=="connected")return;const g=x.getRoom();if(g)return J.setupMic(g).catch(()=>{}),ne.attachRoom(g),ke.attachRoom(g),Ue.refresh(),()=>{J.teardownMic(),ne.teardown(),ke.teardown()}},[x.isControlled,x.connectionState]),n.useEffect(()=>{const g=x.audioElement;g&&(g.muted=Ge)},[x.audioElement,Ge]);const Sn=n.useCallback(g=>{const p=x.getRoom();if(p)try{const B=new TextEncoder().encode(JSON.stringify({type:"user_message",text:g}));p.localParticipant.publishData(B,{reliable:!0})}catch{}},[x]),Cn=n.useCallback(()=>{kn(g=>!g)},[]);n.useEffect(()=>{Ne==null||Ne(x.connectionState),x.connectionState==="connected"?Le==null||Le():x.connectionState==="disconnected"&&(Ee==null||Ee())},[x.connectionState,Le,Ee,Ne]),n.useEffect(()=>{je==null||je(x.transcript)},[x.transcript,je]),n.useEffect(()=>{Re==null||Re(x.agentState)},[x.agentState,Re]),n.useEffect(()=>{rt.setThinking(x.agentState==="thinking")},[x.agentState,rt]);const jt=n.useRef(!1);n.useEffect(()=>{x.isControlled||!y||jt.current||Be&&x.connectionState==="idle"&&(jt.current=!0,x.connect())},[y,x.connectionState,x,Be]);const Ln=n.useCallback(g=>{const p=S==null?void 0:S.find(B=>B.id===g);p&&(Te(!1),g!==de&&(Ve(!0),x.disconnect(),we||pt(g),A==null||A(p)))},[S,de,x,we,A]);n.useEffect(()=>{Ie&&x.connectionState==="connected"&&Ve(!1)},[x.connectionState,Ie]),n.useEffect(()=>{if(!Ye)return;const g=p=>{p.key==="Escape"&&Te(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Ye]);const En=!!$||!!(Y!=null&&Y.avatarImageUrl)||x.isControlled,Ke=an(Fe,a,En);We===void 0&&((Nt=Ke.info)!=null&&Nt.capabilities)&&(xt.current=Ke.info.capabilities);const ot=(Y==null?void 0:Y.name)??T??((At=x.agentConfig)==null?void 0:At.name)??((Mt=Ke.info)==null?void 0:Mt.name)??"Live Layer",bt=(Y==null?void 0:Y.avatarImageUrl)??$??((It=x.agentConfig)==null?void 0:It.avatarImageUrl)??((Tt=Ke.info)==null?void 0:Tt.avatarImageUrl)??null,jn=b??((Pt=x.agentConfig)==null?void 0:Pt.idleLoopUrl)??((Dt=Ke.info)==null?void 0:Dt.idleLoopUrl)??null,Rn=L??null,Nn=n.useCallback(()=>K("expanded"),[K]),An=n.useCallback(()=>K("minimized"),[K]),Rt=n.useCallback(()=>{x.disconnect(),K("hidden")},[x,K]),Mn=n.useCallback(()=>{const g=x.audioElement;g&&g.play().then(()=>re(!1)).catch(()=>{})},[x.audioElement]),In=n.useCallback(()=>{re(!1),x.connect()},[x]),Xe={...ve,..._e?{}:{zIndex:Ae}};k.primaryColor&&(Xe["--ll-color-primary"]=k.primaryColor),k.accentColor&&(Xe["--ll-color-accent"]=k.accentColor),k.backgroundColor&&(Xe["--ll-color-bg"]=k.backgroundColor),k.textColor&&(Xe["--ll-color-fg"]=k.textColor);const Tn=["ll-widget",`ll-widget--${te}`,`ll-widget--${ae?"mobile":"desktop"}`,ft].filter(Boolean).join(" ");return Be?t.jsxs("div",{className:Tn,style:Xe,"data-display-mode":te,"data-position":I,"data-experience-mode":m==="EMBEDDED"?"embedded":"widget",children:[te==="hidden"&&t.jsx(nr,{position:I,isMobile:ae,isSpeaking:x.agentState==="speaking",onExpand:()=>K("expanded"),label:`Open ${ot} widget`,avatarImageUrl:bt,agentName:ot}),te==="minimized"&&t.jsx(ir,{position:I,isMobile:ae,agentName:ot,avatarImageUrl:bt,agentState:x.agentState,isMuted:J.isMuted,audioLevel:fe,onExpand:Nn,onToggleMute:J.toggleMute,onClose:Rt}),te==="expanded"&&t.jsx(sr,{position:I,isMobile:ae,agentName:ot,avatarImageUrl:bt,idleLoopUrl:jn,greeting:Rn,branding:k,teamMembers:S,currentTeamMemberId:de,isSwitchingTeamMember:Ie,teamSwitcherOpen:Ye,onToggleTeamSwitcher:()=>Te(g=>!g),onSelectTeamMember:Ln,connectionState:x.connectionState,agentState:x.agentState,transcript:x.transcript,isMuted:J.isMuted,micDevices:Ue.mics,isCameraEnabled:ne.isEnabled,cameraPreviewEl:ne.previewEl,cameraDevices:Ue.cameras,activeCameraId:ne.activeDeviceId,isScreenShareEnabled:ke.isEnabled,screenPreviewEl:ke.previewEl,isSpeakerMuted:Ge,allowCamera:N,allowScreenShare:z,allowTyping:F,showMinimize:ee,chromeless:X,transforming:Ce,transformingLabel:ue,languageMenuOpen:h,onToggleLanguageMenu:()=>W(g=>!g),needsUserGesture:pe,canResume:x.canResume,micError:J.micError,error:x.error,avatarVideoContainerRef:Et,agentVideoEl:x.videoElement,onConnect:()=>void x.connect(),onDisconnect:()=>x.disconnect(),onRetry:In,onResumeAudio:Mn,onToggleMute:J.toggleMute,onToggleCamera:()=>void ne.toggle(),onSwitchCameraDevice:g=>void ne.switchDevice(g),onToggleScreenShare:()=>void ke.toggle(),onToggleSpeaker:Cn,onSendMessage:Sn,onMinimize:An,onClose:Rt,onClearMicError:J.clearError})]}):null});wn.displayName="AvatarWidgetInner";const _n=n.forwardRef(function(r,i){return t.jsx(Zt,{children:t.jsx(wn,{...r,ref:i})})});_n.displayName="AvatarWidget";const Mr=({agentId:e,baseUrl:r,apiKey:i,mode:o,onAgentEvent:s,className:a,style:u})=>{const d=n.useRef(null),f=n.useRef(null),m=n.useRef(s);m.current=s;const y=n.useCallback(l=>{var E;const c=l.detail;(E=m.current)==null||E.call(m,c)},[]);return n.useEffect(()=>{const l=d.current;if(!l)return;const c=document.createElement("livelayer-widget");return c.setAttribute("agent-id",e),r&&c.setAttribute("base-url",r),i&&c.setAttribute("api-key",i),o&&c.setAttribute("mode",o),c.addEventListener("agent-event",y),l.appendChild(c),f.current=c,()=>{c.removeEventListener("agent-event",y),l.removeChild(c),f.current=null}},[e]),n.useEffect(()=>{f.current&&(o?f.current.setAttribute("mode",o):f.current.removeAttribute("mode"))},[o]),t.jsx("div",{ref:d,className:a,style:u})},Ir=n.forwardRef(function({id:r,intent:i,as:o="div",className:s,style:a,children:u},d){return n.createElement(o,{ref:d,"data-ll-region":r,"data-ll-intent":i,className:s,style:a},u)}),Tr=n.forwardRef(function({id:r,intent:i,children:o,...s},a){return t.jsx("form",{ref:a,"data-ll-form":r,"data-ll-intent":i,...s,children:o})}),Pr=n.forwardRef(function(r,i){const{name:o,label:s,labelClassName:a}=r,u={name:o,"data-ll-field":o};let d;if("as"in r&&r.as==="textarea"){const{name:f,label:m,labelClassName:y,as:l,...c}=r;d=t.jsx("textarea",{ref:i,...u,...c})}else if("as"in r&&r.as==="select"){const{name:f,label:m,labelClassName:y,as:l,children:c,...E}=r;d=t.jsx("select",{ref:i,...u,...E,children:c})}else{const{name:f,label:m,labelClassName:y,as:l,...c}=r;d=t.jsx("input",{ref:i,...u,...c})}return s===void 0?d:t.jsxs("label",{className:a,children:[s,d]})});let Qt=1;function Dr({onMount:e,defaultOpen:r=!1,storageKey:i="ll-debug-open"}){const[o,s]=n.useState(r),[a,u]=n.useState([]),[d,f]=n.useState(""),[m,y]=n.useState(!1),l=n.useRef(new Set),c=n.useRef([]),E=n.useRef(m);E.current=m,n.useEffect(()=>{try{const w=localStorage.getItem(i);w==="1"&&s(!0),w==="0"&&s(!1)}catch{}},[i]),n.useEffect(()=>{try{localStorage.setItem(i,o?"1":"0")}catch{}},[o,i]),n.useEffect(()=>{const w=v=>{(v.metaKey||v.ctrlKey)&&v.shiftKey&&v.key.toLowerCase()==="l"&&(v.preventDefault(),s(S=>!S))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[]),n.useEffect(()=>{const w=setInterval(()=>{if(c.current.length===0||E.current)return;const v=c.current.splice(0,c.current.length);u(S=>[...v.reverse(),...S].slice(0,200))},100);return()=>clearInterval(w)},[]);const I=n.useRef(!1);if(n.useEffect(()=>{!e||I.current||(I.current=!0,e(w=>{c.current.push({id:Qt++,ts:Date.now(),kind:"event",type:w.eventName,data:w.data})}))},[e]),n.useEffect(()=>{const w=console.warn,v=console.log,S=(j,A)=>function(...b){try{const L=typeof b[0]=="string"?b[0]:"";L.startsWith("[LiveLayer]")&&c.current.push({id:Qt++,ts:Date.now(),kind:j,type:L.slice(0,120),data:{args:b.slice(1).map($=>zr($))}})}catch{}return A.apply(this,b)};return console.warn=S("warn",w),console.log=S("log",v),()=>{console.warn=w,console.log=v}},[]),!o)return t.jsx("button",{type:"button",onClick:()=>s(!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 C=a.filter(w=>{if(!d)return!0;const v=d.toLowerCase();return w.type.toLowerCase().includes(v)||JSON.stringify(w.data||{}).toLowerCase().includes(v)});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:()=>y(w=>!w),style:vt(m?"#f59e0b":"transparent"),title:"Pause / resume capture",children:m?"▶ resume":"⏸ pause"}),t.jsx("button",{type:"button",onClick:()=>{u([]),c.current=[]},style:vt("transparent"),title:"Clear buffer",children:"clear"}),t.jsx("button",{type:"button",onClick:()=>s(!1),style:vt("transparent"),"aria-label":"Close",title:"Close (Cmd/Ctrl + Shift + L)",children:"✕"})]}),t.jsx("input",{type:"text",value:d,onChange:w=>f(w.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:C.length===0?t.jsxs("div",{style:{padding:14,fontSize:11,color:"rgba(255,255,255,0.4)",lineHeight:1.5},children:["No events yet. Connect to the agent and trigger a tool call — the events will stream in here. You can also dispatch commands manually in DevTools:",t.jsx("pre",{style:{marginTop:6,background:"rgba(255,255,255,0.04)",padding:6,borderRadius:4,fontSize:10,whiteSpace:"pre-wrap"},children:`window.__livelayerSimulateCommand({
3
3
  type: "navigate",
4
4
  href: "/about"
5
- })`})]}):_.map(w=>t.jsx(Er,{entry:w,expanded:l.current.has(w.id),onToggle:()=>{l.current.has(w.id)?l.current.delete(w.id):l.current.add(w.id),u(b=>[...b])}},w.id))})]})}function Er({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",s=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:s}),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 ft(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 Rr(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function Nr(){const[e,r]=n.useState([]),i=n.useCallback(s=>{r(a=>{const u=a.findIndex(d=>d.id===s.id);if(u>=0){const d=a.slice();return d[u]=s,d}return[...a,s]})},[]),o=n.useCallback(()=>r([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}exports.AvatarWidget=_r;exports.ErrorBoundary=Ut;exports.LiveLayerDebugPanel=jr;exports.LiveLayerField=Lr;exports.LiveLayerForm=Cr;exports.LiveLayerRegion=Sr;exports.LiveLayerWidget=kr;exports.clearPageContextCache=cn;exports.clearRoutesCache=fn;exports.extractPageContext=ln;exports.extractRoutes=dn;exports.getCachedPageContext=pt;exports.getCachedRoutes=nt;exports.matchesPattern=rn;exports.normalizeRouteInput=un;exports.shouldRenderAtPath=on;exports.useAgentInfo=Qt;exports.useAudioLevel=Yt;exports.useCameraState=Kt;exports.useDisplayMode=Zt;exports.useDisplayModePersistence=en;exports.useIsMobile=tn;exports.useLiveKitSession=Vt;exports.useMediaDevices=Jt;exports.useMicrophoneState=Gt;exports.usePathname=nn;exports.useRouteMatch=sn;exports.useScreenShareState=Xt;exports.useTranscript=Nr;
5
+ })`})]}):C.map(w=>t.jsx($r,{entry:w,expanded:l.current.has(w.id),onToggle:()=>{l.current.has(w.id)?l.current.delete(w.id):l.current.add(w.id),u(v=>[...v])}},w.id))})]})}function $r({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",s=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:s}),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 vt(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 zr(e){try{return e instanceof Error?{message:e.message,stack:e.stack}:(JSON.stringify(e),e)}catch{return String(e)}}function Hr(){const[e,r]=n.useState([]),i=n.useCallback(s=>{r(a=>{const u=a.findIndex(d=>d.id===s.id);if(u>=0){const d=a.slice();return d[u]=s,d}return[...a,s]})},[]),o=n.useCallback(()=>r([]),[]);return{entries:e,pushSegment:i,clear:o,latest:e.length>0?e[e.length-1]:null}}exports.AvatarWidget=_n;exports.ErrorBoundary=Zt;exports.LiveLayerDebugPanel=Dr;exports.LiveLayerField=Pr;exports.LiveLayerForm=Tr;exports.LiveLayerRegion=Ir;exports.LiveLayerWidget=Mr;exports.clearPageContextCache=yn;exports.clearRoutesCache=vn;exports.extractPageContext=gn;exports.extractRoutes=bn;exports.getCachedPageContext=wt;exports.getCachedRoutes=lt;exports.matchesPattern=fn;exports.normalizeRouteInput=xn;exports.shouldRenderAtPath=pn;exports.useAgentInfo=an;exports.useAudioLevel=tn;exports.useCameraState=rn;exports.useDisplayMode=ln;exports.useDisplayModePersistence=cn;exports.useIsMobile=un;exports.useLiveKitSession=en;exports.useMediaDevices=sn;exports.useMicrophoneState=nn;exports.usePathname=dn;exports.useRouteMatch=hn;exports.useScreenShareState=on;exports.useTranscript=Hr;